@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
72 lines (71 loc) • 2.86 kB
JavaScript
;
"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 || props.locales ? (0, _componentHelper.extendDeep)({}, _index.default, props.translations || props.locales) : (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 = newTranslations[locale] || newTranslations[_defaults.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 || _index.default[_defaults.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 : _defaults.LOCALE;
}
const Context = (0, _react.createContext)(prepareContext({
locale: _defaults.LOCALE,
currency: _defaults.CURRENCY,
currency_display: _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