add localisation support
currently only en_GB (TODO: dynamic language pack imports)
This commit is contained in:
parent
970590497f
commit
e326ac858e
17 changed files with 263 additions and 90 deletions
60
src/lib/lang.js
Normal file
60
src/lib/lang.js
Normal file
|
@ -0,0 +1,60 @@
|
|||
import * as en_GB from '@cf/lang/en_GB.json';
|
||||
|
||||
/**
|
||||
* @param {string} lang IETH language tag (i.e. en_GB)
|
||||
* @returns Map<string, string | string[]>
|
||||
*/
|
||||
export default function init(lang) {
|
||||
let i18n = new Object();
|
||||
let language;
|
||||
|
||||
// TODO: dynamic imports seem to fail here; it can't find the file.
|
||||
// try {
|
||||
// language = import(`../lang/${lang}.json`);
|
||||
// } catch (error) {
|
||||
// throw error;
|
||||
// }
|
||||
|
||||
language = en_GB;
|
||||
|
||||
i18n.lang = language;
|
||||
i18n.lang_code = lang;
|
||||
i18n.string = function(/* @type string */ key) {
|
||||
const tokens = key.split('.');
|
||||
|
||||
let i = 0;
|
||||
let token = tokens[i];
|
||||
let res = this.lang;
|
||||
while (true) {
|
||||
res = res[token];
|
||||
if (res === undefined) {
|
||||
console.warn(`${key} not found for language ${this.lang_code}`);
|
||||
return key;
|
||||
}
|
||||
if (typeof res === 'string' || res instanceof String)
|
||||
return res;
|
||||
i++;
|
||||
token = tokens[i];
|
||||
}
|
||||
}
|
||||
i18n.stringArray = function(/* @type string */ key) {
|
||||
const tokens = key.split('.');
|
||||
|
||||
let i = 0;
|
||||
let token = tokens[i];
|
||||
let res = this.lang;
|
||||
while (true) {
|
||||
res = res[token];
|
||||
if (res === undefined) {
|
||||
console.warn(`${key} not found for language ${this.lang_code}`);
|
||||
return key;
|
||||
}
|
||||
if (Array.isArray(res))
|
||||
return res;
|
||||
i++;
|
||||
token = tokens[i];
|
||||
}
|
||||
}
|
||||
|
||||
return i18n;
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue