About 1,600 more headings, buttons, table columns, status words, placeholders and short messages are translated. Tables of words built when the app loads are now read when they are drawn, so they follow the language, and a test fails if text is translated at load time. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
183 lines
9.5 KiB
TypeScript
183 lines
9.5 KiB
TypeScript
/**
|
|
* 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("no text is translated when a module loads: a table of words built then would stay in the language of the first paint", async () => {
|
|
const ts = (await import("typescript")).default;
|
|
const { readdirSync } = await import("node:fs");
|
|
const root = new URL("../../web/src/", import.meta.url);
|
|
const files: URL[] = [];
|
|
const walk = (dir: URL) => {
|
|
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
|
if (e.isDirectory()) {
|
|
if (e.name !== "i18n") walk(new URL(`${e.name}/`, dir));
|
|
} else if (/\.tsx?$/.test(e.name)) files.push(new URL(e.name, dir));
|
|
}
|
|
};
|
|
walk(root);
|
|
const offenders: string[] = [];
|
|
for (const file of files) {
|
|
const text = readFileSync(file, "utf8");
|
|
if (!/\btn?\(/.test(text)) continue;
|
|
const sf = ts.createSourceFile(file.pathname, text, ts.ScriptTarget.Latest, true, file.pathname.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
|
|
const visit = (node: import("typescript").Node, inside: boolean) => {
|
|
const fn = ts.isFunctionLike(node) || ts.isClassDeclaration(node);
|
|
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && (node.expression.text === "t" || node.expression.text === "tn") && !inside) offenders.push(`${file.pathname.split("/web/src/")[1]}:${sf.getLineAndCharacterOfPosition(node.getStart()).line + 1}`);
|
|
ts.forEachChild(node, (c) => visit(c, inside || fn));
|
|
};
|
|
visit(sf, false);
|
|
}
|
|
assert.deepEqual(offenders, [], "t() called outside any function; use a getter (get label() { return t(\"…\"); }) or translate where it is shown");
|
|
});
|
|
|
|
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);
|
|
});
|
|
});
|