Skip to content

Internationalization

Pablo Martínez López edited this page Nov 28, 2026 · 14 revisions

Internationalization

English · Español

The interface comes in 15 languages. The code is written in English: every user-visible string is passed through t("<English source>"), and each language is a dictionary keyed by that same English string. There is no runtime i18n library; the whole mechanism is the language table src/lib/languages.ts, src/components/language-provider.tsx, the pure functions in src/i18n/translate.ts, the dictionaries in src/i18n/<code>/ (loaded by src/i18n/load.ts) and the CI-enforced check scripts/check-translations.mjs.

Three different "languages" (do not confuse them)

Name Where it lives What it controls
Interface language LanguageProvider, localStorage key proxybuilder.lang (any code of LANGS) All UI text, number/date formatting and Rust error messages as shown to the user.
Card language useUi().lang (src/stores/ui-store.ts), key inside proxybuilder.preferencias Which language of a card's printing to fetch from Scryfall. The options come from SCRYFALL_LANGUAGES (en es fr de it pt ja ko ru zhs zht, shown by their own names). Chosen in the decklist panel "Options" ("Card language").
Design language PrintSettings.designLang, DesignLang (Rust) Which language the card designer renders text in; see Designer Overview.

This page is mostly about the first. All three share the same codes on purpose (next section).

The language table: src/lib/languages.ts

One table serves the interface and the design languages:

Export Purpose
LANGS The 15 codes, in table order: es, en (source), fr, de, it, pt (Brazil), ro, pl, nl, ru, uk, ja, ko, zhs, zht. type Lang is derived from it (and re-exported by language-provider.tsx).
LANGUAGES One Language per code: code, native (the name in its own language, never translated, so it is recognisable in a picker), country (ISO country of its flag), locale (BCP-47) and printed (whether Scryfall has cards printed in it; false for ro, pl, nl, uk).
isLang(x) Type guard: is x one of the codes.
languageInfo(code) The Language of a code; an unknown code returns English.
localeOf(lang) The BCP-47 locale (es-ES, en-GB, pt-BR, zh-Hans-CN, zh-Hant-TW…).
SCRYFALL_LANGUAGES The 11 languages with Scryfall printings, in Scryfall's list order (English first), Portuguese named just "Português" as on the cards. Replaces three formerly hard-coded lists (decklist panel, variants filters, library).

Why Scryfall codes (pt, zhs, zht) and not BCP-47: the UI language, the design language of a card (DesignLang in Rust uses the same codes in the same order) and the language of a deck are then the same key everywhere, with no mapping table. BCP-47 lives only in locale, for Intl and <html lang>.

Default language policy

Decision: the factory interface language is English; another one is chosen in Settings and remembered. Implementation: readLanguage() (exported from language-provider.tsx) returns the stored code when isLang accepts it, and "en" otherwise (missing, unknown, storage blocked). index.html ships <html lang="en">. The main README and the GitHub release notes are in English as well (README.es.md is the Spanish copy). Inferred: English is the default because the project targets a wide audience; English is also the language strings are authored in, so it needs no translation step.

How t() works

src/components/language-provider.tsx exports:

Export Purpose
LanguageProvider Context provider; state lang.
useLang() Returns { lang, setLang, t, message }. Throws if used outside the provider.
readLanguage() The stored language, or "en". Also used by src/main.tsx.
markForTranslation(source) Identity function that marks a string "translate later, elsewhere". For text stored in data tables (e.g. MARKS in src/lib/cards.ts, PHASES in src/features/decklist/actions.ts, TEXTS in src/lib/errors.ts) that is rendered later through t(variable). The check script sees markForTranslation("...") literals.
standaloneTranslation(source, vars?) t() without the provider (reads proxybuilder.lang directly; uses that language's dictionary if it is already loaded, otherwise English). Used only by ErrorBoundary, which must wrap the provider so a crash inside the provider still shows a translated recovery screen.
type Lang Re-export of the type from src/lib/languages.ts.

t(source, vars) is translate(source, lang, vars, dict, EN) from src/i18n/translate.ts, a pure module (no React) so it can be tested alone:

  • Fallback chain: language → English dictionary → the key itself. A key missing from, say, the Polish dictionary shows the English entry, which is the source string (the English dictionary only adds plural forms); if even that lacks it, the key itself is shown. Never an empty string or a technical key. That safety net also hides missing translations while developing, which is exactly why the check script exists.
  • Context suffix. A key can end in ##context (Storage##counter) to tell apart two uses of the same English text; sourceText strips it, so it is never shown.
  • Plurals. A dictionary value is either a string or a Plural object (src/i18n/types.ts: zero?, one?, two?, few?, many?, other; Translation = string | Plural, Dictionary = Record<string, Translation>). The form is chosen from vars.n with Intl.PluralRules(locale) (cached per locale); a missing form, or an n that is not a finite number, uses other. When the value came from the English fallback, English plural rules choose the form. English has plurals too: a source string cannot say by itself "1 card" against "2 cards", so each counting string ({n}) has its forms in en/, where other is the source string itself.
  • Interpolation. \{(\w+)\} placeholders are replaced from vars; a placeholder with no value (or null/undefined) is left as {name} rather than printed as undefined. Number values are formatted with Intl.NumberFormat of the interface language (always, even when the text fell back to English). Hence the rule: counts passed to t() are numbers, never pre-formatted with toLocaleString/toFixed.
  • Number, date, currency and relative-time formatting outside t() uses localeOf(lang): currencyFormat in src/features/stats/texts.ts, dates in src/features/stats/types.tsx, dates/relative times/prices in src/features/library/parts.tsx, the symbols date in src/features/design/resources-dialog.tsx.
  • The t function is recreated only when lang changes (useMemo([lang])), so it is safe in dependency lists; components re-render on language change because the context value changes.

Switching language

setLang(l) stores the code in localStorage (ignoring storage errors: the language then lives only for this session), loads the dictionary first (loadDictionary) and only then switches the state. While it loads, the previous language stays on screen, so there is no flicker of half-translated text. A ref (requested) remembers the last requested language: if two are requested in a row, the last one wins even if the earlier dictionary arrives later.

<html lang> is set to the full locale (localeOf(lang), e.g. ja-JP, zh-Hant-TW) and not just the code: WebKit uses it to pick the Japanese or Chinese glyph forms for the ideographs both scripts share.

Dictionaries and lazy loading

Each language has src/i18n/<code>/ with one JSON file per area (the same 20 areas as English). Each file is a flat object { "English source": "translation", ... }, formatted by Biome with tab indentation. English is the source, so en/ maps every string to itself, except the counting strings, whose value is a plural object whose other is the source string; pnpm i18n checks both. Spanish is a language like the others: es/ holds its translations (4.1 had them the other way round, with Spanish as the source and a separate file for the Spanish plurals). The dictionaries are data, not code: no TypeScript to get wrong, and the check script reads them without transpiling. There is no index.ts: load.ts merges every area file of a language, so a new area only needs its own file. Keys are always quoted, as JSON requires. Two things the TypeScript build used to reject now fall to pnpm i18n: a key repeated inside one file (JSON.parse would silently keep the last one) and a key present in two areas. The area file names are still the Spanish ones.

File Area
common.json Shared strings; starts with the ErrorCode messages from src/lib/errors.ts.
settings.json Settings dialog (appearance, updates, tweakcn themes).
shell.json Top bar, panel titles, save indicator, update button and toasts.
decklist.json Decklist panel, resolve phases, card marks.
preview.json Preview pages, toolbar, card menu, "move to" dialog.
export.json Export panel, presets, alignment.
library.json Deck library.
cards.json Add card, variants, card editor dialogs.
variants.json A string of the add-card search.
search.json The Search screen and its filters (Card Search).
recognize.json Identify from a photo (Identify From a Photo).
extras.json Statistics entry points and set browser.
link.json Link custom cards to Scryfall; wheel zoom; UI scale.
stats.json Statistics dialog.
design.json The designer view (largest file).
tutorial.json The screen tutorials: help button, step counter and every step's title and text (Tutorials).
table.json The game table: entrance, board, menus, dialogs, shortcuts, the sentences of the game log and Settings > "Game table" (Game Table).
rooms.json A few online-play strings left from the removed rooms server and still used: "With friends…", "Kick", the link chip ("{ms} ms · direct", "{ms} ms · via relay"), "Start" and two server error sentences (Online Play).
friends.json Friends and messages: consent, the list, requests, the conversation, the safety number, reports, leaving, the notification templates (Friends and Messages).
transfer.json Moving decks between devices: send and receive, the code and QR, nearby devices, the offer and what to do with each deck, the images that are missing afterwards (Deck Sharing).

An optional src/i18n/<code>/identical.json lists English source keys whose translation is legitimately identical to English in that language (e.g. "Deck" in German); see the check script.

src/i18n/load.ts:

  • English is bundled in the main chunk (EN): it is the fallback of every language, so it must always be there.
  • The others are lazy: import.meta.glob(["./*/*.json", "!./en/*.json", "!./*/identical.json"], { import: "default" }) makes one lazy module per area file. loadDictionary loads the files of the chosen language together and merges them, so startup does not carry the other 14 dictionaries.
  • loadDictionary(lang) loads a language once and caches it (English is already there); a language without a dictionary, or whose chunk fails to load, resolves to undefined and its texts fall back to English.
  • loadedDictionary(lang) returns the cached dictionary, if any.

src/main.tsx awaits loadDictionary(readLanguage()) before mounting (.finally(() => mount(root)), so a failed load still mounts), so the app never shows for an instant in another language; the window is shown in parallel (showWindow()).

Glossary and form of address

src/i18n/GLOSSARY.md fixes the terminology per language so repeated terms read as on official cards and always the same:

  • In languages with printed cards (fr, de, it, pt, ru, ja, ko, zhs, zht) game terms are taken from real printed cards on Scryfall, with the reference card noted.
  • ro, pl, nl and uk have no printed cards: terms follow community usage and are marked as having no official source.
  • It lists what is never translated (product names, among them the app's own name "Tapete", file formats, .pbdeck, keyboard shortcuts, {x} placeholders) and the form of address per language (e.g. vous in French, du in German, impersonal forms in Polish, です/ます in Japanese).
  • A last table, "Game table terms", fixes the game actions of table.json in every language: the official rules terms where cards are printed, the usual community word (often English) in ro, pl, nl and uk, with * marking terms not confirmed on an official card. There, "playmat" is the common noun and is translated ("tapete" in Spanish); the app's name "Tapete" is not.

Adding or changing a string

  1. In the component, write the visible text through the hook: const { t } = useLang(); then t("English text"). For text outside React, in a module-level table, wrap it in markForTranslation("...") and call t(value) where it is rendered.
  2. Add the pair to the dictionary of the matching area in every language (src/i18n/<code>/<area>.json), following src/i18n/GLOSSARY.md; in en/ the value is the key itself ("English text": "English text"). Reuse an existing key when the English text is identical and means the same thing.
  3. For a count, use {n} and pass a number; where the language has several plural categories, write a Plural object with exactly that language's categories (Russian one/few/many/other, Japanese only other…). English counts the same way: its forms (one, other) go in en/.
  4. Instead of editing 15 files by hand, pipe the new strings to python3 scripts/i18n-add.py <area> (JSON on stdin: the English string as key and, for each of the other 14 languages, its translation or plural object; for a plural, "en" gives the English forms). It appends to every src/i18n/<code>/<area>.json, writes the English value equal to its key unless "en" was given, leaves existing keys alone, rejects an entry that lacks a language, and holds a lock (src/i18n/.lock) so that several people or sessions adding strings to the same area at once do not overwrite each other. The result is formatted with tabs like the rest.
  5. Run pnpm i18n (also part of pnpm check, the pre-commit hook for staged .ts/.tsx, and CI).
  6. Use {name} placeholders for dynamic parts (t("Downloading {version}…", { version })); never concatenate translated fragments.

Disambiguation rule: if the same English word needs two different translations in different places, add a context suffix to the key (Clear##empty, Kick##player). It is never shown. Never introduce a second dictionary.

If you change an existing English source string, change its key in every dictionary too; otherwise the old entries become unused (a warning) and the new string is reported as missing (an error).

scripts/check-translations.mjs (pnpm i18n)

What it does:

  1. Requested strings (readRequested). Walks src/ (skipping node_modules, dot-dirs, bindings, src/i18n/ and *.test.ts(x)) and collects every double-quoted literal in t("...") and markForTranslation("...") (first argument; \" and \n unescaped), with the file where each was first seen.
  2. Languages. Loads src/lib/languages.ts (readLanguageTable), which is code, so it is still transpiled with typescript and imported. Then it reads each dictionary directory (readDictionaries; directories starting with _ are skipped): every <area>.json is parsed with JSON.parse, and its raw text is scanned for keys repeated at the top level of the same file, which JSON.parse would otherwise drop without a trace.
  3. Errors (exit status 1):
    • a language of the table with no directory src/i18n/<code>/, or a directory that is no language of the table;
    • a requested string missing from the merged dictionary;
    • a key present in two areas, or repeated inside one area file;
    • an English area file missing in the language;
    • placeholders {x} different from those of the source key (also checked in each plural form);
    • a plural object on a key without {n}, a category the language does not have, or a missing category (the language's categories are Intl.PluralRules(locale).resolvedOptions().pluralCategories);
    • a value that is neither a string nor a plural object with other;
    • for English, the source: a value (or the other of a plural) that is not the key without its ##context.
  4. Warnings (do not fail): keys no longer requested, and values identical to English (only when they contain letters and are not an allowed exception: the global list ALLOWED_IDENTICAL in the script, or the language's identical.json).
  5. Prints one line per language (✓ <code>: N strings plus the warning count, or ✖ <code>: … followed by each error). --detail also lists each warning.

readRequested, readLanguageTable, readDictionaries and checkLanguage are exported for the tests in scripts/__tests__/check-translations.test.mjs.

Limits to keep in mind:

  • Only double-quoted literals directly inside t( / markForTranslation( are seen. t(variable), single-quoted strings, template literals, or concatenations are invisible to the check, so route such text through markForTranslation("...") at its definition.
  • Text written in JSX without t() is not detected at all.
  • .test.ts(x) files are excluded.
  • A wrong but well-formed translation is not detectable; the identical-to-English warning only catches untranslated copies.

Errors: useLang().message(e)

Rust never writes user-facing prose. Commands return Result<T, AppError> where AppError = { code: ErrorCode, params: { [key]: string } } (src/bindings/AppError.ts, ErrorCode.ts; see IPC and Error Handling). On the screen:

// src/lib/errors.ts
export function errorMessage(e: unknown, t): string {
	if (isAppError(e)) {
		const key = e.params.reason ?? e.params.code;
		const own = key ? REASONS[e.code]?.[key] : undefined;
		return t(own ?? TEXTS[e.code], e.params);
	}
	if (e instanceof Error) return e.message;
	return String(e);
}

TEXTS has one English sentence per ErrorCode (Network, RateLimited, NotFound, Io, Db, InvalidInput, Cancelled, Pdf, Image, Unsupported, Busy, Internal, Rejected, Server), each wrapped in markForTranslation. REASONS adds sentences of their own for known reasons of a code (params.reason, or params.code for the friends server): the game table's rejections (Rejected: the engine's NotFound, NotPermitted, EmptyZone, OutOfTurn, Limit, NotAllowed, plus network and replay reasons such as code, version, full, spectator, game_is_open), the update refused while a game is open (Busy with reason: game_open), invalid input (InvalidInput: missing_list, list, unnamed_list, code, deck, identity), network failures (Network: connection, timeout, response, refused, status, no_reply, disconnected), NotFound with no_room and no_rejoin, Unsupported with version, camera, camera_permission and install_permission (Android: the install-unknown-apps permission for the update), InvalidInput also with deck_code (a deck code of "Receive a deck" where a game code goes), and the friends server's codes (Server); an unknown reason uses the code's general sentence. isAppError accepts any object whose code is a key of TEXTS, so adding an ErrorCode in Rust forces a matching entry (the Record<ErrorCode, string> type fails tsc otherwise). Components call toast.error(message(e)).

Special cases are handled by the component that knows the context, using params: for example TweakcnThemes (src/features/settings/tweakcn-themes.tsx) checks e.params.reason === "theme_link" to show "That is not a tweakcn theme link or id." instead of the generic invalid-input message. SaveIndicator shows message(error) in a tooltip when autosave fails.

The game table log follows the same rule: each engine event reaches the screen as data and src/features/table/event-texts.ts writes its sentence with t() (PHRASES, one per Action, plus the special changes), from the viewer's side so hidden cards are never named (Game Table).

Rust-provided data that is displayed (Scryfall names, oracle text, release notes) is shown as-is: release notes in the update panel are English Markdown from the GitHub release. Designer warnings (DesignWarning) carry a kind and parameters (some a DesignLang); the screen words them and names a language by its own name.

Language picker and flags

LanguagePicker (src/components/language-picker.tsx) is a Select listing languages with their flag and native name (each item gets lang={locale}, so its name is drawn with the right glyphs). It is used for the interface language in SettingsDialog (src/features/settings/settings-dialog.tsx, calls setLang) and for the design language in the export panel and the Design preview (see Designer UI). The change reaches all mounted components as soon as the dictionary has loaded; there is no reload.

Flags are drawn by <Flag country> from src/components/emoji.tsx with Noto Color Emoji images bundled in src/assets/emoji/, not with the system emoji font: Windows' Segoe UI Emoji has no flags and WebKit on macOS does not paint COLRv1 fonts. See Frontend Architecture.

Tests and guards

  • pnpm i18n / scripts/check-translations.mjs guards completeness, placeholders and plural forms. Its logic is tested in scripts/__tests__/check-translations.test.mjs: a complete dictionary passes; a missing string, a changed placeholder and a missing plural form fail; a plural without {n} or with a category the language lacks fails; unused and identical-to-English entries only warn; a missing area file fails, and so does a string duplicated inside one file; for English (checkLanguage (English, the source)), each value must be the source string or a plural whose other is, and a different value, a missing string or a missing area fail, while other languages are not asked to repeat the source.
  • src/i18n/__tests__/translate.test.ts: fallback language → English → key, the Russian plural chosen by n, a non-number n uses other, numbers formatted per language, and loadDictionary (English ready, Spanish loaded on demand, a language without dictionary does not throw).
  • src/lib/__tests__/languages.test.ts: the table (15 codes without repeats in LANGS order, canonical BCP-47 locales, SCRYFALL_LANGUAGES is the 11 printed ones, isLang and the English fallback of languageInfo).
  • src/lib/__tests__/errors.test.ts covers isAppError and errorMessage.
  • Not covered: the quality of translations (reviewed against GLOSSARY.md).

Where to start when extending

  • Add a UI language: add it to LANGS and LANGUAGES in src/lib/languages.ts; create src/i18n/<code>/ with one JSON file per area (the 20 English files, translated); add its terms and form of address to src/i18n/GLOSSARY.md; run node scripts/emoji-noto.mjs to copy its flag; run pnpm i18n. If it should also be a design language, DesignLang in Rust must gain the same code at the same position (see Designer Engine). Inferred: nothing else needs to change on the screen, because every consumer iterates the table.
  • Translating a new feature: see "Adding or changing a string" above. A new area (a feature with a screen of its own, like transfer) is one more <area>.json per language; load.ts merges whatever it finds, and pnpm i18n expects the same set of area files in every language.

See also

Documentation · Documentación

Language: English · Español

Use and build · Uso y desarrollo

Architecture · Arquitectura

Data · Datos

Getting cards · Conseguir cartas

Layout, images, PDF · Maquetación, imagen y PDF

Card designer · Diseñador de cartas

Game table · Mesa de juego

Mobile · Móvil

Frontend · Frontend

Reference · Referencia

Clone this wiki locally