BlueGit

projects-timfalken-com meteors

Files

meteors / src / i18n.js

i18n.js

i18n.js 10.5 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 el.textContent = this.t(key);
284 }
285 nodes = root.querySelectorAll('[data-i18n-html]');
286 for (var i = 0; i < nodes.length; i++)
287 {
288 var el = nodes[i];
289 var key = el.getAttribute('data-i18n-html');
290 if (!key)
291 { continue; }
292 el.innerHTML = this.t(key);
293 }
294 nodes = root.querySelectorAll('[data-i18n-placeholder]');
295 for (var i = 0; i < nodes.length; i++)
296 {
297 nodes[i].setAttribute('placeholder', this.t(nodes[i].getAttribute('data-i18n-placeholder')));
298 }
299 nodes = root.querySelectorAll('[data-i18n-aria]');
300 for (var i = 0; i < nodes.length; i++)
301 {
302 nodes[i].setAttribute('aria-label', this.t(nodes[i].getAttribute('data-i18n-aria')));
303 }
304 nodes = root.querySelectorAll('[data-i18n-title]');
305 for (var i = 0; i < nodes.length; i++)
306 {
307 nodes[i].setAttribute('title', this.t(nodes[i].getAttribute('data-i18n-title')));
308 }
309};
310
311I18n.flagUrl = function (id)
312{
313 var info = this.info(id);
314 return 'images/flags/' + info.flag + '.svg';
315};
316
317I18n.togglePicker = function (force)
318{
319 if (typeof force === 'boolean')
320 { this._pickerOpen = force; }
321 else
322 { this._pickerOpen = !this._pickerOpen; }
323 this.renderPicker();
324};
325
326I18n.renderPicker = function ()
327{
328 if (typeof document === 'undefined')
329 { return; }
330 var wrap = document.getElementById('lang-picker');
331 var btn = document.getElementById('lang-current');
332 var list = document.getElementById('lang-list');
333 if (!wrap || !btn || !list)
334 { return; }
335 var info = this.info();
336 var img = btn.querySelector('img');
337 if (img)
338 {
339 img.src = this.flagUrl(this.locale);
340 img.alt = info.endonym;
341 }
342 btn.setAttribute('aria-label', this.t('lang.current', { name: info.endonym }));
343 btn.setAttribute('aria-expanded', this._pickerOpen ? 'true' : 'false');
344 btn.title = info.endonym;
345 list.innerHTML = '';
346 if (!this._pickerOpen)
347 {
348 list.hidden = true;
349 wrap.classList.remove('open');
350 return;
351 }
352 wrap.classList.add('open');
353 list.hidden = false;
354 for (var i = 0; i < this.LOCALES.length; i++)
355 {
356 var loc = this.LOCALES[i];
357 var opt = document.createElement('button');
358 opt.type = 'button';
359 opt.className = 'lang-option' + (loc.id === this.locale ? ' current' : '');
360 opt.setAttribute('data-locale', loc.id);
361 opt.setAttribute('aria-label', loc.endonym);
362 opt.title = loc.endonym;
363 opt.innerHTML = '<img src="' + this.flagUrl(loc.id) + '" alt="" width="36" height="24">'
364 + '<span>' + loc.endonym + '</span>';
365 (function (id)
366 {
367 opt.addEventListener('click', function (e)
368 {
369 e.stopPropagation();
370 I18n.setLocale(id);
371 I18n.togglePicker(false);
372 });
373 })(loc.id);
374 list.appendChild(opt);
375 }
376};
377
378I18n.bindPicker = function ()
379{
380 if (typeof document === 'undefined')
381 { return; }
382 var btn = document.getElementById('lang-current');
383 var list = document.getElementById('lang-list');
384 if (btn)
385 {
386 btn.addEventListener('click', function (e)
387 {
388 e.stopPropagation();
389 I18n.togglePicker();
390 });
391 }
392 document.addEventListener('click', function (e)
393 {
394 var wrap = document.getElementById('lang-picker');
395 if (!wrap || !I18n._pickerOpen)
396 { return; }
397 if (!wrap.contains(e.target))
398 { I18n.togglePicker(false); }
399 });
400 document.addEventListener('keydown', function (e)
401 {
402 if (e.key === 'Escape' && I18n._pickerOpen)
403 { I18n.togglePicker(false); }
404 });
405 this.renderPicker();
406};
407
408I18n.init = function ()
409{
410 this._load();
411 this.locale = this.readStored();
412 if (typeof document !== 'undefined' && document.documentElement)
413 {
414 document.documentElement.lang = this.info().htmlLang;
415 document.documentElement.setAttribute('data-locale', this.locale);
416 }
417 this.apply();
418};
419
420I18n.applyFromProfile = function (locale)
421{
422 if (this.known(locale))
423 { this.setLocale(locale, { sync: false, persist: true }); }
424};
425
426if (typeof module !== 'undefined' && module.exports)
427{ module.exports = I18n; }
428else if (typeof globalThis !== 'undefined')
429{ globalThis.I18n = I18n; }