/**
* 语言解析纯函数(与 `warmup.html` 的语言判定语义对齐,无副作用,便于单测)。
*
* warmup.html 逻辑:`i18nAutoDetect ? convertDetectedLanguage(?lang > localStorage > navigator) : 'zh-CN'`,
* 再取 `locales[lang]`(回退 zh-CN)。native 侧 L3 无 WebView,`localStorage` 够不着,
* 故语言来源为 `preferredLanguage`(显式)→ 系统语言(best-effort,等价 navigator.language)→ `zh-CN`。
*/
/** 语言归一化:精确匹配 → 前缀匹配(en-GB→en-US / zh-TW→zh-CN)→ 回退 `zh-CN`。 */
export function convertDetectedLanguage(lng: string, supported: string[]): string {
if (lng.length === 0) {
return 'zh-CN';
}
if (supported.indexOf(lng) !== -1) {
return lng;
}
const prefix: string = lng.split('-')[0];
for (let i = 0; i < supported.length; i++) {
if (supported[i].indexOf(prefix) === 0) {
return supported[i];
}
}
return 'zh-CN';
}
/**
* 解析当前应预取的语言(与 warmup.html 逐行对齐)。
*
* warmup.html: `lang = i18nAutoDetect ? convertDetectedLanguage(langParam || localStorage || navigator) : 'zh-CN'`
* ——即 `i18nAutoDetect=false` 时**无视任何语言偏好,恒 `zh-CN`**(真实页此时也恒渲染 zh-CN,
* 预热其他语言纯属缓存 miss)。故 `preferredLanguage` 仅在 `i18nAutoDetect=true` 时生效,
* 扮演 warmup.html 中 `langParam`(最高优先级)的角色;系统语言扮演 `localStorage || navigator`。
*
* @param preferred `config.preferredLanguage`,仅 `i18nAutoDetect=true` 时非空优先
* @param i18nAutoDetect manifest 的 `i18nAutoDetect`
* @param systemLang 系统语言(best-effort,由调用方注入以保持本函数纯净)
* @param supported manifest 的 `supportedLngs`
*/
export function resolveLang(
preferred: string | null,
i18nAutoDetect: boolean,
systemLang: string,
supported: string[]
): string {
// i18nAutoDetect=false → 恒 zh-CN(与 warmup.html / 真实页一致)
if (!i18nAutoDetect) {
return 'zh-CN';
}
const raw: string = (preferred !== null && preferred.length > 0) ? preferred : systemLang;
return convertDetectedLanguage(raw, supported);
}
/** 取语言资源列表;`locales[lang]` 缺失时回退 `locales['zh-CN']`,再缺失返回空数组。 */
export function pickLocaleAssets(locales: Record<string, string[]> | undefined, lang: string): string[] {
if (locales === undefined || locales === null) {
return [];
}
const picked: string[] | undefined = locales[lang];
if (picked !== undefined && picked !== null) {
return picked;
}
const fallback: string[] | undefined = locales['zh-CN'];
return fallback !== undefined && fallback !== null ? fallback : [];
}
|