Localize lang selectors according to the app language (#6207)

* Localize lang selectors according to the app language

* Explicitly ignore RangeError when translating locale names
This commit is contained in:
Stanislas Signoud
2024-12-31 22:27:14 +01:00
committed by GitHub
parent 09297d92cb
commit 9f075b1340
8 changed files with 97 additions and 45 deletions
+39 -3
View File
@@ -5,6 +5,7 @@ import lande from 'lande'
import {hasProp} from '#/lib/type-guards'
import {
AppLanguage,
type Language,
LANGUAGES_MAP_CODE2,
LANGUAGES_MAP_CODE3,
} from './languages'
@@ -31,9 +32,44 @@ export function code3ToCode2Strict(lang: string): string | undefined {
return undefined
}
export function codeToLanguageName(lang: string): string {
const lang2 = code3ToCode2(lang)
return LANGUAGES_MAP_CODE2[lang2]?.name || lang
function getLocalizedLanguage(
langCode: string,
appLang: string,
): string | undefined {
try {
const allNames = new Intl.DisplayNames([appLang], {
type: 'language',
fallback: 'none',
languageDisplay: 'standard',
})
const translatedName = allNames.of(langCode)
if (translatedName) {
// force simple title case (as languages do not always start with an uppercase in Unicode data)
return translatedName[0].toLocaleUpperCase() + translatedName.slice(1)
}
} catch (e) {
// ignore RangeError from Intl.DisplayNames APIs
if (!(e instanceof RangeError)) {
throw e
}
}
}
export function languageName(language: Language, appLang: string): string {
// if Intl.DisplayNames is unavailable on the target, display the English name
if (!(Intl as any).DisplayNames) {
return language.name
}
return getLocalizedLanguage(language.code2, appLang) || language.name
}
export function codeToLanguageName(lang2or3: string, appLang: string): string {
const code2 = code3ToCode2(lang2or3)
const knownLanguage = LANGUAGES_MAP_CODE2[code2]
return knownLanguage ? languageName(knownLanguage, appLang) : code2
}
export function getPostLanguage(
+1 -1
View File
@@ -1,4 +1,4 @@
interface Language {
export interface Language {
code3: string
code2: string
name: string