@nextcloud/l10n
Version:
Nextcloud localization and translation helpers for apps and libraries
87 lines (86 loc) • 2.71 kB
JavaScript
;
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const translation = require("./chunks/translation-CimOTcxq.cjs");
/*!
* SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
class GettextBuilder {
debug = false;
language = "en";
translations = {};
setLanguage(language) {
this.language = language;
return this;
}
/**
* Try to detect locale from context with `en` as fallback value
* This only works within a Nextcloud page context.
*
* @deprecated use `detectLanguage` instead.
*/
detectLocale() {
return this.detectLanguage();
}
/**
* Try to detect locale from context with `en` as fallback value.
* This only works within a Nextcloud page context.
*/
detectLanguage() {
return this.setLanguage(translation.getLanguage().replace("-", "_"));
}
addTranslation(language, data) {
this.translations[language] = data;
return this;
}
enableDebugMode() {
this.debug = true;
return this;
}
build() {
if (this.debug) {
console.debug(`Creating gettext instance for language ${this.language}`);
}
const translations = Object.values(this.translations[this.language]?.translations[""] ?? {}).map(({ msgid, msgid_plural: msgidPlural, msgstr }) => {
if (msgidPlural !== void 0) {
return [`_${msgid}_::_${msgidPlural}_`, msgstr];
}
return [msgid, msgstr[0]];
});
const bundle = {
pluralFunction: (n) => translation.getPlural(n, this.language),
translations: Object.fromEntries(translations)
};
return new GettextWrapper(bundle);
}
}
class GettextWrapper {
constructor(bundle) {
this.bundle = bundle;
}
/**
* Get translated string (singular form), optionally with placeholders
*
* @param original original string to translate
* @param placeholders map of placeholder key to value
*/
gettext(original, placeholders = {}) {
return translation.translate("", original, placeholders, void 0, { bundle: this.bundle });
}
/**
* Get translated string with plural forms
*
* @param singular Singular text form
* @param plural Plural text form to be used if `count` requires it
* @param count The number to insert into the text
* @param placeholders optional map of placeholder key to value
*/
ngettext(singular, plural, count, placeholders = {}) {
return translation.translatePlural("", singular, plural, count, placeholders, { bundle: this.bundle });
}
}
function getGettextBuilder() {
return new GettextBuilder();
}
exports.getGettextBuilder = getGettextBuilder;
//# sourceMappingURL=gettext.cjs.map