import { test, expect, type Page } from "@playwright/test";
import { mkdirSync, writeFileSync } from "node:fs";
import path from "node:path";
import * as urls from "./urls";
import { researchArchiveHref, researchCaseHref, researchHref } from "../lib/research/hrefs";
import { runHref, runsHref } from "../lib/research/runs-hrefs";
// ---------------------------------------------------------------------------
// The audit against the canvas (plans/umtool-redesign.md, P6b): every place and
// tab, at 1366×768, in both themes, holds the colour roles --
// - Signal is interaction only: focus, the lit line, ONE filled action. No
// action is a Signal OUTLINE (the retired `primary` look, or a hand-rolled
// `border-[var(--color-sel)]`), and no page has two filled actions.
// - A verdict colour is a judgement: no action wears one (a delete is
// guarded by its plan and confirm, not by red).
// - It fits: no horizontal scroll at 1366 wide.
// Read-only: it opens pages and writes nothing.
//
// P6B_SHOTS=
also saves each page at 1366×768 and 1440×900 in both themes,
// and `findings.json` (what each page measured), for the audit's record.
// ---------------------------------------------------------------------------
const SHOTS = process.env.P6B_SHOTS ?? "";
const ARTICLE = { site: "articles", id: "zeta" } as const;
const PROJECT = "reports/report-fixture";
const SONG = "reports/videos/alpha";
const PAGES: [string, string][] = [
["inbox", urls.homeHref()],
["research", researchHref()],
["research-results", researchHref({ q: "lighthouse budget" })],
["research-case", researchCaseHref("fixture-board")],
["research-archive", researchArchiveHref()],
["research-runs", runsHref()],
["research-run", runHref("runfix", 1)],
["work", urls.workHref()],
["projects", urls.projectsHref()],
["site", urls.siteHref("priv")],
["site-report", urls.articleHref({ site: "priv", id: "polemic-alpha" })],
...["overview", "article", "iterations", "cut", "media", "build", "deliver", "sources", "history"].map(
(tab) => [`article-${tab}`, urls.articleHref(ARTICLE, { tab })] as [string, string],
),
["article-evidence", urls.articleEvidenceHref({ site: "articles", id: "delta" })],
["article-compare", urls.articleCompareHref("zeta", { a: "1", b: "3" })],
// A project piece's four tabs since the workspace (L7b) -- Media and Build fold into Deliver -- and the views out of
// the tab bar (the Overview, the cut as a list), and the workspace itself.
...["overview", "cut", "deliver", "sources", "history"].map(
(tab) => [`project-${tab}`, urls.projectHref(PROJECT, { tab })] as [string, string],
),
["project-workspace", urls.workspaceHref(PROJECT)],
...["overview", "cuts", "spec", "cover", "notes"].map((tab) => [`song-${tab}`, urls.projectHref(SONG, { tab })] as [string, string]),
["song-cut", urls.cutHref(SONG, "wide")],
["bench-clip", urls.clipBenchHref("reports/bench-shell-fixture", "s01")],
["bench-claim", urls.claimBenchHref("reports/bench-fixture", "k01")],
["bench-narration", urls.narrationHref("reports/narration-review-fixture")],
["bench-takes", urls.takesHref("reports/takes-fixture")],
["bench-review", urls.reviewHref("reports/media-review-fixture", { view: "list" })],
["bench-clips", urls.clipDeckHref("reports/clip-deck-fixture", { show: "all" })],
["create", urls.createHref()],
...(["research", "article", "article-board", "recurring", "video-article", "video-board", "video-recording", "video-highlights", "video-report", "song"] as const).map(
(make) => [`create-${make}`, urls.createHref({ make })] as [string, string],
),
["tools", urls.toolsHref()],
["tools-find", urls.findHref()],
["tools-phrases", urls.phraseFinderHref()],
["tools-mix", urls.mixHref()],
["tools-song", urls.songToolsHref()],
...["sort", "salvage", "verify", "keeps"].map((m) => [`tools-song-${m}`, urls.pileHref(m)] as [string, string]),
["tools-faces", urls.facesHref()],
["tools-trim", urls.trimHref("mk-hooks")],
["tools-sources", urls.sourcesHref()],
["tools-bench", urls.benchHref()],
["tools-digest-context", urls.digestContextHref()],
["settings-generation", urls.generationPolicyHref()],
["settings-system", urls.systemHref()],
];
type Finding = { scroll: number; signalOutlines: string[]; filled: string[]; verdictActions: string[]; lower: string[] };
/** What the page shows, measured by computed colour (so a hand-rolled class is caught too). */
async function measure(page: Page): Promise {
return page.evaluate(() => {
const probe = document.createElement("span");
document.body.appendChild(probe);
const rgb = (v: string) => {
probe.style.color = "";
probe.style.color = `var(${v})`;
return getComputedStyle(probe).color;
};
const signal = new Set([rgb("--signal"), rgb("--signal-text")]);
const verdict = new Set(["--kept", "--kept-text", "--doubt", "--doubt-text", "--reject", "--reject-text"].map(rgb));
probe.remove();
const name = (el: Element) => `${el.tagName.toLowerCase()} "${(el.textContent ?? "").trim().replace(/\s+/g, " ").slice(0, 40)}"`;
const visible = (el: Element) => {
const r = el.getBoundingClientRect();
return r.width > 0 && r.height > 0 && getComputedStyle(el).visibility !== "hidden";
};
// Actions: buttons and links drawn as buttons (a border). A pressed toggle
// is a state of a control, judged by its ground, not here; the current
// item of a list (aria-current) is its lit line; a verdict button's own
// word is its verdict (the chips that set one).
const actions = [...document.querySelectorAll("main button, main a, main [role=button]")].filter(
(el) => visible(el) && el !== document.activeElement && !(el as HTMLElement).closest("[data-verdict-for], [data-verdict-bar]"),
);
const signalOutlines: string[] = [];
const filled: string[] = [];
const verdictActions: string[] = [];
// Labels that start in lower case (reported, not asserted: an id, a
// timecode or a variant's tag is a fine label). The key hints are skipped.
const lower: string[] = [];
for (const el of actions) {
if (el.tagName === "BUTTON" || el.getAttribute("role") === "button") {
const clone = el.cloneNode(true) as HTMLElement;
clone.querySelectorAll("kbd").forEach((k) => k.remove());
const text = (clone.textContent ?? "").trim();
if (/^[a-z]/.test(text)) lower.push(text.replace(/\s+/g, " ").slice(0, 40));
}
const cs = getComputedStyle(el);
const bordered = parseFloat(cs.borderTopWidth) > 0 && cs.borderTopStyle !== "none";
const bg = cs.backgroundColor;
if (signal.has(bg)) filled.push(name(el));
else if (bordered && signal.has(cs.borderTopColor) && el.getAttribute("aria-pressed") !== "true" && !el.hasAttribute("aria-current")) signalOutlines.push(name(el));
if (el.getAttribute("aria-pressed") === "true") continue;
// A button in a verdict's colour, or a bordered link (a chip, a facet) in one.
if ((bordered && (verdict.has(cs.borderTopColor) || verdict.has(cs.color))) || (el.tagName === "BUTTON" && verdict.has(cs.color))) verdictActions.push(name(el));
}
return { scroll: document.documentElement.scrollWidth - document.documentElement.clientWidth, signalOutlines, filled, verdictActions, lower };
});
}
async function shoot(page: Page, name: string) {
for (const theme of ["dark", "light"] as const) {
await page.evaluate((t) => document.documentElement.setAttribute("data-theme", t), theme);
for (const [w, h] of [
[1366, 768],
[1440, 900],
] as const) {
await page.setViewportSize({ width: w, height: h });
await page.waitForTimeout(120);
await page.screenshot({ path: path.join(SHOTS, `${name}-${w}x${h}-${theme}.png`) });
}
}
}
const found: Record = {};
test.describe.configure({ timeout: 90_000 });
for (const [name, url] of PAGES) {
test(`${name} (${url}) holds the colour roles and fits 1366×768`, async ({ page }) => {
if (SHOTS) mkdirSync(SHOTS, { recursive: true });
await page.setViewportSize({ width: 1366, height: 768 });
const res = await page.goto(url);
expect(res?.status(), url).toBeLessThan(400);
await page.waitForLoadState("networkidle", { timeout: 5_000 }).catch(() => {});
found[name] = [];
for (const theme of ["dark", "light"] as const) {
await page.evaluate((t) => document.documentElement.setAttribute("data-theme", t), theme);
found[name].push({ theme, ...(await measure(page)) });
}
if (SHOTS) {
// One file a page: a failed test restarts the worker, so nothing is kept in memory across tests.
mkdirSync(path.join(SHOTS, "findings"), { recursive: true });
writeFileSync(path.join(SHOTS, "findings", `${name}.json`), JSON.stringify(found[name], null, 2));
await shoot(page, name);
}
for (const f of found[name]) {
expect(f.scroll, `${name} ${f.theme}: scrolls sideways at 1366`).toBeLessThanOrEqual(0);
expect(f.signalOutlines, `${name} ${f.theme}: a Signal outline on an action`).toEqual([]);
expect(f.verdictActions, `${name} ${f.theme}: a verdict colour on an action`).toEqual([]);
expect(f.filled.length, `${name} ${f.theme}: filled actions ${f.filled.join(", ")}`).toBeLessThanOrEqual(1);
}
});
}
// ---------------------------------------------------------------------------
// The keyboard-only pass: Inbox → a piece → its bench → back to the piece →
// the Inbox, never touching the mouse, with a visible focus at every stop.
// ---------------------------------------------------------------------------
/** "" when the focused element shows a focus ring (an outline or a ring shadow); else what has none. */
async function focusShown(page: Page): Promise {
return page.evaluate(() => {
const el = document.activeElement as HTMLElement | null;
if (!el || el === document.body) return "nothing focused";
const cs = getComputedStyle(el);
const ring = cs.outlineStyle !== "none" && parseFloat(cs.outlineWidth) > 0;
return ring || cs.boxShadow !== "none" ? "" : `${el.tagName.toLowerCase()} "${(el.textContent ?? "").trim().slice(0, 30)}" shows no focus`;
});
}
/** Tab until the focused element's text starts with `text`, checking the focus ring at every stop. */
async function tabTo(page: Page, text: RegExp, max = 60) {
for (let i = 0; i < max; i++) {
await page.keyboard.press("Tab");
expect(await focusShown(page)).toBe("");
const t = await page.evaluate(() => (document.activeElement?.textContent ?? "").trim());
if (text.test(t)) return;
}
throw new Error(`no focusable element matching ${text} within ${max} tabs`);
}
test("keyboard only: Inbox → a piece → its bench → the piece → the Inbox, focus shown at every stop", async ({ page }) => {
test.setTimeout(120_000);
await page.setViewportSize({ width: 1366, height: 768 });
await page.goto(urls.homeHref());
await expect(page.locator("dialog[data-jump][data-ready]")).toBeAttached();
// The Inbox's lit list: j/k move the light and the focus with it. The list
// streams in after the shell (app/page.tsx), so the keys wait for it to be
// there and listening.
await expect(page.locator("[data-lit-list][data-hydrated]").first()).toBeAttached();
await page.keyboard.press("j");
await page.keyboard.press("k");
expect(await page.evaluate(() => !!document.activeElement?.closest("[data-lit-line]"))).toBe(true);
expect(await focusShown(page)).toBe("");
// Your call's first card is zeta's failed run: its action opens the piece.
await tabTo(page, /^Retry run$/);
await page.keyboard.press("Enter");
await expect(page).toHaveURL(/\/articles\/zeta\?tab=iterations$/);
// The piece's keys: 4 is the Cut tab; its walk opens the clip bench.
await page.keyboard.press("4");
await expect(page).toHaveURL(/tab=cut/);
await tabTo(page, /^Walk the cut/);
await page.keyboard.press("Enter");
await expect(page).toHaveURL(/\/clip\/a1$/);
// The bench's ← the piece goes back to the article piece.
await tabTo(page, /^← /);
await page.keyboard.press("Enter");
await expect(page).toHaveURL(/\/articles\/zeta/);
// And ⌘K to the Inbox.
await expect(page.locator("dialog[data-jump][data-ready]")).toBeAttached();
await page.keyboard.press("Control+k");
await page.keyboard.type("Inbox");
await page.keyboard.press("Enter");
await expect(page).toHaveURL(/\/$/);
});