react-intlayer
Version:
Easily internationalize i18n your React applications with type-safe multilingual content management.
1 lines • 2.55 kB
Source Map (JSON)
{"version":3,"file":"useI18n.mjs","names":["current: any"],"sources":["../../../src/server/useI18n.ts"],"sourcesContent":["import type { ValidDotPathsFor } from '@intlayer/core';\nimport type {\n DictionaryKeys,\n DictionaryRegistryContent,\n GetSubPath,\n LocalesValues,\n} from '@intlayer/types';\nimport { getIntlayer } from '../getIntlayer';\nimport type { DeepTransformContent } from '../plugins';\nimport { IntlayerServerContext } from './IntlayerServerProvider';\nimport { getServerContext } from './serverContext';\n\n/**\n * Hook that provides a translation function `t()` for accessing nested content by key.\n * This hook mimics the pattern found in libraries like i18next, next-intl, and vue-i18n.\n *\n * @param namespace - The dictionary key to scope translations to\n * @param locale - Optional locale override. If not provided, uses the current context locale\n * @returns A translation function `t(key)` that returns the translated content for the given key\n *\n * @example\n * ```tsx\n * const t = useI18n('IndexPage');\n * const title = t('title'); // Returns translated string for 'IndexPage.title'\n * const nestedContent = t('section.subtitle'); // Returns 'IndexPage.section.subtitle'\n * ```\n */\nexport const useI18n = <T extends DictionaryKeys>(\n namespace: T,\n locale?: LocalesValues\n) => {\n const localeTarget =\n locale ?? getServerContext<LocalesValues>(IntlayerServerContext);\n\n // Get the dictionary content for the namespace\n const dictionaryContent = getIntlayer(namespace, localeTarget);\n\n // Return the translation function\n // @ts-ignore Type instantiation is excessively deep and possibly infinite\n const t = <P extends ValidDotPathsFor<T>>(\n path: P\n ): GetSubPath<DeepTransformContent<DictionaryRegistryContent<T>>, P> => {\n if (!path) {\n return dictionaryContent as any;\n }\n\n const pathArray = (path as string).split('.');\n let current: any = dictionaryContent;\n\n for (const key of pathArray) {\n current = current?.[key];\n if (current === undefined) {\n // Return the whole dictionary as fallback if path is not found\n return dictionaryContent as any;\n }\n }\n\n return current;\n };\n\n return t;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA2BA,MAAa,WACX,WACA,WACG;CAKH,MAAM,oBAAoB,YAAY,WAHpC,UAAU,iBAAgC,sBAAsB,CAGJ;CAI9D,MAAM,KACJ,SACsE;AACtE,MAAI,CAAC,KACH,QAAO;EAGT,MAAM,YAAa,KAAgB,MAAM,IAAI;EAC7C,IAAIA,UAAe;AAEnB,OAAK,MAAM,OAAO,WAAW;AAC3B,aAAU,UAAU;AACpB,OAAI,YAAY,OAEd,QAAO;;AAIX,SAAO;;AAGT,QAAO"}