Files
Hello/web/src/i18n/I18nProvider.tsx
T
Thomas KarnerandClaude Opus 5 384b09371a UI: scaffold the web app - shell, themes, i18n, auth plumbing
React 19 + TypeScript + Vite + TanStack Query/Router in web/, built on the
dev machine and shipped as static files (SPEC section 6). Typechecks and
builds clean; the System page reads live /health through the Vite proxy,
which proves browser -> proxy -> FastAPI -> PostgreSQL end to end.

Themes: light, dark and blue (dark navy), as design tokens on data-theme.
An inline script applies the stored theme before first paint. No colour
literal lives outside tokens.css.

check-contrast.mjs asserts WCAG AA for every text/background pair in every
theme, with no dependencies. It failed on its first run and found three
--border-strong values below the 3:1 that WCAG 1.4.11 wants for interactive
boundaries; all three are fixed and 36 pairs now pass. Colour contrast is
the classic silently-regressing property, so it gets a test rather than a
promise.

i18n is hand-written and typed rather than react-i18next: en.ts defines the
key set, de.ts is typed against it, so a missing German string fails the
build instead of quietly showing English to a German user.

Authentication is built but NOT enforced, deliberately. /auth/session,
/auth/login and /auth/logout do not exist yet, so router.tsx does not wrap
routes in RequireAuth and a banner says so plainly. There is no development
bypass: a bypass that works is the kind of code that survives into
production, and an auth bypass that works is the worst possible bug.

Gallery and Devices render honest empty states rather than mock rows. Fake
data hides the layout problems real data exposes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 01:17:07 +02:00

97 lines
3.0 KiB
TypeScript

/* 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<Locale, Catalogue> = { de, en };
const STORAGE_KEY = "poorbird.locale";
/** Values substituted into `{placeholders}`. */
export type TranslationVars = Record<string, string | number>;
export type Translate = (key: TranslationKey, vars?: TranslationVars) => string;
interface I18nValue {
locale: Locale;
setLocale: (locale: Locale) => void;
t: Translate;
}
const I18nContext = createContext<I18nValue | null>(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<Locale>(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<Translate>(
(key, vars) => interpolate(CATALOGUES[locale][key], vars),
[locale]
);
const value = useMemo<I18nValue>(() => ({ locale, setLocale, t }), [locale, setLocale, t]);
return <I18nContext value={value}>{children}</I18nContext>;
}
export function useI18n(): I18nValue {
const value = useContext(I18nContext);
if (value === null) {
throw new Error("useI18n must be used inside <I18nProvider>");
}
return value;
}
/** Shorthand for the common case: `const t = useT()`. */
export function useT(): Translate {
return useI18n().t;
}