BlueGit

projects-timfalken-com allianties

Files

allianties / src / i18n.js

i18n.js

i18n.js 9.3 KiB Download Raw
1'use strict';
2
3/**
4 * Player-facing translations for Allianties.
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: 'allianties-locale',
24 COOKIE: 'allianties-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.error = function (msg)
142{
143 if (!msg)
144 { return ''; }
145 this._load();
146 var map = this._catalog.errors || {};
147 if (map[msg])
148 { return this.t(map[msg]); }
149 var m = /^The server returned (\d+)\.$/.exec(msg) || /^De server gaf (\d+)$/.exec(msg);
150 if (m)
151 { return this.t('error.serverStatus', { status: m[1] }); }
152 return msg;
153};
154
155I18n.readStored = function ()
156{
157 try
158 {
159 if (typeof localStorage !== 'undefined')
160 {
161 var v = localStorage.getItem(this.STORAGE_KEY);
162 if (this.known(v))
163 { return v; }
164 }
165 }
166 catch (e) { /* private mode */ }
167 return this.DEFAULT;
168};
169
170I18n._writeStored = function (id)
171{
172 try
173 {
174 if (typeof localStorage !== 'undefined')
175 { localStorage.setItem(this.STORAGE_KEY, id); }
176 }
177 catch (e) { /* ignore */ }
178 try
179 {
180 if (typeof document !== 'undefined')
181 {
182 document.cookie = this.COOKIE + '=' + encodeURIComponent(id)
183 + ';path=/;max-age=31536000;SameSite=Lax';
184 }
185 }
186 catch (e) { /* ignore */ }
187};
188
189I18n.setLocale = function (id, opts)
190{
191 opts = opts || {};
192 if (!this.known(id))
193 { id = this.DEFAULT; }
194 var changed = id !== this.locale;
195 this.locale = id;
196 if (opts.persist !== false)
197 { this._writeStored(id); }
198 if (typeof document !== 'undefined' && document.documentElement)
199 {
200 document.documentElement.lang = this.info(id).htmlLang;
201 document.documentElement.setAttribute('data-locale', id);
202 }
203 this.apply();
204 this.renderPicker();
205 if (changed || opts.force)
206 {
207 for (var i = 0; i < this._listeners.length; i++)
208 {
209 try
210 { this._listeners[i](id); }
211 catch (e) { /* listener errors must not break i18n */ }
212 }
213 }
214 if (opts.sync !== false && typeof Api !== 'undefined' && Api.me && Api.setLocale)
215 { Api.setLocale(id); }
216 return id;
217};
218
219I18n.onChange = function (fn)
220{
221 if (typeof fn === 'function')
222 { this._listeners.push(fn); }
223};
224
225I18n.apply = function (root)
226{
227 if (typeof document === 'undefined')
228 { return; }
229 root = root || document;
230 var nodes = root.querySelectorAll('[data-i18n]');
231 for (var i = 0; i < nodes.length; i++)
232 {
233 var el = nodes[i];
234 var key = el.getAttribute('data-i18n');
235 if (!key)
236 { continue; }
237 el.textContent = this.t(key);
238 }
239 nodes = root.querySelectorAll('[data-i18n-html]');
240 for (var i = 0; i < nodes.length; i++)
241 {
242 var el = nodes[i];
243 var key = el.getAttribute('data-i18n-html');
244 if (!key)
245 { continue; }
246 el.innerHTML = this.t(key);
247 }
248 nodes = root.querySelectorAll('[data-i18n-placeholder]');
249 for (var i = 0; i < nodes.length; i++)
250 {
251 nodes[i].setAttribute('placeholder', this.t(nodes[i].getAttribute('data-i18n-placeholder')));
252 }
253 nodes = root.querySelectorAll('[data-i18n-aria]');
254 for (var i = 0; i < nodes.length; i++)
255 {
256 nodes[i].setAttribute('aria-label', this.t(nodes[i].getAttribute('data-i18n-aria')));
257 }
258 nodes = root.querySelectorAll('[data-i18n-title]');
259 for (var i = 0; i < nodes.length; i++)
260 {
261 nodes[i].setAttribute('title', this.t(nodes[i].getAttribute('data-i18n-title')));
262 }
263};
264
265I18n.flagUrl = function (id)
266{
267 var info = this.info(id);
268 return 'images/flags/' + info.flag + '.svg';
269};
270
271I18n.togglePicker = function (force)
272{
273 if (typeof force === 'boolean')
274 { this._pickerOpen = force; }
275 else
276 { this._pickerOpen = !this._pickerOpen; }
277 this.renderPicker();
278};
279
280I18n.renderPicker = function ()
281{
282 if (typeof document === 'undefined')
283 { return; }
284 var wrap = document.getElementById('lang-picker');
285 var btn = document.getElementById('lang-current');
286 var list = document.getElementById('lang-list');
287 if (!wrap || !btn || !list)
288 { return; }
289 var info = this.info();
290 var img = btn.querySelector('img');
291 if (img)
292 {
293 img.src = this.flagUrl(this.locale);
294 img.alt = info.endonym;
295 }
296 btn.setAttribute('aria-label', this.t('lang.current', { name: info.endonym }));
297 btn.setAttribute('aria-expanded', this._pickerOpen ? 'true' : 'false');
298 btn.title = info.endonym;
299 list.innerHTML = '';
300 if (!this._pickerOpen)
301 {
302 list.hidden = true;
303 wrap.classList.remove('open');
304 return;
305 }
306 wrap.classList.add('open');
307 list.hidden = false;
308 for (var i = 0; i < this.LOCALES.length; i++)
309 {
310 var loc = this.LOCALES[i];
311 var opt = document.createElement('button');
312 opt.type = 'button';
313 opt.className = 'lang-option' + (loc.id === this.locale ? ' current' : '');
314 opt.setAttribute('data-locale', loc.id);
315 opt.setAttribute('aria-label', loc.endonym);
316 opt.title = loc.endonym;
317 opt.innerHTML = '<img src="' + this.flagUrl(loc.id) + '" alt="" width="36" height="24">'
318 + '<span>' + loc.endonym + '</span>';
319 (function (id)
320 {
321 opt.addEventListener('click', function (e)
322 {
323 e.stopPropagation();
324 I18n.setLocale(id);
325 I18n.togglePicker(false);
326 });
327 })(loc.id);
328 list.appendChild(opt);
329 }
330};
331
332I18n.bindPicker = function ()
333{
334 if (typeof document === 'undefined')
335 { return; }
336 var btn = document.getElementById('lang-current');
337 var list = document.getElementById('lang-list');
338 if (btn)
339 {
340 btn.addEventListener('click', function (e)
341 {
342 e.stopPropagation();
343 I18n.togglePicker();
344 });
345 }
346 document.addEventListener('click', function (e)
347 {
348 var wrap = document.getElementById('lang-picker');
349 if (!wrap || !I18n._pickerOpen)
350 { return; }
351 if (!wrap.contains(e.target))
352 { I18n.togglePicker(false); }
353 });
354 document.addEventListener('keydown', function (e)
355 {
356 if (e.key === 'Escape' && I18n._pickerOpen)
357 { I18n.togglePicker(false); }
358 });
359 this.renderPicker();
360};
361
362I18n.init = function ()
363{
364 this._load();
365 this.locale = this.readStored();
366 if (typeof document !== 'undefined' && document.documentElement)
367 {
368 document.documentElement.lang = this.info().htmlLang;
369 document.documentElement.setAttribute('data-locale', this.locale);
370 }
371 this.apply();
372};
373
374I18n.applyFromProfile = function (locale)
375{
376 if (this.known(locale))
377 { this.setLocale(locale, { sync: false, persist: true }); }
378};
379
380if (typeof module !== 'undefined' && module.exports)
381{ module.exports = I18n; }
382else if (typeof globalThis !== 'undefined')
383{ globalThis.I18n = I18n; }