UNPKG

@navikt/ds-react

Version:

React components from the Norwegian Labour and Welfare Administration.

50 lines 2.25 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useI18n = useI18n; exports.useDateLocale = useDateLocale; const Provider_1 = require("../../provider/Provider"); const get_1 = require("./get"); /* https://regex101.com/r/LYKWi3/1 */ const REPLACE_REGEX = /{[^}]*}/g; function useI18n(componentName, ...localTranslations) { const context = (0, Provider_1.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 = (0, get_1.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; } function useDateLocale() { const context = (0, Provider_1.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