Updated Language Context

This commit is contained in:
Tola Leng
2025-05-23 20:40:29 +08:00
parent 1ee63ec74a
commit 641e98c001
+21 -5
View File
@@ -1,11 +1,11 @@
import React, { createContext, useContext, useState, ReactNode } from "react";
import { translations, Language, TranslationKey } from "@/translations";
import { translations, Language, TranslationModule, TranslationKey } from "@/translations";
type LanguageContextType = {
language: Language;
setLanguage: (language: Language) => void;
t: (key: string) => string;
t: <M extends TranslationModule>(key: string, module?: M) => string;
};
const LanguageContext = createContext<LanguageContextType>({
@@ -19,8 +19,24 @@ export const useLanguage = () => useContext(LanguageContext);
export const LanguageProvider = ({ children }: { children: ReactNode }) => {
const [language, setLanguage] = useState<Language>("en");
const t = (key: string) => {
return translations[language][key as TranslationKey] || key;
const t = <M extends TranslationModule>(key: string, module?: M): string => {
// If module is provided, look up in that specific module
if (module) {
const translatedValue = translations[language][module][key as TranslationKey<M>];
return typeof translatedValue === 'string' ? translatedValue : key;
}
// If no module is provided, search through all modules
for (const mod in translations[language]) {
const moduleKey = mod as TranslationModule;
const translatedValue = translations[language][moduleKey][key as any];
if (translatedValue && typeof translatedValue === 'string') {
return translatedValue;
}
}
// If no translation found, return the key
return key;
};
return (
@@ -28,4 +44,4 @@ export const LanguageProvider = ({ children }: { children: ReactNode }) => {
{children}
</LanguageContext.Provider>
);
};
};