UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

70 lines (69 loc) 2.82 kB
"use strict"; "use client"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; exports.destructFlatTranslation = destructFlatTranslation; exports.prepareContext = prepareContext; var _react = require("react"); var _defaults = require("./defaults.js"); var _index = _interopRequireDefault(require("./locales/index.js")); var _componentHelper = require("./component-helper.js"); var _index2 = _interopRequireDefault(require("../extensions/forms/utils/json-pointer/index.js")); function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } 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 ? (0, _componentHelper.extendDeep)({}, _index.default, props.translations) : (0, _componentHelper.extendDeep)({}, _index.default); const localeWithFallback = handleLocaleFallbacks(props.locale || _defaults.LOCALE, translations); const translation = destructFlatTranslation((0, _componentHelper.extendDeep)({}, _index.default[_defaults.LOCALE], translations[localeWithFallback])); const context = { ...props, updateTranslation: (locale, newTranslations) => { context.translation = destructFlatTranslation((0, _componentHelper.extendDeep)({}, _index.default[_defaults.LOCALE], newTranslations[locale] || newTranslations[_defaults.LOCALE])); context.translations = newTranslations; }, getTranslation: localProps => { if (localProps) { const locale = localProps.lang || localProps.locale; if (locale && context.translations[locale] && locale !== localeWithFallback) { return destructFlatTranslation((0, _componentHelper.extendDeep)({}, _index.default[_defaults.LOCALE], context.translations[locale])); } } return context.translation || _index.default[_defaults.LOCALE]; }, translations, translation }; return { ...context }; } function handleLocaleFallbacks(locale, translations = {}) { if (translations[locale]) { return locale; } if (locale === 'en' || String(locale).split('-')[0] === 'en') { return 'en-GB'; } return translations[locale] ? locale : _defaults.LOCALE; } const Context = (0, _react.createContext)(prepareContext({ locale: _defaults.LOCALE, currency: _defaults.CURRENCY, currencyDisplay: _defaults.CURRENCY_DISPLAY })); var _default = exports.default = Context; function destructFlatTranslation(source) { for (const k in source) { if (String(k).includes('.')) { _index2.default.set(source, '/' + k.replace(/\./g, '/'), source[k]); } } return source; } //# sourceMappingURL=Context.js.map