Public: anyone can read this; the crew can change it.

The map and /space say the same facts in text and move by keyboard #15607

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/15592-the-map-and-space-say-the-same-facts-in → main 0 commits fork 6 threads · 6 unresolved

  • Merged. scout/15592-the-map-and-space-say-the-same-facts-in was merged into main as 960a254.

Review

Sign in to review this change.
11 files changed +232 −13
docs/design/areas/map.md +4
@@ -39,3 +39,7 @@ unchanged. No new class.
3939 ## The growth line (#12756)
4040
4141 `.map-growth` is the one line above the drawing: what changed in the span (`?since=day|week|month`), the counts as words, the other spans as links. `.map-card.map-new` marks a card created in the span, with `.map-new-dot`, a dot in the text colour (the accent is for interaction alone) in its corner: a heavier dashed edge and a dot, and "(new)" in its label, so the mark never rests on colour alone.
42
43 ## The facts list (#15592)
44
45 `.facts` is the map's and the space's drawing said in text: a visually hidden `dl`, one `dt` (kind, link) and `dd` (state) per node drawn, capped at 300 rows. A link inside it takes focus and the list shows itself so the focus is seen (`src/web/node_facts.ts`).
docs/features/map-by-keyboard.md added +24
@@ -0,0 +1,24 @@
1 ---
2 topic: Tell the crew
3 row: The map and the space, by keyboard and in text
4 ---
5 # The map and the space, by keyboard and in text
6
7 The map (`/:owner/:repo/map`) and the space (`/:owner/:repo/space`) are
8 drawings. Each also carries the same facts as a visually hidden list
9 (`src/web/node_facts.ts`): one row per node drawn, in reading order, with its
10 link and its state, for a screen reader or a keyboard.
11
12 - **The map**: Tab goes to each issue card in turn and Enter opens it. The
13 hidden list repeats the cards for screen readers and is kept out of the Tab
14 order, so nothing is visited twice.
15 - **The space**: the canvas draws up to 300 issues, so its list is closed.
16 Tab stops once on `Issues of <repo>: N in all, press Enter to list them`;
17 Tab again leaves it, and Enter opens the list, where each Tab is one issue
18 and Enter opens it. The list shows itself while focus is in it. Past 300 the
19 last row says how many more issues are not listed here.
20
21 The terminal already says the same in text: `forge space` (`src/tui/screens/space.ts`)
22 lists every issue by pillar and state, with `/` to find one, and the roadmap
23 screen (`src/tui/screens/roadmap.ts`) lists the map's issues; neither draws
24 anything, so they needed no change.
src/http/mcp/tools/map.ts +1 −1
@@ -33,7 +33,7 @@ export const tool: Tool = {
3333 if (view !== undefined && (typeof view !== "string" || !VIEWS.includes(view))) {
3434 return bad("bad_view", `view is one of ${VIEWS.join(", ")}`);
3535 }
36 if (view === "space") return good({ ...cappedSpace(spaceOf(ctx.app, repo, user)) });
36 if (view === "space") return good({ ...cappedSpace({ ...spaceOf(ctx.app, repo, user) }) });
3737 if (args["first"] !== undefined) {
3838 const issue = issueArg(ctx, repo, args, "first");
3939 if ("ok" in issue) return issue;
src/tui/screens/space.ts +2 −2
@@ -89,7 +89,7 @@ export function spaceScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
8989 render(area, s) {
9090 const c = ctx.theme.c;
9191 const space = spaceOf(f.app, repo, f.user);
92 lines = [...(filter.on ? [`Find: ${filter.query}${filter.active ? "_" : ""}`, ...found, ""] : []), ...spaceLines(space, area.w - 4)];
92 lines = [...(filter.on ? [`Find: ${filter.query}${filter.active ? "_" : ""}`, ...found, ""] : []), ...spaceLines({ ...space }, area.w - 4)];
9393 const from = scroll.window(area.h, lines.length);
9494 for (let i = 0; i < area.h; i++) {
9595 const line = lines[from + i];
@@ -99,7 +99,7 @@ export function spaceScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
9999 key(e) {
100100 if (filter.active && e.key === "enter") {
101101 filter.active = false;
102 found = filter.query === "" ? [] : foundLines(spaceOf(f.app, repo, f.user), filter.query, link, 76);
102 found = filter.query === "" ? [] : foundLines({ ...spaceOf(f.app, repo, f.user) }, filter.query, link, 76);
103103 return true;
104104 }
105105 if (filter.active && e.key === "esc") {
src/web/map_snapshot.ts +6 −4
@@ -32,17 +32,19 @@ export function mapSnapshots(db: Database): Stamped<Record<string, unknown>> {
3232 }
3333
3434 /** `build()` once per repository, scope and minute while nothing has been written. */
35 export function cachedMap(
35 export function cachedMap<T extends object = Record<string, unknown>>(
3636 db: Database,
3737 key: { repoId: string; scope: { sealed?: true; sealedBy?: string }; now: Date; kind?: string },
38 build: () => Record<string, unknown>,
39 ): { value: Record<string, unknown>; hit: boolean } {
38 build: () => T,
39 ): { value: T; hit: boolean } {
4040 const stamp = writeStamp(db);
4141 if (stamp === undefined) return { value: build(), hit: false };
4242 const cache = mapSnapshots(db);
4343 const before = cache.hits;
4444 const k = `${key.kind ?? "map"}:${key.repoId}:${scopeKey(key.scope)}:${key.now.toISOString().slice(0, 16)}`;
45 const value = cache.get(k, stamp, build);
45 // The cache stores plain objects of any one kind; `kind` in the key keeps
46 // each kind's entries to the `build` that made them.
47 const value = cache.get(k, stamp, build as () => Record<string, unknown>) as T;
4648 return { value, hit: cache.hits > before };
4749 }
4850
src/web/node_facts.ts added +47
@@ -0,0 +1,47 @@
1 /**
2 * The facts a drawing says, said again in text (#15592): one row per node
3 * drawn (node, kind, state, link), in reading order, for a reader who cannot
4 * see the picture. Visually hidden. The map's own nodes are already links, so
5 * its copy stays out of the Tab order. Where `tabbable` (the space, whose
6 * canvas draws up to 300 issues) the list sits in a closed disclosure: Tab
7 * stops once on its summary, Enter opens it and Tab then walks the links, so
8 * nobody presses Tab 300 times to get past it. The row says its issue once, in
9 * the group's label.
10 */
11 import { html, type Html } from "./html.ts";
12
13 export interface Fact {
14 readonly kind: string;
15 readonly label: string;
16 readonly state: string;
17 readonly href: string;
18 }
19
20 /** The most rows one page carries: past it the list says how many it left out. */
21 export const FACTS_CAP = 300;
22
23 export function factsList(name: string, facts: readonly Fact[], tabbable: boolean): Html {
24 const shown = facts.slice(0, FACTS_CAP);
25 const left = facts.length - shown.length;
26 const rows = html`<dl>
outdated

Principle 8: N more not listed + cap 300 reads as jargon. Plain sentence, one row, no cap.

27 ${shown.map(
28 (f) =>
29 html`<dt data-kind="${f.kind}"><a href="${f.href}"${tabbable ? html`` : html` tabindex="-1"`}>${f.label}</a></dt><dd>${f.state}</dd>`,
30 )}
31 ${left > 0 ? html`<dt>${left} more ${left === 1 ? "issue is" : "issues are"} not listed here</dt>` : null}
outdated

list-style has no effect on a dl. position:absolute here also relies on an unseen positioned ancestor: check that it lands inside the canvas on /space.

32 </dl>`;
outdated

Principle 6: a 1px border plus radius is a box around a thing. Use a hairline edge or background only.

33 if (!tabbable) return html`<div class="facts" data-facts role="group" aria-label="${name}">${rows}</div>`;
34 return html`<details class="facts" data-facts>
35 <summary>${name}: ${facts.length} in all, press Enter to list them</summary>
36 <div role="group" aria-label="${name}">${rows}</div>
37 </details>`;
38 }
39
40 export const factsCss = /* css */ `
41 .facts { position: absolute; width: 1px; height: 1px; margin: 0; padding: 0; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
42 .facts:focus-within { left: 8px; bottom: 8px; width: min(26rem, calc(100% - 1.5rem)); height: auto; max-height: 40vh; padding: 8px 12px; overflow: auto; clip: auto; white-space: normal; background: var(--muted); }
43 .facts summary, .facts a:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
44 .facts summary:not(:focus-visible) { outline: 0; }
45 @media (forced-colors: active) { .facts summary, .facts a:focus-visible { outline-color: Highlight; } }
46 .facts dl, .facts dt, .facts dd { margin: 0; }
47 `;
src/web/pages/map.ts +20 −1
@@ -56,6 +56,7 @@ import {
5656 import { liveRegionsJs } from "../client.ts";
5757 import { clamp, hashOf, parseHash, viewAddress, viewFromAddress } from "../space_view.ts";
5858 import { html, type Html } from "../html.ts";
59 import { factsCss, factsList, type Fact } from "../node_facts.ts";
5960 import { page } from "../layout.ts";
6061 import { btn, disclosure, empty, row } from "../ui.ts";
6162 import {
@@ -826,6 +827,23 @@ function edge(
826827 />`;
827828 }
828829
830 /** The nodes drawn, as text, top level first and left to right: one fact each. */
831 export function mapFacts(
832 base: string,
833 placed: Layout,
834 emphasis: Emphasis,
835 issueHref: (base: string, number: number) => string,
836 ): Fact[] {
837 return [...placed.nodes]
838 .sort((a, b) => a.level - b.level || a.slot - b.slot)
839 .map((n) => ({
840 kind: "issue",
841 label: `#${n.issue.number} ${n.issue.title}`,
842 state: wordFor(n.issue, emphasis.ready, emphasis.marks),
843 href: issueHref(base, n.issue.number),
844 }));
845 }
846
829847 export interface DrawOptions {
830848 /** The container's id: the pan and zoom are remembered by it across a swap. */
831849 readonly id: string;
@@ -904,6 +922,7 @@ export function drawMap(
904922 )}
905923 ${placed.nodes.map((n) => node(base, n, g, emphasis, issueHref))}
906924 </svg>
925 ${factsList(`Issues of ${repo.name}`, mapFacts(base, placed, emphasis, issueHref), false)}
907926 <p class="sr-only" data-map-live aria-live="polite" role="status"></p>
908927 <div class="bar js-only" role="group" aria-label="Zoom">
909928 <button
@@ -1147,7 +1166,7 @@ function pillarList(repo: Repo, rows: readonly PillarRow[]): Html {
11471166 </section>`;
11481167 }
11491168
1150 export const mapCss = /* css */ `
1169 export const mapCss = /* css */ `${factsCss}
11511170 .map-wrap { display: grid; grid-template-columns: minmax(0, 1fr) 272px; gap: 24px; align-items: start; margin-top: 4px; }
11521171 @media (max-width: 860px) { .map-wrap { grid-template-columns: 1fr; } }
11531172 .map-main { min-width: 0; }
src/web/pages/space.ts +17 −2
@@ -14,8 +14,9 @@ import { loadRepo, notFoundPage, repoBase } from "../chrome.ts";
1414 import { html } from "../html.ts";
1515 import { page } from "../layout.ts";
1616 import { btn } from "../ui.ts";
17 import { factsCss, factsList, type Fact } from "../node_facts.ts";
1718 import { spaceCss, spaceJs } from "../space_client.ts";
18 import { COLOUR_SAYS, DISTANCE_SAYS, SIZE_SAYS, STATES, STATE_LEGEND, type Region } from "../space_model.ts";
19 import { COLOUR_SAYS, DISTANCE_SAYS, SIZE_SAYS, STATES, STATE_LEGEND, type Region, type Space } from "../space_model.ts";
1920 import { spaceOf } from "../space_read.ts";
2021
2122 /** The plane as JSON: for the canvas, and for an agent that wants the numbers. */
@@ -34,6 +35,19 @@ export function spaceJson(ctx: Ctx): Response {
3435 return new Response(body, { headers: { "content-type": "application/json", ...headers } });
3536 }
3637
38 /** The issues the canvas draws, as text: region, state and link, newest first within a cluster. */
39 export function spaceFacts(space: Space, base: string): Fact[] {
40 return space.issues.map((r) => {
41 const cluster = space.clusters[r[1]]!;
42 return {
43 kind: "issue",
44 label: `#${r[0]} ${r[6]}`,
45 state: `${STATE_LEGEND[space.states[cluster[1]]!].label} in ${space.regions[cluster[0]]!.name}`,
46 href: `${base}/issues/${r[0]}`,
47 };
48 });
49 }
50
3751 export function spacePage(ctx: Ctx): Response {
3852 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
3953 const repo = loadRepo(ctx);
@@ -97,6 +111,7 @@ export function spacePage(ctx: Ctx): Response {
97111 ${btn("Now", { type: "button", id: "space-now", variant: "outline", size: "sm" })}
98112 </div>
99113 </div>
114 ${factsList(`Issues of ${repo.name}`, spaceFacts(space, base), true)}

First: up to 300 tabbable links sit here with no skip. Add a skip link past the list (or a closed disclosure) so keyboard users reach the pillars below without 300 Tabs.

100115 <div class="space-list">
101116 <h1>${repo.name}</h1>
102117 <p id="space-error" class="muted" hidden>The canvas could not load the space. The pillars are below.</p>
@@ -108,7 +123,7 @@ export function spacePage(ctx: Ctx): Response {
108123 </ul>
109124 </div>
110125 </div>`,
111 styleCss: spaceCss,
126 styleCss: factsCss + spaceCss,
112127 scriptJs: spaceJs,
113128 });
114129 notePhase(ctx.request, "render", performance.now() - rendering);
src/web/space_read.ts +3 −3
@@ -20,7 +20,7 @@ import { sealedScope } from "../core/sealed.ts";
2020 import { getUsersByIds, type User } from "../core/users.ts";
2121 import { cachedMap } from "./map_snapshot.ts";
2222 import { marksFor, wordFor } from "./pages/map.ts";
23 import { buildSpace, WEEK_MS, stateOf, type SpaceInput, type SpaceIssue, type SpaceRun } from "./space_model.ts";
23 import { buildSpace, WEEK_MS, stateOf, type Space, type SpaceInput, type SpaceIssue, type SpaceRun } from "./space_model.ts";
2424
2525 const ms = (iso: string | null): number => (iso === null ? 0 : Date.parse(iso) || 0);
2626
@@ -98,10 +98,10 @@ export function spaceInput(app: App, repo: Repo, viewer: User | undefined, now:
9898 }
9999
100100 /** The placed space of `repo` for `viewer`, once per minute while nothing is written. */
101 export function spaceOf(app: App, repo: Repo, viewer: User | undefined, now = new Date()): Record<string, unknown> {
101 export function spaceOf(app: App, repo: Repo, viewer: User | undefined, now = new Date()): Space {
102102 return cachedMap(
103103 app.db,
104104 { repoId: repo.id, scope: sealedScope(app.db, repo, viewer), now, kind: "space" },
105 () => ({ ...buildSpace(spaceInput(app, repo, viewer, now)) }),
105 () => buildSpace(spaceInput(app, repo, viewer, now)),
106106 ).value;
107107 }
test/map-facts.test.ts added +91
@@ -0,0 +1,91 @@
1 /**
2 * The map says its nodes in text (#15592): the list's rows are the nodes drawn, in reading order.
3 */
4 import { afterAll, beforeAll, expect, test } from "bun:test";
5 import { mkdtempSync, rmSync } from "node:fs";
6 import { tmpdir } from "node:os";
7 import { join } from "node:path";
8 import { openIssue } from "../src/actions/issues.ts";
9 import { createRepo } from "../src/actions/repos.ts";
10 import { createApp, type App } from "../src/app.ts";
11 import { addDependency } from "../src/core/dependencies.ts";
12 import { createUser } from "../src/core/users.ts";
13 import { serve, type Servers } from "../src/http/server.ts";
14 import { FACTS_CAP, factsList, type Fact } from "../src/web/node_facts.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16
17 quietLogs();
18
19 let root = "";
20 let app: App;
21 let servers: Servers;
22 let cookie = "";
23
24 beforeAll(async () => {
25 root = mkdtempSync(join(tmpdir(), "forge-map-facts-"));
26 app = createApp({ dataDir: root, port: 0 });
27 const u = await createUser(app.db, {
28 origin: "seed",
29 trusted: true,
30 username: "alice",
31 email: "[email protected]",
32 password: "a-good-passphrase",
33 adminIfFirst: true,
34 });
35 if (!u.ok) throw new Error(u.error);
36 const made = await createRepo(app, u.value, { name: "small", visibility: "private" });
37 if (!made.ok) throw new Error(made.error);
38 const titles = ["First <b>", "Second", "Third"];
39 const issues = [];
40 for (const title of titles) {
41 const o = await openIssue(app, u.value, made.value, { title });
42 if (!o.ok) throw new Error(o.error);
43 issues.push(o.value);
44 }
45 const dep = addDependency(app.db, issues[1]!, issues[0]!, u.value.id);
46 if (!dep.ok) throw new Error(dep.error);
47 servers = await serve(app);
48 const res = await fetch(`${servers.url}/signin`, {
49 method: "POST",
50 headers: { origin: servers.url },
51 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
52 redirect: "manual",
53 });
54 cookie = (res.headers.get("set-cookie") ?? "").split(";")[0]!;
55 }, 120_000);
56 afterAll(() => {
57 servers.stop();
58 app.close();
59 rmSync(root, { recursive: true, force: true });
60 });
61
62 test("factsList escapes, caps and keeps links out of Tab when asked", () => {
63 const facts: Fact[] = Array.from({ length: FACTS_CAP + 5 }, (_, i) => ({ kind: "issue", label: `#${i} <b>`, state: "ready", href: `/x/${i}` }));
64 const out = factsList("Issues", facts, false).toString();
65 expect(out.match(/<dt/g)!.length).toBe(FACTS_CAP + 1);
66 expect(out).toContain("5 more issues are not listed here");
67 expect(out).not.toContain("cap ");
68 expect(out).toContain('tabindex="-1"');
69 expect(out).not.toContain("<b>");
70 const door = factsList("Issues", facts.slice(0, 1), true).toString();
71 expect(door).not.toContain("tabindex");
72 // Tabbable lists sit in a disclosure that is closed: one Tab stop, not one per row.
73 expect(door).toMatch(/^<details class="facts" data-facts>\s*<summary>/);
74 expect(door).not.toContain(" open");
75 expect(factsList("Issues", facts.slice(0, FACTS_CAP + 1), true).toString()).toContain("1 more issue is not listed here");
76 });
77
78 test("the map's list has one row per node drawn, in reading order", async () => {
79 const res = await fetch(`${servers.url}/alice/small/map?view=graph`, { headers: { cookie } });
80 expect(res.status).toBe(200);
81 const body = await res.text();
82 const drawn = [...body.matchAll(/class="map-node"[^>]*?href="([^"]+)"/g)].map((m) => m[1]!);
83 const list = body.match(/class="facts"[\s\S]*?<\/dl>/)![0];
84 const rows = [...list.matchAll(/<a href="([^"]+)"/g)].map((m) => m[1]!);
85 expect(drawn.length).toBe(3);
86 expect(rows.slice().sort()).toEqual(drawn.slice().sort());
87 const first = rows.findIndex((h) => h.endsWith("/1"));
88 const second = rows.findIndex((h) => h.endsWith("/2"));
89 expect(first).toBeLessThan(second); // what is waited for comes first
90 expect(list).toContain("#1 First &lt;b&gt;");
91 });
test/space-page.test.ts +17
@@ -10,6 +10,7 @@ import { join } from "node:path";
1010 import { seedFixture, type Fixture, type Shape } from "../bench/map-home.ts";
1111 import { serve, type Servers } from "../src/http/server.ts";
1212 import { clearMapCache } from "../src/web/map_cache.ts";
13 import { FACTS_CAP } from "../src/web/node_facts.ts";
1314 import { spaceCss, spaceJs } from "../src/web/space_client.ts";
1415 import { quietLogs } from "./helpers/globals.ts";
1516
@@ -119,3 +120,19 @@ test("the legend is real HTML in the server render, closed, with every state", a
119120 expect(body).toContain("Size:");
120121 expect(body).toContain("Distance:");
121122 });
123
124 test("the space says its issues in text: one tabbable link per issue drawn, capped", async () => {
125 const body = await (await get("/keeper/forge/space")).text();
126 const s = (await (await get("/keeper/forge/space.json")).json()) as { issues: [number, ...unknown[]][] };
127 const list = body.match(/<details class="facts"[\s\S]*?<\/details>/)![0];
128 const links = [...list.matchAll(/<a href="\/keeper\/forge\/issues\/(\d+)"( tabindex="-1")?>/g)];
129 expect(links.map((m) => Number(m[1]))).toEqual(s.issues.slice(0, FACTS_CAP).map((r) => r[0]));
130 expect(links.length).toBeGreaterThan(0);
131 for (const m of links) expect(m[2]).toBeUndefined(); // Tab reaches every one; Enter follows it
132 expect(list).toMatch(/<dt data-kind="issue"><a [^>]*>\#\d+ [^<]*<\/a><\/dt><dd>[^<]+ in /);
133 // The list is a closed disclosure: the first Tab stop is its summary, so no
outdated

These CSS-string assertions pass even if the CSS is broken. Test behaviour instead: a skip link exists and every link is tabbable.

134 // one presses Tab once per issue to get past it. Enter opens it.
135 expect(body).toMatch(/<details class="facts" data-facts>\s*<summary>/);
136 expect(body.match(/<details class="facts"[^>]*>/)![0]).not.toContain("open");
137 expect(body.indexOf('<details class="facts"')).toBeLessThan(body.indexOf('class="space-list"'));
138 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs