From 3cf30aaf089a7e1a38f291851fca7e8184dd4d01 Mon Sep 17 00:00:00 2001 From: Nils Maier Date: Tue, 3 Sep 2019 07:19:37 +0200 Subject: [PATCH] Use _ version of language codes Closes #50 --- _locales/{zh-CN => zh_CN}/messages.json | 0 lib/i18n.ts | 31 ++++++++++++++++--------- 2 files changed, 20 insertions(+), 11 deletions(-) rename _locales/{zh-CN => zh_CN}/messages.json (100%) diff --git a/_locales/zh-CN/messages.json b/_locales/zh_CN/messages.json similarity index 100% rename from _locales/zh-CN/messages.json rename to _locales/zh_CN/messages.json diff --git a/lib/i18n.ts b/lib/i18n.ts index 48bfb1c..b83b269 100644 --- a/lib/i18n.ts +++ b/lib/i18n.ts @@ -121,19 +121,28 @@ function loadCached() { } async function loadRawLocales() { - // en is the base locale + // en is the base locale, always to be loaded + // The loader will override string from it with more specific string + // from other locales const langs = new Set(["en"]); - const ui = (typeof browser !== "undefined" ? browser : chrome). - i18n.getUILanguage(); - langs.add(ui); - // Try the base too - if (ui.includes("-")) { - langs.add(ui.split(/[-]+/)[0]); - } - else if (ui.includes("_")) { - langs.add(ui.split(/[_]+/)[0]); - } + const uiLang: string = (typeof browser !== "undefined" ? browser : chrome). + i18n.getUILanguage(); + + // Chrome will only look for underscore versions of locale codes, + // while Firefox will look for both. + // So we better normalize the code to the underscore version. + // However, the API seems to always return the dash-version. + + // Add all base locales into ascending order of priority, + // starting with the most unspecific base locale, ending + // with the most specific locale. + // e.g. this will transform ["zh", "CN"] -> ["zh", "zh_CN"] + uiLang.split(/[_-]/g).reduce((prev, curr) => { + prev.push(curr); + langs.add(prev.join("_")); + return prev; + }, []); const fetched = await Promise.all(Array.from(langs, fetchLanguage)); return fetched.filter(e => !!e);