okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-027-i18n: French as the ninth app language and the Polish README52ba0b781

main
4.1 KiB77 linesraw
1// serve/web/i18n.js - the web page's translations.
2//
3// The English text sits in the code, next to the key:  tr("chat.rewind", "Rewind to here")  and
4// tr("chat.hidden", {one: "{n} message hidden", other: "{n} messages hidden"}, {n: 3}).  Static page text is marked
5// data-i18n="key" (also data-i18n-title, data-i18n-label, data-i18n-placeholder) and holds its English text in the HTML.
6// So the page reads fine with no catalog at all.  Every other language is a catalog, serve/web/locales/<lang>.json
7// (a flat {"key": "text"} object; a plural is {"one": "...", "other": "..."}, the CLDR names of the language).
8// serve/test_web_i18n.py keeps the catalogs complete: same keys as the English text in the code, same {placeholders}.
9//
10// The language is the user's choice (About > Settings), kept in this browser.  Nothing is chosen for them from the
11// browser's language: a page that is translated in part would mix two languages.
12"use strict";
13(function (root) {
14  // [code, the language's own name].  A new language is a locales/<code>.json file plus one line here.
15  const LANGUAGES = [["en", "English"], ["de", "Deutsch"], ["fr", "Français"], ["es", "Español"], ["ja", "日本語"], ["ko", "한국어"],
16                     ["pt", "Português"], ["ru", "Русский"], ["zh", "中文"]];
17  let lang = "en", catalog = null, rules = null;
18
19  const fill = (s, vars) => String(s).replace(/\{(\w+)\}/g, (m, k) => (vars && k in vars ? String(vars[k]) : m));
20  function pick(entry, vars) {
21    if (entry && typeof entry === "object") {
22      const n = vars && vars.n != null ? Number(vars.n) : 1;
23      let cat = "other";
24      try { cat = (rules || new Intl.PluralRules(lang === "en" ? "en" : lang)).select(n); } catch (e) { /* other */ }
25      return entry[cat] != null ? entry[cat] : entry.other != null ? entry.other : entry.one;
26    }
27    return entry;
28  }
29  // tr(key, english, vars): the catalog's text for the chosen language, else the English text in the code
30  function tr(key, english, vars) {
31    const own = catalog && Object.prototype.hasOwnProperty.call(catalog, key) ? catalog[key] : undefined;
32    const text = pick(own != null ? own : english, vars);
33    return fill(text == null ? key : text, vars);
34  }
35
36  // marked page text: the English text is read once from the HTML and kept, so switching back restores it
37  const ATTRS = [["data-i18n", null], ["data-i18n-title", "title"], ["data-i18n-label", "aria-label"],
38                 ["data-i18n-placeholder", "placeholder"]];
39  function apply(scope) {
40    const doc = scope || root.document;
41    if (!doc || !doc.querySelectorAll) return;
42    for (const [mark, attr] of ATTRS) {
43      for (const el of doc.querySelectorAll(`[${mark}]`)) {
44        const key = el.getAttribute(mark);
45        const slot = "en_" + mark.replace(/[^a-z]/g, "");
46        if (el.dataset[slot] === undefined) el.dataset[slot] = attr ? (el.getAttribute(attr) || "") : el.textContent;
47        const text = tr(key, el.dataset[slot]);
48        if (attr) el.setAttribute(attr, text); else el.textContent = text;
49      }
50    }
51    if (root.document && root.document.documentElement) root.document.documentElement.lang = lang;
52  }
53
54  const known = (code) => LANGUAGES.some((l) => l[0] === code);
55  // load a catalog; English, or a catalog that cannot be read, leaves the English text in the code
56  async function setLanguage(code) {
57    code = known(code) ? code : "en";
58    let next = null;
59    if (code !== "en") {
60      try {
61        const r = await root.fetch(`web/locales/${code}.json`);
62        const j = r.ok ? await r.json() : null;
63        if (j && typeof j === "object" && !Array.isArray(j)) next = j;
64      } catch (e) { /* the English text stays */ }
65      if (!next) code = "en";
66    }
67    lang = code; catalog = next; rules = null;
68    try { rules = new Intl.PluralRules(lang); } catch (e) { /* other */ }
69    apply();
70    return lang;
71  }
72
73  const api = {LANGUAGES, tr, apply, setLanguage, get lang() { return lang; }, fill, pick};
74  root.StrataI18n = api;
75  root.tr = tr;
76  if (typeof module !== "undefined" && module.exports) module.exports = api;
77})(typeof globalThis !== "undefined" ? globalThis : this);