Translations and Strings
A Monogatari game shows two kinds of text. Interface strings are the engine’s own words: the Start button, the settings headings, the “Are you sure you want to overwrite this slot?” question. They live in translation tables, one per language, and each string has a key ('Start', 'SlotOverwrite') that is the same in every language. The script is the game’s own words. A game in one language has one script; a game with the MultiLanguage setting on has one script per language.
src/engine/i18n.ts ties both to the player’s Language preference. It answers string('Start'), rewrites every element that names a key when the language changes, replaces _(Key) markers and {{variable}} placeholders in a statement before the statement is matched to an action, and sets the date locale. Like the other modules in src/engine/, it is a set of functions the engine object calls (Architecture): monogatari.localize() is a one-line call to localize() in i18n.ts.
This page follows that code. To add a language to the engine through a merge request, Contributing Translations has the steps; for what a game developer writes, see Translating Your Game.
What it’s for
The subsystem has three jobs:
- The interface in the player’s language. Components write their labels with
string(key)and mark the element withdata-string="key".localize()rewrites every marked element when the language changes. - Translated and personalized statements. Every string statement goes through
replaceVariables()before the engine looks for its action:_(Key)becomes the string for that key in the current language,{{name}}becomes the value stored undername. Some actions and components callreplaceVariables()on the fields they show (a choice’s text, a message’s body, a character’s name). - A script per language. With
MultiLanguageon,script()andlabel()read the branch of the script named after the current language, every time they are called.
The language itself is a player preference (preference('Language')), stored with the other preferences under the Settings key of the game’s storage (Saving and Loading). It is not part of a save: loading a game keeps the language the player has now.
The files
| File | What it does | Cypress specs |
|---|---|---|
src/engine/i18n.ts |
translateString() (behind string()), translateLabel() for labels that are a key or text, localize(), translate() for _(Key), replaceVariables() for {{variables}}, isLanguageAvailable(), and the table accessors translations(), translation(), languageMetadata() |
engine/translations.spec.js (variables, markers, interface strings, labels, the page’s language, language changes), actions/input.spec.js (interpolates {{player.name}} into dialog lines) |
src/translations/*.ts |
The 18 bundled tables. Each file’s default export is a flat object of 62 keys | none |
src/index.ts |
Monogatari._translations and Monogatari._languageMetadata: the bundled tables and their metadata, keyed by language name |
none |
src/monogatari.ts |
The public wrappers (string(), localize(), translate(), replaceVariables(), translations(), translation(), languageMetadata()), preference() (which stores the language), the Language default in _preferences, script() and label() per language, the stored language’s check in setup(), the first-run branch and the localize() call in init() |
engine/translations.spec.js |
src/engine/lifecycle.ts |
prepareAction() runs replaceVariables() on every string statement before matching, and again with escaped values for an action whose escapeInterpolatedValues is true |
every action spec, indirectly |
src/components/language-selection-screen/index.ts |
The first-run language picker | none |
src/components/settings-screen/index.ts |
The language <select> of a multi-language game |
none |
src/components/slot-container/index.ts |
The only built-in component that re-renders on didLocalize |
components/save-screen.spec.js, components/load-screen.spec.js (not their language) |
src/components/message-modal/index.ts, src/components/text-input/index.ts, src/components/alert-modal/index.ts |
Buttons and messages whose label is a key or text (actionString, an alert’s message and button label), through translateLabel() |
actions/message.spec.js, engine/translations.spec.js, actions/input.spec.js |
src/engine/ui.ts |
Swaps the quick menu’s Auto/Stop and Hide/Show labels, text and data-string key together |
engine/translations.spec.js |
debug/index.js |
The error dialogs this page mentions: engine:translation:key_not_found, engine:translation:language_not_found, engine:script:language_not_found, engine:storage:variable_not_found, engine:storage:variable_loop, component:language_selection_screen:metadata_not_found |
none |
dist/js/options.js |
The starter game’s MultiLanguage (false), LanguageSelectionScreen (true) and Language ('English') |
none |
How it works
The code runs at three moments: when the engine boots, on every statement, and on every language change.
The tables
src/index.ts imports every file in src/translations/ and assigns two objects to the engine, keyed by the language’s name, written in that language:
Monogatari._translations = {
'Bahasa Indonesia': indonesian,
'Български': bulgarian,
// …
'English': english,
'Español': spanish,
// …
'toki pona': tokipona,
};
Monogatari._languageMetadata = {
// …
'Español': {
code: 'es',
icon: '🇲🇽',
},
// …
};The name is the identifier everywhere: the Language preference holds it, the script’s top-level keys use it, the settings <select> shows it. The file name doesn’t matter (Espanol.ts, Hungarian.ts for 'Magyar', Russian.ts for 'Русский'). The metadata has two fields: code, the locale handed to Luxon for dates, and icon, the flag emoji the language selection screen shows.
| Name | File | code |
|---|---|---|
Bahasa Indonesia |
Bahasa_Indonesia.ts |
id |
Български |
Bulgarian.ts |
bg |
Беларуская |
Беларуская.ts |
be |
Deutsch |
Deutsch.ts |
de |
English |
English.ts |
en |
Español |
Espanol.ts |
es |
Français |
Francais.ts |
fr |
Magyar |
Hungarian.ts |
hu |
Nederlands |
Nederlands.ts |
nl |
Português |
Portugues.ts |
pt |
Português do Brasil |
Portugues_Brasil.ts |
pt-br |
Русский |
Russian.ts |
ru |
اللغه العربية |
العربية.ts |
ar |
한국어 |
한국어.ts |
ko |
日本語 |
日本語.ts |
ja |
繁體中文 |
繁體中文.ts |
zh-hant |
简体中文 |
简体中文.ts |
zh-hans |
toki pona |
tokipona.ts |
en |
At 2.9.0, 13 tables have all 64 keys of English.ts, none of them empty; Bulgarian, Hungarian, Беларуская, العربية and toki pona lack StorageBlocked and StorageUpdated, which they show in English. toki pona has had the code en since dates were first localized (b37678be), so its dates are formatted the English way; the record gives no reason.
A game changes the tables at run time through three methods on the engine object:
translation(language, strings)mergesstringsinto that language’s table, or creates the table. Withoutstringsit returns the table.translations(name)returns one table;translations()returns all of them.translations(object)callstranslation()for each language it names, so it merges too:translations({ 'Español': { 'Start': 'Vamos' } })changes one Spanish string and keeps the other 61. (Before 2.9.0 it assigned the object over the registry withObject.assign(), which replaced each language it named.)languageMetadata(language, { code, icon })merges into that language’s metadata, or creates it.
At boot: choosing the language
The Language preference starts as 'English' (_preferences in src/monogatari.ts; the starter’s js/options.js sets the same). setup() merges whatever Storage.get('Settings') returns into _preferences, so a language the player picked before wins over the game’s default. On a first run there is nothing stored: setup() sets the _first_run global and stores the preferences at once, except when the game is multi-language with the selection screen on. Then nothing is stored until the player picks a language, and the picker shows on every load until they do.
init() calls localize() once, after bind(), so the markup in index.html and every component rendered by then is in the stored language before the first screen shows.
The language selection screen (<language-selection-screen> in dist/index.html) lists the script’s languages, Object.keys(engine._script), read when the element is constructed. Each button needs metadata for its icon; a language without it shows component:language_selection_screen:metadata_not_found. Every timeout milliseconds (the prop defaults to 2000) the title moves to the next language’s SelectYourLanguage string. A click sets the preference and calls localize(); the didLocalize listener init() registered then stores the preferences and calls displayInitialScreen().

string(): one interface string
string(key) calls translateString():
- It reads
preference('Language'). - When there is no table for that language, it shows
engine:translation:language_not_foundand returns the English string. - When the table has no such key, it shows
engine:translation:key_not_found, listing the elements that carrydata-string="key", and returns the English string. - Otherwise it returns the string.
English is the fallback because it is the one table the engine keeps complete. A key English doesn’t have either gives undefined, and a component that interpolates ${this.engine.string('Key')} into its template then writes the text undefined. Each dialog shows once per burst of calls: reportOnce() keeps the errors it showed in a set that a microtask empties, so localize() rewriting fifty elements, or a screen rendering all its buttons, opens one dialog per missing key or language instead of one per element. The error dialogs only appear with the debug module loaded and its level above 0 (Errors and the Debug Module).
translateLabel(engine, label) serves the labels a game can give either as a key or as text: an alert’s message and buttons, a message’s or an input’s actionString. When the player’s language or English has label as a key, it returns the translation and the key, and the component puts the key in the element’s data-string, so localize() translates it again; otherwise it returns the label as written, with no key and no error dialog.
localize(): the whole interface
localize():
- triggers
willLocalizeon the<visual-novel>element; - when the language’s metadata has a
code: sets Luxon’sSettings.defaultLocaleto it (the save slots and the save screen’s default slot name format their dates with it), sets<html lang>to it, and sets<html dir>tortlorltrwithlanguageDirection(), which reads the code’s script subtag (Arab,Hebr…) or, without one, its language (ar,fa,he,ur…); - for every element inside
<visual-novel>with adata-stringattribute, callstranslateString()with the attribute’s value and, when the result is a non-empty string, replaces the element’s text with it ($_(element).text(…), which removes the element’s children); - does the same for four attributes,
placeholder,title,aria-labelandalt, on the elements that name a key indata-string-placeholder,data-string-titleand so on (the save screen’s name field uses the first); - triggers
didLocalize.
Three places call it: init(), the settings screen’s language <select>, and a click on the language selection screen. A game that changes preference('Language') from its own code calls monogatari.localize() itself.
What a language change reaches and what it doesn’t:
| Reached | Not reached |
|---|---|
Every element with data-string inside <visual-novel>: the menus, the screens’ headings, the alert, message and input buttons whose label is a key |
Text a component rendered with string() but no data-string: the settings screen’s resolution options, the iOS audio warning |
The four attributes named by data-string-<attribute> |
Elements outside <visual-novel> |
The save slots: slot-container listens to didLocalize and re-renders |
The line of dialog on screen, until the next statement |
The settings screen’s language <select>, which listens to didLocalize |
Labels a game gave as text instead of a key: they stay as written |
Dates formatted after the change, <html lang> and <html dir> |
With dir="rtl" the whole page mirrors: the main menu and the quick menu move to the left, and the text box (which aligns to the start of the line) puts the name and the dialog on the right. The text box’s own rtl class predates this and swaps the side image’s column, which dir="rtl" already does; nothing adds the class.
_(Key) and {{variables}} in a statement
prepareAction() in src/engine/lifecycle.ts calls engine.replaceVariables(statement) on every string statement, then splits the result at each space and asks the actions to match it (Statements and Actions). When the action it finds has a static escapeInterpolatedValues of true (Dialog sets it), it interpolates the statement again with { escapeValues: true, reportMissing: false } and gives the action those words instead. Object statements are not interpolated as a whole; the actions that show text call replaceVariables() on the fields they show.
replaceVariables(statement):
- Translates first.
translate()finds every_(Key)with/_\(([^()\s]+)\)/g(a key has no spaces or parentheses, so(_(Day))and_(Day)/_(Night)are found), splits the key at dots and walks the current language’s table, then English’s. A string at the end replaces the marker. Anything else, a path that walks past a string included, leaves the marker in the text, with no error. Since the tables are the same onesstring()reads, a game adds its keys withmonogatari.translation('English', { 'Greeting': 'Good morning' }). - Then the variables. It finds every
{{path}}with the lazy/{{\S+?}}/g, splits the path at dots and walksstorage(). A value replaces the placeholder asString(value), through a replacer function, so$&or$1in a value is inserted as written. WithescapeValues, the value goes throughescapeHtml()first (&,<,>,",'), unless theAllowHTMLInVariablessetting istrue: that one check inreplaceVariablesOnce()turns the escaping off for every caller. - A missing variable stays as written. When a part of the path is missing, it shows
engine:storage:variable_not_found(once per call, unlessreportMissingisfalse) and leaves{{path}}in the text. - It reads its own result again, so a stored value can hold markers and placeholders of its own. It stops when a pass changes nothing (every placeholder left is missing), when no placeholder is left, or after 16 passes; then it shows
engine:storage:variable_loopand returns the text as it is.
Because the interpolation happens before matching, what the variables hold can change the action: with storage({ cmd: 'jump Start' }), the statement '{{cmd}}' is a Jump. The matching uses the raw values; only the words handed to an action with escapeInterpolatedValues are escaped, so <b> in a player’s name shows as text in the text box, while <b> written in the statement itself stays markup. A game that wants the old behaviour everywhere sets 'AllowHTMLInVariables': true; monogatari.action('Dialog').escapeInterpolatedValues = false still turns it off for dialog alone.
The other callers, each at the moment it shows the text:
| Caller | Fields | Values escaped |
|---|---|---|
Dialog |
the character’s name, in the text box ([data-ui="who"]) and in NVL mode |
when Dialog.escapeInterpolatedValues is true (the default) |
dialog-log |
the character’s name in each entry | yes |
choice-container |
each choice’s Text |
yes |
Message |
title, subtitle, body, actionString |
yes |
Notify |
every field of the notification | no: the browser shows them as text |
InputModal, text-input |
Text, the options’ values and labels, the field’s attributes |
yes |
text-input |
Warning, the default |
no: written with .text(), or compared |
credits-screen |
section names, titles and values | yes |
A character named '_(AikoName)' therefore follows the language from the next line it speaks on.
A script per language
With MultiLanguage off, script() returns engine._script. With it on, script() reads preference('Language') and returns engine._script[language]; when the script has no such branch it shows engine:script:language_not_found and falls back to the top level. script(name) returns the label name from that result, and label() with no arguments returns script(state('label')).
monogatari.script({
'English': {
'Start': ['One.', 'Two.', 'Three.', 'end'],
},
'Español': {
'Start': ['Uno.', 'Dos.', 'Tres.', 'end'],
},
});Nothing caches the result. next() runs label()[step + 1], the revert cycle reads label()[step - 1], a load reads the saved label and step: each one asks for the language in effect at that moment. That is the whole multi-language mechanism, and it is why every language’s labels must hold the same statements at the same steps.
script(object) merges top-level keys with Object.assign(). A second script() call adds its keys next to the existing ones, and the language lists (the selection screen and the settings <select>) are the script’s top-level keys: in a game that calls script() once with labels and once with languages, Start shows up as a language.
label(key, language, value) writes one label into one language’s branch.
Changing the language
The settings screen builds its <select> when didInit fires, and only when MultiLanguage is on; otherwise it removes the language group. Its options are the script’s top-level keys. A change calls preference('Language', value), which stores the preferences, then localize().
The data
From src/lib/types/Monogatari.ts, src/lib/types/PlayerPreferences.ts and src/lib/types/GameSettings.ts:
// The registries on the engine object
_languageMetadata: Record<string, { code: string; icon: string }>;
_translations: Record<string, Record<string, string>>; // @internal
// The methods
string: (key: string) => string | undefined;
localize: () => void;
translate: (statement: string) => string;
replaceVariables: (statement: string) => string;
translations: (object?: string | Record<string, Record<string, string>> | null) => Record<string, string> | Record<string, Record<string, string>> | undefined;
translation: (language: string, strings?: Record<string, string>) => Record<string, string>;
languageMetadata: (language: string, object?: { code?: string; icon?: string } | null) => { code: string; icon: string } | Record<string, { code: string; icon: string }> | undefined;
interface PlayerPreferences {
Language: string;
// Volume, Resolution, TextSpeed, AutoPlaySpeed…
}
interface GameSettings {
MultiLanguage: boolean;
LanguageSelectionScreen: boolean;
// …
}The tables are typed as flat string maps. translate() walks dotted keys, so a game written in JavaScript can nest them (translation('English', { 'Menu': { 'Start': 'Begin' } }) and _(Menu.Start) gives Begin), but none of the bundled tables does.
A bundled table, from src/translations/English.ts:
export default {
'AdvanceHelp': 'To advance through the game, left-click or tap anywhere on the game screen or press the space key',
'AllowPlayback': 'Click here to allow audio playback',
'Audio': 'Audio',
'AutoPlay': 'Auto',
// … 62 keys in all
'Windowed': 'Windowed',
};Rules and why
- The language name is the identifier, in four places. The key in
_translations, the key in_languageMetadata, the script’s top-level key and theLanguagepreference must be spelled the same, accents included. A mismatch shows up aslanguage_not_foundin one place and works in the others. - A table needs every key English has. A missing key is an error dialog in development and English text in the player’s language, in development and in a released game. Only a key English lacks too shows
undefined. - Every language needs metadata. The selection screen leaves out a language without it (and shows
metadata_not_found), andlocalize()needs itscodeto format dates; without one the date locale stays on the previous language’s. - Put
data-stringon an element that holds only the string.localize()replaces the element’s whole text, so an icon inside it is gone after the first language change. - A string written without
data-stringmust followdidLocalizeitself.localize()only knows elements that carry the attribute. Either add it or re-render ondidLocalize, asslot-containerdoes. - Labels must line up across languages. A save stores the label and the step; a language change continues at the next step of the other script; rollback reverts the step before from the other script. A shorter label in one language moves every later step. A
nextstatement fills a gap without showing anything. - Interpolation happens before matching. An action’s constructor receives words with markers and placeholders already replaced. An action that writes its words into the page as HTML sets
static escapeInterpolatedValues = true, so a variable holding text the player typed can’t add markup. - Escape variables at every HTML sink. A component or action that puts an interpolated field into markup calls
replaceVariables(field, { escapeValues: true }). Text set with.text()or handed to a browser API (a notification) takes the raw value. - A label is a key or text. Run labels a game gives (button labels, alert messages) through
translateLabel(), and setdata-stringonly when it returns a key.
How to make the common changes
Add an interface string to a component
Render it with string() and mark the element with the key, so a language change reaches it:
override render(): string {
return `
<h3 data-string="Gallery">${this.engine.string ('Gallery')}</h3>
`;
}Add the key to all 18 files in src/translations/, in alphabetical order with the others. When you don’t know the word in a language, use the English text there and say so in the merge request. This script, saved as check-keys.ts at the repository’s root and run with bun check-keys.ts, lists what each table lacks compared to English:
import { readdirSync } from 'node:fs';
const english = (await import('./src/translations/English.ts')).default;
for (const file of readdirSync('./src/translations')) {
const table = (await import(`./src/translations/${file}`)).default;
const missing = Object.keys(english).filter((key) => !(key in table));
console.log(`${file}: ${missing.length === 0 ? 'complete' : `missing ${missing.join(', ')}`}`);
}Delete it afterwards; the repository has no such check of its own.
Add a language to the engine
Copy src/translations/English.ts, translate the values, and register the file in both objects in src/index.ts. Exercise 1 does it end to end; Contributing Translations is the version for contributors.
Follow a language change from a component
When the text can’t carry a data-string (an attribute, a string built from several keys), re-render on didLocalize, and stop listening when the element goes away:
class LanguageBadge extends Component {
static override tag = 'language-badge';
private onLanguage = (): void => {
void this.forceRender();
};
override async didMount(): Promise<void> {
this.engine.on('didLocalize', this.onLanguage);
}
override async willUnmount(): Promise<void> {
this.engine.off('didLocalize', this.onLanguage);
}
override render(): string {
return `<span>${this.engine.string('Start')}</span>`;
}
}engine.on() adds a listener on the <visual-novel> element, so it outlives the component unless willUnmount() removes it. slot-container registers its listener with an inline function and never removes it.
Show a translatable field from an action
Call this.engine.replaceVariables(field, { escapeValues: true }) in apply(), when the text is shown, not in the constructor: the player can change the language and the storage between the two. Message.apply() does this for each of its fields. Leave escapeValues out only when the text isn’t inserted as HTML.
Pitfalls and history
_(Key)arrived insidereplaceVariables(). 394e4d9c (2018-07-21, “Add a way to include translations in dialogs and names”) addedtranslate()and madereplaceVariables()call it first, which is why every caller ofreplaceVariables()also translates. The matcher from that commit,/_\(\S+\)/g, read up to the last)before a space, so two markers with no space between them (_(Day)/_(Night)) or a marker inside parentheses ((_(Day))) stayed untranslated before 2.9.0, which excludes parentheses from the key. Exercise 3 fixes it on thev2.8.1tag.- A key that walked past a string. Before 2.9.0, the dotted-path loop kept the last value when it couldn’t go deeper, so
_(Start.anything)becameStart. 2.9.0’slookupKey()givesundefinedinstead, and the marker stays. - The greedy variable matcher. ef34954c (2019-03-17, “Fix multiple variable replacement”) changed
/{{\S+}}/gto the lazy/{{\S+?}}/g; before it, two placeholders in one word were read as one. - A missing variable emptied the whole statement. From at least v2.0.2 until 2.9.0,
replaceVariables()returned''(next to the commentTODO: Is an empty string correct here?), and the player saw an empty line. 2.9.0 leaves the placeholder in the text. The TypeScript migration (bbc0c637) added the object check beforein, so a path through a string or a number reports the error instead of throwing aTypeError. - A value that contained itself never ended. Before 2.9.0,
replaceVariables()called itself on its result until no{{was left, sostorage({ loop: 'again {{loop}}' })and'{{loop}}'ended inRangeError: Maximum call stack size exceeded, and so did a value with$&in it, whichString.replace()read as “the match”. 2.9.0 loops at most 16 times and inserts values with a replacer function. Player input is still interpolated again, placeholders included, which is whyengine:storage:variable_loop’s help mentions it. - Values were markup. Before 2.9.0 a stored
<b>bold</b>was markup in the text box, and a player who typed<img src=x onerror=…>as their name ran code. 2.9.0 escapes values at the HTML sinks (see the callers table). - Dates follow the metadata code. b37678be (2019-12-25, “Localize dates”) added a
_languageCodesobject and set moment’s locale from it; 445491ef fixed Dutch the same day, which haden. a7535709 (2020-09-11) renamed the object to_languageMetadataand added the icons, and 4ccdcb66 (2023-12-19) replaced moment with Luxon, which is whereSettings.defaultLocalecomes from. actionStringwas a key, not text. b41f092e (2020-02-08, “Allow setting the string to use for the action button”) made the message and input buttons callstring(actionString), so before 2.9.0actionString: 'Close Letter'showed a button labelledundefined. Andmessage-modalkeptdata-string="Close"on that button, so a language change while a message was open relabelled a custom button “Close”. 2.9.0 reads every such label withtranslateLabel(). Exercise 4 fixes the second part on thev2.8.1tag.- The quick menu’s swapped labels. Before 2.9.0,
autoPlay()wrote “Stop” into the Auto button’s[data-string]element without changing the attribute, so alocalize()during auto-play put “Auto” back while auto-play ran;distractionFree()did the same with Hide and Show. 2.9.0 changes the attribute with the text. - The language selection screen came with a7535709 (2020-09-11), and 1aa324cf the same day skipped its work in single-language games. It shows only on a first run, which is why a developer who turns
MultiLanguageon after playing their game never sees it: the preferences are already stored. MultiLanguagewith a script that isn’t split showsengine:script:language_not_foundon boot, then keeps working, becausescript()falls back to the top level. A split script with no branch for the player’s language shows the same error, finds no label, and the Start button does nothing.- Settings changed before
init()finishes. A Cypress spec’s body can run while the engine still boots (cy.open()waits forMonogatari.default, not fordidInit). TurningMultiLanguageon there, on a first run, sends the engine to the language selection screen, which lists every top-level key of the starter’s script as a language. SetLanguageSelectionScreentofalsein the same spec, as exercise 2 does. - The settings
<select>was built with${array.map(…)}and nojoin('')before 2.9.0, so commas ended up between the options as text nodes (the browser didn’t show them), and it only read the language atdidInit, so a language picked on the selection screen showed the old one until a reload. - A removed language. Before 2.9.0, a player whose stored language a new version of the game no longer had got
engine:script:language_not_foundand an empty page. 2.9.0’ssetup()checks the stored language withisLanguageAvailable()(a script branch in a multi-language game, a table in any other) and falls back to the game’s ownLanguage.
Exercises
Each check is a Cypress spec in cypress/e2e/exercises/ of a scratch copy of the repository (How Each Part Works), run with:
bunx cypress run --browser chromium --spec 'cypress/e2e/exercises/<name>.spec.js'The specs load dist/index.html, which runs the built bundle: after changing src/, rebuild it with bun build.ts --browser before running the spec. When you’re done, put everything back with git checkout -- src dist/engine/core, delete cypress/e2e/exercises/, and delete any file you added under src/. Testing has the rest of the Cypress setup.
Exercise 1: add a language to the engine
What to do. Add Italian (Italiano, code it, icon 🇮🇹) as a bundled language, so a game whose player picks it gets the whole interface in Italian.
Hint. Two objects in src/index.ts take every language. Start the table from English so no key is missing.
Check. This spec fails on the unchanged engine (there is no Italiano table, and switching to it opens language_not_found dialogs), and passes once the bundle is rebuilt with your language:
context('Exercise: a built-in interface language', () => {
beforeEach(() => {
cy.open();
});
afterEach(function() {
this.monogatari.preference('Language', 'English');
});
it('ships Italiano with every key English has', function() {
const english = Object.keys(this.monogatari.translation('English'));
const italian = this.monogatari.translation('Italiano');
expect(italian, 'the Italiano table').to.be.an('object');
expect(Object.keys(italian)).to.include.members(english);
expect(this.monogatari.languageMetadata('Italiano')).to.deep.equal({ code: 'it', icon: '🇮🇹' });
});
it('shows the interface in Italian', function() {
this.monogatari.preference('Language', 'Italiano');
this.monogatari.localize();
cy.get('main-menu [data-action="start"] [data-string]').should('have.text', 'Inizia');
cy.window().its('Monogatari.Luxon.Settings.defaultLocale').should('equal', 'it');
cy.get('[data-error]').should('not.exist');
});
});Solution
Copy src/translations/English.ts to src/translations/Italiano.ts, change the header, and translate the values (the spec checks Start; a real contribution translates all 62):
/**
* ============================================================
* Italiano
* ============================================================
*/
export default {
'AdvanceHelp': 'Per andare avanti, fai clic o tocca lo schermo di gioco, oppure premi la barra spaziatrice',
// …
'Start': 'Inizia',
// …
};Register it in src/index.ts, in the table and in the metadata:
import bulgarian from './translations/Bulgarian';
+import italian from './translations/Italiano';
Monogatari._translations = {
…
'Français': french,
+ 'Italiano': italian,
'Magyar': hungarian,
…
};
Monogatari._languageMetadata = {
…
+ 'Italiano': {
+ code: 'it',
+ icon: '🇮🇹',
+ },
'Magyar': {Then bun build.ts --browser and run the spec. Without the metadata, the first test fails on languageMetadata('Italiano') and the second on the Luxon locale: localize() only sets it when the language has a code.
Exercise 2: predict a language change in the middle of a game
What to do. In a two-language game, the player reads the second line in English, switches to Spanish, continues, then goes back once. Before running anything, write down what the text box shows after each of the three moves. Then write a spec that asserts your prediction.
Hint. Read script() and label() in src/monogatari.ts, then ask which code reads the label after the switch: the line on screen, next(), and the revert cycle.
Check. The spec below passes on the unchanged engine. If your prediction differed, change the asserted text to what you expected and run it again: it fails, and the failure tells you which step you got wrong.
Solution
context('Exercise: the script follows the language', () => {
beforeEach(() => {
cy.open();
});
afterEach(function() {
this.monogatari.preference('Language', 'English');
});
it('reads each statement from the label of the current language', function() {
this.monogatari.setting('TypeAnimation', false);
this.monogatari.setting('MultiLanguage', true);
this.monogatari.setting('LanguageSelectionScreen', false);
this.monogatari.preference('Language', 'English');
this.monogatari.script({
'English': {
'Start': ['One.', 'Two.', 'Three.', 'end'],
},
'Español': {
'Start': ['Uno.', 'Dos.', 'Tres.', 'end'],
},
});
cy.start();
cy.get('text-box').contains('One.');
cy.proceed();
cy.get('text-box').contains('Two.');
cy.then(() => {
this.monogatari.preference('Language', 'Español');
this.monogatari.localize();
});
// The interface changes at once, the line on screen does not
cy.get('quick-menu [data-action="back"] [data-string]').should('have.text', 'Atrás');
cy.get('text-box').contains('Two.');
// The next statement comes from the Español label, same step
cy.proceed();
cy.get('text-box').contains('Tres.');
// Going back reverts the statement before, also from the Español label
cy.rollback();
cy.get('text-box').contains('Dos.');
cy.get('[data-error]').should('not.exist');
});
});localize() rewrites only [data-string] elements, so the quick menu changes and “Two.” stays. next() adds one to the step and runs label()[step], and label() reads the preference at that moment: “Tres.”. Rolling back runs the revert cycle on label()[step - 1], also read now: “Dos.”, which was never shown before. The LanguageSelectionScreen line matters: without it, a first run in Cypress sends the engine to the language selection screen, because the spec turns MultiLanguage on while init() is still running.
Exercise 3: translate every marker
What to do. Make _(Key) markers work next to each other and inside parentheses: '(_(Day))' should give (Monday) and '_(Day)/_(Night)' should give Monday/night, while a marker for a missing key stays as written. 2.9.0 fixed this bug, so do the exercise on the v2.8.1 tag: in your scratch copy, run git switch --detach v2.8.1 and bun install first.
Hint. Read the matcher in translate() in src/engine/i18n.ts, and work out by hand what /_\(\S+\)/g matches in (_(Day)).
Check. This spec fails on the tag’s engine at (_(Day)) and in the dialog test, and passes after your fix and a rebuild:
context('Exercise: translation markers', () => {
beforeEach(() => {
cy.open();
});
it('translates every marker, wherever it sits', function() {
this.monogatari.preference('Language', 'English');
this.monogatari.translation('English', {
'Day': 'Monday',
'Night': 'night',
});
expect(this.monogatari.translate('_(Day), _(Night).')).to.equal('Monday, night.');
expect(this.monogatari.translate('(_(Day))')).to.equal('(Monday)');
expect(this.monogatari.translate('_(Day)/_(Night)')).to.equal('Monday/night');
expect(this.monogatari.translate('_(Missing) stays')).to.equal('_(Missing) stays');
});
it('translates them in a line of dialog', function() {
this.monogatari.setting('TypeAnimation', false);
this.monogatari.preference('Language', 'English');
this.monogatari.translation('English', {
'Day': 'Monday',
'Night': 'night',
});
this.monogatari.script({
'Start': ['It is _(Day) (_(Night)).', 'end'],
});
cy.start();
cy.get('text-box [data-ui="say"]').should('have.text', 'It is Monday (night).');
});
});Solution
\S+ takes every character up to a space and gives back only what the final \) needs, so in (_(Day)) it matches _(Day)), the key becomes Day), and nothing is found. Exclude parentheses from the key and replace each match with a callback:
export const translate = (engine: VisualNovelEngine, statement: string): string => {
const language = engine.preference('Language') as string;
const translationsForLang = translations(engine, language) as Record<string, unknown> | undefined;
if (!translationsForLang) {
return statement;
}
// A key is everything between "_(" and the first ")", without spaces or
// parentheses, so "(_(Day))" and "_(Day)/_(Night)" are found too.
return statement.replace(/_\(([^()\s]+)\)/g, (match: string, key: string) => {
let data: unknown = translationsForLang;
for (const part of key.split('.')) {
data = (typeof data === 'object' && data !== null) ? (data as Record<string, unknown>)[part] : undefined;
}
return typeof data === 'string' ? data : match;
});
};The loop also fixes the dotted-path pitfall: a path that walks past a string now leaves the marker as written instead of returning the string. bunx eslint src/engine/i18n.ts and bunx tsc --noEmit pass with this version.
2.9.0’s translate() uses the same pattern and replacer, and also reads a key the player’s language lacks from English; compare it with yours (git show v2.9.0:src/engine/i18n.ts, once the release is tagged).
Exercise 4: keep a custom button label through a language change
What to do. A message whose actionString is 'Cancel' shows a “Cancel” button. Switch the language to Spanish while the message is open: the button should read “Cancelar”, not “Cerrar”. 2.9.0 fixed this bug, so do the exercise on the v2.8.1 tag (git switch --detach v2.8.1 in your scratch copy).
Hint. Compare what the button’s text is rendered from with what localize() reads to rewrite it.
Check. On the tag’s engine this spec fails with expected 'Cerrar' to equal 'Cancelar'; it passes after the fix and a rebuild:
context('Exercise: a button keeps its string across languages', () => {
beforeEach(() => {
cy.open();
});
afterEach(function() {
this.monogatari.preference('Language', 'English');
});
it('translates the custom button of a message again', function() {
this.monogatari.preference('Language', 'English');
this.monogatari.action('Message').messages({
'Letter': {
title: 'A letter',
body: 'It has no sender.',
actionString: 'Cancel',
},
});
this.monogatari.script({
'Start': ['show message Letter', 'end'],
});
cy.start();
cy.get('message-modal [data-action="close"]').should('have.text', 'Cancel');
cy.then(() => {
this.monogatari.preference('Language', 'Español');
this.monogatari.localize();
});
cy.get('message-modal [data-action="close"]').should('have.text', 'Cancelar');
});
});Solution
render() in src/components/message-modal/index.ts writes the text from actionString but marks the button with the fixed key Close, and localize() trusts the attribute. Mark it with the key it was rendered from:
-<button data-action="close" data-close="message-modal" data-string="Close">${this.engine.string(this.props.actionString)}</button>
+<button data-action="close" data-close="message-modal" data-string="${this.props.actionString}">${this.engine.string(this.props.actionString)}</button>The text-input’s submit button had the opposite problem on the tag: it rendered string(actionString) with no data-string at all, so a language change never reached it.
2.9.0 goes further: translateLabel() in src/engine/i18n.ts tells a key from text, and the message, input and alert components set data-string to the key only when the label is one, so a label written as text shows as written and keeps no stale key. actions/message.spec.js has this exercise’s test.
Related pages
- Contributing Translations: adding or fixing a language through a merge request.
- Translating Your Game: the same machinery from a game developer’s side.
- Configuration:
MultiLanguage,LanguageSelectionScreenand theLanguagepreference. - Language Selection Screen, Settings Screen, Message Modal: the components this page reads.
- Dialogs, Message and Input: the actions that show translated and interpolated text.
- Variables and Storage: what
{{name}}reads. - Events:
willLocalizeanddidLocalize. - Diagnosing Errors: the dialogs named on this page.
- Statements and Actions:
prepareAction()and matching, right after interpolation. - Saving and Loading: the
Settingskey that holds the language. - Components and Screens: rendering,
forceRender()and the screens. - Errors and the Debug Module: when the dialogs above appear.
- Architecture and Testing.