Add a Swedish interface with a per-person language switch

A small translation system (the English text is its own key, so anything
without a Swedish entry stays English) and a Language switch in the user menu,
saved on the account (users.language) and following the browser when no choice
has been made. Swedish covers the menu, shared parts (search, tables, dialogs,
relative times), the sign-in page and the everyday pages: Dashboard, Alerts,
Servers, Updates, Maintenance, My work, Coming up, To do, Integrations and the
display settings. Server-written messages stay English for now.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-12 21:49:49 +01:00
1 parent e7f23ba13f
commit 645816d5a8
168 files changed
+12142 -1422

No files matched your search

+3 -3
View File
@@ -81,9 +81,9 @@ describe("links, targets and names", () => {
});
test("the controls the sweep found without a name have one", () => {
assert.match(web("pages", "Alerts.tsx"), /aria-label="Severity"/);
assert.match(web("pages", "Alerts.tsx"), /aria-label="Kind of alert"/);
assert.match(web("pages", "Secrets.tsx"), /aria-label="Status"/);
assert.match(web("pages", "Alerts.tsx"), /aria-label=\{t\("Severity"\)\}/);
assert.match(web("pages", "Alerts.tsx"), /aria-label=\{t\("Kind of alert"\)\}/);
assert.match(web("pages", "Secrets.tsx"), /aria-label=\{t\("Status"\)\}/);
assert.match(web("pages", "Users.tsx"), /aria-label=\{`Role of \$\{u\.name \?\? u\.email \?\? "this user"\}`\}/);
});
+154
View File
@@ -0,0 +1,154 @@
/**
* The Swedish interface: how a text is looked up and filled in, that the Swedish keeps the placeholders of the English, that every page of the menu has its Swedish name, and the
* account setting that remembers a person's language.
*
* Run with: npm test --workspace server
*/
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { AddressInfo } from "node:net";
import type { Server } from "node:http";
const dir = mkdtempSync(join(tmpdir(), "hm-lang-"));
process.env.DATABASE_PATH = join(dir, "test.sqlite");
process.env.SESSION_DIR = join(dir, "sessions");
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
process.env.HEALTH_STARTUP_GRACE_MS = "0";
const express = (await import("express")).default;
const { db } = await import("../src/db/client.js");
const { users } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { meRouter, parseLanguage, LANGUAGES } = await import("../src/routes/me.js");
const i18n = await import("../../web/src/i18n/index.js");
const { sv } = await import("../../web/src/i18n/sv.js");
const { formatAgo } = await import("../../web/src/utils/duration.js");
const { eq } = await import("drizzle-orm");
await runMigrations();
const placeholders = (s: string) => [...s.matchAll(/\{(\w+)\}/g)].map((m) => m[1]).sort();
describe("looking a text up", () => {
test("English is the text as written; Swedish is its entry, or the English when there is none", () => {
assert.equal(i18n.translate("en", "Save"), "Save");
assert.equal(i18n.translate("sv", "Save"), "Spara");
assert.equal(i18n.translate("sv", "A text nobody has translated yet"), "A text nobody has translated yet");
});
test("{placeholders} are filled in, and one with no value is left as it is", () => {
assert.equal(i18n.translate("en", "Page {page} of {pages} ({total} total)", { page: 2, pages: 5, total: 90 }), "Page 2 of 5 (90 total)");
assert.equal(i18n.translate("sv", "Page {page} of {pages} ({total} total)", { page: 2, pages: 5, total: 90 }), "Sida 2 av 5 (90 totalt)");
assert.equal(i18n.fill("Hello {name}, {missing}", { name: "Ada" }), "Hello Ada, {missing}");
assert.equal(i18n.fill("No placeholders"), "No placeholders");
});
test("the language in use decides t(), tn() and the formats; the tests start in English whatever the machine is set to", () => {
assert.equal(i18n.getLanguage(), "en", "no window, no browser language to follow");
assert.equal(i18n.t("Cancel"), "Cancel");
assert.equal(i18n.tn(1, "{n} active alert", "{n} active alerts"), "1 active alert");
assert.equal(i18n.tn(3, "{n} active alert", "{n} active alerts"), "3 active alerts");
assert.equal(i18n.locale(), "en");
i18n.setLanguage("sv", false);
try {
assert.equal(i18n.t("Cancel"), "Avbryt");
assert.equal(i18n.tn(1, "{n} active alert", "{n} active alerts"), "1 aktivt larm");
assert.equal(i18n.tn(3, "{n} active alert", "{n} active alerts"), "3 aktiva larm");
assert.equal(i18n.locale(), "sv-SE");
assert.equal(formatAgo(new Date(Date.now() - 5 * 60_000).toISOString()), "för 5 min sedan", "relative times are in the language too");
assert.equal(formatAgo(new Date().toISOString()), "nyss");
} finally {
i18n.setLanguage("en", false);
}
assert.equal(formatAgo(new Date(Date.now() - 5 * 60_000).toISOString()), "5 min ago");
});
});
describe("the Swedish text", () => {
test("keeps the placeholders of the English, no more and no fewer", () => {
const wrong = Object.entries(sv).filter(([en, swedish]) => placeholders(en).join() !== placeholders(swedish).join());
assert.deepEqual(wrong.map(([en]) => en), []);
});
test("has no empty text, and none that is the English left in", () => {
const empty = Object.entries(sv).filter(([, swedish]) => swedish.trim() === "");
assert.deepEqual(empty, []);
});
test("names every page of the menu", () => {
const source = readFileSync(new URL("../../web/src/layout/nav.tsx", import.meta.url), "utf8");
// The words that are the same in both languages (a brand, or a word Swedish borrows) are not asked for.
const SAME = new Set(["Proxmox", "Synology", "Docker", "Hetzner Cloud", "Hetzner Robot", "Tailscale", "Home Assistant", "Jellyfin", "Immich", "Paperless", "Nextcloud", "Authentik", "Duplicati", "DNS", "AdGuard Home", "Technitium DNS", "NetBox", "Uptime Kuma", "UPS", "Prometheus", "Grafana", "Speedtest", "Semaphore", "Gitea", "n8n", "osTicket", "Automation", "Generator", "Administration", "Info"]);
const labels = [...source.matchAll(/label: "([^"]+)"/g)].map((m) => m[1]).filter((l) => !SAME.has(l));
assert.ok(labels.length > 25, `found the menu's labels (${labels.length})`);
assert.deepEqual(labels.filter((l) => !(l in sv)), [], "labels with no Swedish name");
});
test("translates the words the app's own lists show (the ranges, the density, the task states)", () => {
for (const w of ["24 hours", "7 days", "30 days", "90 days", "1 year", "Compact", "Normal", "Roomy"]) assert.ok(w in sv, w);
});
});
describe("remembering a person's language", () => {
let app: Server;
let base = "";
let who = "ada";
const call = (method: string, path: string, body?: unknown) => fetch(`${base}${path}`, { method, headers: { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
before(async () => {
await db.insert(users).values([
{ oidcSub: "ada", name: "Ada", role: "admin" },
{ oidcSub: "bo", name: "Bo", role: "viewer" },
]);
const a = express();
a.use(express.json());
a.use((req, _res, next) => {
(req as unknown as { session: unknown }).session = { user: { sub: who } };
next();
});
a.use("/api/me", meRouter);
app = await new Promise<Server>((resolve) => {
const x = a.listen(0, "127.0.0.1", () => resolve(x));
});
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/me`;
});
after(() => {
app.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
test("what is stored is read back as a language, or as no choice", () => {
assert.deepEqual(LANGUAGES, ["en", "sv"]);
assert.equal(parseLanguage("sv"), "sv");
assert.equal(parseLanguage("en"), "en");
for (const odd of [null, undefined, "", "de", "SV", "sv-SE"]) assert.equal(parseLanguage(odd), null, String(odd));
});
test("nobody has chosen at first; each person's choice is theirs alone and follows them", async () => {
assert.equal((await (await call("GET", "/")).json()).user.language, null);
assert.equal((await call("PUT", "/language", { language: "sv" })).status, 200);
assert.equal((await (await call("GET", "/")).json()).user.language, "sv");
who = "bo";
assert.equal((await (await call("GET", "/")).json()).user.language, null, "someone else's choice does not reach them");
assert.equal((await call("PUT", "/language", { language: "en" })).status, 200);
assert.equal((await (await call("GET", "/")).json()).user.language, "en");
who = "ada";
assert.equal((await (await call("GET", "/")).json()).user.language, "sv", "and Ada's is still Swedish");
});
test("it can be taken back to following the browser, and nothing else is accepted", async () => {
assert.equal((await call("PUT", "/language", { language: null })).status, 200);
assert.equal((await (await call("GET", "/")).json()).user.language, null);
for (const bad of [{ language: "de" }, { language: "" }, { language: 5 }, {}, { lang: "sv" }]) assert.equal((await call("PUT", "/language", bad)).status, 400, JSON.stringify(bad));
const [row] = await db.select().from(users).where(eq(users.oidcSub, "ada"));
assert.equal(row.language, null);
});
});