refactor locale generation; en-US is default

Refactor the locale generation to be easier to understand.

Also changed the fallback locale from Japanese to English. The Chinese
fallback has been removed.
This commit is contained in:
Johann150 2022-07-10 11:15:11 +02:00
parent b9c837f106
commit 3924b1cbc6
Signed by untrusted user: Johann150
GPG key ID: 9EE6577A2A06F8F1

View file

@ -8,11 +8,13 @@ const yaml = require('js-yaml');
const merge = (...args) => args.reduce((a, c) => ({ const merge = (...args) => args.reduce((a, c) => ({
...a, ...a,
...c, ...c,
// this is necessary to merge "sub-objects" correctly instead of overwriting them
...Object.entries(a) ...Object.entries(a)
.filter(([k]) => c && typeof c[k] === 'object') .filter(([k]) => c && typeof c[k] === 'object')
.reduce((a, [k, v]) => (a[k] = merge(v, c[k]), a), {}) .reduce((a, [k, v]) => (a[k] = merge(v, c[k]), a), {})
}), {}); }), {});
// For a language to be generated as a locale it has to be listed here.
const languages = [ const languages = [
'ar-SA', 'ar-SA',
'cs-CZ', 'cs-CZ',
@ -40,29 +42,28 @@ const languages = [
'zh-TW', 'zh-TW',
]; ];
const primaries = { // Load the locales listed above.
'en': 'US', const locales = languages.reduce(
'ja': 'JP', (acc, lang) => {
'zh': 'CN', acc[lang] = yaml.load(
}; fs.readFileSync(`${__dirname}/${lang}.yml`, 'utf-8')
// Remove backspace characters, which for some reason can get mixed in with the string and break the YAML.
// 何故か文字列にバックスペース文字が混入することがあり、YAMLが壊れるので取り除く .replaceAll('\b', '')
const clean = (text) => text.replace(new RegExp(String.fromCodePoint(0x08), 'g'), ''); ) || {};
return acc;
const locales = languages.reduce((a, c) => (a[c] = yaml.load(clean(fs.readFileSync(`${__dirname}/${c}.yml`, 'utf-8'))) || {}, a), {}); },
{} // initial accumulator
);
module.exports = Object.entries(locales) module.exports = Object.entries(locales)
.reduce((a, [k ,v]) => (a[k] = (() => { .reduce((acc, [lang, strings]) => {
const [lang] = k.split('-'); if (k == 'en-US') {
switch (k) { acc[lang] = strings;
case 'ja-JP': return v; } else {
case 'ja-KS': // all other locales fall back to en-US
case 'en-US': return merge(locales['ja-JP'], v); acc[lang] = merge(locales['en-US'], strings);
default: return merge( }
locales['ja-JP'], return acc;
locales['en-US'], },
locales[`${lang}-${primaries[lang]}`] || {}, {} // initial accumulator
v );
);
}
})(), a), {});