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

The fork tree page is a keyboard-walkable tree that reads on a phone #12452

Merged opened this

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

Merged

scout/forge:scout/12415-the-fork-tree-page-is-a-keyboard-walkabl → main 5 commits fork 3 threads · 3 unresolved

  • Merged. scout/12415-the-fork-tree-page-is-a-keyboard-walkabl was merged into main as 55dbcdf.

Review

Sign in to review this change.
7 files changed +256 −15
docs/features/fork-tree.md +10
@@ -30,3 +30,13 @@ below the root; `limit` is 1-200 nodes (default 200). `truncated` is true when m
3030
3131 One query per generation plus one for the follow modes, not one per fork; the test counts statements
3232 (`test/fork-tree-reader.test.ts`), not a clock.
33
34 ## On the web: `/family`
35
36 The forge family is a `role="tree"` of `treeitem`s, each with `aria-level` and, for a branch, `aria-expanded`.
37 Without script every branch is open and the page is plain nested lists. With script, Up/Down walk the visible rows,
38 Right opens a branch (or steps in), Left closes it (or steps out), Home/End jump. Each node says its depth as text
39 ("level 2") and how it follows as a word (`follows`, `proposes`: `FOLLOW_WORD`), never colour alone;
40 the tree is at most four levels deep, so indentation is at most three steps. The row itself is the `treeitem`
41 (it takes focus, so it says its level and state); the "level N" text is hidden from screen readers, which hear `aria-level`.
42 A child cannot report a severed mode, so that word is not drawn. Test: `test/family-a11y.test.ts`.
src/web/pages/family.ts +28 −11
@@ -17,20 +17,24 @@ import { pageHead } from "../chrome.ts";
1717 import { html, type Html } from "../html.ts";
1818 import { page } from "../layout.ts";
1919 import { badge, row } from "../ui.ts";
20 import { FOLLOW_WORD } from "../../actions/follow_words.ts";
21 import { familyTreeJs } from "./family_tree_js.ts";
2022
21 interface Node {
23 export interface Node {
2224 readonly label: string;
2325 readonly href: string | null;
2426 readonly meta: readonly Html[];
2527 readonly badge: Html | null;
2628 readonly here?: boolean;
29 /** How it follows its upstream in one word (follows, proposes), or null. */
30 readonly word?: string | null;
2731 readonly children: readonly Node[];
2832 }
2933
3034 const plural = (n: number, one: string, many = `${one}s`) =>
3135 `${n} ${n === 1 ? one : many}`;
3236
33 function standingNode(c: FamilyChild): Node {
37 export function standingNode(c: FamilyChild): Node {
3438 // One plain line: how it follows and how far behind. The rest is on /forges.
3539 const meta: Html[] = [];
3640 if (c.state === "unheard") meta.push(html`has not reported yet`);
@@ -44,6 +48,7 @@ function standingNode(c: FamilyChild): Node {
4448 return {
4549 label: c.name,
4650 href: c.url,
51 word: c.mode === null ? null : FOLLOW_WORD[c.mode],
4752 meta,
4853 badge:
4954 c.state === "reporting"
@@ -55,21 +60,32 @@ function standingNode(c: FamilyChild): Node {
5560 };
5661 }
5762
58 /** The tree as §5 rows: each forge's row holds the rows of the forges it sent. */
59 function treeRow(n: Node, depth: number): Html {
63 /**
64 * One node as a `row()` that is a `treeitem`: the row is what takes focus, so
65 * it carries the level and `aria-expanded` itself. Every branch is open in the
66 * markup, so without script the page is plain nested lists; `familyTreeJs`
67 * adds the keys and the folding. Depth shows as indentation and, quietly, as
68 * "level N" text for sighted readers (hidden from screen readers, which hear
69 * `aria-level`).
70 */
71 export function treeRow(n: Node, depth: number): Html {
72 const kids = depth + 1 >= MAX_DEPTH ? [] : n.children;
6073 const trail = [n.here ? badge("you are here", { variant: "outline" }) : null, n.badge].filter(
6174 (t): t is Html => t !== null,
6275 );
63 const kids = depth + 1 >= MAX_DEPTH ? [] : n.children.map((c) => treeRow(c, depth + 1));
76 const bits = [
77 ...(n.word ? [html`<span data-word>${n.word}</span>`] : []),
78 ...n.meta,
79 html`<span data-level aria-hidden="true">level ${depth + 1}</span>`,
outdated

Principle 7 / design system: row markup hand-rolled instead of the named row() component, in one very long template line. Extend row() and use it.

80 ];
6481 return row({
6582 title: n.label,
outdated

role=treeitem and aria-expanded are on the <li>, but focus goes to the inner [data-node]. Assistive tech announces the focused element, so state and level are lost. Make the focused element the treeitem.

6683 ...(n.href === null ? {} : { href: n.href }),
67 ...(n.meta.length === 0
68 ? {}
69 : { meta: html`${n.meta.map((m, i) => html`${i > 0 ? " · " : ""}${m}`)}` }),
84 meta: html`${bits.map((m, i) => html`${i > 0 ? " · " : ""}${m}`)}`,
7085 ...(trail.length === 0 ? {} : { trail: html`${trail}` }),
71 current: n.here === true,
72 children: kids,
86 ...(n.here ? { current: true } : {}),
87 tree: { level: depth + 1, open: true },
88 children: kids.map((c) => treeRow(c, depth + 1)),
7389 });
7490 }
7591
@@ -113,11 +129,12 @@ export async function familyPage(
113129 const response = page({
114130 ctx,
115131 title: "Family",
132 scriptJs: familyTreeJs,
116133 body: html`<div class="narrow-wide" data-family>
117134 ${pageHead("Family", {
118135 sub: "The forge this one came from, and the forges it sent. Children report in; nothing here reaches into one.",
119136 })}
120 <ul class="list bare-tree" aria-label="Forges, by who sent whom">
137 <ul class="list bare-tree" role="tree" data-tree aria-label="Forges, by who sent whom">
121138 ${treeRow(root, 0)}
122139 </ul>
123140 ${kids.more > 0 ? html`<p class="muted small">${plural(kids.more, "more forge")} not shown.</p>` : null}
src/web/pages/family_tree_js.ts added +75
@@ -0,0 +1,75 @@
1 /**
2 * The keys of the family tree (#12415). The markup is already a complete,
3 * open tree; this only adds a roving focus on the treeitem rows: Up/Down walk
4 * the visible rows, Right opens a branch (or steps into it), Left closes it
5 * (or steps out), Home/End jump. A closed branch hides its group with `hidden`.
6 *
7 * The navigation is one pure function, `treeStep`, over the visible rows as
8 * plain data; the script embeds that very function's source, and the test
9 * calls it directly.
10 */
11
12 export interface TreeRow {
13 readonly level: number;
14 /** true/false for a branch, null for a leaf. */
15 readonly open: boolean | null;
16 }
17 export type TreeMove = { readonly focus: number } | { readonly toggle: number; readonly open: boolean } | null;
18
19 /** What a key does at row `i` of the visible `rows`: focus another row, open/close this one,
20 * or nothing. */
21 export function treeStep(rows: readonly TreeRow[], i: number, key: string): TreeMove {
22 const cur = rows[i];
23 if (cur === undefined) return null;
24 if (key === "ArrowDown") return i + 1 < rows.length ? { focus: i + 1 } : null;
25 if (key === "ArrowUp") return i > 0 ? { focus: i - 1 } : null;
26 if (key === "Home") return { focus: 0 };
27 if (key === "End") return { focus: rows.length - 1 };
28 if (key === "ArrowRight") {
29 if (cur.open === false) return { toggle: i, open: true };
30 if (cur.open === true && i + 1 < rows.length) return { focus: i + 1 };
31 return null;
32 }
33 if (key === "ArrowLeft") {
34 if (cur.open === true) return { toggle: i, open: false };
35 for (let j = i - 1; j >= 0; j--) if (rows[j]!.level < cur.level) return { focus: j };
36 return null;
37 }
38 return null;
39 }
40
41 export const familyTreeJs = /* js */ `
42 (function () {
43 var tree = document.querySelector('[data-tree]');
44 if (!tree) return;
45 ${treeStep.toString().replace(/<\/script/gi, "<\\/script")}
46 var all = function () { return Array.prototype.slice.call(tree.querySelectorAll('[role=treeitem]')); };
47 var visible = function () { return all().filter(function (n) { return !n.closest('[hidden]'); }); };
48 var data = function (n) {
49 var e = n.getAttribute('aria-expanded');
50 return { level: Number(n.getAttribute('aria-level')), open: e === null ? null : e === 'true' };
51 };
52 function focusNode(n) {
53 all().forEach(function (x) { x.tabIndex = -1; });
54 n.tabIndex = 0;
55 n.focus();
56 }
57 var first = all()[0];
58 if (first) first.tabIndex = 0;
59 tree.addEventListener('keydown', function (e) {
60 var cur = e.target.closest && e.target.closest('[role=treeitem]');
61 if (!cur || e.altKey || e.ctrlKey || e.metaKey) return;
62 var list = visible();
63 var move = treeStep(list.map(data), list.indexOf(cur), e.key);
64 if (move === null) { if (/^(Arrow|Home$|End$)/.test(e.key)) e.preventDefault(); return; }
65 if ('focus' in move) focusNode(list[move.focus]);
66 else {
67 var n = list[move.toggle];
68 var g = n.parentElement.querySelector(':scope > [role=group]');
69 n.setAttribute('aria-expanded', move.open ? 'true' : 'false');
70 if (g) g.hidden = !move.open;
71 }
72 e.preventDefault();
73 });
74 })();
75 `;
src/web/style/components.ts +5
@@ -483,6 +483,11 @@ a.row:hover, .row[data-nav]:hover { background: var(--muted); color: inherit; }
483483 /* A bare tree (/family, docs/design/areas/family.md): names and a line each; indentation is the only structure. */
484484 .list.bare-tree > li, .list.bare-tree .row-children > li { border: 0; }
485485 .list.bare-tree .row-children { border-left: 0; margin-left: var(--tree-indent, 20px); }
486 /* The tree is at most four levels deep (MAX_DEPTH), so indentation is at most 3 steps.
487 "level N" is quiet (#12415). */
488 .list.bare-tree [data-level] { font-variant-numeric: tabular-nums; opacity: .8; }
489 .list.bare-tree [data-word] { font-weight: 600; }
490 .list.bare-tree [hidden] { display: none; }
486491 .list.bare-tree .row { padding-top: 10px; padding-bottom: 10px; }
487492 .list.bare-tree .row-title, .list.bare-tree .row-meta { white-space: normal; overflow: visible; overflow-wrap: anywhere; }
488493 /* A row's look thumbs (/review): inset like a row, side by side at any width; the link's hit area grows to 44px. */
src/web/ui.ts +12 −3
@@ -997,6 +997,10 @@ export interface RowOptions {
997997 fold?: { id: string; open: boolean; body: Html };
998998 /** Why the list's count leaves this row out on purpose (`data-apart`, `bind.ts`): a sealed report. */
999999 apart?: string | undefined;
1000 /** The row is a node of an ARIA tree: the row itself is the `treeitem` (it is what takes focus,
1001 * so it says its level and, for a branch, `aria-expanded`), its `<li>` is `role="none"`,
1002 * its children a `role="group"`. */
1003 tree?: { level: number; open: boolean };
10001004 }
10011005
10021006 /** One list row. `<a>` when it navigates, `<div>` when it holds its own
@@ -1026,13 +1030,18 @@ export function row(o: RowOptions): Html {
10261030 ${o.trail && o.trail.text.trim() !== ""
10271031 ? html`<span class="row-trail">${o.trail}</span>`
10281032 : null}`;
1033 const branch = o.children !== undefined && o.children.length > 0;
1034 const treeAttrs =
1035 o.tree === undefined
1036 ? null
1037 : html` role="treeitem" aria-level="${o.tree.level}"${branch ? html` aria-expanded="${String(o.tree.open)}"` : null}${o.current ? raw(' aria-current="true"') : null} data-node tabindex="-1"`;
10291038 const attrs = html`class="row"
10301039 ${o.state ? html`data-state="${o.state}"` : null}
1031 ${o.nav ? raw('data-nav tabindex="-1"') : null}`;
1040 ${o.nav ? raw('data-nav tabindex="-1"') : null}${treeAttrs}`;
10321041 const data = Object.entries(o.data ?? {})
10331042 .filter(([key]) => /^[a-z][a-z-]*$/.test(key))
10341043 .map(([key, value]) => html` data-${raw(key)}="${value}"`);
1035 return html`<li${o.id === undefined ? null : html` id="${o.id}"`}${o.after === undefined ? null : raw(' class="has-after"')}${data}${o.apart === undefined ? null : html` data-apart="${o.apart}"`}${o.current ? raw(' aria-current="true"') : null}>
1044 return html`<li${o.id === undefined ? null : html` id="${o.id}"`}${o.after === undefined ? null : raw(' class="has-after"')}${data}${o.apart === undefined ? null : html` data-apart="${o.apart}"`}${o.tree !== undefined ? raw(' role="none"') : o.current ? raw(' aria-current="true"') : null}>
10361045 ${o.fold !== undefined
10371046 ? html`<details id="${o.fold.id}" ${o.fold.open ? raw("open") : null}>
10381047 <summary ${attrs}>${inner}</summary>
@@ -1042,7 +1051,7 @@ export function row(o: RowOptions): Html {
10421051 ? html`<a href="${o.href}" ${attrs}>${inner}</a>`
10431052 : html`<div ${attrs}>${inner}</div>`}${o.after === undefined ? null : html`<div class="row-after">${o.after}</div>`}${o.children === undefined || o.children.length === 0
10441053 ? null
1045 : html`<ul class="row-children">${[...o.children]}</ul>`}
1054 : html`<ul${o.tree === undefined ? null : raw(' role="group"')} class="row-children">${[...o.children]}</ul>`}
10461055 </li>`;
10471056 }
10481057
test/family-a11y.test.ts added +125
@@ -0,0 +1,125 @@
1 /** The family tree reads as a tree (#12415): roles, open without script, level and word as text. */
2 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
3 import { mkdir, mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { createUser } from "../src/core/users.ts";
8 import { serve, type Servers } from "../src/http/server.ts";
9 import { MAX_DEPTH } from "../src/spawn/heartbeat.ts";
10 import { standingNode, treeRow } from "../src/web/pages/family.ts";
11 import { familyTreeJs, treeStep, type TreeRow } from "../src/web/pages/family_tree_js.ts";
12 import { components } from "../src/web/style/components.ts";
13 import type { FamilyChild } from "../src/spawn/family.ts";
14 import { html } from "../src/web/html.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16
17 quietLogs();
18
19 let dir: string;
20 let app: App;
21 let servers: Servers;
22 let page: string;
23
24 beforeAll(async () => {
25 dir = await mkdtemp(join(tmpdir(), "forge-family-a11y-"));
26 app = createApp({ dataDir: dir, port: 0, parentUrl: "https://up.example.test" });
27 servers = await serve(app);
28 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
29 if (!made.ok) throw new Error(made.error);
30 await mkdir(join(dir, "spawn"), { recursive: true });
31 await Bun.write(join(dir, "spawn", "kid.json"), JSON.stringify({ name: "kid", bodyId: "b1", url: "https://kid.example.test", planHash: "x", done: true, createdAt: new Date().toISOString() }));
32 const cookie = ((await fetch(`${servers.url}/signin`, { method: "POST", body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }), redirect: "manual" })).headers.get("set-cookie") ?? "").split(";")[0]!;
33 page = await (await fetch(`${servers.url}/family`, { headers: { cookie } })).text();
34 }, 30_000);
35 afterAll(async () => {
36 servers.stop();
37 app.close();
38 await rm(dir, { recursive: true, force: true });
39 });
40
41 const child = (name: string, mode: FamilyChild["mode"]): FamilyChild => ({
42 name, url: `https://${name}.example.test`, state: "reporting", lastSeen: 1, version: null, behind: null,
43 openProposals: null, ownChildren: null, forgeTip: null, severedAt: null, mode, upstreamBehind: null,
44 conflict: false, spendTodayUsd: null, ceilingUsd: null, apps: null, placement: null,
45 } as FamilyChild);
46
47 describe("the family tree markup", () => {
48 test("the focused row is the treeitem: it carries role, level and aria-expanded; the li is none", () => {
49 expect(page).toContain('role="tree"');
50 expect(page).toMatch(/<li role="none"[^>]*>\s*<(?:a|div)[^>]*\srole="treeitem" aria-level="1" aria-expanded="true"[^>]* data-node tabindex="-1"/);
outdated

No test asserts the follow word (follows/proposes/severed) as text. Seed children with modes and assert them.

51 expect(page).toContain('aria-level="2"');
52 expect(page).toContain('aria-level="3"');
53 expect(page).toContain('role="group"');
54 expect(page).not.toMatch(/<li[^>]* role="treeitem"/);
55 });
56
57 test("without script every branch is open and nothing is hidden", () => {
58 expect(page).not.toContain('aria-expanded="false"');
59 expect(page).not.toMatch(/<ul role="group"[^>]* hidden/);
60 });
61
62 test("the level is quiet text, hidden from screen readers that hear aria-level", () => {
63 expect(page).toContain('<span data-level aria-hidden="true">level 1</span>');
64 expect(page).toContain("level 3");
65 expect(components).toMatch(/\[data-level\][^{]*\{[^}]*opacity/);
66 });
67
68 test("a child that follows says follows, one that tells says proposes, one that said nothing says neither", () => {
69 const root = { label: "here", href: null, meta: [], badge: null, here: true, children: [
70 standingNode(child("a", "take-updates")), standingNode(child("b", "tell-me")), standingNode(child("c", null)),
71 ] };
72 const out = String(treeRow(root, 0));
73 expect(out).toContain("<span data-word>follows</span>");
74 expect(out).toContain("<span data-word>proposes</span>");
75 expect(out.match(/data-word/g)!.length).toBe(2);
76 expect(out).not.toContain("severed");
77 });
78
79 test("the tree stops at MAX_DEPTH, so no deeper indentation rule is needed", () => {
80 let n: Parameters<typeof treeRow>[0] = { label: "leaf", href: null, meta: [], badge: null, children: [] };
81 for (let i = 0; i < 8; i++) n = { label: `n${i}`, href: null, meta: [html`x`], badge: null, children: [n] };
82 const out = String(treeRow(n, 0));
83 expect(Math.max(...[...out.matchAll(/aria-level="(\d+)"/g)].map((m) => Number(m[1])))).toBe(MAX_DEPTH);
84 expect(components).not.toContain('data-depth="4"');
85 });
86
87 test("360 px: indentation of the deepest level leaves most of the line, and long words wrap", () => {
88 const indent = Number(components.match(/\.bare-tree \.row-children \{[^}]*var\(--tree-indent, (\d+)px\)/)![1]);
89 expect((MAX_DEPTH - 1) * indent).toBeLessThanOrEqual(360 / 4);
90 expect(components).toMatch(/\.bare-tree \.row-title[^{]*\{[^}]*overflow-wrap:\s*anywhere/);
91 expect(components).not.toMatch(/\.bare-tree[^{]*\{[^}]*white-space:\s*nowrap/);
92 });
93 });
94
95 describe("the keys, as a function of the visible rows", () => {
96 // here (open) > a (open) > a1 (leaf); b (closed branch); c (leaf)
97 const rows: TreeRow[] = [
98 { level: 1, open: true }, { level: 2, open: true }, { level: 3, open: null }, { level: 2, open: false }, { level: 2, open: null },
99 ];
100 test("Up/Down walk and stop at the ends; Home/End jump", () => {
101 expect(treeStep(rows, 0, "ArrowDown")).toEqual({ focus: 1 });
102 expect(treeStep(rows, 4, "ArrowDown")).toBeNull();
103 expect(treeStep(rows, 0, "ArrowUp")).toBeNull();
104 expect(treeStep(rows, 3, "ArrowUp")).toEqual({ focus: 2 });
105 expect(treeStep(rows, 2, "Home")).toEqual({ focus: 0 });
106 expect(treeStep(rows, 2, "End")).toEqual({ focus: 4 });
107 });
108 test("Right opens a closed branch, steps into an open one, does nothing on a leaf", () => {
109 expect(treeStep(rows, 3, "ArrowRight")).toEqual({ toggle: 3, open: true });
110 expect(treeStep(rows, 1, "ArrowRight")).toEqual({ focus: 2 });
111 expect(treeStep(rows, 2, "ArrowRight")).toBeNull();
112 });
113 test("Left closes an open branch, steps out from a leaf or closed branch, does nothing at the root's top", () => {
114 expect(treeStep(rows, 1, "ArrowLeft")).toEqual({ toggle: 1, open: false });
115 expect(treeStep(rows, 2, "ArrowLeft")).toEqual({ focus: 1 });
116 expect(treeStep(rows, 4, "ArrowLeft")).toEqual({ focus: 0 });
117 expect(treeStep(rows, 3, "ArrowLeft")).toEqual({ focus: 0 });
118 expect(treeStep([{ level: 1, open: null }], 0, "ArrowLeft")).toBeNull();
119 expect(treeStep(rows, 0, "x")).toBeNull();
120 });
121 test("the page script embeds this very function and listens on treeitems", () => {
122 expect(familyTreeJs).toContain("function treeStep(");
123 expect(familyTreeJs).toContain("[role=treeitem]");
124 });
125 });
test/family-heartbeat.test.ts +1 −1
@@ -314,7 +314,7 @@ describe("family heartbeats", () => {
314314 expect(page).not.toMatch(/class="card/);
315315 expect(page).toContain('<ul class="list bare-tree"');
316316 // The tree stays a tree: what this forge sent is a list inside this forge's row.
317 expect(page).toContain('<ul class="row-children">');
317 expect(page).toContain('<ul role="group" class="row-children">');
318318 expect(page.indexOf('aria-current="true"')).toBeLessThan(page.indexOf("row-children"));
319319 });
320320

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs