Add an English/Czech interface language switch

English stays the default; Czech is a full translation. Only the app chrome
is translated - notes and generated decks keep their own language, which is a
core feature, not a setting.

i18n
- lib/i18n-dict.ts: flat en/cs dictionaries (441 keys each), translate() and
  translatePlural() with real Czech plural rules (1 sada / 2-4 sady / 5+ sad).
  English is the default and the fallback for a missing key.
- lib/i18n.ts: browser store (freezmo.locale.v1), useI18n() hook, and the
  x-freezmo-locale header. The hook's t/plural are bound to the locale React
  is rendering with, so the first client render matches the server HTML and
  then re-renders in the stored language; module-level t is only for event
  handlers and non-React helpers.
- <html lang> follows the choice (inline script + setLocale).

UI
- Settings -> Language segmented control (English / Cestina), plus an EN/CS
  button on the key gate for first run.
- Every screen translated: sidebar, header, tab bar, library, deck cards,
  folder bar, create flow, all seven activities, study chrome, results,
  settings + health panel, API-key gate and help, install sheet, offline and
  the deck-not-found page.
- Plural-aware counts everywhere (decks, folders, activities, runs, photos,
  documents, pages, words, wrong attempts).

Server
- API routes and guards (generate, grade, health, http-guard, rate-limit,
  ollama error mapping) answer in the request's language, so error cards and
  the health panel never fall back to English mid-sentence.

Fixes
- A hydration mismatch when a non-default locale was stored silently dropped
  the .dark class after hydration; render-time t() is now bound to the
  hook's locale (UploadScreen.describeExtraction, ResultsScreen.answerFor,
  DeckCard's folder fallback).
- Bumped the service worker cache to freezmo-v4 for this deploy.

Tests: i18n 27/27 (gate toggle, persistence, html lang, Czech plurals,
settings switch) and a rebuilt regression suite 72/72 (English default,
library, create, all 7 activity types, results, settings, install sheet,
offline, PWA, security, Czech smoke).
This commit is contained in:
Martin Dvořák 2026-10-08 13:56:32 +00:00
commit 618ad5fb9c
42 changed files with 1892 additions and 509 deletions

View file

@ -1,5 +1,6 @@
"use client";
import { localeHeader, t } from "./i18n";
import type { Activity, Difficulty } from "./schemas";
import { API_KEY_HEADER, authHeaders } from "./settings";
@ -55,23 +56,23 @@ export async function generateDeck(
try {
response = await fetch("/api/generate", {
method: "POST",
headers: { "Content-Type": "application/json", ...authHeaders() },
headers: { "Content-Type": "application/json", ...authHeaders(), ...localeHeader() },
body: JSON.stringify(input),
signal: options.signal,
});
} catch (error) {
if (error instanceof Error && error.name === "AbortError") {
throw new ApiError("Generation was cancelled.", "aborted");
throw new ApiError(t("api.cancelled"), "aborted");
}
throw new ApiError("Could not reach the Freezmo server. Is it still running?", "network");
throw new ApiError(t("api.unreachable"), "network");
}
if (!response.ok) {
const body = (await response.json().catch(() => null)) as { error?: string; kind?: string } | null;
throw new ApiError(body?.error ?? `The server returned HTTP ${response.status}.`, body?.kind);
throw new ApiError(body?.error ?? t("api.httpError", { status: response.status }), body?.kind);
}
if (!response.body) {
throw new ApiError("The server sent an empty response.", "bad_response");
throw new ApiError(t("api.empty"), "bad_response");
}
const reader = response.body.getReader();
@ -96,7 +97,7 @@ export async function generateDeck(
deck = event.deck;
meta = event.meta ?? {};
sawActivity = true;
options.onProgress?.({ stage: "done", message: "Almost there…" });
options.onProgress?.({ stage: "done", message: t("api.almost") });
} else if (event.type === "error") {
streamError = new ApiError(event.error, event.kind);
}
@ -119,8 +120,8 @@ export async function generateDeck(
if (!deck) {
throw new ApiError(
sawActivity
? "The server finished without sending a deck."
: "No deck came back from the server. Check your Ollama settings and try again.",
? t("api.incomplete")
: t("api.noDeck"),
"bad_response",
);
}
@ -129,7 +130,7 @@ export async function generateDeck(
(activity) => activity && typeof activity.type === "string" && typeof activity.id === "string",
);
if (!valid || valid.length === 0) {
throw new ApiError("The generated deck had no usable activities. Try again.", "bad_response");
throw new ApiError(t("api.noActivities"), "bad_response");
}
return { deck: { ...(deck as StreamedDeck), activities: valid }, meta };
@ -147,15 +148,15 @@ export async function gradeAnswer(input: {
try {
response = await fetch("/api/grade", {
method: "POST",
headers: { "Content-Type": "application/json", ...authHeaders() },
headers: { "Content-Type": "application/json", ...authHeaders(), ...localeHeader() },
body: JSON.stringify(input),
signal: input.signal,
});
} catch (error) {
if (error instanceof Error && error.name === "AbortError") {
throw new ApiError("Grading was cancelled.", "aborted");
throw new ApiError(t("api.gradingCancelled"), "aborted");
}
throw new ApiError("Could not reach the Freezmo server.", "network");
throw new ApiError(t("api.unreachableShort"), "network");
}
const body = (await response.json().catch(() => null)) as
@ -163,7 +164,7 @@ export async function gradeAnswer(input: {
| null;
if (!response.ok || !body || body.error) {
throw new ApiError(body?.error ?? `Grading failed with HTTP ${response.status}.`, body?.kind);
throw new ApiError(body?.error ?? t("api.gradingFailed", { status: response.status }), body?.kind);
}
return {
@ -202,21 +203,21 @@ export type Health = {
export async function fetchHealth(): Promise<Health> {
let response: Response;
try {
response = await fetch("/api/health", { cache: "no-store", headers: authHeaders() });
response = await fetch("/api/health", { cache: "no-store", headers: { ...authHeaders(), ...localeHeader() } });
} catch {
throw new ApiError("Could not reach the Freezmo server.", "network");
throw new ApiError(t("api.unreachableShort"), "network");
}
const body = (await response.json().catch(() => null)) as (Partial<Health> & { error?: string; kind?: string }) | null;
if (!response.ok) {
throw new ApiError(
body?.error ?? `The health check failed with HTTP ${response.status}.`,
body?.error ?? t("api.healthFailed", { status: response.status }),
body?.kind ?? "http",
);
}
// Guard against anything that isn't a health payload (e.g. a proxy error
// page) so consumers can rely on the shape.
if (!body || typeof body !== "object" || !body.vision || !body.text) {
throw new ApiError("The Freezmo server sent an unexpected health response.", "bad_response");
throw new ApiError(t("api.healthUnexpected"), "bad_response");
}
return body as Health;
}
@ -237,12 +238,12 @@ export async function verifyOllamaKey(apiKey: string): Promise<KeyCheck> {
try {
response = await fetch("/api/health", {
cache: "no-store",
headers: { [API_KEY_HEADER]: apiKey },
headers: { [API_KEY_HEADER]: apiKey, ...localeHeader() },
});
} catch {
return {
result: "offline",
message: "Could not reach the Freezmo server. Is it still running?",
message: t("api.unreachable"),
};
}
@ -250,7 +251,7 @@ export async function verifyOllamaKey(apiKey: string): Promise<KeyCheck> {
if (!response.ok || !body) {
return {
result: "offline",
message: "The Freezmo server answered unexpectedly. Try again in a moment.",
message: t("api.serverUnexpected"),
};
}
@ -258,8 +259,7 @@ export async function verifyOllamaKey(apiKey: string): Promise<KeyCheck> {
return {
result: "invalid",
message:
body.error ??
"Ollama rejected this key. Check for typos, or create a new one at ollama.com/settings/keys.",
body.error ?? t("api.keyRejected"),
};
}
if (body.keyAccepted === true) return { result: "valid" };
@ -268,7 +268,7 @@ export async function verifyOllamaKey(apiKey: string): Promise<KeyCheck> {
return {
result: "offline",
message:
body.error ?? "Couldn't reach Ollama just now. Check your connection and try again.",
body.error ?? t("api.ollamaUnreachable"),
};
}

View file

@ -6,6 +6,7 @@
*/
import { sanitiseApiKey } from "./http-guard";
import { translate, type Locale } from "./i18n-dict";
export type AuthMode = "user-key" | "server" | "local";
@ -103,15 +104,16 @@ export function getServerConfig(): ServerConfig {
* Human-readable explanation for every auth configuration problem, so the UI
* never has to show a bare "unauthorised".
*/
export const AUTH_ERROR_MESSAGES: Record<"missing_key" | "server_key_missing" | "local_with_cloud_url", string> = {
missing_key:
"Add your Ollama API key first — open the settings dialog (⚙️) and paste a key from ollama.com/settings/keys.",
server_key_missing:
"This server is configured to use its own Ollama API key (OLLAMA_AUTH=server), but OLLAMA_API_KEY is empty in .env.local.",
local_with_cloud_url:
"This server is set to OLLAMA_AUTH=local but points at https://ollama.com. A signed-in local daemon can't be used against the cloud URL — either set OLLAMA_AUTH=user-key, or point OLLAMA_BASE_URL at http://localhost:11434.",
const AUTH_ERROR_KEYS: Record<"missing_key" | "server_key_missing" | "local_with_cloud_url", string> = {
missing_key: "server.authMissingKey",
server_key_missing: "server.authServerKeyMissing",
local_with_cloud_url: "server.authLocalCloud",
};
export function authErrorMessage(locale: Locale, error: keyof typeof AUTH_ERROR_KEYS): string {
return translate(locale, AUTH_ERROR_KEYS[error]);
}
export function authErrorKind(error: "missing_key" | "server_key_missing" | "local_with_cloud_url"): string {
if (error === "missing_key") return "needs_key";
return "config";

View file

@ -14,6 +14,7 @@
* to the API routes. Photos uploaded as images keep working exactly as before.
*/
import { t } from "./i18n";
import { prepareImageFromBlob, type PreparedImage } from "./image";
export const MAX_DOCUMENT_BYTES = 40 * 1024 * 1024; // 40 MB per file
@ -114,10 +115,10 @@ export function isDocumentFile(file: File): boolean {
export function describeDocumentError(file: File): string | null {
if (!isDocumentFile(file)) {
return `"${file.name}" is not a supported document (use PDF, DOCX, PPTX, ODT/ODP or text).`;
return t("file.notDocument", { name: file.name });
}
if (file.size > MAX_DOCUMENT_BYTES) {
return `"${file.name}" is larger than 40 MB.`;
return t("file.documentTooLarge", { name: file.name });
}
return null;
}
@ -224,7 +225,7 @@ async function extractPdf(
for (let pageNumber = 1; pageNumber <= totalPages; pageNumber++) {
onProgress?.({
message: `Reading page ${pageNumber} of ${totalPages}…`,
message: t("doc.readingPage", { n: pageNumber, total: totalPages }),
progress: pageNumber / totalPages,
});
@ -452,16 +453,16 @@ export async function extractDocument(
case "pdf":
return extractPdf(file, onProgress);
case "docx":
onProgress?.({ message: "Reading the Word document…" });
onProgress?.({ message: t("doc.readingWord") });
return extractDocx(file);
case "pptx":
onProgress?.({ message: "Reading the slides…" });
onProgress?.({ message: t("doc.readingSlides") });
return extractOoxmlPackage(file, "pptx");
case "opendocument":
onProgress?.({ message: "Reading the OpenDocument file…" });
onProgress?.({ message: t("doc.readingOpen") });
return extractOoxmlPackage(file, "opendocument");
case "text":
onProgress?.({ message: "Reading the text file…" });
onProgress?.({ message: t("doc.readingText") });
return extractPlainText(file);
}
}

View file

@ -8,6 +8,7 @@
* never persisted — it is simply every deck with no `folderId`.
*/
import { t } from "./i18n";
import { folderSchema, UNORGANIZED_ID, type Folder } from "./schemas";
import { uid } from "./utils";
@ -99,8 +100,8 @@ export function getFolder(id: string | undefined): Folder | undefined {
}
export function folderName(id: string | undefined): string {
if (!id || id === UNORGANIZED_ID) return "Unorganized";
return getFolder(id)?.name ?? "Unorganized";
if (!id || id === UNORGANIZED_ID) return t("common.unorganized");
return getFolder(id)?.name ?? t("common.unorganized");
}
export function findFolderByName(name: string): Folder | undefined {
@ -111,8 +112,8 @@ export function findFolderByName(name: string): Folder | undefined {
/** Case-insensitive uniqueness; returns the existing folder when it matches. */
export function createFolder(name: string): { folder: Folder } | { error: string } {
const trimmed = name.trim().replace(/\s+/g, " ");
if (!trimmed) return { error: "Give the folder a name." };
if (trimmed.length > 60) return { error: "That name is a bit long (60 characters max)." };
if (!trimmed) return { error: t("folder.nameRequired") };
if (trimmed.length > 60) return { error: t("folder.nameTooLong") };
const existing = findFolderByName(trimmed);
if (existing) return { folder: existing };
@ -125,11 +126,11 @@ export function createFolder(name: string): { folder: Folder } | { error: string
export function renameFolder(id: string, name: string): { ok: true } | { error: string } {
const trimmed = name.trim().replace(/\s+/g, " ");
if (!trimmed) return { error: "Give the folder a name." };
if (!trimmed) return { error: t("folder.nameRequired") };
const clash = folderStore
.getSnapshot()
.find((folder) => folder.id !== id && folder.name.trim().toLowerCase() === trimmed.toLowerCase());
if (clash) return { error: "Another folder already has that name." };
if (clash) return { error: t("folder.nameTaken") };
ensureLoaded();
write(folderStore.getSnapshot().map((folder) => (folder.id === id ? { ...folder, name: trimmed } : folder)));

View file

@ -1,3 +1,5 @@
import { LOCALE_HEADER, normaliseLocale, translate } from "./i18n-dict";
/**
* Small server-side guards shared by the API routes.
*
@ -6,6 +8,11 @@
* bodies exhausting memory, and (c) odd values ending up in outbound headers.
*/
/** The language this request asked for (browsers send x-freezmo-locale). */
export function requestLocale(request: Request) {
return normaliseLocale(request.headers.get(LOCALE_HEADER));
}
function formatBytes(bytes: number): string {
if (bytes < 1024 * 1024) return `${Math.max(1, Math.round(bytes / 1024))} KB`;
return `${(bytes / 1024 / 1024).toFixed(bytes < 10 * 1024 * 1024 ? 1 : 0)} MB`;
@ -19,7 +26,10 @@ export function rejectOversizedBody(request: Request, maxBytes: number): Respons
if (Number.isFinite(length) && length > maxBytes) {
return Response.json(
{
error: `Request body is too large (${formatBytes(length)}). Limit is ${formatBytes(maxBytes)}.`,
error: translate(requestLocale(request), "server.bodyTooLarge", {
size: formatBytes(length),
limit: formatBytes(maxBytes),
}),
kind: "too_large",
},
{ status: 413 },
@ -46,7 +56,10 @@ export function rejectCrossOrigin(request: Request): Response | null {
try {
originHost = new URL(origin).host;
} catch {
return Response.json({ error: "Invalid Origin header.", kind: "forbidden" }, { status: 403 });
return Response.json(
{ error: translate(requestLocale(request), "server.invalidOrigin"), kind: "forbidden" },
{ status: 403 },
);
}
const host = request.headers.get("host");
@ -62,7 +75,7 @@ export function rejectCrossOrigin(request: Request): Response | null {
if (loopback.has(bare(originHost)) && loopback.has(bare(host ?? ""))) return null;
return Response.json(
{ error: "Cross-origin requests are not allowed.", kind: "forbidden" },
{ error: translate(requestLocale(request), "server.crossOrigin"), kind: "forbidden" },
{ status: 403 },
);
}

1093
lib/i18n-dict.ts Normal file

File diff suppressed because it is too large Load diff

127
lib/i18n.ts Normal file
View file

@ -0,0 +1,127 @@
"use client";
/**
* Browser-side locale store + React bindings.
*
* English is the default and the source of truth; Czech is a full translation.
* Only *interface* copy lives in the dictionaries — your notes and the generated
* decks always keep their own language (that is a core feature, not a setting).
*
* The dictionaries themselves live in ./i18n-dict so the server can translate
* its API messages into the same language.
*/
import { useSyncExternalStore } from "react";
import {
DEFAULT_LOCALE,
LOCALE_HEADER,
LOCALES,
normaliseLocale,
translate,
translatePlural,
type Locale,
type Vars,
} from "./i18n-dict";
export { LOCALES, DEFAULT_LOCALE, LOCALE_HEADER, translate, translatePlural };
export type { Locale };
const STORAGE_KEY = "freezmo.locale.v1";
let cached: Locale | null = null;
const listeners = new Set<() => void>();
function read(): Locale {
if (typeof window === "undefined") return DEFAULT_LOCALE;
try {
return normaliseLocale(window.localStorage.getItem(STORAGE_KEY));
} catch {
return DEFAULT_LOCALE;
}
}
function emit(): void {
listeners.forEach((listener) => listener());
}
export const localeStore = {
subscribe(listener: () => void): () => void {
listeners.add(listener);
const onStorage = (event: StorageEvent) => {
if (event.key === STORAGE_KEY) {
cached = read();
emit();
}
};
window.addEventListener("storage", onStorage);
return () => {
listeners.delete(listener);
window.removeEventListener("storage", onStorage);
};
},
getSnapshot(): Locale {
if (cached === null) cached = read();
return cached;
},
getServerSnapshot(): Locale {
return DEFAULT_LOCALE;
},
};
export function getLocale(): Locale {
return localeStore.getSnapshot();
}
export function setLocale(locale: Locale): void {
cached = normaliseLocale(locale);
try {
window.localStorage.setItem(STORAGE_KEY, cached);
} catch {
/* private mode */
}
try {
document.documentElement.lang = cached;
} catch {
/* SSR */
}
emit();
}
/** React hook: re-renders when the locale changes. */
export function useLocale(): Locale {
return useSyncExternalStore(localeStore.subscribe, localeStore.getSnapshot, localeStore.getServerSnapshot);
}
/** Translate a key for the current locale. */
export function t(key: string, vars?: Vars): string {
return translate(localeStore.getSnapshot(), key, vars);
}
/** Plural-aware translate for the current locale. */
export function plural(n: number, base: string, vars?: Vars): string {
return translatePlural(localeStore.getSnapshot(), n, base, vars);
}
/** Header handed to our own API routes so they answer in the chosen language. */
export function localeHeader(): Record<string, string> {
return { [LOCALE_HEADER]: localeStore.getSnapshot() };
}
/**
* Convenience hook for components.
*
* `t` / `plural` are bound to the locale React is currently rendering with
* (the server snapshot during hydration, then the stored choice), so the first
* client render always matches the server HTML. Use the module-level `t` only
* in event handlers and non-React helpers.
*/
export function useI18n() {
const locale = useLocale();
return {
locale,
setLocale,
t: (key: string, vars?: Vars) => translate(locale, key, vars),
plural: (n: number, base: string, vars?: Vars) => translatePlural(locale, n, base, vars),
};
}

View file

@ -1,5 +1,7 @@
"use client";
import { t } from "./i18n";
/** Client-side image helpers: validation, resizing and compression. */
export const MAX_IMAGE_DIMENSION = 1600;
@ -23,8 +25,8 @@ export function isImageFile(file: File): boolean {
}
export function describeFileError(file: File): string | null {
if (!isImageFile(file)) return `"${file.name}" is not an image.`;
if (file.size > MAX_FILE_BYTES) return `"${file.name}" is larger than 20 MB.`;
if (!isImageFile(file)) return t("file.notImage", { name: file.name });
if (file.size > MAX_FILE_BYTES) return t("file.imageTooLarge", { name: file.name });
return null;
}

View file

@ -9,6 +9,7 @@
* This module must only ever be imported from server code (route handlers).
*/
import { DEFAULT_LOCALE, translate, type Locale } from "./i18n-dict";
import { getServerConfig, resolveModelName, type OllamaAuth } from "./config";
export type OllamaMessage = {
@ -41,25 +42,31 @@ export class OllamaError extends Error {
}
}
export function friendlyErrorMessage(error: unknown, baseUrl?: string): string {
export function friendlyErrorMessage(
error: unknown,
baseUrl?: string,
locale: Locale = DEFAULT_LOCALE,
): string {
if (error instanceof OllamaError) {
switch (error.kind) {
case "unreachable":
return `Ollama isn't reachable at ${baseUrl ?? "the configured URL"}. Check your settings and make sure the daemon is running.`;
return translate(locale, "server.ollamaUnreachable", {
url: baseUrl ?? "the configured URL",
});
case "timeout":
return "Ollama took too long to answer. Try fewer/smaller images, a faster model, or retry.";
return translate(locale, "server.ollamaTimeout");
case "auth":
return "Ollama rejected the request. If you are using https://ollama.com, check OLLAMA_API_KEY (create one at ollama.com/settings/keys).";
return translate(locale, "server.ollamaAuth");
case "no_credits":
return error.message;
case "model_missing":
return error.message;
default:
return error.message || "Ollama returned an unexpected response.";
return error.message || translate(locale, "server.ollamaUnexpected");
}
}
if (error instanceof Error) return error.message;
return "Something went wrong while talking to Ollama.";
return translate(locale, "server.ollamaGeneric");
}
type ChatOptions = {

View file

@ -7,6 +7,7 @@
* share state with others — fine for Freezmo, documented in the README.
*/
import { DEFAULT_LOCALE, translate, type Locale } from "./i18n-dict";
type Hits = { timestamps: number[] };
/**
@ -86,12 +87,10 @@ export function clientKey(request: Request): string {
);
}
export function rateLimitResponse(result: RateLimitResult, message?: string): Response {
export function rateLimitResponse(result: RateLimitResult, locale: Locale = DEFAULT_LOCALE): Response {
return Response.json(
{
error:
message ??
`Too many requests — this app allows ${result.limit} per window. Try again in ${result.retryAfter}s.`,
error: translate(locale, "server.rateLimited", { limit: result.limit, retry: result.retryAfter }),
kind: "rate_limited",
retryAfter: result.retryAfter,
},

View file

@ -5,6 +5,7 @@
* Exposes a tiny observable store so every screen stays in sync.
*/
import { t } from "./i18n";
import { deckSchema, UNORGANIZED_ID, type Activity, type Deck } from "./schemas";
import { createFolder, findFolderByName, getFolder, removeFolder } from "./folders";
import { uid } from "./utils";
@ -224,7 +225,7 @@ export function importDeck(raw: string): { deck: Deck } | { error: string } {
try {
parsed = JSON.parse(raw);
} catch {
return { error: "That file is not valid JSON." };
return { error: t("import.notJson") };
}
const bundle = parsed && typeof parsed === "object" && "deck" in parsed ? (parsed as { folder?: unknown }) : null;
@ -232,7 +233,7 @@ export function importDeck(raw: string): { deck: Deck } | { error: string } {
const result = deckSchema.safeParse(candidate);
if (!result.success) {
return { error: "That file doesn't look like a Freezmo deck." };
return { error: t("import.notDeck") };
}
// Recreate the exported folder (or reuse an existing one with the same name).

View file

@ -1,5 +1,6 @@
"use client";
import { t } from "./i18n";
import { useCallback, useEffect, useState, useSyncExternalStore } from "react";
import { fetchHealth, type Health } from "./client-api";
@ -25,7 +26,7 @@ export function useHealth() {
try {
setHealth(await fetchHealth());
} catch (loadError) {
setError(loadError instanceof Error ? loadError.message : "Could not reach the Freezmo server.");
setError(loadError instanceof Error ? loadError.message : t("api.unreachableShort"));
} finally {
setLoading(false);
}