Files
explicata/e2e/helpers.ts
T
thalladaandClaude Opus 5.5 8f6afaecdd Curves draw the rules they land in; tabs for folded and scrolled panes; peek on both axes
- A curve runs on along the rule under its pane's title (any kind of pane: section, page, article,
  article section) and draws it, the pane's own rule left out, so the two are one stroke, set on
  device pixels (the curves' layer measured from its whole pixel; a hairline is one device pixel).
- The landing: the title's rule when it shows, else the tab's foot, whether the pane is folded down
  its column or scrolled past its title. A pane scrolled past its title shows its tab at its top
  (an observer on the rule, nothing per scroll or key).
- A curve out of a folded pane whose source is out of sight leaves from the end of its tab's foot,
  solid, the foot drawn with it; the stacked pane's own top edge under it is left out.
- Colours: the panes' and curves' colour came out as the neutral ink on every curve (a selector
  outweighed the colour's); the neutral is nearer the text's ink. Colour depends on the tree only.
- A covered pane peeks out across and down at once, and stays out while the wheel scrolls it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab
2026-11-16 20:38:59 -05:00

160 lines
8.2 KiB
TypeScript

/**
* What the browser tests share: driving the page from the keyboard, reading the store the page
* exposes as globalThis.__ie, waiting for it to settle, and the links written into the shared
* library over the op API, as an outside agent would (every kind of target, a note that also links,
* a cross-document node link, two documents mentioning one article, a link and a note on the same
* words, links on the screenshot's cells; the articles are the mock
* Wikipedia's fixtures in server/wikiMock.ts).
*/
import { writeFileSync } from "node:fs";
import { inflateSync } from "node:zlib";
import type { APIRequestContext, Page } from "@playwright/test";
/** A keypress → paint timing, as the page records it. */
export interface Sample {
what: string;
ms: number;
}
/** Run a function on the page's store and return what it returns. */
export const state = <T>(page: Page, fn: (s: any) => T): Promise<T> => page.evaluate(`(${fn})(globalThis.__ie)`) as Promise<T>;
/**
* Let this page's layout follow the window, as a reader's does (`/view auto`), from its first load:
* the tests start in the column (playwright.config.ts). Later loads keep what the page has set.
*/
export const autoLayout = (page: Page) =>
page.addInitScript(() => {
if (sessionStorage.getItem("e2e:auto")) return;
sessionStorage.setItem("e2e:auto", "1");
localStorage.removeItem("ie:settings");
});
/** Press space-separated keys, in order. */
export const keys = async (page: Page, seq: string) => {
for (const k of seq.split(" ")) await page.keyboard.press(k);
};
/** / then a title then Enter: jump to a section. */
export const jump = async (page: Page, title: string) => {
await page.keyboard.press("/");
await page.keyboard.type(title);
await page.keyboard.press("Enter");
};
/** : then text then Enter. */
export const command = async (page: Page, text: string) => {
await page.keyboard.press(":");
await page.keyboard.type(text);
await page.keyboard.press("Enter");
};
/** Wait until no generation, reconciliation or link scan is running. */
export const idle = (page: Page) =>
page.waitForFunction(() => {
const s = (globalThis as any).__ie;
return s.busy === 0 && s.pending.size === 0 && s.links.busy === 0;
});
/** Wait until the server has every edit the page made. */
export const synced = (page: Page) => page.waitForFunction(() => (globalThis as any).__ie.synced());
/** The tests share one server-side library: let each test's work reach it before the page closes. */
export async function settle(page: Page) {
if (!(await page.evaluate(() => !!(globalThis as any).__ie?.ready).catch(() => false))) return;
await idle(page);
await synced(page);
}
export const focusedTitle = (page: Page) => state(page, (s) => s.snap.nodes[s.focus.node].title);
/** The selected words. */
export const selected = (page: Page) => state(page, (s) => (s.focus.range ? s.snap.nodes[s.focus.node].body.slice(s.focus.range[0], s.focus.range[1]) : "") as string);
/** Write a latency report to test-results/latency-<name>.json. */
export const writeReport = (name: string, report: unknown) => writeFileSync(`test-results/latency-${name}.json`, JSON.stringify(report, null, 2));
// ---- links written into the shared library ----
interface Snap {
root: string;
nodes: Record<string, { id: string; parent: string | null; kind: string; title: string; body: string; slug?: string; ref?: unknown; anchors: { text: string }[]; children: string[] }>;
}
const W = (title: string) => ({ kind: "wiki", title, lang: "en" });
/** Find a section by its document's slug and title path. */
function find(s: Snap, slug: string, ...path: string[]): string {
let at = s.nodes[s.root].children.find((c) => s.nodes[c].slug === slug)!;
for (const t of path) at = s.nodes[at].children.find((c) => s.nodes[c].kind === "section" && s.nodes[c].title === t)!;
if (!at) throw new Error(`no ${slug}/${path.join("/")}`);
return at;
}
const noteOn = (s: Snap, parent: string, quote: string) => s.nodes[parent].children.find((c) => s.nodes[c].kind === "note" && s.nodes[c].anchors[0]?.text === quote)!;
export async function seedLinks(request: APIRequestContext) {
const s: Snap = await (await request.get("/api/tree")).json();
const recursion = find(s, "fixed-points", "Recursion without names");
if (s.nodes[recursion].children.some((c) => s.nodes[c].ref)) return; // already seeded by an earlier test
const howY = find(s, "fixed-points", "Recursion without names", "How Y works");
const triple = find(s, "origin-of-the-elements", "Fusion in ordinary stars", "The triple-alpha process");
const separate = find(s, "octopus-minds", "A separate experiment");
const ancestor = find(s, "octopus-minds", "A separate experiment", "The common ancestor");
const programs = find(s, "what-a-proof-is", "Proof assistants", "Proofs as programs");
const kinds = find(s, "the-eukaryotic-cell", "Two kinds of cell");
const ops = [
{ op: "create", parent: recursion, kind: "note", quote: "fixed-point combinator", ref: W("Fixed-point combinator") },
{ op: "update", id: noteOn(s, recursion, "lambda calculus"), ref: W("Lambda calculus") },
{ op: "create", parent: recursion, kind: "note", quote: "Y combinator", ref: { kind: "node", id: howY, doc: "fixed-points", path: ["Recursion without names", "How Y works"] } },
{ op: "create", parent: recursion, kind: "note", quote: "self-reference", ref: { kind: "url", url: "https://plato.stanford.edu/entries/self-reference/", title: "Self-Reference (Stanford Encyclopedia of Philosophy)" } },
{ op: "update", id: noteOn(s, triple, "an excited state at almost exactly the energy"), ref: W("Hoyle state") },
{ op: "create", parent: triple, kind: "note", quote: "Fred Hoyle", ref: W("Fred Hoyle") },
{ op: "create", parent: separate, kind: "note", quote: "octopus", ref: W("Octopus") },
{ op: "update", id: noteOn(s, separate, "cephalopod"), ref: W("Cephalopod") },
// A link on words that already carry a note of their own: two notes on one span.
{ op: "create", parent: ancestor, kind: "note", quote: "The camera-like eye", ref: W("Cephalopod") },
{ op: "create", parent: programs, kind: "note", quote: "a function turning proofs", ref: W("Lambda calculus") },
{ op: "create", parent: programs, kind: "note", quote: "Several of the leading systems", ref: { kind: "node", id: recursion, doc: "fixed-points", path: ["Recursion without names"] } },
{ op: "create", parent: kinds, kind: "note", quote: "Eukaryotes", ref: W("Eukaryote") },
{ op: "create", parent: kinds, kind: "note", quote: "Bacteria", ref: W("Bacteria") },
];
const res = await request.post("/api/ops", { data: { author: "linker", message: "Seed links for the link tests", ops } });
if (!res.ok()) throw new Error(`seeding links failed: ${res.status()} ${await res.text()}`);
}
/** A screenshot's pixels (a PNG of 8-bit RGB or RGBA, as Playwright writes them): px(x, y) is [r, g, b]. */
export function pixels(buf: Buffer): { w: number; h: number; px: (x: number, y: number) => [number, number, number] } {
let at = 8;
let w = 0;
let h = 0;
let type = 6;
const data: Buffer[] = [];
while (at < buf.length) {
const len = buf.readUInt32BE(at);
const kind = buf.toString("ascii", at + 4, at + 8);
const body = buf.subarray(at + 8, at + 8 + len);
if (kind === "IHDR") {
w = body.readUInt32BE(0);
h = body.readUInt32BE(4);
type = body[9];
} else if (kind === "IDAT") data.push(body);
at += 12 + len;
}
const bpp = type === 6 ? 4 : 3;
const raw = inflateSync(Buffer.concat(data));
const stride = w * bpp;
const out = Buffer.alloc(h * stride);
for (let y = 0; y < h; y++) {
const f = raw[y * (stride + 1)];
for (let i = 0; i < stride; i++) {
const x = raw[y * (stride + 1) + 1 + i];
const a = i >= bpp ? out[y * stride + i - bpp] : 0;
const b = y ? out[(y - 1) * stride + i] : 0;
const c = y && i >= bpp ? out[(y - 1) * stride + i - bpp] : 0;
const p = a + b - c;
const pr = Math.abs(p - a) <= Math.abs(p - b) && Math.abs(p - a) <= Math.abs(p - c) ? a : Math.abs(p - b) <= Math.abs(p - c) ? b : c;
out[y * stride + i] = (x + [0, a, b, (a + b) >> 1, pr][f]) & 255;
}
}
return { w, h, px: (x, y) => [out[y * stride + x * bpp], out[y * stride + x * bpp + 1], out[y * stride + x * bpp + 2]] };
}