Language fixes (#5384)

* Add some comments

* Decouple language settings

* Normalize on read/write

* Refactor

* Support device locale on app startup

* Cleanup, port to web

* Clean up comments

* Comment

* Try not to mutate

* Protect util handling, update test

* Dedupe array values
This commit is contained in:
Eric Bailey
2024-09-20 10:50:33 -05:00
committed by GitHub
parent cd88cbeab8
commit fa6f6f9e47
14 changed files with 240 additions and 53 deletions
+53
View File
@@ -0,0 +1,53 @@
import {getLocales as defaultGetLocales, Locale} from 'expo-localization'
import {dedupArray} from '#/lib/functions'
type LocalWithLanguageCode = Locale & {
languageCode: string
}
/**
* Normalized locales
*
* Handles legacy migration for Java devices.
*
* {@link https://github.com/bluesky-social/social-app/pull/4461}
* {@link https://xml.coverpages.org/iso639a.html}
*/
export function getLocales() {
const locales = defaultGetLocales?.() ?? []
const output: LocalWithLanguageCode[] = []
for (const locale of locales) {
if (typeof locale.languageCode === 'string') {
if (locale.languageCode === 'in') {
// indonesian
locale.languageCode = 'id'
}
if (locale.languageCode === 'iw') {
// hebrew
locale.languageCode = 'he'
}
if (locale.languageCode === 'ji') {
// yiddish
locale.languageCode = 'yi'
}
// @ts-ignore checked above
output.push(locale)
}
}
return output
}
export const deviceLocales = getLocales()
/**
* BCP-47 language tag without region e.g. array of 2-char lang codes
*
* {@link https://docs.expo.dev/versions/latest/sdk/localization/#locale}
*/
export const deviceLanguageCodes = dedupArray(
deviceLocales.map(l => l.languageCode),
)
+23 -1
View File
@@ -160,8 +160,13 @@ export function sanitizeAppLanguageSetting(appLanguage: string): AppLanguage {
return AppLanguage.en
}
/**
* Handles legacy migration for Java devices.
*
* {@link https://github.com/bluesky-social/social-app/pull/4461}
* {@link https://xml.coverpages.org/iso639a.html}
*/
export function fixLegacyLanguageCode(code: string | null): string | null {
// handle some legacy code conversions, see https://xml.coverpages.org/iso639a.html
if (code === 'in') {
// indonesian
return 'id'
@@ -176,3 +181,20 @@ export function fixLegacyLanguageCode(code: string | null): string | null {
}
return code
}
/**
* Find the first language supported by our translation infra. Values should be
* in order of preference, and match the values of {@link AppLanguage}.
*
* If no match, returns `en`.
*/
export function findSupportedAppLanguage(languageTags: (string | undefined)[]) {
const supported = new Set(Object.values(AppLanguage))
for (const tag of languageTags) {
if (!tag) continue
if (supported.has(tag as AppLanguage)) {
return tag
}
}
return AppLanguage.en
}