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:
1 parent
e7f23ba13f
commit
645816d5a8
168 files changed
+12142
-1422
No files matched your search
@@ -0,0 +1 @@
|
||||
ALTER TABLE `users` ADD `language` text;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -666,6 +666,13 @@
|
||||
"when": 1794350837756,
|
||||
"tag": "0094_integration_figures",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 95,
|
||||
"version": "6",
|
||||
"when": 1794514473426,
|
||||
"tag": "0095_user_language",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -32,6 +32,8 @@ export const users = sqliteTable("users", {
|
||||
// The address of the picture the identity provider gave for this person (the OIDC "picture" claim), as of their last sign-in. Only an address:
|
||||
// nothing is fetched from it unless Settings → Sign-in → Profile pictures allows it, and then only by this server, never by the browser.
|
||||
pictureUrl: text("picture_url"),
|
||||
// The language this person chose for the interface: "en" or "sv". Null: they have not chosen, so the browser's language decides. Follows them to any browser.
|
||||
language: text("language"),
|
||||
});
|
||||
|
||||
// ─── Audit log ──────────────────────────────────────────────────────────────
|
||||
|
||||
+17
-2
@@ -11,6 +11,13 @@ import { getSettings } from "../services/settingsStore.js";
|
||||
|
||||
export const meRouter = Router();
|
||||
|
||||
/** The languages the interface is written in. */
|
||||
export const LANGUAGES = ["en", "sv"] as const;
|
||||
export type Language = (typeof LANGUAGES)[number];
|
||||
|
||||
/** What is stored, read back as a language; anything else is "no choice yet". */
|
||||
export const parseLanguage = (stored: string | null | undefined): Language | null => (LANGUAGES as readonly string[]).includes(stored ?? "") ? (stored as Language) : null;
|
||||
|
||||
/** The most pages anyone can pin: enough for a working set, not a second menu. */
|
||||
export const MAX_FAVORITES = 24;
|
||||
|
||||
@@ -40,9 +47,9 @@ export function parseDashboardLayout(stored: string | null): DashboardLayout {
|
||||
|
||||
meRouter.get("/", requireAuth, asyncHandler(async (req, res) => {
|
||||
const me = req.currentUser!;
|
||||
const { id, email, name, role, oidcSub, favorites, dashboardLayout, serverPageLayout } = me;
|
||||
const { id, email, name, role, oidcSub, favorites, dashboardLayout, serverPageLayout, language } = me;
|
||||
const avatarUrl = avatarUrlFor(me, (await getSettings()).profilePictures);
|
||||
res.json({ user: { id, sub: oidcSub, email, name, role, avatarUrl, favorites: parseFavorites(favorites), dashboard: parseDashboardLayout(dashboardLayout), serverPage: parsePageLayout(serverPageLayout) } });
|
||||
res.json({ user: { id, sub: oidcSub, email, name, role, avatarUrl, favorites: parseFavorites(favorites), dashboard: parseDashboardLayout(dashboardLayout), serverPage: parsePageLayout(serverPageLayout), language: parseLanguage(language) } });
|
||||
}));
|
||||
|
||||
// Paths inside the app only: a slash, then letters, digits, dashes, underscores and further slashes — and, for a saved view of a page,
|
||||
@@ -93,6 +100,14 @@ export function parsePageLayout(stored: string | null): PageLayout {
|
||||
}
|
||||
}
|
||||
|
||||
// The language of the signed-in person's interface: "en" or "sv", or null to go back to following the browser. Only ever their own.
|
||||
meRouter.put("/language", requireAuth, asyncHandler(async (req, res) => {
|
||||
const parsed = z.object({ language: z.enum(LANGUAGES).nullable() }).safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "Choose en or sv, or null for the browser's language." });
|
||||
await db.update(users).set({ language: parsed.data.language }).where(eq(users.id, req.currentUser!.id));
|
||||
res.json({ language: parsed.data.language });
|
||||
}));
|
||||
|
||||
// Replaces the signed-in person's pinned pages. Only ever their own.
|
||||
meRouter.put("/favorites", requireAuth, asyncHandler(async (req, res) => {
|
||||
const parsed = favoritesSchema.safeParse(req.body);
|
||||
|
||||
@@ -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"\}`\}/);
|
||||
});
|
||||
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user