refactor(i18n): improve translation handling and add English fallback
- Add English as the default fallback language; automatically use English when a translation for the current language is missing.
This commit is contained in:
@@ -1,4 +1,4 @@
|
|||||||
import React, { createContext, useContext, useState, ReactNode } from "react";
|
import React, { createContext, useContext, useState, ReactNode, useCallback } from "react";
|
||||||
import { translations, Language, TranslationModule, TranslationKey } from "@/translations";
|
import { translations, Language, TranslationModule, TranslationKey } from "@/translations";
|
||||||
|
|
||||||
type LanguageContextType = {
|
type LanguageContextType = {
|
||||||
@@ -21,23 +21,35 @@ export const useLanguage = () => {
|
|||||||
|
|
||||||
export const LanguageProvider = ({ children }: { children: ReactNode }) => {
|
export const LanguageProvider = ({ children }: { children: ReactNode }) => {
|
||||||
const [language, setLanguage] = useState<Language>("en");
|
const [language, setLanguage] = useState<Language>("en");
|
||||||
|
const fallbackLanguage: Language = "en";
|
||||||
|
|
||||||
const t = <M extends TranslationModule>(key: string, module?: M): string => {
|
const t = useCallback(<M extends TranslationModule>(key: string, module?: M): string => {
|
||||||
|
const langPack = translations[language];
|
||||||
|
const fallbackPack = translations[fallbackLanguage];
|
||||||
if (module) {
|
if (module) {
|
||||||
const translatedValue = translations[language][module][key as TranslationKey<M>];
|
const valCur = langPack?.[module]?.[key as TranslationKey<M>];
|
||||||
return typeof translatedValue === "string" ? translatedValue : key;
|
if (typeof valCur === "string") return valCur;
|
||||||
|
|
||||||
|
const valEn = fallbackPack?.[module]?.[key as TranslationKey<M>];
|
||||||
|
if (typeof valEn === "string") return valEn;
|
||||||
|
|
||||||
|
return key;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const mod in translations[language]) {
|
for (const mod in langPack) {
|
||||||
const moduleKey = mod as TranslationModule;
|
const m = mod as TranslationModule;
|
||||||
const translatedValue = translations[language][moduleKey][key as any];
|
const val = langPack[m]?.[key as any];
|
||||||
if (translatedValue && typeof translatedValue === "string") {
|
if (typeof val === "string") return val;
|
||||||
return translatedValue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for (const mod in fallbackPack) {
|
||||||
|
const m = mod as TranslationModule;
|
||||||
|
const val = fallbackPack[m]?.[key as any];
|
||||||
|
if (typeof val === "string") return val;
|
||||||
}
|
}
|
||||||
|
|
||||||
return key;
|
return key;
|
||||||
};
|
}, [language]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<LanguageContext.Provider value={{ language, setLanguage, t }}>
|
<LanguageContext.Provider value={{ language, setLanguage, t }}>
|
||||||
|
|||||||
Reference in New Issue
Block a user