@bemedev/i18n
Version:
Internationalization library for Bemedev projects, providing utilities for managing translations and locale-specific content.
106 lines (103 loc) • 3.23 kB
JavaScript
import { typings } from '@bemedev/types';
import { defineTranslation, getTranslation, addFn } from './helpers.js';
class I18n {
_config;
get config() {
return this._config;
}
get translations() {
return this.#translations;
}
get keys() {
return Object.keys(this.#translations);
}
/**
* @deprecated Used only for typing (TypeScript). Do not use this property at runtime.
*/
get __key() {
return typings.commons();
}
/**
* @deprecated Used only for typing (TypeScript). Do not use this property at runtime.
*/
get __translation() {
return typings.commons();
}
constructor(_config, ...initials) {
this._config = _config;
this.#initials = initials;
for (const initial of this.#initials) {
this.#translations[initial] = _config;
}
}
#translations = {};
#initials;
#addTranslation = (key, func) => {
const isFunction = typeof func === 'function';
if (isFunction)
this.#translations[key] = func(defineTranslation);
else
this.#translations[key] = func;
};
provideTranslation = (key, func) => {
const out = new I18n(this._config, ...this.#initials);
out.#translations = { ...this.#translations };
out.#addTranslation(key, func);
return out;
};
#getOrderedLocaleAndParentLocales = (locale) => {
const locales = [];
if (typeof locale !== 'string')
return locales;
let parentLocale = locale;
while (parentLocale !== '') {
locales.push(parentLocale);
parentLocale = parentLocale.replace(/-?[^-]+$/, '');
}
return locales;
};
translateWithLocale = (locale, values) => {
const orderedLocales = new Set([
...this.#getOrderedLocaleAndParentLocales(locale),
...Object.keys(this.#translations).flatMap(this.#getOrderedLocaleAndParentLocales),
]);
let out1 = '';
for (const locale of orderedLocales) {
const translationFile = this.#translations[locale];
if (translationFile == null)
continue;
const __values = values;
const _values = typeof __values === 'string'
? { key: __values, args: {} }
: __values;
const translation = getTranslation(locale, translationFile, _values.key, _values.args);
if (translation) {
out1 = translation;
break;
}
}
return out1;
};
//@ts-expect-error for build
translate = (key, args) => {
const _args = {
key,
args,
};
const to = (locale) => this.translateWithLocale(locale, _args);
return addFn(to, { to });
};
}
// #endregion
const create = (func, ...fallbacks) => {
const isFunction = typeof func === 'function';
let config;
if (isFunction)
config = func(defineTranslation);
else
config = func;
const out = new I18n(config, ...fallbacks);
return out;
};
export { create };
//# sourceMappingURL=class.js.map