feedback5 WAD: language packs are the first type of content packs — a language is a file in a language folder (public/i18n/<code>.json, optional data/i18n/<code>.json) or a pack folder (packs/<id>/pack.json); the server lists them live at /packs/index.json (server/packs.js), the menu shows every pack, strings fall back pack → base → declared fallback (English) → Chinese, broken placeholders are skipped, plurals follow Intl.PluralRules (English unchanged), English carries a _meta manifest like any pack; tools: i18n.mjs template / check <code>, packs.mjs list / index, build-i18n --lang ja|ko|zh-TW (the official JP / KR / TW clients); the release zip ships packs/ and a generated packs/index.json; golden unchanged
This commit is contained in:
1 parent
f1df0d359d
commit
25b2a87b26
22 files changed
+2222
-241
No files matched your search
+298
-49
@@ -2,51 +2,156 @@
|
||||
//
|
||||
// The Chinese source string is the message id: `t('整备区已满')`, `t('还剩 {n} 秒', { n })`. A message without a
|
||||
// translation in the current language falls back to the Chinese text, so an untranslated string is never blank.
|
||||
// Chinese ('zh') is the default language; English ('en') is a switch (the owner's decision of 2026-10-05: an English
|
||||
// browser still opens in Chinese until the player picks English). docs/I18N.md explains how to add and translate
|
||||
// strings.
|
||||
// Chinese ('zh') is the default language; every other language is a pack (shared/i18nPacks.js): a file in
|
||||
// public/i18n/ that the client lists from /i18n/index.json and loads on demand (ui/lang.js). Nothing here knows a
|
||||
// language by name (the owner's decisions of 2026-10-05 and 2026-10-07: Chinese by default, a language is a file in the
|
||||
// language folder). docs/I18N.md explains how to add and translate strings and how to add a language.
|
||||
//
|
||||
// Fallback chain per string: the chosen pack → its base (pt-BR → pt; zh-TW has none) → the packs its `_meta.fallback`
|
||||
// names (e.g. English) → the Chinese msgid (i18nPacks.js computeChain). A partial pack is fine: what it lacks falls
|
||||
// through. A translation that drops a placeholder of its msgid, or uses one the caller does not pass, or has a broken
|
||||
// plural form, is skipped like a missing one (setI18nWarn reports it; the client warns in development).
|
||||
//
|
||||
// Context: the same Chinese text may need two translations ('关闭' = "Close" on a button, "Off" on a switch):
|
||||
// `tc('toggle', '关闭')` looks up the key 'toggle::关闭' first, then '关闭'; Chinese shows '关闭'.
|
||||
// Module-level tables are evaluated once, before a language can change: mark their strings N_('…') (a no-op that
|
||||
// `tc('toggle', '关闭')` looks up the key 'toggle::关闭' first, then '关闭' (in each language of the chain); Chinese shows
|
||||
// '关闭'. Module-level tables are evaluated once, before a language can change: mark their strings N_('…') (a no-op that
|
||||
// tools/i18n.mjs extracts) and call t() where they are shown.
|
||||
//
|
||||
// Placeholders (the same in msgids and translations):
|
||||
// {name} the value of params.name (params may also be an array: {0}, {1} …)
|
||||
// {n|one|other} `one` when Number(params.n) === 1, else `other` — the only plural form (English needs no more)
|
||||
// A value that is an array renders as a list joined with the language's separator ('、' / ', '); a value `{ dn: '…' }`
|
||||
// (made by `dn()`) is a game-data name, translated through the name resolver the client installs (setNameResolver).
|
||||
// A placeholder whose value is missing stays verbatim, so official templates such as '{0}博士…' survive untouched.
|
||||
// {name} the value of params.name (params may also be an array: {0}, {1} …)
|
||||
// {n|one|other} two plain forms: `one` when the language's plural category of Number(params.n) is 'one'
|
||||
// (Intl.PluralRules; in English exactly when n is 1), else `other`
|
||||
// {n|one:…|few:…|other:…} named forms for languages with more categories (zero, one, two, few, many, other; `other`
|
||||
// is required): the form of the category, else `other`
|
||||
// A value that is an array renders as a list joined with the language's separator (the translation of 'list::、', '、' in
|
||||
// Chinese, ', ' without one); a value `{ dn: '…' }` (made by `dn()`) is a game-data name, translated through the name
|
||||
// resolver the client installs (setNameResolver). A placeholder whose value is missing stays verbatim, so official
|
||||
// templates such as '{0}博士…' survive untouched.
|
||||
//
|
||||
// Server → client messages (m.toast / m.ticker): the server builds `msg(msgid, params)` and sends
|
||||
// `wireMessage(m)` = { text: <the Chinese rendering>, msgid, params } — `text` keeps older clients working, the client
|
||||
// renders `translateWire(frame)` in its own language. A plain string message is its own msgid.
|
||||
|
||||
/** Supported languages; the first one is the default and the source language of every msgid. */
|
||||
export const LANGS = Object.freeze(['zh', 'en']);
|
||||
export const DEFAULT_LANG = 'zh';
|
||||
import { SOURCE_LANG, canonicalLang, primaryLang, packMeta, computeChain } from './i18nPacks.js';
|
||||
|
||||
/** List separator per language (array params). */
|
||||
const LIST_SEP = Object.freeze({ zh: '、', en: ', ' });
|
||||
/** The default language, the source language of every msgid. */
|
||||
export const DEFAULT_LANG = SOURCE_LANG;
|
||||
|
||||
/** @typedef {import('./i18nPacks.js').LangMeta} LangMeta */
|
||||
|
||||
/** The source language: built in, no pack, no catalog. */
|
||||
const SOURCE_META = Object.freeze({
|
||||
code: SOURCE_LANG, name: '中文', englishName: 'Chinese (Simplified)', authors: [], credits: '', version: '', app: '', // i18n-ignore: its own name
|
||||
base: null, fallback: [], complete: true, numberUnits: ['万', '亿'], builtin: true, // i18n-ignore: the Chinese number units
|
||||
});
|
||||
|
||||
/** @type {Map<string, LangMeta>} code → metadata: the source, the packs of the index, languages given messages */
|
||||
const registry = new Map([[SOURCE_LANG, /** @type {LangMeta} */ (/** @type {unknown} */ (SOURCE_META))]]);
|
||||
/** @type {Map<string, Map<string, string>>} lang → msgid → translation */
|
||||
const catalogs = new Map();
|
||||
let current = DEFAULT_LANG;
|
||||
/** @type {Set<(lang: string, prev: string) => void>} */
|
||||
const listeners = new Set();
|
||||
/** @type {Set<() => void>} */
|
||||
const langsListeners = new Set();
|
||||
/** @type {((name: string, lang: string) => string) | null} */
|
||||
let nameResolver = null;
|
||||
/** @type {Map<string, string[]>} lang → its chain (cleared whenever the registry changes) */
|
||||
const chains = new Map();
|
||||
/** @type {Map<string, Map<string, { ok: boolean, problems: string[], extras: string[] }>>} lang → key → checkTranslation */
|
||||
const checked = new Map();
|
||||
/** @type {((info: { lang: string, key: string, problems: string[] }) => void) | null} */
|
||||
let warnHook = null;
|
||||
/** lang + key already reported (once each) */
|
||||
const warned = new Set();
|
||||
|
||||
const report = (lang, key, problems) => {
|
||||
if (!warnHook) return;
|
||||
const id = `${lang}\u0000${key}`;
|
||||
if (warned.has(id)) return;
|
||||
warned.add(id);
|
||||
try { warnHook({ lang, key, problems }); } catch { /* a broken hook never breaks a render */ }
|
||||
};
|
||||
|
||||
const notifyLangs = () => {
|
||||
chains.clear();
|
||||
for (const fn of [...langsListeners]) {
|
||||
try { fn(); } catch (err) { /** @type {any} */ (globalThis).console?.error('[i18n] listener failed', err); }
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* A supported language code from loose input ('en-US' → 'en', 'zh_CN' → 'zh'), or null.
|
||||
* Register languages (the client: the entries of /i18n/index.json; a pack's own `_meta` when it loads). A known code
|
||||
* is merged with what is there. Listeners of onLangsChange run once.
|
||||
* @param {Partial<LangMeta>[]} entries each with a `code`
|
||||
* @returns {number} languages registered
|
||||
*/
|
||||
export function registerLangs(entries) {
|
||||
let n = 0;
|
||||
for (const e of Array.isArray(entries) ? entries : []) {
|
||||
const code = canonicalLang(e?.code);
|
||||
if (!code || code === SOURCE_LANG) continue;
|
||||
const prev = registry.get(code);
|
||||
registry.set(code, /** @type {LangMeta} */ ({ ...(prev || packMeta(code, null)), ...e, code }));
|
||||
n++;
|
||||
}
|
||||
if (n) notifyLangs();
|
||||
return n;
|
||||
}
|
||||
|
||||
/**
|
||||
* The known languages, the source first, then by code: what the language menu lists.
|
||||
* @returns {LangMeta[]}
|
||||
*/
|
||||
export function getLangs() {
|
||||
const rest = [...registry.values()].filter((m) => m.code !== SOURCE_LANG).sort((a, b) => (a.code < b.code ? -1 : a.code > b.code ? 1 : 0));
|
||||
return [registry.get(SOURCE_LANG), ...rest];
|
||||
}
|
||||
|
||||
/** The metadata of a known language, or null. @param {string} [lang] */
|
||||
export const langInfo = (lang = current) => registry.get(String(lang)) || null;
|
||||
|
||||
/**
|
||||
* Subscribe to changes of the known languages (the index arrived, a pack loaded).
|
||||
* @param {() => void} fn
|
||||
* @returns {() => void} unsubscribe
|
||||
*/
|
||||
export function onLangsChange(fn) {
|
||||
langsListeners.add(fn);
|
||||
return () => { langsListeners.delete(fn); };
|
||||
}
|
||||
|
||||
/**
|
||||
* The languages a lookup tries for `lang`, best first; the Chinese msgid comes after them (i18nPacks.js computeChain).
|
||||
* Empty for the source language.
|
||||
* @param {string} [lang]
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function langChain(lang = current) {
|
||||
const code = String(lang);
|
||||
if (code === SOURCE_LANG) return [];
|
||||
let c = chains.get(code);
|
||||
if (!c) {
|
||||
c = computeChain(code, (x) => registry.get(x), (x) => registry.has(x) || catalogs.has(x));
|
||||
chains.set(code, c);
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
/**
|
||||
* A known language code from loose input ('en-US' → 'en' when 'en' is known, 'zh_CN' → 'zh', 'PT-br' → 'pt-BR'), or
|
||||
* null: the exact code, then the same code in any case, then its language part.
|
||||
* @param {unknown} v
|
||||
* @returns {string|null}
|
||||
*/
|
||||
export function normalizeLang(v) {
|
||||
const s = typeof v === 'string' ? v.trim().toLowerCase() : '';
|
||||
if (!s) return null;
|
||||
for (const l of LANGS) if (s === l || s.startsWith(`${l}-`) || s.startsWith(`${l}_`)) return l;
|
||||
return null;
|
||||
const code = canonicalLang(v);
|
||||
if (!code) return null;
|
||||
if (registry.has(code)) return code;
|
||||
const lower = code.toLowerCase();
|
||||
for (const c of registry.keys()) if (c.toLowerCase() === lower) return c;
|
||||
const p = primaryLang(code);
|
||||
return registry.has(p) ? p : null;
|
||||
}
|
||||
|
||||
/** The current language code. */
|
||||
@@ -79,23 +184,30 @@ export function onLangChange(fn) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Add translations for a language (merged into what is there). Keys starting with '_' are metadata and skipped; only
|
||||
* non-empty string values count.
|
||||
* Add translations for a language (merged into what is there; the language is registered — with the pack's `_meta`
|
||||
* when the dict carries one). Keys starting with '_' are metadata and skipped; only non-empty string values count.
|
||||
* @param {string} lang
|
||||
* @param {Record<string, unknown> | null | undefined} dict msgid → translation
|
||||
* @param {Record<string, unknown> | null | undefined} dict msgid → translation (a whole pack file)
|
||||
* @returns {number} entries added
|
||||
*/
|
||||
export function addMessages(lang, dict) {
|
||||
const l = normalizeLang(lang);
|
||||
const l = canonicalLang(lang);
|
||||
if (!l || !dict || typeof dict !== 'object') return 0;
|
||||
let cat = catalogs.get(l);
|
||||
if (!cat) { cat = new Map(); catalogs.set(l, cat); }
|
||||
checked.delete(l);
|
||||
let n = 0;
|
||||
for (const [k, v] of Object.entries(dict)) {
|
||||
if (k.startsWith('_') || typeof v !== 'string' || !v) continue;
|
||||
cat.set(k, v);
|
||||
n++;
|
||||
}
|
||||
if (l !== SOURCE_LANG && !registry.get(l)?.packId && (dict._meta || !registry.has(l))) {
|
||||
// a language the pack index did not list (no index, tests): what its own `_meta` says; an index entry (made from
|
||||
// the pack's manifest by the server) stays as it is
|
||||
registry.set(l, packMeta(l, dict));
|
||||
notifyLangs();
|
||||
} else chains.clear();
|
||||
return n;
|
||||
}
|
||||
|
||||
@@ -106,14 +218,15 @@ export function addMessages(lang, dict) {
|
||||
* @returns {number}
|
||||
*/
|
||||
export function setMessages(lang, dict) {
|
||||
const l = normalizeLang(lang);
|
||||
const l = canonicalLang(lang);
|
||||
if (!l) return 0;
|
||||
catalogs.delete(l);
|
||||
checked.delete(l);
|
||||
return addMessages(l, dict);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a msgid has a translation in a language (the default language always "has" its own msgids).
|
||||
* Whether a msgid has a translation in a language's own pack (the default language always "has" its own msgids).
|
||||
* @param {string} msgid
|
||||
* @param {string} [lang]
|
||||
*/
|
||||
@@ -122,6 +235,13 @@ export function hasMessage(msgid, lang = current) {
|
||||
return l === DEFAULT_LANG || !!catalogs.get(l)?.has(String(msgid));
|
||||
}
|
||||
|
||||
/**
|
||||
* Install the reporter of skipped translations (a dropped or unknown placeholder, a broken plural form): called once per
|
||||
* language and key. The client installs console.warn in development (ui/lang.js); null turns it off.
|
||||
* @param {((info: { lang: string, key: string, problems: string[] }) => void) | null} fn
|
||||
*/
|
||||
export function setI18nWarn(fn) { warnHook = typeof fn === 'function' ? fn : null; warned.clear(); }
|
||||
|
||||
/**
|
||||
* Install the translator of game-data names (`{ dn: '…' }` params and `tName`). The client maps a Chinese name to the
|
||||
* current language through the localized game data; without a resolver names stay Chinese.
|
||||
@@ -150,6 +270,19 @@ export const dn = (name) => ({ dn: name == null ? '' : String(name) });
|
||||
|
||||
const own = (o, k) => o != null && typeof o === 'object' && Object.prototype.hasOwnProperty.call(o, k);
|
||||
|
||||
/**
|
||||
* The list separator of a language: its translation of 'list::、' through its chain; '、' in Chinese; ', ' without one.
|
||||
* @param {string} lang
|
||||
*/
|
||||
function listSep(lang) {
|
||||
if (lang === DEFAULT_LANG) return '、';
|
||||
for (const l of langChain(lang)) {
|
||||
const s = catalogs.get(l)?.get('list::、');
|
||||
if (s) return s;
|
||||
}
|
||||
return ', ';
|
||||
}
|
||||
|
||||
/**
|
||||
* Render one param value.
|
||||
* @param {unknown} v
|
||||
@@ -159,7 +292,7 @@ const own = (o, k) => o != null && typeof o === 'object' && Object.prototype.has
|
||||
*/
|
||||
function renderValue(v, lang, resolve) {
|
||||
if (v == null) return '';
|
||||
if (Array.isArray(v)) return v.map((x) => renderValue(x, lang, resolve)).filter((s) => s !== '').join(LIST_SEP[lang] || LIST_SEP.en);
|
||||
if (Array.isArray(v)) return v.map((x) => renderValue(x, lang, resolve)).filter((s) => s !== '').join(listSep(lang));
|
||||
if (typeof v === 'object') {
|
||||
if (own(v, 'dn')) {
|
||||
const name = String(/** @type {any} */ (v).dn ?? '');
|
||||
@@ -171,10 +304,72 @@ function renderValue(v, lang, resolve) {
|
||||
return String(v);
|
||||
}
|
||||
|
||||
const PLACEHOLDER = /\{([A-Za-z0-9_$]+)(?:\|([^{}|]*)\|([^{}|]*))?\}/g;
|
||||
/** `{name}` or a plural `{name|form|form…}` (two or more forms); group 2 is the forms with their leading '|'. */
|
||||
const PLACEHOLDER = /\{([A-Za-z0-9_$]+)((?:\|[^{}|]*){2,})?\}/g;
|
||||
/** The CLDR plural categories (Intl.PluralRules). */
|
||||
export const PLURAL_CATEGORIES = Object.freeze(['zero', 'one', 'two', 'few', 'many', 'other']);
|
||||
const NAMED_FORM = /^(zero|one|two|few|many|other):/;
|
||||
|
||||
/**
|
||||
* Fill a template's placeholders (pure: no global language state).
|
||||
* The forms of a plural placeholder ('|second|seconds' or '|one:день|few:дня|many:дней|other:дня') by category, or null
|
||||
* when malformed: two plain forms are one / other; named forms need `other` and no repeats; plain and named are not
|
||||
* mixed, and three or more plain forms are refused (the order of a language's categories is not stable across engines).
|
||||
* @param {string} forms the forms with their leading '|'
|
||||
* @returns {Record<string, string> | null}
|
||||
*/
|
||||
export function parsePluralForms(forms) {
|
||||
const parts = String(forms).slice(1).split('|');
|
||||
const named = parts.map((p) => NAMED_FORM.exec(p));
|
||||
if (named.every(Boolean)) {
|
||||
/** @type {Record<string, string>} */
|
||||
const out = {};
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const cat = named[i][1];
|
||||
if (own(out, cat)) return null;
|
||||
out[cat] = parts[i].slice(named[i][0].length);
|
||||
}
|
||||
return own(out, 'other') ? out : null;
|
||||
}
|
||||
if (parts.length === 2 && !named.some(Boolean)) return { one: parts[0], other: parts[1] };
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @type {Map<string, any>} lang → Intl.PluralRules (null: the runtime does not know the language) */
|
||||
const pluralRules = new Map();
|
||||
|
||||
/**
|
||||
* The plural category of a number in a language (Intl.PluralRules; a language the runtime does not know counts one
|
||||
* for exactly 1, other for the rest — the English rule).
|
||||
* @param {string} lang
|
||||
* @param {number} n
|
||||
* @returns {string}
|
||||
*/
|
||||
export function pluralCategory(lang, n) {
|
||||
if (!Number.isFinite(n)) return 'other';
|
||||
let pr = pluralRules.get(lang);
|
||||
if (pr === undefined) {
|
||||
pr = null;
|
||||
try {
|
||||
const PR = /** @type {any} */ (globalThis).Intl?.PluralRules;
|
||||
const tag = PR && [lang, primaryLang(lang)].find((x) => PR.supportedLocalesOf([x]).length);
|
||||
if (tag) pr = new PR(tag);
|
||||
} catch { /* no Intl data for it */ }
|
||||
pluralRules.set(lang, pr);
|
||||
}
|
||||
if (pr) return pr.select(n);
|
||||
return n === 1 ? 'one' : 'other';
|
||||
}
|
||||
|
||||
/** The form of a plural placeholder for a value (null when the forms are malformed). */
|
||||
function pluralForm(forms, v, lang) {
|
||||
const f = parsePluralForms(forms);
|
||||
if (!f) return null;
|
||||
const cat = pluralCategory(lang, Number(v));
|
||||
return own(f, cat) ? f[cat] : f.other;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fill a template's placeholders (pure: no global language state but the list separator and plural rules of `lang`).
|
||||
* @param {unknown} template
|
||||
* @param {Record<string, unknown> | unknown[] | null | undefined} [params]
|
||||
* @param {{ lang?: string, resolveName?: ((name: string, lang: string) => string) | null }} [opts]
|
||||
@@ -185,14 +380,79 @@ export function format(template, params, opts = {}) {
|
||||
if (!params || typeof params !== 'object' || !s.includes('{')) return s;
|
||||
const lang = normalizeLang(opts.lang) || DEFAULT_LANG;
|
||||
const resolve = opts.resolveName || null;
|
||||
return s.replace(PLACEHOLDER, (m, key, one, other) => {
|
||||
return s.replace(PLACEHOLDER, (m, key, forms) => {
|
||||
if (!own(params, key)) return m;
|
||||
const v = /** @type {any} */ (params)[key];
|
||||
if (one !== undefined) return Number(v) === 1 ? one : other;
|
||||
if (forms !== undefined) return pluralForm(forms, v, lang) ?? m;
|
||||
return renderValue(v, lang, resolve);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a translation fits its msgid: it keeps every plain placeholder of the msgid as a plain placeholder, and its
|
||||
* plural forms parse. `extras`: the placeholder names it uses that the msgid lacks — allowed when the caller passes them
|
||||
* (a plural selector beside a markup value: '{n} {count|unit|units}'), which t() checks per call and
|
||||
* `node tools/i18n.mjs check` against the call sites.
|
||||
* @param {string} msgid the msgid (for a tc() key, the part after '::')
|
||||
* @param {string} text the translation
|
||||
* @returns {{ ok: boolean, problems: string[], extras: string[] }}
|
||||
*/
|
||||
export function checkTranslation(msgid, text) {
|
||||
const names = new Set();
|
||||
const plain = new Set();
|
||||
for (const m of String(msgid).matchAll(PLACEHOLDER)) {
|
||||
names.add(m[1]);
|
||||
if (m[2] === undefined) plain.add(m[1]);
|
||||
}
|
||||
const kept = new Set();
|
||||
const extras = [];
|
||||
const problems = [];
|
||||
for (const m of String(text).matchAll(PLACEHOLDER)) {
|
||||
if (m[2] === undefined) kept.add(m[1]);
|
||||
else if (!parsePluralForms(m[2])) problems.push(`malformed plural ${m[0]}`);
|
||||
if (!names.has(m[1]) && !extras.includes(m[1])) extras.push(m[1]);
|
||||
}
|
||||
for (const k of plain) if (!kept.has(k)) problems.push(`drops {${k}}`);
|
||||
return { ok: problems.length === 0, problems, extras };
|
||||
}
|
||||
|
||||
/** The checkTranslation of a catalog entry (cached per language). */
|
||||
function checkedEntry(lang, key, text) {
|
||||
let m = checked.get(lang);
|
||||
if (!m) { m = new Map(); checked.set(lang, m); }
|
||||
let c = m.get(key);
|
||||
if (!c) {
|
||||
const sep = key.indexOf('::');
|
||||
c = checkTranslation(sep >= 0 ? key.slice(sep + 2) : key, text);
|
||||
m.set(key, c);
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
/**
|
||||
* The translation of the first key (in order) that a language of the current chain has and that fits: in each
|
||||
* language the keys in order (a tc() context key, then its plain msgid), then the next language. Null: show the msgid.
|
||||
* @param {string[]} keys
|
||||
* @param {Record<string, unknown> | unknown[] | null | undefined} params
|
||||
* @returns {string|null}
|
||||
*/
|
||||
function lookup(keys, params) {
|
||||
for (const l of langChain(current)) {
|
||||
const cat = catalogs.get(l);
|
||||
if (!cat) continue;
|
||||
for (const key of keys) {
|
||||
const tr = cat.get(key);
|
||||
if (!tr) continue;
|
||||
const c = checkedEntry(l, key, tr);
|
||||
if (!c.ok) { report(l, key, c.problems); continue; }
|
||||
const unknown = c.extras.filter((k) => !own(params, k));
|
||||
if (unknown.length) { report(l, key, unknown.map((k) => `uses {${k}}, which the caller does not pass`)); continue; }
|
||||
return tr;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translate a message into the current language (gettext style: the msgid is the Chinese text).
|
||||
* @param {unknown} msgid
|
||||
@@ -201,11 +461,7 @@ export function format(template, params, opts = {}) {
|
||||
*/
|
||||
export function t(msgid, params) {
|
||||
const id = msgid == null ? '' : String(msgid);
|
||||
let text = id;
|
||||
if (current !== DEFAULT_LANG) {
|
||||
const tr = catalogs.get(current)?.get(id);
|
||||
if (tr) text = tr;
|
||||
}
|
||||
const text = current === DEFAULT_LANG ? id : lookup([id], params) ?? id;
|
||||
return params ? format(text, params, { lang: current, resolveName: nameResolver }) : text;
|
||||
}
|
||||
|
||||
@@ -218,11 +474,8 @@ export function t(msgid, params) {
|
||||
*/
|
||||
export function tc(context, msgid, params) {
|
||||
const id = msgid == null ? '' : String(msgid);
|
||||
if (current !== DEFAULT_LANG) {
|
||||
const tr = catalogs.get(current)?.get(`${context}::${id}`);
|
||||
if (tr) return params ? format(tr, params, { lang: current, resolveName: nameResolver }) : tr;
|
||||
}
|
||||
return t(id, params);
|
||||
const text = current === DEFAULT_LANG ? id : lookup([`${context}::${id}`, id], params) ?? id;
|
||||
return params ? format(text, params, { lang: current, resolveName: nameResolver }) : text;
|
||||
}
|
||||
|
||||
/** A tParts() param kept as it is: an object that is not a `{ dn }` name (a vnode), or an array holding one. */
|
||||
@@ -231,7 +484,7 @@ const isMarkup = (v) => !!v && typeof v === 'object' && !own(v, 'dn') && (!Array
|
||||
/**
|
||||
* A message as pieces for a renderer, for a sentence with markup inside (「第 <b>14</b> 回合」): the translation split at
|
||||
* its placeholders; a param that is markup (a vnode, or an array holding vnodes) is kept as it is, the others render as
|
||||
* in t() ({ dn } names, lists, {n|one|other}). Adjacent text joins, empty text is dropped, so the Chinese pieces are the
|
||||
* in t() ({ dn } names, lists, plural forms). Adjacent text joins, empty text is dropped, so the Chinese pieces are the
|
||||
* text around the markup exactly as written before:
|
||||
* html`<span>${tParts('第 {r} 回合 · 最终攻势', { r: html`<b class="num">${n}</b>` })}</span>`
|
||||
* @param {unknown} msgid
|
||||
@@ -240,11 +493,7 @@ const isMarkup = (v) => !!v && typeof v === 'object' && !own(v, 'dn') && (!Array
|
||||
*/
|
||||
export function tParts(msgid, params) {
|
||||
const id = msgid == null ? '' : String(msgid);
|
||||
let text = id;
|
||||
if (current !== DEFAULT_LANG) {
|
||||
const tr = catalogs.get(current)?.get(id);
|
||||
if (tr) text = tr;
|
||||
}
|
||||
const text = current === DEFAULT_LANG ? id : lookup([id], params) ?? id;
|
||||
/** @type {unknown[]} */
|
||||
const out = [];
|
||||
const push = (s) => {
|
||||
@@ -255,11 +504,11 @@ export function tParts(msgid, params) {
|
||||
let last = 0;
|
||||
if (params && typeof params === 'object') {
|
||||
for (const m of text.matchAll(PLACEHOLDER)) {
|
||||
const [whole, key, one, other] = m;
|
||||
const [whole, key, forms] = m;
|
||||
if (!own(params, key)) continue;
|
||||
push(text.slice(last, m.index));
|
||||
const v = /** @type {any} */ (params)[key];
|
||||
if (one !== undefined) push(Number(v) === 1 ? one : other);
|
||||
if (forms !== undefined) push(pluralForm(forms, v, current) ?? whole);
|
||||
else if (isMarkup(v)) out.push(v);
|
||||
else push(renderValue(v, current, nameResolver));
|
||||
last = m.index + whole.length;
|
||||
|
||||
Reference in new issue
Block a user