"use client"; import { createContext, useCallback, useContext, useEffect, useMemo, useSyncExternalStore, type ReactNode, } from "react"; import { DEFAULT_LOCALE, LOCALE_EVENT_NAME, LOCALE_HTML_LANG, LOCALE_STORAGE_KEY, normalizeLocale, type Locale, } from "./config"; import { dictionaries, type Messages } from "./dictionaries"; /* -------------------------------------------------------------------------- */ /* Dot-path key typing */ /* -------------------------------------------------------------------------- */ /** * Recursively build the union of dot-separated leaf paths of the message * catalog, e.g. `"nav.chatAgent" | "sidebar.collapse" | ...`. This gives * `t()` callers autocomplete + compile-time protection against typos. */ type DotPaths = { [K in keyof T & string]: T[K] extends string ? K : `${K}.${DotPaths}`; }[keyof T & string]; export type MessageKey = DotPaths; /** Variables substituted into `{placeholder}` tokens. */ export type TranslateVars = Record; export type TranslateFn = (key: MessageKey, vars?: TranslateVars) => string; /* -------------------------------------------------------------------------- */ /* External store (localStorage-backed, SSR-safe) */ /* -------------------------------------------------------------------------- */ // In-module cache shared by every hook instance so we don't hit localStorage // on each render. `null` means "not yet hydrated". let cachedLocale: Locale | null = null; function readFromStorage(): Locale { if (cachedLocale !== null) return cachedLocale; if (typeof window === "undefined") { cachedLocale = DEFAULT_LOCALE; return cachedLocale; } try { cachedLocale = normalizeLocale( window.localStorage.getItem(LOCALE_STORAGE_KEY), ); } catch { cachedLocale = DEFAULT_LOCALE; } return cachedLocale; } function subscribe(notify: () => void): () => void { if (typeof window === "undefined") return () => {}; const handler = (event: Event) => { cachedLocale = normalizeLocale((event as CustomEvent).detail); notify(); }; // Cross-tab sync: `storage` events fire only in OTHER tabs/windows. const onStorage = (event: StorageEvent) => { if (event.key !== LOCALE_STORAGE_KEY) return; cachedLocale = normalizeLocale(event.newValue); notify(); }; window.addEventListener(LOCALE_EVENT_NAME, handler as EventListener); window.addEventListener("storage", onStorage); return () => { window.removeEventListener(LOCALE_EVENT_NAME, handler as EventListener); window.removeEventListener("storage", onStorage); }; } function getSnapshot(): Locale { return readFromStorage(); } // SSR always renders the default locale (matching ``); // React reconciles to the stored value during hydration. function getServerSnapshot(): Locale { return DEFAULT_LOCALE; } function writeLocale(next: Locale): void { cachedLocale = next; try { window.localStorage.setItem(LOCALE_STORAGE_KEY, next); } catch { // Ignore write errors (private mode, quota, etc.). } window.dispatchEvent(new CustomEvent(LOCALE_EVENT_NAME, { detail: next })); } /* -------------------------------------------------------------------------- */ /* Message resolution */ /* -------------------------------------------------------------------------- */ function resolvePath(dict: Messages, key: string): string | undefined { const value = key .split(".") .reduce( (acc, part) => acc && typeof acc === "object" && Object.prototype.hasOwnProperty.call(acc, part) ? (acc as Record)[part] : undefined, dict, ); return typeof value === "string" ? value : undefined; } function interpolate(template: string, vars?: TranslateVars): string { if (!vars) return template; return template.replace(/\{(\w+)\}/g, (match, name: string) => name in vars ? String(vars[name]) : match, ); } /* -------------------------------------------------------------------------- */ /* Context */ /* -------------------------------------------------------------------------- */ interface I18nContextValue { locale: Locale; setLocale: (next: Locale) => void; t: TranslateFn; } const I18nContext = createContext(null); export function LocaleProvider({ children }: { children: ReactNode }) { const locale = useSyncExternalStore( subscribe, getSnapshot, getServerSnapshot, ); // Keep the document language attribute in sync with the active locale. useEffect(() => { document.documentElement.lang = LOCALE_HTML_LANG[locale]; }, [locale]); const setLocale = useCallback((next: Locale) => { writeLocale(next); }, []); const t = useCallback( (key, vars) => { const dict = dictionaries[locale]; const template = resolvePath(dict, key) ?? // Fall back to the source-of-truth catalog, then the raw key, so a // missing translation degrades gracefully instead of rendering blank. resolvePath(dictionaries[DEFAULT_LOCALE], key) ?? key; return interpolate(template, vars); }, [locale], ); const value = useMemo( () => ({ locale, setLocale, t }), [locale, setLocale, t], ); return {children}; } /** * Access the active locale, a setter, and the `t()` translate function. * Must be called under a ``. */ export function useI18n(): I18nContextValue { const ctx = useContext(I18nContext); if (!ctx) { throw new Error("useI18n must be used within a "); } return ctx; } /** Convenience hook returning only the `t()` function. */ export function useTranslate(): TranslateFn { return useI18n().t; }