Skip to content

Commit 260d392

Browse files
xrgzsGitHub Copilot
andauthored
feat(i18n): fallback to English when translation is missing (#554)
- Cache English dictionary for reuse as fallback - Merge non-English locales with English base (locale on top) - Fall back to English if a locale fails to load entirely Co-authored-by: GitHub Copilot <copilot@github.com>
1 parent 0ce86cf commit 260d392

1 file changed

Lines changed: 25 additions & 2 deletions

File tree

src/app/i18n.ts

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,13 +39,36 @@ export type Lang = keyof typeof langs
3939
export type RawDictionary = typeof en.dict
4040
export type Dictionary = i18n.Flatten<RawDictionary>
4141

42-
// Fetch and flatten the dictionary
42+
// English dictionary cache for fallback
43+
let enDictCache: Dictionary | null = null
44+
45+
const fetchEnDict = async (): Promise<Dictionary> => {
46+
if (!enDictCache) {
47+
const dict: RawDictionary = (await import("~/lang/en/entry")).dict
48+
enDictCache = i18n.flatten(dict)
49+
}
50+
return enDictCache
51+
}
52+
53+
// Fetch and flatten the dictionary, with English fallback
4354
const fetchDictionary = async (locale: Lang): Promise<Dictionary> => {
4455
try {
4556
const dict: RawDictionary = (await import(`~/lang/${locale}/entry.ts`)).dict
46-
return i18n.flatten(dict) // Flatten dictionary for easier access to keys
57+
const flatDict = i18n.flatten(dict)
58+
59+
// If not English, merge with English as fallback (English keys underneath, locale on top)
60+
if (locale !== "en") {
61+
const enDict = await fetchEnDict()
62+
return { ...enDict, ...flatDict } as Dictionary
63+
}
64+
65+
return flatDict
4766
} catch (err) {
4867
console.error(`Error loading dictionary for locale: ${locale}`, err)
68+
// Fallback to English if the requested locale fails to load
69+
if (locale !== "en") {
70+
return await fetchEnDict()
71+
}
4972
throw new Error(`Failed to load dictionary for ${locale}`)
5073
}
5174
}

0 commit comments

Comments
 (0)