@necord/localization
Version:
Localize your Discord bot with Necord!
35 lines (34 loc) • 1.94 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.NestedLocalizationAdapter = void 0;
const base_localization_adapter_1 = require("./base-localization.adapter");
class NestedLocalizationAdapter extends base_localization_adapter_1.BaseLocalizationAdapter {
getTranslation(key, locale, placeholders) {
var _a;
const translations = this.getTranslations(locale);
const translation = (_a = this.findTranslation(translations, key)) !== null && _a !== void 0 ? _a : this.getFallbackTranslation(key);
return translation.replace(/{{\s*([^}\s]+)\s*}}/g, (_, placeholder) => { var _a; return (_a = placeholders === null || placeholders === void 0 ? void 0 : placeholders[placeholder]) !== null && _a !== void 0 ? _a : ''; });
}
getTranslations(locale) {
var _a, _b, _c;
return (_c = (_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.locales) === null || _b === void 0 ? void 0 : _b[locale]) !== null && _c !== void 0 ? _c : {};
}
findTranslation(translations, key) {
const keys = key.split('.');
let currentTranslation = translations;
for (const k of keys) {
if (!(typeof currentTranslation === 'object' && k in currentTranslation)) {
return undefined;
}
currentTranslation = currentTranslation[k];
}
return typeof currentTranslation === 'string' ? currentTranslation : undefined;
}
getFallbackTranslation(key) {
var _a, _b, _c;
const fallbackLocale = (_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.fallbackLocale) !== null && _b !== void 0 ? _b : 'en-US';
const translations = this.getTranslations(fallbackLocale);
return (_c = this.findTranslation(translations, key)) !== null && _c !== void 0 ? _c : key;
}
}
exports.NestedLocalizationAdapter = NestedLocalizationAdapter;