mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
at ruby-v 100 lines 2.7 kB view raw
1import { 2 AppBskyLabelerDefs, 3 ComAtprotoLabelDefs, 4 InterpretedLabelValueDefinition, 5 interpretLabelValueDefinition, 6 LABELS, 7} from '@atproto/api' 8import {useLingui} from '@lingui/react' 9import * as bcp47Match from 'bcp-47-match' 10 11import { 12 GlobalLabelStrings, 13 useGlobalLabelStrings, 14} from '#/lib/moderation/useGlobalLabelStrings' 15import {useLabelDefinitions} from '#/state/preferences' 16 17export interface LabelInfo { 18 label: ComAtprotoLabelDefs.Label 19 def: InterpretedLabelValueDefinition 20 strings: ComAtprotoLabelDefs.LabelValueDefinitionStrings 21 labeler: AppBskyLabelerDefs.LabelerViewDetailed | undefined 22} 23 24export function useLabelInfo(label: ComAtprotoLabelDefs.Label): LabelInfo { 25 const {i18n} = useLingui() 26 const {labelDefs, labelers} = useLabelDefinitions() 27 const globalLabelStrings = useGlobalLabelStrings() 28 const def = getDefinition(labelDefs, label) 29 return { 30 label, 31 def, 32 strings: getLabelStrings(i18n.locale, globalLabelStrings, def), 33 labeler: labelers.find(labeler => label.src === labeler.creator.did), 34 } 35} 36 37export function getDefinition( 38 labelDefs: Record<string, InterpretedLabelValueDefinition[]>, 39 label: ComAtprotoLabelDefs.Label, 40): InterpretedLabelValueDefinition { 41 // check local definitions 42 const customDef = 43 !label.val.startsWith('!') && 44 labelDefs[label.src]?.find( 45 def => def.identifier === label.val && def.definedBy === label.src, 46 ) 47 if (customDef) { 48 return customDef 49 } 50 51 // check global definitions 52 const globalDef = LABELS[label.val as keyof typeof LABELS] 53 if (globalDef) { 54 return globalDef 55 } 56 57 // fallback to a noop definition 58 return interpretLabelValueDefinition( 59 { 60 identifier: label.val, 61 severity: 'none', 62 blurs: 'none', 63 defaultSetting: 'ignore', 64 locales: [], 65 }, 66 label.src, 67 ) 68} 69 70export function getLabelStrings( 71 locale: string, 72 globalLabelStrings: GlobalLabelStrings, 73 def: InterpretedLabelValueDefinition, 74): ComAtprotoLabelDefs.LabelValueDefinitionStrings { 75 if (!def.definedBy) { 76 // global definition, look up strings 77 if (def.identifier in globalLabelStrings) { 78 return globalLabelStrings[ 79 def.identifier 80 ] as ComAtprotoLabelDefs.LabelValueDefinitionStrings 81 } 82 } else { 83 // try to find locale match in the definition's strings 84 const localeMatch = def.locales.find( 85 strings => bcp47Match.basicFilter(locale, strings.lang).length > 0, 86 ) 87 if (localeMatch) { 88 return localeMatch 89 } 90 // fall back to the zero item if no match 91 if (def.locales[0]) { 92 return def.locales[0] 93 } 94 } 95 return { 96 lang: locale, 97 name: def.identifier, 98 description: `Labeled "${def.identifier}"`, 99 } 100}