A platform for community discussion. Free, open, simple.
if (window.I18n) {
throw new Error(
"I18n already defined, discourse-i18n unexpectedly loaded twice!"
);
}
import * as MessageFormatRuntime from "@messageformat/runtime";
import * as MessageFormatRuntimeCardinals from "@messageformat/runtime/lib/cardinals";
import * as MessageFormatRuntimeMessages from "@messageformat/runtime/messages";
import Messages from "@messageformat/runtime/messages";
import * as Cardinals from "make-plural/cardinals";
// The placeholder format. Accepts `{{placeholder}}` and `%{placeholder}`.
const PLACEHOLDER = /(?:\{\{|%\{)(.*?)(?:\}\}?)/gm;
const SEPARATOR = ".";
export class I18n {
// Set default locale to english
defaultLocale = "en";
// Set current locale to null
locale = null;
fallbackLocale = null;
translations = null;
extras = {};
noFallbacks = false;
testing = false;
verbose = false;
verboseIndices = new Map();
pluralizationRules = Cardinals;
translate = (scope, options = {}) => {
return this.verbose
? this._verboseTranslate(scope, options)
: this._translate(scope, options);
};
// shortcut
t = this.translate;
get currentBcp47Locale() {
return this.currentLocale().replace("_", "-");
}
get pluralizationNormalizedLocale() {
if (this.currentLocale() === "pt") {
return "pt_PT";
}
return this.currentLocale().replace(/[_-].*/, "");
}
currentLocale() {
return this.locale || this.defaultLocale;
}
enableVerboseLocalization() {
this.noFallbacks = true;
this.verbose = true;
}
enableVerboseLocalizationSession() {
sessionStorage.setItem("verbose_localization", "true");
this.enableVerboseLocalization();
return "Verbose localization is enabled. Close the browser tab to turn it off. Reload the page to see the translation keys.";
}
disableVerboseLocalizationSession() {
sessionStorage.removeItem("verbose_localization");
return "Verbose localization disabled. Reload the page.";
}
toNumber(number, options) {
options = this.prepareOptions(options, this.lookup("number.format"), {
precision: 3,
separator: SEPARATOR,
delimiter: ",",
strip_insignificant_zeros: false,
});
let negative = number < 0;
let string = Math.abs(number).toFixed(options.precision).toString();
let parts = string.split(SEPARATOR);
let buffer = [];
let formattedNumber;
number = parts[0];
while (number.length > 0) {
let pos = Math.max(0, number.length - 3);
buffer.unshift(number.slice(pos, pos + 3));
number = number.slice(0, -3);
}
formattedNumber = buffer.join(options.delimiter);
if (options.precision > 0) {
formattedNumber += options.separator + parts[1];
}
if (negative) {
formattedNumber = "-" + formattedNumber;
}
if (options.strip_insignificant_zeros) {
let regex = {
separator: new RegExp(options.separator.replace(/\./, "\\.") + "$"),
zeros: /0+$/,
};
formattedNumber = formattedNumber
.replace(regex.zeros, "")
.replace(regex.separator, "");
}
return formattedNumber;
}
toHumanSize(number, options) {
let kb = 1024;
let size = number;
let iterations = 0;
let unit, precision;
while (size >= kb && iterations < 4) {
size = size / kb;
iterations += 1;
}
if (iterations === 0) {
unit = this.t("number.human.storage_units.units.byte", { count: size });
precision = 0;
} else {
unit = this.t(
"number.human.storage_units.units." +
[null, "kb", "mb", "gb", "tb"][iterations]
);
precision = size - Math.floor(size) === 0 ? 0 : 1;
}
options = this.prepareOptions(options, {
precision,
format: this.t("number.human.storage_units.format"),
delimiter: "",
});
number = this.toNumber(size, options);
number = options.format.replace("%u", unit).replace("%n", number);
return number;
}
pluralize(translation, scope, options) {
if (typeof translation !== "object") {
return translation;
}
options = this.prepareOptions(options);
let count = options.count.toString();
let pluralizer = this.pluralizer(
options.locale || this.pluralizationNormalizedLocale
);
let key = pluralizer(Math.abs(count));
let keys = typeof key === "object" && key instanceof Array ? key : [key];
let message = this.findAndTranslateValidNode(keys, translation);
if (message !== null || options.ignoreMissing) {
return message;
}
return this.missingTranslation(scope, keys[0]);
}
pluralizer(locale) {
return this.pluralizationRules[locale] ?? this.pluralizationRules["en"];
}
listJoiner(listOfStrings, delimiter) {
if (listOfStrings.length === 1) {
return listOfStrings[0];
}
if (listOfStrings.length === 2) {
return listOfStrings[0] + " " + delimiter + " " + listOfStrings[1];
}
let lastString = listOfStrings.pop();
return listOfStrings.concat(delimiter).join(`, `) + " " + lastString;
}
interpolate(message, options, scope) {
options = this.prepareOptions(options);
let value;
if (message === undefined) {
// Throw a generic error to be caught in _translate()
throw new Error();
}
const placeholders = this.findPlaceholders(message);
if (placeholders.size === 0) {
return message;
}
for (const [name, placeholderValues] of placeholders) {
if (typeof options[name] === "string") {
// The dollar sign (`$`) is a special replace pattern, and `$&` inserts
// the matched string. Thus dollars signs need to be escaped with the
// special pattern `$$`, which inserts a single `$`.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter
value = options[name].replace(/\$/g, "$$$$");
} else {
value = options[name];
}
for (const placeholder of placeholderValues) {
if (!this.isValidNode(options, name)) {
value = "[missing " + placeholder + " value]";
if (this.testing) {
throw new I18nMissingInterpolationArgument(`${scope}: ${value}`);
}
}
let regex = new RegExp(
placeholder.replace(/\{/gm, "\\{").replace(/\}/gm, "\\}")
);
message = message.replace(regex, value);
}
}
return message;
}
/**
* Extract the placeholders from the translated string before interpolation.
*
* @param {String} message The translated string.
*
* @returns {Map<String, Array<String>>} A Map keyed by the placeholder name, with the value set to
* how the placeholder appears in the string. If it appears multiple times, each instance will be
* recorded (eg, "foo" => ["%{foo}", "{{foo}}"]).
*/
findPlaceholders(message) {
if (!message) {
return new Map();
}
const placeholders = message.match(PLACEHOLDER) || [];
const placeholderMap = new Map();
placeholders.forEach((placeholder) => {
const name = placeholder.replace(PLACEHOLDER, "$1");
const values = placeholderMap.get(name) ?? [];
values.push(placeholder);
placeholderMap.set(name, values);
});
return placeholderMap;
}
findTranslation(scope, options) {
let translation = this.lookup(scope, options);
if (translation && options.needsPluralization) {
translation = this.pluralize(translation, scope, options);
}
return translation;
}
/**
* Given the current options (and if fallback is enabled), find the translation
* for the given scope.
*
* @param {String} scope The reference for the translatable string.
* @param {Object} options Custom options for this string.
*
* @returns {Array<String>|String} The translated string, or array of strings for pluralizable translations.
*/
findTranslationWithFallback(scope, options) {
let translation = this.findTranslation(scope, options);
if (!this.noFallbacks) {
// An empty string is a valid translation, so only fall back when the
// translation is genuinely missing (`null`/`undefined`). Using a falsy
// check here would treat an intentionally-blank value as missing and
// surface the raw key when no fallback locale provides the value.
if (translation == null && this.fallbackLocale) {
options.locale = this.fallbackLocale;
translation = this.findTranslation(scope, options);
}
options.ignoreMissing = false;
if (translation == null && this.currentLocale() !== this.defaultLocale) {
options.locale = this.defaultLocale;
translation = this.findTranslation(scope, options);
}
if (translation == null && this.currentLocale() !== "en") {
options.locale = "en";
translation = this.findTranslation(scope, options);
}
}
return translation;
}
findAndTranslateValidNode(keys, translation) {
for (let key of keys) {
if (this.isValidNode(translation, key)) {
return translation[key];
}
}
return null;
}
lookup(scope, options = {}) {
let translations = this.prepareOptions(this.translations);
let locale = options.locale || this.currentLocale();
let messages = translations[locale] || {};
let currentScope;
options = this.prepareOptions(options);
if (typeof scope === "object") {
scope = scope.join(SEPARATOR);
}
if (options.scope) {
scope = options.scope.toString() + SEPARATOR + scope;
}
let originalScope = scope;
scope = scope.split(SEPARATOR);
if (scope.length > 0 && scope[0] !== "js") {
scope.unshift("js");
}
while (messages && scope.length > 0) {
currentScope = scope.shift();
messages = messages[currentScope];
}
if (messages === undefined && this.extras && this.extras[locale]) {
messages = this.extras[locale];
scope = originalScope.split(SEPARATOR);
while (messages && scope.length > 0) {
currentScope = scope.shift();
messages = messages[currentScope];
}
}
if (messages === undefined) {
messages = options.defaultValue;
}
return messages;
}
missingTranslation(scope, key, options) {
let message = "[" + this.currentLocale() + SEPARATOR + scope;
if (key) {
message += SEPARATOR + key;
}
if (options && options.hasOwnProperty("count")) {
message += " count=" + JSON.stringify(options.count);
}
return message + "]";
}
// Merge several hash options, checking if value is set before
// overwriting any value. The precedence is from left to right.
//
// I18n.prepareOptions({name: "John Doe"}, {name: "Mary Doe", role: "user"});
// #=> {name: "John Doe", role: "user"}
//
prepareOptions(...args) {
let options = {};
let count = args.length;
let opts;
for (let i = 0; i < count; i++) {
opts = arguments[i];
if (!opts) {
continue;
}
for (let key in opts) {
if (!this.isValidNode(options, key)) {
options[key] = opts[key];
}
}
}
return options;
}
isValidNode(obj, node) {
return obj[node] !== null && obj[node] !== undefined;
}
messageFormat(key, options) {
const message = this._mfMessages?.hasMessage(
key,
this._mfMessages.locale,
this._mfMessages.defaultLocale
);
if (!message) {
return "Missing Key: " + key;
}
try {
return this._mfMessages.get(key, options);
} catch (err) {
return err.message;
}
}
loadData() {
const localeData = window._discourse_locale_data;
this.translations = localeData.translations;
this.locale = localeData.locale;
this.fallbackLocale = localeData.fallbackLocale;
this.#loadMessageFormatData(localeData.messageFormatData);
if (localeData.overrides) {
this.#applyOverrides(localeData.overrides);
}
if (localeData.extra?.admin_js) {
this.#loadExtra(localeData.extra.admin_js);
}
if (localeData.extra?.wizard_js) {
this.#loadExtra(localeData.extra.wizard_js);
}
if (localeData.theme) {
this.#loadTheme(localeData.theme);
}
}
#applyOverrides(overrides) {
for (const [locale, overridesForLocale] of Object.entries(
overrides || {}
)) {
for (const [key, value] of Object.entries(overridesForLocale)) {
const segs = key.replace(/^admin_js\./, "js.").split(".");
let node = this.translations[locale] || {};
for (let i = 0; i < segs.length - 1; i++) {
if (!(segs[i] in node)) {
node[segs[i]] = {};
}
node = node[segs[i]];
}
if (typeof node === "object") {
node[segs[segs.length - 1]] = value;
}
}
}
}
#loadMessageFormatData(callback) {
const msgData = callback({
"@messageformat/runtime/lib/cardinals": MessageFormatRuntimeCardinals,
"@messageformat/runtime/messages": MessageFormatRuntimeMessages,
"@messageformat/runtime": MessageFormatRuntime,
});
const messages = new Messages(msgData, this.locale.replaceAll("_", "-"));
messages.defaultLocale = "en";
this._mfMessages = messages;
}
#loadExtra(extras) {
for (const [locale, data] of Object.entries(extras)) {
this.extras[locale] ??= {};
Object.assign(this.extras[locale], data);
}
}
#loadTheme(themeTranslations) {
for (const [themeId, data] of Object.entries(themeTranslations)) {
for (const [lang, langData] of Object.entries(data)) {
this.translations[lang] ??= {};
this.translations[lang].js ??= {};
this.translations[lang].js.theme_translations ??= {};
this.translations[lang].js.theme_translations[themeId] = langData;
}
}
}
_translate(scope, options) {
options = this.prepareOptions(options);
options.needsPluralization = typeof options.count === "number";
options.ignoreMissing = !this.noFallbacks;
const translation = this.findTranslationWithFallback(scope, options);
try {
return this.interpolate(translation, options, scope);
} catch (error) {
if (error instanceof I18nMissingInterpolationArgument) {
throw error;
} else {
return (
options.translatedFallback ||
this.missingTranslation(scope, null, options)
);
}
}
}
_verboseTranslate(scope, options) {
const result = this._translate(scope, options);
let i = this.verboseIndices.get(scope);
if (!i) {
i = this.verboseIndices.size + 1;
this.verboseIndices.set(scope, i);
}
let message = `Translation #${i}: ${scope}`;
if (options && Object.keys(options).length > 0) {
message += `, parameters: ${JSON.stringify(options)}`;
}
// eslint-disable-next-line no-console
console.info(message);
return `${result} (#${i})`;
}
}
export class I18nMissingInterpolationArgument extends Error {
constructor(message) {
super(message);
this.name = "I18nMissingInterpolationArgument";
}
}
// Export a default/global instance
const I18nInstance = (globalThis.I18n = new I18n());
I18nInstance.loadData();
export default I18nInstance;
export const i18n = I18nInstance.t;