@dodona/papyros
Version:
Scratchpad for multiple programming languages in the browser.
75 lines • 2.72 kB
JavaScript
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { State, StateMap, stateProperty } from "@dodona/lit-state";
import Polyglot from "node-polyglot";
import { DUTCH_TRANSLATION, ENGLISH_TRANSLATION } from "./Translations";
export class I18n extends State {
get availableLocales() {
return [...this.translations.keys()];
}
setTranslations(locale, translations) {
this.translations.set(locale, translations);
if (this.locale === locale) {
this.dispatchStateEvent("t");
this.polyglot.replace(this.translations.get(locale));
}
}
set locale(locale) {
if (this.translations.has(locale)) {
this.dispatchStateEvent("t");
this._locale = locale;
this.polyglot.locale(locale);
this.polyglot.replace(this.translations.get(locale));
}
else {
throw new Error(`Locale ${locale} not loaded`);
}
}
get locale() {
return this._locale;
}
t(phrase, options) {
this.recordRead("t");
return this.polyglot.t(phrase, options);
}
getTranslations(key) {
if (!this.translations.has(this.locale)) {
return undefined;
}
if (!key) {
return this.translations.get(this.locale);
}
const keys = key.split(".");
let record = this.translations.get(this.locale);
for (const k of keys) {
if (typeof record === "string" || !(k in record)) {
return undefined;
}
record = record[k];
}
if (typeof record === "string") {
return undefined;
}
return record;
}
constructor() {
super();
this.polyglot = new Polyglot();
this.translations = new StateMap();
this._locale = "en";
this.polyglot.locale(this.locale);
this.setTranslations("en", ENGLISH_TRANSLATION);
this.setTranslations("nl", DUTCH_TRANSLATION);
}
}
__decorate([
stateProperty
], I18n.prototype, "_locale", void 0);
__decorate([
stateProperty
], I18n.prototype, "locale", null);
//# sourceMappingURL=I18n.js.map