UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

64 lines (63 loc) 2.38 kB
"use client"; import { createContext } from 'react'; import { LOCALE, CURRENCY, CURRENCY_DISPLAY } from "./defaults.js"; import defaultLocales from "./locales/index.js"; import { extendDeep } from "./component-helper.js"; import pointer from "../extensions/forms/utils/json-pointer/index.js"; export function prepareContext(props = {}) { var _props; if ((_props = props) !== null && _props !== void 0 && _props.__context__) { props = Object.assign({}, props, props.__context__); delete props.__context__; } const translations = props.translations || props.locales ? extendDeep({}, defaultLocales, props.translations || props.locales) : extendDeep({}, defaultLocales); const localeWithFallback = handleLocaleFallbacks(props.locale || LOCALE, translations); const translation = destructFlatTranslation(extendDeep({}, defaultLocales[LOCALE], translations[localeWithFallback])); const context = { ...props, updateTranslation: (locale, newTranslations) => { context.translation = newTranslations[locale] || newTranslations[LOCALE]; context.translation = destructFlatTranslation(context.translation); context.translations = newTranslations; if (context.locales) { context.locales = context.translations; } }, getTranslation: localProps => { if (localProps) { const locale = localProps.lang || localProps.locale; if (locale && (context.translations || context.locales)[locale] && locale !== localeWithFallback) { return destructFlatTranslation((context.translations || context.locales)[locale]); } } return context.translation || defaultLocales[LOCALE]; }, locales: translations, translations, translation }; return { ...context }; } function handleLocaleFallbacks(locale, translations = {}) { if (locale === 'en' || String(locale).split('-')[0] === 'en') { return 'en-GB'; } return translations[locale] ? locale : LOCALE; } const Context = createContext(prepareContext({ locale: LOCALE, currency: CURRENCY, currency_display: CURRENCY_DISPLAY })); export default Context; export function destructFlatTranslation(source) { for (const k in source) { if (String(k).includes('.')) { pointer.set(source, '/' + k.replace(/\./g, '/'), source[k]); } } return source; } //# sourceMappingURL=Context.js.map