fix(i18n): resolve startup locales consistently

Prefer a supported saved language over the cache and browser locale.
Align frontend alias resolution with Rust and ignore unsupported saved
values when the layout mounts so they cannot overwrite the fallback.

In Rust, walk borrowed prefixes instead of rebuilding strings. This
preserves locale resolution and removes quadratic work on long tags.
Across all 14 shipped locale IDs (equally weighted),
median lookup time fell from 40.0 to 22.4 ns and heap allocations fell
from 4 to 2 per lookup. A synthetic 64 KiB tag fell from 771 ms to 240 µs.
This commit is contained in:
Tunglies
2026-12-03 12:59:02 +08:00
parent 9bdd2c0623
commit 16ef6fbc34
4 changed files with 57 additions and 87 deletions
+6 -20
View File
@@ -1,21 +1,16 @@
import { useState, useCallback } from 'react'
import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import {
changeLanguage,
resolveLanguage,
supportedLanguages,
} from '@/services/i18n'
import { changeLanguage, resolveSupportedLanguage } from '@/services/i18n'
export const useI18n = () => {
const { i18n, t } = useTranslation()
const [isLoading, setIsLoading] = useState(false)
const { i18n } = useTranslation()
const switchLanguage = useCallback(
async (language: string) => {
const targetLanguage = resolveLanguage(language)
const targetLanguage = resolveSupportedLanguage(language)
if (!supportedLanguages.includes(targetLanguage)) {
if (!targetLanguage) {
console.warn(`Unsupported language: ${language}`)
return
}
@@ -24,23 +19,14 @@ export const useI18n = () => {
return
}
setIsLoading(true)
try {
await changeLanguage(targetLanguage)
} catch (error) {
console.error('Failed to change language:', error)
} finally {
setIsLoading(false)
}
},
[i18n.language],
)
return {
currentLanguage: i18n.language,
supportedLanguages,
switchLanguage,
isLoading,
t,
}
return { switchLanguage }
}