arbret/frontend/app/hooks/useLanguage.tsx
counterweight e35e79e84d
Fix date/time formatting to use es-ES locale
- Update all date/time formatting functions to use 'es-ES' locale instead of 'en-US' or 'de-DE'
- Update utility functions in utils/date.ts and utils/exchange.ts
- Update all component files that use date formatting
- Update e2e test helper to match new Spanish date format
- All formatting now uses Spanish locale regardless of selected language as per PR requirements
2025-12-26 11:38:17 +01:00

55 lines
1.6 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 }) {
// Start with default locale for SSR consistency
const [locale, setLocaleState] = useState<Locale>(DEFAULT_LOCALE);
const [isHydrated, setIsHydrated] = useState(false);
// Load locale from localStorage after hydration
useEffect(() => {
const stored = localStorage.getItem(LOCALE_STORAGE_KEY);
if (stored && (stored === "es" || stored === "en" || stored === "ca")) {
setLocaleState(stored as 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;
}