BlueGit

projects-timfalken-com meteors

Files

meteors / src / i18n.js

i18n.js

i18n.js 10.8 KiB Download Raw
1'use strict';
2
3/**
4 * Player-facing translations for Meteors (t1141).
5 * Default locale is English. The player's choice is stored in
6 * localStorage and, when they are logged in, on their server profile.
7 */
8
9var I18n = {
10 LOCALES: [
11 { id: 'en', flag: 'gb', endonym: 'English', htmlLang: 'en' },
12 { id: 'nl', flag: 'nl', endonym: 'Nederlands', htmlLang: 'nl' },
13 { id: 'de', flag: 'de', endonym: 'Deutsch', htmlLang: 'de' },
14 { id: 'fr', flag: 'fr', endonym: 'Français', htmlLang: 'fr' },
15 { id: 'ja', flag: 'jp', endonym: '日本語', htmlLang: 'ja' },
16 { id: 'zh', flag: 'cn', endonym: '简体中文', htmlLang: 'zh-Hans' },
17 { id: 'ko', flag: 'kr', endonym: '한국어', htmlLang: 'ko' },
18 { id: 'pl', flag: 'pl', endonym: 'Polski', htmlLang: 'pl' },
19 { id: 'ru', flag: 'ru', endonym: 'Русский', htmlLang: 'ru' },
20 { id: 'es', flag: 'es', endonym: 'Español', htmlLang: 'es' }
21 ],
22 DEFAULT: 'en',
23 STORAGE_KEY: 'meteors-locale',
24 COOKIE: 'meteors-locale',
25 locale: 'en',
26 _catalog: null,
27 _listeners: [],
28 _pickerOpen: false
29};
30
31I18n._load = function ()
32{
33 if (this._catalog)
34 { return this._catalog; }
35 var data = null;
36 if (typeof I18N_CATALOG !== 'undefined' && I18N_CATALOG)
37 { data = I18N_CATALOG; }
38 else if (typeof require !== 'undefined')
39 {
40 try
41 { data = require('../server/lib/i18n.json'); }
42 catch (e) { data = null; }
43 }
44 this._catalog = data && data.locales ? data : { locales: { en: {} }, errors: {} };
45 return this._catalog;
46};
47
48I18n.known = function (id)
49{
50 if (!id)
51 { return false; }
52 for (var i = 0; i < this.LOCALES.length; i++)
53 {
54 if (this.LOCALES[i].id === id)
55 { return true; }
56 }
57 return false;
58};
59
60I18n.info = function (id)
61{
62 id = id || this.locale;
63 for (var i = 0; i < this.LOCALES.length; i++)
64 {
65 if (this.LOCALES[i].id === id)
66 { return this.LOCALES[i]; }
67 }
68 return this.LOCALES[0];
69};
70
71I18n.t = function (key, params, fallback)
72{
73 this._load();
74 var loc = this._catalog.locales[this.locale] || {};
75 var en = this._catalog.locales.en || {};
76 var s = loc[key];
77 if (s == null || s === '')
78 { s = en[key]; }
79 if (s == null || s === '')
80 { s = fallback != null ? fallback : key; }
81 s = String(s);
82 if (params)
83 {
84 s = s.replace(/\{(\w+)\}/g, function (_, k)
85 {
86 return params[k] != null ? String(params[k]) : '';
87 });
88 }
89 return s;
90};
91
92/** Slavic-style plural: one / few / many (falls back to other). */
93I18n.pluralForm = function (n, locale)
94{
95 n = Math.abs(parseInt(n, 10) || 0);
96 locale = locale || this.locale;
97 if (locale === 'ru')
98 {
99 var mod10 = n % 10, mod100 = n % 100;
100 if (mod10 === 1 && mod100 !== 11)
101 { return 'one'; }
102 if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14))
103 { return 'few'; }
104 return 'many';
105 }
106 if (locale === 'pl')
107 {
108 if (n === 1)
109 { return 'one'; }
110 var mod10 = n % 10, mod100 = n % 100;
111 if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14))
112 { return 'few'; }
113 return 'many';
114 }
115 if (locale === 'fr' || locale === 'es')
116 { return (n === 0 || n === 1) ? 'one' : 'other'; }
117 if (locale === 'ja' || locale === 'zh' || locale === 'ko')
118 { return 'other'; }
119 return n === 1 ? 'one' : 'other';
120};
121
122I18n.plural = function (base, n, params)
123{
124 params = params || {};
125 params.n = n;
126 var form = this.pluralForm(n);
127 var key = base + '.' + form;
128 this._load();
129 var loc = this._catalog.locales[this.locale] || {};
130 var en = this._catalog.locales.en || {};
131 if (loc[key] == null && en[key] == null)
132 {
133 if (form === 'few' || form === 'many')
134 { key = base + '.other'; }
135 }
136 if ((loc[key] == null && en[key] == null) && form !== 'one')
137 { key = base + '.other'; }
138 return this.t(key, params);
139};
140
141I18n.place = function (n)
142{
143 return this.t('podium.place.' + (n === 1 ? '1' : n === 2 ? '2' : n === 3 ? '3' : 'n'), { n: n }, String(n));
144};
145
146I18n.planetName = function (planet)
147{
148 if (!planet)
149 { return ''; }
150 if (planet.custom)
151 { return planet.name || ''; }
152 return this.t('planet.' + planet.id + '.name', null, planet.name || planet.id);
153};
154
155I18n.peopleName = function (planet)
156{
157 if (!planet)
158 { return ''; }
159 if (planet.custom)
160 { return planet.people || ''; }
161 return this.t('planet.' + planet.id + '.people', null, planet.people || '');
162};
163
164I18n.blockName = function (id, fallback)
165{
166 if (!id)
167 { return fallback || ''; }
168 return this.t('block.' + id, null, fallback || id);
169};
170
171I18n.error = function (msg)
172{
173 if (!msg)
174 { return ''; }
175 this._load();
176 var map = this._catalog.errors || {};
177 if (map[msg])
178 { return this.t(map[msg]); }
179 var m = /^Deze lobby is vol \(maximaal (\d+) spelers\)\.$/.exec(msg);
180 if (m)
181 { return this.t('error.lobbyFull', { n: m[1] }); }
182 m = /^Je hebt het maximum van (\d+) planeten bereikt\.$/.exec(msg);
183 if (m)
184 { return this.t('error.maxPlanets', { n: m[1] }); }
185 m = /^Vul een (.+) in\.$/.exec(msg);
186 if (m)
187 {
188 var field = m[1];
189 if (field === 'planeetnaam')
190 { field = this.t('error.fieldPlanet'); }
191 else if (field === 'bevolkingsnaam')
192 { field = this.t('error.fieldPeople'); }
193 return this.t('error.fillField', { field: field });
194 }
195 m = /^De server gaf (\d+)$/.exec(msg);
196 if (m)
197 { return this.t('error.serverStatus', { status: m[1] }); }
198 return msg;
199};
200
201I18n.readStored = function ()
202{
203 try
204 {
205 if (typeof localStorage !== 'undefined')
206 {
207 var v = localStorage.getItem(this.STORAGE_KEY);
208 if (this.known(v))
209 { return v; }
210 }
211 }
212 catch (e) { /* private mode */ }
213 return this.DEFAULT;
214};
215
216I18n._writeStored = function (id)
217{
218 try
219 {
220 if (typeof localStorage !== 'undefined')
221 { localStorage.setItem(this.STORAGE_KEY, id); }
222 }
223 catch (e) { /* ignore */ }
224 try
225 {
226 if (typeof document !== 'undefined')
227 {
228 document.cookie = this.COOKIE + '=' + encodeURIComponent(id)
229 + ';path=/;max-age=31536000;SameSite=Lax';
230 }
231 }
232 catch (e) { /* ignore */ }
233};
234
235I18n.setLocale = function (id, opts)
236{
237 opts = opts || {};
238 if (!this.known(id))
239 { id = this.DEFAULT; }
240 var changed = id !== this.locale;
241 this.locale = id;
242 if (opts.persist !== false)
243 { this._writeStored(id); }
244 if (typeof document !== 'undefined' && document.documentElement)
245 {
246 document.documentElement.lang = this.info(id).htmlLang;
247 document.documentElement.setAttribute('data-locale', id);
248 }
249 this.apply();
250 this.renderPicker();
251 if (changed || opts.force)
252 {
253 for (var i = 0; i < this._listeners.length; i++)
254 {
255 try
256 { this._listeners[i](id); }
257 catch (e) { /* listener errors must not break i18n */ }
258 }
259 }
260 if (opts.sync !== false && typeof Online !== 'undefined' && Online.me && Online.setLocale)
261 { Online.setLocale(id); }
262 return id;
263};
264
265I18n.onChange = function (fn)
266{
267 if (typeof fn === 'function')
268 { this._listeners.push(fn); }
269};
270
271I18n.apply = function (root)
272{
273 if (typeof document === 'undefined')
274 { return; }
275 root = root || document;
276 var nodes = root.querySelectorAll('[data-i18n]');
277 for (var i = 0; i < nodes.length; i++)
278 {
279 var el = nodes[i];
280 var key = el.getAttribute('data-i18n');
281 if (!key)
282 { continue; }
283 // Fall back to English (inside t) then the existing label so a
284 // missing/stale key never replaces visible text with the raw key.
285 el.textContent = this.t(key, null, el.textContent);
286 }
287 nodes = root.querySelectorAll('[data-i18n-html]');
288 for (var i = 0; i < nodes.length; i++)
289 {
290 var el = nodes[i];
291 var key = el.getAttribute('data-i18n-html');
292 if (!key)
293 { continue; }
294 el.innerHTML = this.t(key, null, el.innerHTML);
295 }
296 nodes = root.querySelectorAll('[data-i18n-placeholder]');
297 for (var i = 0; i < nodes.length; i++)
298 {
299 var el = nodes[i];
300 el.setAttribute('placeholder', this.t(el.getAttribute('data-i18n-placeholder'), null, el.getAttribute('placeholder')));
301 }
302 nodes = root.querySelectorAll('[data-i18n-aria]');
303 for (var i = 0; i < nodes.length; i++)
304 {
305 var el = nodes[i];
306 el.setAttribute('aria-label', this.t(el.getAttribute('data-i18n-aria'), null, el.getAttribute('aria-label')));
307 }
308 nodes = root.querySelectorAll('[data-i18n-title]');
309 for (var i = 0; i < nodes.length; i++)
310 {
311 var el = nodes[i];
312 el.setAttribute('title', this.t(el.getAttribute('data-i18n-title'), null, el.getAttribute('title')));
313 }
314};
315
316I18n.flagUrl = function (id)
317{
318 var info = this.info(id);
319 return 'images/flags/' + info.flag + '.svg';
320};
321
322I18n.togglePicker = function (force)
323{
324 if (typeof force === 'boolean')
325 { this._pickerOpen = force; }
326 else
327 { this._pickerOpen = !this._pickerOpen; }
328 this.renderPicker();
329};
330
331I18n.renderPicker = function ()
332{
333 if (typeof document === 'undefined')
334 { return; }
335 var wrap = document.getElementById('lang-picker');
336 var btn = document.getElementById('lang-current');
337 var list = document.getElementById('lang-list');
338 if (!wrap || !btn || !list)
339 { return; }
340 var info = this.info();
341 var img = btn.querySelector('img');
342 if (img)
343 {
344 img.src = this.flagUrl(this.locale);
345 img.alt = info.endonym;
346 }
347 btn.setAttribute('aria-label', this.t('lang.current', { name: info.endonym }));
348 btn.setAttribute('aria-expanded', this._pickerOpen ? 'true' : 'false');
349 btn.title = info.endonym;
350 list.innerHTML = '';
351 if (!this._pickerOpen)
352 {
353 list.hidden = true;
354 wrap.classList.remove('open');
355 return;
356 }
357 wrap.classList.add('open');
358 list.hidden = false;
359 for (var i = 0; i < this.LOCALES.length; i++)
360 {
361 var loc = this.LOCALES[i];
362 var opt = document.createElement('button');
363 opt.type = 'button';
364 opt.className = 'lang-option' + (loc.id === this.locale ? ' current' : '');
365 opt.setAttribute('data-locale', loc.id);
366 opt.setAttribute('aria-label', loc.endonym);
367 opt.title = loc.endonym;
368 opt.innerHTML = '<img src="' + this.flagUrl(loc.id) + '" alt="" width="36" height="24">'
369 + '<span>' + loc.endonym + '</span>';
370 (function (id)
371 {
372 opt.addEventListener('click', function (e)
373 {
374 e.stopPropagation();
375 I18n.setLocale(id);
376 I18n.togglePicker(false);
377 });
378 })(loc.id);
379 list.appendChild(opt);
380 }
381};
382
383I18n.bindPicker = function ()
384{
385 if (typeof document === 'undefined')
386 { return; }
387 var btn = document.getElementById('lang-current');
388 var list = document.getElementById('lang-list');
389 if (btn)
390 {
391 btn.addEventListener('click', function (e)
392 {
393 e.stopPropagation();
394 I18n.togglePicker();
395 });
396 }
397 document.addEventListener('click', function (e)
398 {
399 var wrap = document.getElementById('lang-picker');
400 if (!wrap || !I18n._pickerOpen)
401 { return; }
402 if (!wrap.contains(e.target))
403 { I18n.togglePicker(false); }
404 });
405 document.addEventListener('keydown', function (e)
406 {
407 if (e.key === 'Escape' && I18n._pickerOpen)
408 { I18n.togglePicker(false); }
409 });
410 this.renderPicker();
411};
412
413I18n.init = function ()
414{
415 this._load();
416 this.locale = this.readStored();
417 if (typeof document !== 'undefined' && document.documentElement)
418 {
419 document.documentElement.lang = this.info().htmlLang;
420 document.documentElement.setAttribute('data-locale', this.locale);
421 }
422 this.apply();
423};
424
425I18n.applyFromProfile = function (locale)
426{
427 if (this.known(locale))
428 { this.setLocale(locale, { sync: false, persist: true }); }
429};
430
431if (typeof module !== 'undefined' && module.exports)
432{ module.exports = I18n; }
433else if (typeof globalThis !== 'undefined')
434{ globalThis.I18n = I18n; }