lbry-desktop/ui/util/default-languages.js
infinite-persistence 81e4730037 Simplify language lists
- SUPPORTED_SUB_LANGUAGE_CODES[] that I introduced was pretty redundant when SUPPORTED_LANGUAGES[] already hold the information. The logic to ignore sub-languages (i.e. reduce the locale's "en-GB" to "en" is now located in getDefaultLanguage()).

- SUPPORTED_BROWSER_LANGUAGES[] and SUPPORTED_LANGUAGES[] look so similar and hard to tell what the former is for at first glance. The functionality to map 'zh-CN' to 'zh-Hans' is now handled by resolveLanguageAlias(), which makes the intention clearer.

This leaves us with a single list -- SUPPORTED_LANGUAGES[], whose key also tells us the desired language code to use.
Also, clients now need to call `resolveLanguageAlias` to map any language code aliases, as they differ depending on how it is queried (e.g. `navigator.language` vs. `app.getLocal()` uses different standards).

I think we no longer need to explicitly migrate existing user's 'zh-CN' into 'zh-Hans' because the rest of the system will always use the desired language code as long as 'resolveLanguageAlias' is called appropriately. e.g. the system uses `selectLanguage` and `selectLanguage` calls `resolveLanguageAlias`.
2021-04-04 22:54:33 -04:00

53 lines
1.7 KiB
JavaScript

import homepages from 'homepages';
import SUPPORTED_LANGUAGES from 'constants/supported_languages';
const DEFAULT_LANG = 'en';
/**
* Checks if the given language is an alias of a language that we support, and
* returns the version that the rest of the application (lbry-sdk, Transifex)
* expects. If the given language is not an expected alias, the original value
* is returned.
*
* @param lang
* @returns {*}
*/
export function resolveLanguageAlias(lang) {
const KNOWN_LANG_ALIASES = {
'zh-CN': 'zh-Hans',
'zh-TW': 'zh-Hant',
};
return KNOWN_LANG_ALIASES[lang] ? KNOWN_LANG_ALIASES[lang] : lang;
}
/**
* Returns the native language of the system, filtered/resolved
* to the language code format that the application expects.
*
* @returns {string|*}
*/
export const getDefaultLanguage = () => {
const browserLanguage = resolveLanguageAlias(window.navigator.language);
if (SUPPORTED_LANGUAGES[browserLanguage]) {
return browserLanguage;
} else {
if (browserLanguage.includes('-')) {
// Perhaps it is a sub-lang that we are currently not supporting.
// See if we support the main one.
const mainLang = browserLanguage.substring(0, browserLanguage.indexOf('-'));
if (SUPPORTED_LANGUAGES[mainLang]) {
return mainLang;
} else {
return DEFAULT_LANG;
}
} else {
return DEFAULT_LANG;
}
}
};
// If homepages has a key "zh-Hant" return that, otherwise return "zh", otherwise "en"
export const getDefaultHomepageKey = () => {
const language = getDefaultLanguage();
return (homepages[language] && language) || (homepages[language.slice(0, 2)] && language.slice(0, 2)) || DEFAULT_LANG;
};