/* Kit i18n (v1) - texts in several languages for HTML games. From _Tools\Library\web\kit. Needs kit-core.js. Dictionaries live in game/lang.js (a script, not JSON: file:// cannot fetch). game/lang.js: window.LANG = { en: { play: 'Play', score: 'Score {n}' }, de: { play: 'Spielen' } }; const L = Kit.i18n(window.LANG, { prefix: 'mygame' }); L.t('score', { n: 5 }) "Score 5" - missing key: English, then the key itself (visible = easy to spot) L.lang / L.langs current language / ['en', 'de'] L.set('de') switch + remember; re-fills data-i18n elements, calls onChange listeners L.next() cycle to the next language (one "English / Deutsch" button) L.apply(root) fills [data-i18n="key"] (text), [data-i18n-html] (HTML), [data-i18n-title], [data-i18n-placeholder]; runs once at start and after every set() L.onChange(fn) re-render menus/HUD after a switch Start language: saved choice, else browser language if there is a dictionary, else the first one. */ (function (root) { 'use strict'; const Kit = (root.Kit = root.Kit || {}); Kit.i18n = (dicts, opt = {}) => { const langs = Object.keys(dicts || {}); if (!langs.length) throw new Error('Kit.i18n: no dictionaries (game/lang.js loaded?)'); const st = Kit.store(opt.prefix || 'kit'); const fallback = dicts.en ? 'en' : langs[0]; const listeners = []; const browser = (typeof navigator !== 'undefined' && (navigator.language || '').slice(0, 2).toLowerCase()) || ''; const saved = st.get('lang', null); const api = { langs, lang: langs.includes(saved) ? saved : langs.includes(browser) ? browser : fallback, }; api.t = (key, vars) => { let s = dicts[api.lang]?.[key] ?? dicts[fallback]?.[key] ?? key; if (vars) for (const [k, v] of Object.entries(vars)) s = s.split(`{${k}}`).join(String(v)); return s; }; api.apply = (scope = typeof document !== 'undefined' ? document : null) => { if (!scope) return; for (const el of scope.querySelectorAll('[data-i18n]')) el.textContent = api.t(el.dataset.i18n); for (const el of scope.querySelectorAll('[data-i18n-html]')) el.innerHTML = api.t(el.dataset.i18nHtml); for (const el of scope.querySelectorAll('[data-i18n-title]')) el.title = api.t(el.dataset.i18nTitle); for (const el of scope.querySelectorAll('[data-i18n-placeholder]')) el.placeholder = api.t(el.dataset.i18nPlaceholder); if (typeof document !== 'undefined') document.documentElement.lang = api.lang; }; api.set = l => { if (!langs.includes(l) || l === api.lang) return; api.lang = l; st.set('lang', l); api.apply(); for (const fn of listeners) fn(l); }; api.next = () => api.set(langs[(langs.indexOf(api.lang) + 1) % langs.length]); api.onChange = fn => { listeners.push(fn); }; if (typeof document !== 'undefined') { if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => api.apply()); else api.apply(); } return api; }; })(typeof window !== 'undefined' ? window : globalThis);