@seemusic/ui-components
Version:
A Vue 3 UI Library. Uses Composable.
1 lines • 2.04 kB
Source Map (JSON)
{"version":3,"file":"useLocale.mjs","sources":["../../src/composables/useLocale.ts"],"sourcesContent":["import { inject, isRef, ref, computed, unref } from 'vue';\nimport zhCN from '../locales/lang/zh-cn';\nimport type { InjectionKey, ComputedRef } from 'vue';\nimport type { Language } from '../locales';\n\ntype Recordable = Record<string, string | number>\n\nexport const localeContextKey: InjectionKey<Language> = Symbol('sopLocaleContextKey');\n\nconst get = (object: Language, path: string, defaultValue = 'undefined') => {\n let newPath: string[] = [];\n newPath = path.replace(/\\[/g, '.').replace(/\\]/g, '').split('.');\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return newPath.reduce((a: any, b: string) => {\n return (a || {})[b];\n }, object) || defaultValue;\n};\n\nconst getLocaleContent = (locale: ComputedRef<Language>) => {\n return (path: string, option?: Recordable) =>\n (get(unref(locale), path) as string)\n .replace(\n /\\{(\\w+)\\}/g,\n (_, key) => `${option?.[key]}`\n );\n};\n\nexport const useLocale = () => {\n const locale = inject(localeContextKey) || zhCN;\n\n const localeRef = isRef(locale) ? locale : ref(locale);\n const lang = computed(() => unref(locale).name);\n\n return {\n lang,\n localeRef,\n t: getLocaleContent(computed(() => locale))\n };\n};\n"],"names":[],"mappings":";;AAOa,MAAA,mBAA2C,OAAO,qBAAqB;AAEpF,MAAM,MAAM,CAAC,QAAkB,MAAc,eAAe,gBAAgB;AAC1E,MAAI,UAAoB,CAAA;AACd,YAAA,KAAK,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,EAAE,EAAE,MAAM,GAAG;AAG/D,SAAO,QAAQ,OAAO,CAAC,GAAQ,MAAc;AACnC,YAAA,KAAK,IAAI,CAAC;AAAA,EAAA,GACjB,MAAM,KAAK;AAChB;AAEA,MAAM,mBAAmB,CAAC,WAAkC;AACnD,SAAA,CAAC,MAAc,WACnB,IAAI,MAAM,MAAM,GAAG,IAAI,EACrB;AAAA,IACC;AAAA,IACA,CAAC,GAAG,QAAQ,GAAG,iCAAS,IAAI;AAAA,EAAA;AAEpC;AAEO,MAAM,YAAY,MAAM;AACvB,QAAA,SAAS,OAAO,gBAAgB,KAAK;AAE3C,QAAM,YAAY,MAAM,MAAM,IAAI,SAAS,IAAI,MAAM;AACrD,QAAM,OAAO,SAAS,MAAM,MAAM,MAAM,EAAE,IAAI;AAEvC,SAAA;AAAA,IACL;AAAA,IACA;AAAA,IACA,GAAG,iBAAiB,SAAS,MAAM,MAAM,CAAC;AAAA,EAAA;AAE9C;"}