UNPKG

@navikt/ds-react

Version:

React components from the Norwegian Labour and Welfare Administration.

46 lines 2.08 kB
import { useProvider } from "../../provider/Provider.js"; import { get } from "./get.js"; /* https://regex101.com/r/LYKWi3/1 */ const REPLACE_REGEX = /{[^}]*}/g; export function useI18n(componentName, ...localTranslations) { const context = useProvider(); const contextTranslations = context.translations || []; const i18nObjects = [ ...localTranslations, ...(Array.isArray(contextTranslations) ? contextTranslations.map((t) => t[componentName]) : [contextTranslations[componentName]]), context.locale[componentName], ]; /* https://github.com/Shopify/polaris/blob/2115f9ba2f5bcbf2ad15745233501bff2db81ecf/polaris-react/src/utilities/i18n/I18n.ts#L24 */ const translate = (keypath, replacements) => { const text = get(keypath, i18nObjects); if (replacements) { return text.replace(REPLACE_REGEX, (match) => { const replacement = match.substring(1, match.length - 1); if (replacements[replacement] === undefined) { const replacementData = JSON.stringify(replacements); throw new Error(`Error translating key '${keypath}'. No replacement syntax ({}) found for key '${replacement}'. The following replacements were passed: '${replacementData}'`); } return replacements[replacement]; // can also be a number, but JS doesn't mind... }); } return text; }; return translate; } export function useDateLocale() { const context = useProvider(); const contextTranslations = context.translations || []; const i18nObjects = Array.isArray(contextTranslations) ? contextTranslations.map((t) => t.global) : [contextTranslations.global]; i18nObjects.push(context.locale.global); for (const obj of i18nObjects) { if (obj === null || obj === void 0 ? void 0 : obj.dateLocale) { return obj.dateLocale; } } throw new Error("dateLocale not found."); } //# sourceMappingURL=i18n.hooks.js.map