2022-09-29 08:01:37 +00:00
|
|
|
import {getGristConfig} from 'app/common/urlUtils';
|
2022-10-19 11:43:55 +00:00
|
|
|
import {DomContents} from 'grainjs';
|
2022-09-29 08:01:37 +00:00
|
|
|
import i18next from 'i18next';
|
2022-10-19 18:44:56 +00:00
|
|
|
import {G} from 'grainjs/dist/cjs/lib/browserGlobals';
|
2022-09-29 08:01:37 +00:00
|
|
|
|
|
|
|
export async function setupLocale() {
|
|
|
|
const now = Date.now();
|
|
|
|
const supportedLngs = getGristConfig().supportedLngs ?? ['en'];
|
|
|
|
let lng = window.navigator.language || 'en';
|
|
|
|
// If user agent language is not in the list of supported languages, use the default one.
|
|
|
|
if (!supportedLngs.includes(lng)) {
|
|
|
|
// Test if server supports general language.
|
|
|
|
if (lng.includes("-") && supportedLngs.includes(lng.split("-")[0])) {
|
|
|
|
lng = lng.split("-")[0]!;
|
|
|
|
} else {
|
|
|
|
lng = 'en';
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-13 09:23:55 +00:00
|
|
|
const ns = getGristConfig().namespaces ?? ['client'];
|
2022-09-29 08:01:37 +00:00
|
|
|
// Initialize localization plugin
|
|
|
|
try {
|
|
|
|
// We don't await this promise, as it is resolved synchronously due to initImmediate: false.
|
|
|
|
i18next.init({
|
|
|
|
// By default we use english language.
|
|
|
|
fallbackLng: 'en',
|
|
|
|
// Fallback from en-US, en-GB, etc to en.
|
|
|
|
nonExplicitSupportedLngs: true,
|
|
|
|
// We will load resources ourselves.
|
|
|
|
initImmediate: false,
|
|
|
|
// Read language from navigator object.
|
|
|
|
lng,
|
2022-10-13 09:23:55 +00:00
|
|
|
// By default we use client namespace.
|
|
|
|
defaultNS: 'client',
|
2022-09-29 08:01:37 +00:00
|
|
|
// Read namespaces that are supported by the server.
|
|
|
|
// TODO: this can be converted to a dynamic list of namespaces, for async components.
|
|
|
|
// for now just import all what server offers.
|
2022-10-13 09:23:55 +00:00
|
|
|
// We can fallback to client namespace for any addons.
|
|
|
|
fallbackNS: 'client',
|
2022-09-29 08:01:37 +00:00
|
|
|
ns,
|
|
|
|
supportedLngs
|
|
|
|
}).catch((err: any) => {
|
|
|
|
// This should not happen, the promise should be resolved synchronously, without
|
|
|
|
// any errors reported.
|
|
|
|
console.error("i18next failed unexpectedly", err);
|
|
|
|
});
|
|
|
|
// Detect what is resolved languages to load.
|
|
|
|
const languages = i18next.languages;
|
|
|
|
// Fetch all json files (all of which should be already preloaded);
|
|
|
|
const loadPath = `${document.baseURI}locales/{{lng}}.{{ns}}.json`;
|
|
|
|
const pathsToLoad: Promise<any>[] = [];
|
|
|
|
async function load(lang: string, n: string) {
|
|
|
|
const resourceUrl = loadPath.replace('{{lng}}', lang).replace('{{ns}}', n);
|
|
|
|
const response = await fetch(resourceUrl);
|
|
|
|
if (!response.ok) {
|
|
|
|
throw new Error(`Failed to load ${resourceUrl}`);
|
|
|
|
}
|
|
|
|
i18next.addResourceBundle(lang, n, await response.json());
|
|
|
|
}
|
|
|
|
for (const lang of languages) {
|
|
|
|
for (const n of ns) {
|
|
|
|
pathsToLoad.push(load(lang, n));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
await Promise.all(pathsToLoad);
|
|
|
|
console.log("Localization initialized in " + (Date.now() - now) + "ms");
|
|
|
|
} catch (error: any) {
|
|
|
|
reportError(error);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2022-10-19 11:43:55 +00:00
|
|
|
* Resolves the translation of the given key using the given options.
|
2022-09-29 08:01:37 +00:00
|
|
|
*/
|
2022-10-19 18:44:56 +00:00
|
|
|
export function tString(key: string, args?: any, instance = i18next): string {
|
|
|
|
if (!instance.exists(key, args || undefined)) {
|
2022-09-29 08:01:37 +00:00
|
|
|
const error = new Error(`Missing translation for key: ${key} and language: ${i18next.language}`);
|
|
|
|
reportError(error);
|
|
|
|
}
|
2022-10-19 11:43:55 +00:00
|
|
|
return instance.t(key, args);
|
|
|
|
}
|
|
|
|
|
2022-10-20 08:34:38 +00:00
|
|
|
// We will try to infer result from the arguments passed to `t` function.
|
|
|
|
// For plain objects we expect string as a result. If any property doesn't look as a plain value
|
|
|
|
// we assume that it might be a dom node and the result is DomContents.
|
|
|
|
type InferResult<T> = T extends Record<string, string | number | boolean>|undefined|null ? string : DomContents;
|
2022-10-19 11:43:55 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Resolves the translation of the given key and substitutes. Supports dom elements interpolation.
|
|
|
|
*/
|
2022-12-09 19:14:59 +00:00
|
|
|
export function t<T extends Record<string, any>>(key: string, args?: T|null, instance = i18next): InferResult<T> {
|
2022-10-19 18:44:56 +00:00
|
|
|
if (!instance.exists(key, args || undefined)) {
|
2022-10-19 11:43:55 +00:00
|
|
|
const error = new Error(`Missing translation for key: ${key} and language: ${i18next.language}`);
|
|
|
|
reportError(error);
|
|
|
|
}
|
2022-12-09 19:14:59 +00:00
|
|
|
// Don't need to bind `t` function.
|
|
|
|
return domT(key, args, instance.t);
|
|
|
|
}
|
|
|
|
|
|
|
|
function domT(key: string, args: any, tImpl: typeof i18next.t) {
|
2022-10-19 11:43:55 +00:00
|
|
|
// If there are any DomElements in args, handle it with missingInterpolationHandler.
|
2022-10-19 18:44:56 +00:00
|
|
|
const domElements = !args ? [] : Object.entries(args).filter(([_, value]) => isLikeDomContents(value));
|
2022-10-19 11:43:55 +00:00
|
|
|
if (!args || !domElements.length) {
|
2022-12-27 18:35:03 +00:00
|
|
|
return tImpl(key, args || undefined);
|
2022-10-19 11:43:55 +00:00
|
|
|
} else {
|
|
|
|
// Make a copy of the arguments, and remove any dom elements from it. It will instruct
|
|
|
|
// i18next library to use `missingInterpolationHandler` handler.
|
|
|
|
const copy = {...args};
|
|
|
|
domElements.forEach(([prop]) => delete copy[prop]);
|
|
|
|
|
|
|
|
// Passing `missingInterpolationHandler` will allow as to resolve all missing keys
|
|
|
|
// and replace them with a marker.
|
2022-12-09 19:14:59 +00:00
|
|
|
const result: string = tImpl(key, {...copy, missingInterpolationHandler});
|
2022-10-19 11:43:55 +00:00
|
|
|
|
|
|
|
// Now replace all markers with dom elements passed as arguments.
|
2022-10-19 18:44:56 +00:00
|
|
|
const parts = result.split(/(\[\[\[[^\]]+?\]\]\])/);
|
2022-10-19 11:43:55 +00:00
|
|
|
for (let i = 1; i < parts.length; i += 2) { // Every second element is our dom element.
|
2022-10-19 18:44:56 +00:00
|
|
|
const propName = parts[i].substring(3, parts[i].length - 3);
|
2022-10-19 11:43:55 +00:00
|
|
|
const domElement = args[propName] ?? `{{${propName}}}`; // If the prop is not there, simulate default behavior.
|
|
|
|
parts[i] = domElement;
|
|
|
|
}
|
2022-10-20 08:34:38 +00:00
|
|
|
return parts.filter(p => p !== '') as any; // Remove empty parts.
|
2022-10-19 11:43:55 +00:00
|
|
|
}
|
2022-09-29 08:01:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Checks if the given key exists in the any supported language.
|
|
|
|
*/
|
|
|
|
export function hasTranslation(key: string) {
|
|
|
|
return i18next.exists(key);
|
|
|
|
}
|
2022-10-19 11:43:55 +00:00
|
|
|
|
|
|
|
function missingInterpolationHandler(key: string, value: any) {
|
2022-10-19 18:44:56 +00:00
|
|
|
return `[[[${value[1]}]]]`;
|
2022-10-19 11:43:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Very naive detection if an element has DomContents type.
|
|
|
|
*/
|
|
|
|
function isLikeDomContents(value: any): boolean {
|
|
|
|
// As null and undefined are valid DomContents values, we don't treat them as such.
|
|
|
|
if (value === null || value === undefined) { return false; }
|
|
|
|
return value instanceof G.Node || // Node
|
|
|
|
(Array.isArray(value) && isLikeDomContents(value[0])) || // DomComputed
|
|
|
|
typeof value === 'function'; // DomMethod
|
|
|
|
}
|
2022-10-20 08:34:38 +00:00
|
|
|
|
|
|
|
/**
|
2022-12-09 19:14:59 +00:00
|
|
|
* Helper function to create a scoped t function. Scoped t function is bounded to a specific
|
|
|
|
* namespace and a key prefix (a scope).
|
2022-10-20 08:34:38 +00:00
|
|
|
*/
|
2022-12-09 19:14:59 +00:00
|
|
|
export function makeT(scope: string, instance?: typeof i18next) {
|
2022-12-12 10:29:16 +00:00
|
|
|
// Can't create the scopedInstance yet as it might not be initialized.
|
2022-12-09 19:14:59 +00:00
|
|
|
let scopedInstance: null|typeof i18next = null;
|
|
|
|
let scopedResolver: null|typeof i18next.t = null;
|
|
|
|
return function<T extends Record<string, any>>(key: string, args?: T|null) {
|
|
|
|
// Create a scoped instance with disabled namespace and nested features.
|
|
|
|
// This enables keys like `key1.key2:key3` to be resolved properly.
|
|
|
|
if (!scopedInstance) {
|
|
|
|
scopedInstance = (instance ?? i18next).cloneInstance({
|
|
|
|
keySeparator: false,
|
|
|
|
nsSeparator: false,
|
|
|
|
});
|
|
|
|
// Create a version of `t` function that will use the provided prefix as default.
|
|
|
|
scopedResolver = scopedInstance.getFixedT(null, null, scope);
|
|
|
|
}
|
|
|
|
// If the key has interpolation or we did pass some arguments, make sure that
|
|
|
|
// the key exists.
|
|
|
|
if ((args || key.includes("{{")) && !scopedInstance.exists(`${scope}.${key}`, args || undefined)) {
|
|
|
|
const error = new Error(`Missing translation for key: ${key} and language: ${i18next.language}`);
|
|
|
|
reportError(error);
|
|
|
|
}
|
|
|
|
return domT(key, args, scopedResolver!);
|
2022-12-27 18:35:03 +00:00
|
|
|
};
|
2022-10-20 08:34:38 +00:00
|
|
|
}
|