/* A small typed translator instead of a library. * * Two languages and a few hundred strings do not need i18next, and the * hand-written catalogue buys something i18next does not give by default: * a missing German string fails the build rather than falling back silently * to English in front of the user. * * If this ever needs plurals with real grammar, ICU MessageFormat or * react-i18next is the upgrade path and the call sites do not change shape. */ import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react"; import type { ReactNode } from "react"; import { de } from "./de"; import { en } from "./en"; import type { Catalogue, TranslationKey } from "./en"; export const LOCALES = ["de", "en"] as const; export type Locale = (typeof LOCALES)[number]; const CATALOGUES: Record = { de, en }; const STORAGE_KEY = "poorbird.locale"; /** Values substituted into `{placeholders}`. */ export type TranslationVars = Record; export type Translate = (key: TranslationKey, vars?: TranslationVars) => string; interface I18nValue { locale: Locale; setLocale: (locale: Locale) => void; t: Translate; } const I18nContext = createContext(null); function isLocale(value: unknown): value is Locale { return typeof value === "string" && (LOCALES as readonly string[]).includes(value); } function initialLocale(): Locale { try { const stored = localStorage.getItem(STORAGE_KEY); if (isLocale(stored)) return stored; } catch { // Private mode or blocked storage. Fall through to the browser setting. } return navigator.language.toLowerCase().startsWith("de") ? "de" : "en"; } function interpolate(template: string, vars?: TranslationVars): string { if (!vars) return template; return template.replace(/\{(\w+)\}/g, (whole, name: string) => { const value = vars[name]; // Leaving the placeholder visible beats printing "undefined" at a user. return value === undefined ? whole : String(value); }); } export function I18nProvider({ children }: { children: ReactNode }) { const [locale, setLocaleState] = useState(initialLocale); useEffect(() => { document.documentElement.lang = locale; try { localStorage.setItem(STORAGE_KEY, locale); } catch { // Not worth telling the user about; the choice just will not persist. } }, [locale]); const setLocale = useCallback((next: Locale) => setLocaleState(next), []); const t = useCallback( (key, vars) => interpolate(CATALOGUES[locale][key], vars), [locale] ); const value = useMemo(() => ({ locale, setLocale, t }), [locale, setLocale, t]); return {children}; } export function useI18n(): I18nValue { const value = useContext(I18nContext); if (value === null) { throw new Error("useI18n must be used inside "); } return value; } /** Shorthand for the common case: `const t = useT()`. */ export function useT(): Translate { return useI18n().t; }