{"version":3,"file":"index.mjs","sources":["../../../../../packages/hooks/use-locale/index.ts"],"sourcesContent":["import ZhCN from '@ll-plus/locale/lang/zh-cn'\r\nimport { get } from 'lodash-es'\r\nimport { computed, inject, isRef, ref, unref } from 'vue'\r\n\r\nimport type { ILocalLanguage } from '@ll-plus/locale'\r\nimport type { MaybeRef } from '@vueuse/core'\r\nimport type { InjectionKey, Ref } from 'vue'\r\n\r\nexport type TranslatorOption = Record<string, string | number>\r\nexport type Translator = (path: string, option?: TranslatorOption) => string\r\nexport type LocaleContext = {\r\n  locale: Ref<ILocalLanguage>\r\n  lang: Ref<string>\r\n  t: Translator\r\n}\r\n\r\nexport const buildTranslator =\r\n  (locale: MaybeRef<ILocalLanguage>): Translator =>\r\n  (path, option) =>\r\n    translate(path, option, unref(locale))\r\n\r\nexport const translate = (\r\n  path: string,\r\n  option: undefined | TranslatorOption,\r\n  locale: ILocalLanguage\r\n): string =>\r\n  (get(locale, path, path) as string).replace(\r\n    /\\{(\\w+)\\}/g,\r\n    (_, key) => `${option?.[key] ?? `{${key}}`}`\r\n  )\r\n\r\nexport const buildLocaleContext = (\r\n  locale: MaybeRef<ILocalLanguage>\r\n): LocaleContext => {\r\n  const lang = computed(() => unref(locale).name)\r\n  const localeRef = isRef(locale) ? locale : ref(locale)\r\n  return {\r\n    lang,\r\n    locale: localeRef,\r\n    t: buildTranslator(locale),\r\n  }\r\n}\r\n\r\nexport const localeContextKey: InjectionKey<Ref<ILocalLanguage | undefined>> =\r\n  Symbol('localeContextKey')\r\n\r\nexport const useLocale = (\r\n  localeOverrides?: Ref<ILocalLanguage | undefined>\r\n) => {\r\n  const locale = localeOverrides || inject(localeContextKey, ref())!\r\n  return buildLocaleContext(computed(() => locale.value || ZhCN) as any)\r\n}\r\n"],"names":[],"mappings":";;;;;AAgBO,MAAM,eAAA,GACX,CAAC,MAAA,KACD,CAAC,IAAA,EAAM,MAAA,KACL,SAAA,CAAU,IAAA,EAAM,MAAA,EAAQ,KAAA,CAAM,MAAM,CAAC;AAElC,MAAM,SAAA,GAAY,CACvB,IAAA,EACA,MAAA,EACA,WAEC,GAAA,CAAI,MAAA,EAAQ,IAAA,EAAM,IAAI,CAAA,CAAa,OAAA;AAAA,EAClC,YAAA;AAAA,EACA,CAAC,GAAG,GAAA,KAAQ,CAAA,EAAG,SAAS,GAAG,CAAA,IAAK,CAAA,CAAA,EAAI,GAAG,CAAA,CAAA,CAAG,CAAA;AAC5C;AAEK,MAAM,kBAAA,GAAqB,CAChC,MAAA,KACkB;AAClB,EAAA,MAAM,OAAO,QAAA,CAAS,MAAM,KAAA,CAAM,MAAM,EAAE,IAAI,CAAA;AAC9C,EAAA,MAAM,YAAY,KAAA,CAAM,MAAM,CAAA,GAAI,MAAA,GAAS,IAAI,MAAM,CAAA;AACrD,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,MAAA,EAAQ,SAAA;AAAA,IACR,CAAA,EAAG,gBAAgB,MAAM;AAAA,GAC3B;AACF;AAEO,MAAM,gBAAA,0BACJ,kBAAkB;AAEpB,MAAM,SAAA,GAAY,CACvB,eAAA,KACG;AACH,EAAA,MAAM,MAAA,GAAS,eAAA,IAAmB,MAAA,CAAO,gBAAA,EAAkB,KAAK,CAAA;AAChE,EAAA,OAAO,mBAAmB,QAAA,CAAS,MAAM,MAAA,CAAO,KAAA,IAAS,IAAI,CAAQ,CAAA;AACvE;;;;"}