Translation
x4js includes a translation system, called i18n (internationalisation).
The framework sometimes needs to display strings: the text of an OK button, a required-field message, the names of the months. In a multilingual system, none of this is hard-coded.
Two languages are provided, French and English. You can add your own translations, change the existing ones, or create new languages.
Reading a translation
Section titled “Reading a translation”Everything goes through a read-only global variable named _tr.
import { _tr } from 'x4js';
console.log( _tr.global.ok );console.log( _tr.global.day_long[0] );Choosing the language
Section titled “Choosing the language”x4js starts in French. The language is chosen like this:
import { selectLanguage } from 'x4js';
selectLanguage( "en" );Adding your own translations
Section titled “Adding your own translations”Declare one translation object per language, then add it.
import { _tr, addTranslation, selectLanguage } from 'x4js';
const app_fr = { app: { open: "Ouvrir", close: "Fermer", }};
// same shape as app_fr: the compiler reports a missing textconst app_en: typeof app_fr = { app: { open: "Open", close: "Close", }};
addTranslation( "fr", app_fr );addTranslation( "en", app_en );
// the language is chosen after the translations are addedselectLanguage( "en" );The tree can be as deep as needed, for example to group texts by feature.
Keeping the editor’s help
Section titled “Keeping the editor’s help”_tr knows the texts of the framework, not yours. For the editor to suggest the texts of the application too, give it their shape:
export const tr = _tr as typeof _tr & typeof app_fr;
console.log( tr.app.open );This is only a type hint: tr and _tr are the same object.
Adding a language
Section titled “Adding a language”import { createLanguage } from 'x4js';
createLanguage( "de", "en" );The second parameter is the base language. Define the languages before any use.
Fallback
Section titled “Fallback”A translation missing in a language is looked up in its base language. In the example, a text that does not exist in German is displayed in English. So you can translate progressively.
Inspection
Section titled “Inspection”import { getAvailableLanguages, getCurrentLanguage } from 'x4js';
console.log( getCurrentLanguage( ) );console.log( getAvailableLanguages( ) );Complex elements
Section titled “Complex elements”Translations can contain arrays:
const app_fr = { app: { modes: [ "simple", "normal", "avancé" ], }};The rule
Section titled “The rule”If you write components, do not hard-code any text. You do not know which language they will be used in, and it is far simpler to plan for it from the start than to go back over all the code later.