UNPKG

stackpress

Version:

Incept is a content management framework.

59 lines (58 loc) 1.62 kB
export default class Language { static _key = 'locale'; static _languages = {}; static get locales() { return Object.keys(this._languages); } static get key() { return this._key; } static configure(key, languages) { this._key = key; this._languages = languages; return this; } static language(name) { if (!this._languages[name]) { return null; } return { label: this._languages[name].label, translations: Object.assign({}, this._languages[name].translations) }; } static load(req, defaults = 'en_US') { const locale = req.session(this.key); const language = new Language(); language.locale = locale || defaults; return language; } _locale = 'en_US'; get label() { return Language._languages[this._locale]?.label || this._locale; } get locale() { return this._locale; } get translations() { return Language._languages[this._locale]?.translations || {}; } set locale(locale) { this._locale = locale; } save(res) { res.session.set(Language.key, this._locale); return this; } update(locale, res) { this._locale = locale; return this.save(res); } translate(phrase, ...variables) { let translation = this.translations[phrase] || phrase; for (let i = 0; i < variables.length; i++) { translation = translation.replace('%s', String(variables[i])); } return translation; } }