use-i18n.tsx 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. 'use client';
  2. import { createContext, useContext, useEffect, ReactNode } from 'react';
  3. import { useTranslation } from 'react-i18next';
  4. import { type Locale, defaultLocale, supportedLocales } from '@/lib/i18n';
  5. import '@/lib/i18n/config';
  6. const LOCALE_STORAGE_KEY = 'locale';
  7. /** Match a browser language code (e.g. 'en', 'zh-TW') to a supported locale */
  8. function resolveLocale(lang: string): Locale {
  9. // Exact match
  10. const exact = supportedLocales.find((l) => l.code === lang);
  11. if (exact) return exact.code;
  12. // Prefix match: 'en' → 'en-US', 'zh' → 'zh-CN'
  13. const prefix = lang.split('-')[0].toLowerCase();
  14. const match = supportedLocales.find((l) => l.code.toLowerCase().startsWith(prefix));
  15. return match?.code ?? defaultLocale;
  16. }
  17. type I18nContextType = {
  18. locale: Locale;
  19. setLocale: (locale: Locale) => void;
  20. t: (key: string, options?: Record<string, unknown>) => string;
  21. };
  22. const I18nContext = createContext<I18nContextType | undefined>(undefined);
  23. export function I18nProvider({ children }: { children: ReactNode }) {
  24. const { t, i18n } = useTranslation();
  25. const locale = (i18n.language || defaultLocale) as Locale;
  26. // Detect language after hydration to avoid SSR mismatch.
  27. // i18next handles fallback automatically: if the detected language
  28. // has no matching JSON file, it falls back to fallbackLng.
  29. useEffect(() => {
  30. try {
  31. const stored = localStorage.getItem(LOCALE_STORAGE_KEY);
  32. const raw = stored || navigator.language || defaultLocale;
  33. const target = resolveLocale(raw);
  34. if (target !== i18n.language) i18n.changeLanguage(target);
  35. } catch {
  36. // localStorage unavailable, keep default
  37. }
  38. }, []); // eslint-disable-line react-hooks/exhaustive-deps
  39. const setLocale = (newLocale: Locale) => {
  40. i18n.changeLanguage(newLocale);
  41. try {
  42. localStorage.setItem(LOCALE_STORAGE_KEY, newLocale);
  43. } catch {
  44. // localStorage unavailable
  45. }
  46. };
  47. return <I18nContext.Provider value={{ locale, setLocale, t }}>{children}</I18nContext.Provider>;
  48. }
  49. export function useI18n() {
  50. const context = useContext(I18nContext);
  51. if (!context) {
  52. throw new Error('useI18n must be used within I18nProvider');
  53. }
  54. return context;
  55. }