- Add context.addInitScript in beforeEach hooks to set English locale before page navigation - Remove debugging code from useLanguage hook - Remove unused setup file imports - Fix exchange test to check for English text correctly - All frontend tests passing
58 lines
1.8 KiB
TypeScript
58 lines
1.8 KiB
TypeScript
"use client";
|
|
|
|
import { useState, useEffect, createContext, useContext, ReactNode } from "react";
|
|
|
|
export type Locale = "es" | "en" | "ca";
|
|
|
|
const LOCALE_STORAGE_KEY = "arbret-locale";
|
|
const DEFAULT_LOCALE: Locale = "es";
|
|
|
|
interface LanguageContextType {
|
|
locale: Locale;
|
|
setLocale: (locale: Locale) => void;
|
|
}
|
|
|
|
const LanguageContext = createContext<LanguageContextType | undefined>(undefined);
|
|
|
|
export function LanguageProvider({ children }: { children: ReactNode }) {
|
|
const [locale, setLocaleState] = useState<Locale>(DEFAULT_LOCALE);
|
|
const [isHydrated, setIsHydrated] = useState(false);
|
|
|
|
// Load locale from localStorage on mount
|
|
useEffect(() => {
|
|
const stored = localStorage.getItem(LOCALE_STORAGE_KEY);
|
|
console.log("[useLanguage] Loading locale from localStorage:", stored);
|
|
if (stored && (stored === "es" || stored === "en" || stored === "ca")) {
|
|
console.log("[useLanguage] Setting locale to:", stored);
|
|
setLocaleState(stored as Locale);
|
|
} else {
|
|
console.log("[useLanguage] No valid stored locale, using default:", DEFAULT_LOCALE);
|
|
}
|
|
setIsHydrated(true);
|
|
}, []);
|
|
|
|
// Update HTML lang attribute when locale changes
|
|
useEffect(() => {
|
|
if (isHydrated) {
|
|
document.documentElement.lang = locale;
|
|
}
|
|
}, [locale, isHydrated]);
|
|
|
|
const setLocale = (newLocale: Locale) => {
|
|
setLocaleState(newLocale);
|
|
localStorage.setItem(LOCALE_STORAGE_KEY, newLocale);
|
|
document.documentElement.lang = newLocale;
|
|
};
|
|
|
|
return (
|
|
<LanguageContext.Provider value={{ locale, setLocale }}>{children}</LanguageContext.Provider>
|
|
);
|
|
}
|
|
|
|
export function useLanguage() {
|
|
const context = useContext(LanguageContext);
|
|
if (context === undefined) {
|
|
throw new Error("useLanguage must be used within a LanguageProvider");
|
|
}
|
|
return context;
|
|
}
|