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

Add the key tree, which-key and combos; move home's Bridge onto one focus layer #17173

opened this

Merged 37h 31m ago, live in production

slice1 → main 0 commits 3 threads · 3 unresolved

  • Merged. slice1 was merged into main as fd20049.

Review

Sign in to review this change.
68 files changed +1575 −327
docs/design/areas/home-flow.md +1 −1
@@ -16,7 +16,7 @@
1616 - `.lane-times` — one line under the health, "now 18m · typical 9m" (the median age of the cards the viewer can see, and the median time cards spent in it over 24 hours; a viewer who is not a forge admin sees "typical —"). It is one line tall, empty where there is nothing to say. `.lane-bottleneck` — the word "Slowest" at `--fg` weight in the head of the lane whose now median is furthest above its typical (`data-bottleneck` on the lane); at most one lane wears it. A tile's clock is its age in the lane.
1717 - `.lane-list` — the lane's tiles, in the order the next worker takes them.
1818 - `.lane-more`, `.lane-more-link`, `.lane-more-lg`, `.lane-more-md`, `.lane-more-sm`, `.lane-toggle`, `.lane-all` — what lies past the tiles. On a desk "N more" opens the table filtered to the lane. On a phone a lane shows its first four tiles (two lines each: the title, then the app, who has it and where it is, with the clock beside the title); with script "Show all N" opens the lane in place up to twelve tiles, then "All N in the table", and the lane keeps `data-open` through every redraw; without script "N more" is the table link.
19 - `.br-bar`, `.br-body`, `.br-top`, `.br-close`, `.br-head`, `.br-verbs`, `.br-said`, `.br-room` (`data-over` when that many do not fit: the danger colour, and the words themselves say they do not fit, so the colour is never the only signal) — the bridge (`src/web/bridge_client.ts`): the selected tile's verbs in one bar under the lanes, each a button with its key (`data-shortcut`, so `?` lists them), docked at the foot of the screen with the safe area under it. It is empty and hidden until a tile is selected (`j`/`k`, a focus, or a first tap on a phone); a selected tile wears an accent outline (`data-selected`). No motion: it is used many times a day.
19 - `.br-bar`, `.br-body`, `.br-top`, `.br-close`, `.br-head`, `.br-verbs`, `.br-said`, `.br-room` (`data-over` when that many do not fit: the danger colour, and the words themselves say they do not fit, so the colour is never the only signal) — the bridge (`src/web/bridge_client.ts`): the selected tile's verbs in one bar under the lanes, each a button with its key (`data-shortcut`, so `?` lists them), docked at the foot of the screen with the safe area under it. It is empty and hidden until a tile is selected (`j`/`k`, a focus, or a first tap on a phone); a selected tile wears an accent outline (`data-selected`), and a picked one (`v`, `data-picked`) a dashed one. No motion: it is used many times a day.
2020 - `.tile`, `.tile-link`, `.tile-top`, `.tile-app`, `.tile-no`, `.tile-clock`, `.tile-title`, `.tile-hint`, `.tile-who` — one change: the app and number, how long it has been in this lane, its title in plain words, who has it and one sentence of where it is. `data-key` is stable across lanes, so the page glides a tile from the lane it left to the lane it reached (`home_flow_client.ts`); `data-state` is `waiting`, `active` (a pulse on the clock) or `done` (live).
2121 - `.hf-forges` — the hosted forges in one line: how many, how many awake, any that is awake but silent.
2222 - `.hf-foot` — a line saying what the page shows, and the way to the feed.
docs/design/areas/keys.md added +7
@@ -0,0 +1,7 @@
1 # Keys: the tree and which-key
2
3 The key tree (`keymap.ts` `TREE`, `LEADER`, `GO`) in the browser, `src/web/focus/which.ts`, drawn by the shell on every page.
4
5 - `.wk`, `.wk-head`, `.wk-keys`: which-key. After a prefix (Space, a group, or `g`) and a short pause, the next keys and their words, sticky at the foot of `main` as the Bridge's bar is, with the safe area under it. A group is marked `+`. Static, no motion; a fast typist never sees it. Hidden (`[hidden]`) the rest of the time.
6
7 The shared focus layer (`src/web/focus/core.ts`) draws into the page's own bar (home's `.br-*`, `docs/design/areas/home-flow.md`); a picked thing (`v`) wears `[data-picked]`.
docs/design/size-budget/board.json +2 −2
@@ -1,5 +1,5 @@
11 {
22 "page": "/board",
3 "js": 29440,
4 "css": 52736
3 "js": 30208,
4 "css": 52992
55 }
docs/design/size-budget/changelog.json +2 −2
@@ -1,5 +1,5 @@
11 {
22 "page": "/changelog",
3 "js": 30208,
4 "css": 52736
3 "js": 30720,
4 "css": 52992
55 }
docs/design/size-budget/claim.json +2 −2
@@ -1,5 +1,5 @@
11 {
22 "page": "/claim",
3 "js": 27648,
4 "css": 52736
3 "js": 28160,
4 "css": 52992
55 }
docs/design/size-budget/explore.json +2 −2
@@ -1,5 +1,5 @@
11 {
22 "page": "/explore",
3 "js": 24576,
4 "css": 52736
3 "js": 25344,
4 "css": 52992
55 }
docs/design/size-budget/feed.json +2 −2
@@ -1,5 +1,5 @@
11 {
22 "page": "/feed",
3 "js": 39680,
4 "css": 52736
3 "js": 40448,
4 "css": 52992
55 }
docs/design/size-budget/fleet.json +2 −2
@@ -1,5 +1,5 @@
11 {
22 "page": "/fleet",
3 "js": 24576,
4 "css": 52736
3 "js": 25344,
4 "css": 52992
55 }
docs/design/size-budget/forges-new.json +2 −2
@@ -1,5 +1,5 @@
11 {
22 "page": "/forges/new",
3 "js": 24576,
4 "css": 52736
3 "js": 25344,
4 "css": 52992
55 }
docs/design/size-budget/home.json +2 −2
@@ -1,5 +1,5 @@
11 {
22 "page": "/",
3 "js": 24832,
4 "css": 52736
3 "js": 25600,
4 "css": 52992
55 }
docs/design/size-budget/maintenance.json +2 −2
@@ -1,5 +1,5 @@
11 {
22 "page": "/maintenance",
3 "js": 24576,
4 "css": 52736
3 "js": 25344,
4 "css": 52992
55 }
docs/design/size-budget/map.json +2 −2
@@ -1,5 +1,5 @@
11 {
22 "page": "/map",
3 "js": 32256,
4 "css": 54528
3 "js": 32768,
4 "css": 54784
55 }
docs/design/size-budget/owner-name-next.json +2 −2
@@ -1,5 +1,5 @@
11 {
22 "page": "/:owner/:name/next",
3 "js": 26368,
4 "css": 52992
3 "js": 27392,
4 "css": 53504
55 }
docs/design/size-budget/owner-name-pulls-number.json +2 −2
@@ -1,5 +1,5 @@
11 {
22 "page": "/:owner/:name/pulls/:number",
3 "js": 35072,
4 "css": 52736
3 "js": 35840,
4 "css": 52992
55 }
docs/design/size-budget/owner-name-space.json +2 −2
@@ -1,5 +1,5 @@
11 {
22 "page": "/:owner/:name/space",
3 "js": 33536,
4 "css": 54016
3 "js": 34304,
4 "css": 54272
55 }
docs/design/size-budget/owner-name.json +2 −2
@@ -1,5 +1,5 @@
11 {
22 "page": "/:owner/:name",
3 "js": 41728,
4 "css": 52736
3 "js": 42496,
4 "css": 52992
55 }
docs/design/size-budget/pricing.json +2 −2
@@ -1,5 +1,5 @@
11 {
22 "page": "/pricing",
3 "js": 24576,
4 "css": 52736
3 "js": 25344,
4 "css": 52992
55 }
docs/design/size-budget/system.json +2 −2
@@ -1,5 +1,5 @@
11 {
22 "page": "/system",
3 "js": 26368,
4 "css": 52736
3 "js": 27392,
4 "css": 52992
55 }
docs/design/size-budget/talk.json +2 −2
@@ -1,5 +1,5 @@
11 {
22 "page": "/talk",
3 "js": 43008,
4 "css": 59392
3 "js": 43776,
4 "css": 59904
55 }
docs/design/size-budget/templates.json +2 −2
@@ -1,5 +1,5 @@
11 {
22 "page": "/templates",
3 "js": 24576,
4 "css": 52736
3 "js": 25344,
4 "css": 52992
55 }
docs/features/keymap.md +30 −1
@@ -21,6 +21,16 @@ The owner, after the bridge: "tying together all the keybinds is really what im
2121 - **Ranked lists, the space and /system:** /next's rows move with `T` top, `K` up, `J` down and `p` not now, on the page and in the terminal's Next up, where `P` pauses the planner; the space's canvas zooms with `+` and `-`, fits with `0`, jumps to now with `n` and steps bodies with `]` and `[`; /system's process table toggles CPU and memory with `S`, which each sort button carries as its hint. The terminal's cockpit puts a card off with `p` (later, the keymap's park), not `l`. Their old keys (`t` `u` `d` `l`, `c` `m`, the cockpit's `l`) say the new one until 2026-12-15.
2222 - **/boards, /flow and Talk** bind no keys of their own: they answer the shell's moves and nothing fires while typing in Talk's box. The test now has no page left that chooses a key.
2323
24 ## The key tree and combos

Both doors: this adds Space, which-key, counts, . and v on the web only. State here what the terminal does for each, and put the terminal side in src/tui/ or add a No door: <why> line to a commit.

25
26 - **Space, a group, a leaf** (`keymap.ts` `TREE`): `Space g` go, `Space p` this pull (merge, approve, send back, update, close), `Space i` issue (assign, sharpen, park, close), `Space r` runs (queue again, stop, take the wheel, watch), `Space c` crew (tell, slots, flow, the week), `Space f` find (file, command, search, page by name), `Space t` Talk, `Space y` copy (link, commit, branch), `Space ?` the whole tree. A leaf that is a verb presses that verb on what has the focus, so `Space p m` and `m` on a focused pull are one act. Space is the leader only off a control: a button, input, select, editable text, or anything with a control's role (`role=button`, a menu item, a tab, a checkbox) keeps its own Space, and `j`/`k` and Page Down still scroll. The tree and its panel load on the first Space or `g` a page sees (`src/web/which_asset.ts`); the keys typed while it loads are held and played, so a page no one types on carries only a few lines of it.
27 - **Which-key:** after a prefix (Space, a group, or `g`) and a short pause, the next keys and their words show at the foot of the page, static; a fast typist never sees them. Escape or Backspace goes up a level; a key that is nothing says so.
28 - **Combos** (`src/web/focus/core.ts`, home's Bridge first): a count before a move (`3j`); `.` does the last verb again on the newly focused thing; `v` starts picking, the moves add to it, and a verb on the picked says its forecast ("Move to Later 3 rows: 3 will change.") and acts on the second press, with one receipt and Undo.
29
30 ## Go and scopes
31
32 `g` and a letter is a destination in the scope the page is in (`keymap.ts` `GO`, one table): inside a repository `g c` code, `g i` issues, `g p` pulls, `g r` runs, `g m` map, `g l` log (commits), `g b` branches, `g k` forks, `g s` settings; elsewhere `g h` home, `g e` explore, `g f` flow, `g t` Talk, `g n` next up, `g y` system, `g b` boards. A forge place a repository shadows is `g` and the capital there (`g B` boards), or `Space g`, or Cmd/Ctrl K. The chords that moved say where they went until 2026-12-15 when they would now do nothing (`g a`: the map is `g m`; `g s` outside a repository: System is `g y`).
33
2434 ## The terminal gives up g
2535
2636 No terminal screen takes `g` for a verb of its own, so `g` can start a jump there as it does on the web (`test/keymap-terminal.test.ts` holds it). "Read again" is `R` (the map's `reread`). Each screen's own `g` took a letter of its verb:
@@ -34,6 +44,25 @@ No terminal screen takes `g` for a verb of its own, so `g` can start a jump ther
3444 - forges: `M` move to a machine;
3545 - System: `T` telemetry.
3646
37 The old `g` says where each went until 2026-12-15 (`src/tui/screens/moved_key.ts`). A list's own `g`/`G` (top, end) stays until the jump arrives and takes `g g` for the top.
47 The old `g` says where each went until 2026-12-15 (`src/tui/screens/moved_key.ts`), in the title of the go panel it now opens.
48
49 ## The tree in the terminal
50
51 The web and the terminal answer the same tree, `g` table and `v`. The counts (`3j`) and `.` are the Bridge's, on home's lanes, which the terminal has no screen of; its lists move with `j`/`k` and Page Down.
52
53 The terminal reads the same tables (`src/tui/app/which.ts`):
54
55 - **`Space`, a group, a leaf.** A verb presses its key on the screen, so `Space p m` and `m` are one act. A place opens its palette command. What only a web page does (a settings page with no screen, copying a link) says so.
56 - **`g` and a letter** opens a forge place by its palette command (`g h` home, `g f` flow, `g t` Talk, `g y` System, `g b` boards, `g n` next up). **`g g`** is the top of a list, as `Home` is; `G` is still the end.
57 - **The panel** of next keys sits at the foot while a chord is open. Escape or Backspace goes up a level, and a key that is nothing says so.
58 - **Space is the leader only off a control.** A form's checkbox, a picker's tick and the git stage (lazygit-style) keep their Space; `test/keymap-terminal.test.ts` lists them.
59 - **Space moved elsewhere:**
60 - marking is `v` (the dashboard, the Later gate's ticks), and the dashboard's feed link, which had `v`, is `Y`;
61 - the crew and duty switches turn on `Enter`, which they already did;
62 - a grants cell toggles on `Enter`;
63 - the captain's on/off is `o`;
64 - the crew fallback turns on `Enter`.
65
66 The old Space says where it went until 2026-12-15, in the Space panel's title.
3867
3968 Proof: `test/keymap.test.ts`, `test/bridge.test.ts`.
src/http/routes/discovery.ts +2
@@ -3,6 +3,7 @@
33 * the agent and MCP cards, the service worker.
44 */
55
6 import { whichAsset } from "../../web/which_asset.ts";
67 import { TOOLBAR_LAB_PATH, toolbarLabPage, TOOLBAR_LAB_SCRIPT_PATH, toolbarLabScript } from "../../apps/toolbar_lab.ts";
78 import { TOOLBAR_NAME, toolbarResponse } from "../../apps/toolbar.ts";
89 import { registryItem } from "../../registry/serve.ts";
@@ -79,6 +80,7 @@ export function discoveryRoutes(router: Router<Handler>): void {
7980 const dir = ctx.app.config.dataDir;
8081 if (ctx.params.name === shell.name) return assetResponse(ctx.request, shell);
8182 if (ctx.params.name === beaconAsset().name) return assetResponse(ctx.request, beaconAsset());
83 if (ctx.params.name === whichAsset().name) return assetResponse(ctx.request, whichAsset());
8284 const prev = keptAssetNamed(dir, ctx.params.name!, "js");
8385 if (prev !== undefined) return fileResponse(ctx.request, prev);
8486 if (ctx.params.name === TOOLBAR_NAME) return toolbarResponse(ctx.request);
src/tui/app/app.ts +103 −1
@@ -10,6 +10,7 @@
1010 * owns an `AbortController` that `pop()` aborts.
1111 */
1212
13 import { chordOf, whichRows, whichStep, type Chord } from "./which.ts";
1314 import { defect } from "../../kernel/error.ts";
1415 import { oldKeys } from "../../web/keymap.ts";
1516 import { MOUSE_OFF, MOUSE_ON } from "../term/ansi.ts";
@@ -152,6 +153,11 @@ export interface Ctx {
152153 leaveRepo(repoId: string): void;
153154 invalidate(): void;
154155 toast(text: string, tone?: Tone): void;
156 /**
157 * A moved key's line, said in the panel the key now opens (the go panel for an old `g`) instead
158 * of a toast; the key then goes on to the app (`screens/moved_key.ts`).
159 */
160 hint?(text: string): void;
155161 /** Where the terminal caret belongs this frame, if anywhere. */
156162 setCursor(pos: CursorPos | null): void;
157163 /**
@@ -316,7 +322,11 @@ export class App {
316322 private running = false;
317323 private themeName: ThemeName;
318324 private cursor: CursorPos | null = null;
319 private overlay: "none" | "help" | "palette" | "theme" = "none";
325 private overlay: "none" | "help" | "palette" | "theme" | "which" = "none";
326 /** The open Space or g chord, while the which panel is up (`which.ts`). */
327 private chord: Chord | null = null;
328 /** A moved key's line for the panel its key opened (`Ctx.hint`); cleared with the chord. */
329 hinted = "";
320330 private palette = new Palette();
321331 private themeIndex = 0;
322332 /** Where the picker's cursor is: a theme row, then graphics, then icons. */
@@ -436,6 +446,9 @@ export class App {
436446 leaveRepo: (id) => app.leaveRepo(id),
437447 invalidate: () => app.invalidate(),
438448 toast: (text, tone) => app.toast(text, tone),
449 hint: (text) => {
450 app.hinted = text;
451 },
439452 track: (work) => app.track(work),
440453 setCursor: (pos) => {
441454 app.cursor = pos;
@@ -848,6 +861,20 @@ export class App {
848861 // meant an editor with no undo key.
849862 if (e.ctrl && e.key === "z") return;
850863
864 // Space and g, when the screen did not take them, open a chord of the forge's one key tree
865 // (`which.ts`): Space a group a leaf, g a place.
866 const chord = e.ctrl || e.alt ? null : chordOf(e.key);
867 if (chord !== null) {
868 this.chord = chord;
869 this.overlay = "which";
870 return;
871 }
872 if (this.hinted !== "") {
873 this.toast(this.hinted);
874 this.hinted = "";
875 return;
876 }
877
851878 // A key that moved in the forge's one keymap (web/keymap.ts) says where it went, for two weeks,
852879 // on a screen where the new key works: r on a screen that refreshes on R.
853880 if (!e.ctrl && !e.alt) {
@@ -926,7 +953,57 @@ export class App {
926953 ];
927954 }
928955
956 /** The palette commands here: the app's and the top screen's, by id. */
957 private commandsHere(): Command[] {
958 return [...this.commands, ...(this.top().screen.commands?.() ?? [])];
959 }
960
961 /**
962 * One key into the open chord: descend, act, or say it is nothing; Escape and Backspace go up.
963 */
964 private chordKey(e: KeyEvent): void {
965 const chord = this.chord;
966 if (chord === null) {
967 this.overlay = "none";
968 return;
969 }
970 if (e.key === "escape" || (e.key === "backspace" && chord.path.length === 0)) {
971 this.chord = null;
972 this.hinted = "";
973 this.overlay = "none";
974 return;
975 }
976 if (e.key === "backspace") {
977 this.chord = { ...chord, path: chord.path.slice(0, -1) };
978 return;
979 }
980 const commands = this.commandsHere();
981 const step = whichStep(chord, e.key, new Set(commands.map((c) => c.id)));
982 if ("open" in step) {
983 this.chord = step.open;
984 return;
985 }
986 this.chord = null;
987 this.hinted = "";
988 this.overlay = "none";
989 if ("miss" in step) return this.toast(step.miss);
990 const act = step.act;
991 if ("say" in act) return this.toast(act.say);
992 if ("command" in act) {
993 const command = commands.find((c) => c.id === act.command);
994 if (command !== undefined) this.run(command);
995 return;
996 }
997 // A verb or a key: pressed on the screen as if typed, so the screen, Tell and the app's own
998 // keys answer it the way they answer the key itself.
999 this.onKey({ type: "key", key: act.press, ctrl: act.ctrl === true, alt: false, shift: false });
1000 }
1001
9291002 private overlayKey(e: KeyEvent): void {
1003 if (this.overlay === "which") {
1004 this.chordKey(e);
1005 return;
1006 }
9301007 if (this.overlay === "palette") {
9311008 const before = this.palette.query;
9321009 const result = this.palette.key(e);
@@ -1116,6 +1193,7 @@ export class App {
11161193 }
11171194 if (this.overlay === "help") this.drawHelp(body!, c);
11181195 if (this.overlay === "theme") this.drawThemes(body!, c);
1196 if (this.overlay === "which") this.drawWhich(body!, c);
11191197 this.flush();
11201198 this.flushImage();
11211199 }
@@ -1234,6 +1312,30 @@ export class App {
12341312 });
12351313 }
12361314
1315 /**
1316 * The open chord's next keys, at the foot of the body: a group marked +. Static, as on the web.
1317 */
1318 private drawWhich(area: Rect, c: Tokens): void {
1319 const s = this.surface;
1320 if (this.chord === null) return;
1321 const drawn = whichRows(this.chord, new Set(this.commandsHere().map((x) => x.id)));
1322 const title = this.hinted === "" ? drawn.title : `${drawn.title} · ${this.hinted}`;
1323 const rows = drawn.rows;
1324 const cols = Math.max(1, Math.floor((area.w - 2) / 26));
1325 const lines = Math.ceil(rows.length / cols);
1326 const height = Math.min(area.h, lines + 2);
1327 const r = { x: area.x, y: area.y + Math.max(0, area.h - height), w: area.w, h: height };
1328 const inner = card(s, r, c, { title, focused: true });
1329 rows.forEach((row, i) => {
1330 const x = inner.x + Math.floor(i / lines) * 26;
1331 const y = inner.y + (i % lines);
1332 if (y >= inner.y + inner.h || x >= inner.x + inner.w) return;
1333 const k = row.key === " " ? "space" : row.key;
1334 s.text(x, y, k, style(c.accent, c.card), inner.x + inner.w);
1335 s.text(x + 4, y, truncate(`${row.group === true ? "+" : ""}${row.label}`, 21), style(c.fg, c.card), inner.x + inner.w);
1336 });
1337 }
1338
12371339 /**
12381340 * Appearance: the theme list, then the two terminal preferences, then a
12391341 * line of real icons in the set that is currently chosen.
src/tui/app/which.ts added +111
@@ -0,0 +1,111 @@
1 /**
2 * The key tree in the terminal (web/keymap.ts TREE, LEADER, GO): the web's Space and `g`, read
3 * from the same tables, so a key learned on one door works on the other.
4 *
5 * - `Space`, a group, a leaf. A leaf that is a verb presses that verb's key on the screen, so
6 * `Space p m` and `m` are one act; a place opens its palette command; what only a web page does
7 * (a settings page with no screen yet, copying a link) says so.
8 * - `g` and a letter opens a forge place by its palette command; `g g` is the top of a list.
9 * - The panel listing the next keys is drawn while a chord is open; Escape or Backspace goes up a
10 * level, and a key that is nothing says so.
11 *
12 * Space is the leader only when the screen did not take it: a form's checkbox, a picker's tick and
13 * the git stage keep their Space, as a control does on the web.
14 */
15 import { GO, GO_PREFIX, KEYMAP, LEADER, TREE, type TreeLeaf } from "../../web/keymap.ts";
16
17 export interface Chord {
18 readonly kind: "leader" | "go";
19 /** The keys pressed after the prefix. */
20 readonly path: readonly string[];
21 }
22
23 export interface WhichRow {
24 readonly key: string;
25 readonly label: string;
26 readonly group?: boolean;
27 }
28
29 /**
30 * What a chord's last key does: press a key on the screen, run a palette command, or say a line.
31 */
32 export type WhichAct = { readonly press: string; readonly ctrl?: boolean } | { readonly command: string } | { readonly say: string };
33
34 export type WhichStep = { readonly open: Chord } | { readonly act: WhichAct } | { readonly miss: string };
35
36 /** The forge's places, as the terminal's palette commands that open them. */
37 const PLACE_COMMAND: Record<keyof typeof GO.global, string> = {
38 home: "home",
39 explore: "explore",
40 flow: "flow",
41 talk: "conversations",
42 next: "next-up",
43 system: "system",
44 boards: "boards",
45 };
46 const PLACE_WORD: Record<keyof typeof GO.global, string> = {
47 home: "Home",
48 explore: "Explore",
49 flow: "Flow",
50 talk: "Talk",
51 next: "Next up",
52 system: "System",
53 boards: "Boards",
54 };
55 /** A tree leaf's web address, as the terminal command that shows the same thing. */
56 const HREF_COMMAND: Record<string, string> = { "/flow": "flow", "/talk": "conversations", "/?view=lanes#slots": "home" };
57
58 /** The g places this terminal offers: those with a command here. */
59 function places(commands: ReadonlySet<string>): { key: string; label: string; command: string }[] {
60 return (Object.keys(GO.global) as (keyof typeof GO.global)[])
61 .filter((p) => commands.has(PLACE_COMMAND[p]))
62 .map((p) => ({ key: GO.global[p], label: PLACE_WORD[p], command: PLACE_COMMAND[p] }));
63 }
64
65 function leafAct(f: TreeLeaf): WhichAct {
66 const d = f.does;
67 if ("verb" in d) return { press: KEYMAP[d.verb].key };
68 if ("press" in d) return d.press.startsWith("Mod+") ? { press: d.press.slice(4), ctrl: true } : { press: d.press };
69 if ("href" in d) {
70 const command = HREF_COMMAND[d.href];
71 return command === undefined ? { say: `That is a page on the web: ${d.href}` } : { command };
72 }
73 return { say: "Copying is the web page's: Space y there." };
74 }
75
76 /** The panel for an open chord: its title and the next keys. */
77 export function whichRows(chord: Chord, commands: ReadonlySet<string>): { title: string; rows: WhichRow[] } {
78 if (chord.kind === "go")
79 return {
80 title: "g · go",
81 rows: [{ key: GO_PREFIX, label: "top of the list" }, ...places(commands).map(({ key, label }) => ({ key, label }))],
82 };
83 const [group] = chord.path;
84 if (group === undefined) return { title: "Space", rows: TREE.map((g) => ({ key: g.key, label: g.label, group: true })) };
85 if (group === GO_PREFIX) return { title: "Space g · go", rows: places(commands).map(({ key, label }) => ({ key, label })) };
86 const g = TREE.find((x) => x.key === group);
87 return { title: `Space ${group} · ${g?.label ?? ""}`, rows: (g?.leaves ?? []).map((f) => ({ key: f.key, label: f.label })) };
88 }
89
90 /** One more key into an open chord. */
91 export function whichStep(chord: Chord, key: string, commands: ReadonlySet<string>): WhichStep {
92 const said = `${chord.kind === "leader" ? "Space" : GO_PREFIX} ${[...chord.path, key].join(" ")}`.replace(/ +/g, " ");
93 const miss = { miss: `${said === "Space " ? "Space Space" : said} is nothing here.` };
94 if (chord.kind === "go") {
95 if (key === GO_PREFIX) return { act: { press: "home" } };
96 const place = places(commands).find((p) => p.key === key);
97 return place === undefined ? miss : { act: { command: place.command } };
98 }
99 const [group] = chord.path;
100 if (group === undefined) return TREE.some((g) => g.key === key) ? { open: { kind: "leader", path: [key] } } : miss;
101 if (group === GO_PREFIX) {
102 const place = places(commands).find((p) => p.key === key);
103 return place === undefined ? miss : { act: { command: place.command } };
104 }
105 const leaf = TREE.find((g) => g.key === group)?.leaves.find((f) => f.key === key);
106 return leaf === undefined ? miss : { act: leafAct(leaf) };
107 }
108
109 /** Whether `key` opens a chord, and which. */
110 export const chordOf = (key: string): Chord | null =>
111 key === LEADER || key === "space" ? { kind: "leader", path: [] } : key === GO_PREFIX ? { kind: "go", path: [] } : null;
src/tui/screens/captain.ts +5 −2
@@ -9,6 +9,7 @@
99 * space turn a routine on or off p post a routine now r read again
1010 */
1111
12 import { movedKey } from "./moved_key.ts";
1213 import { runRoutine } from "../../crew/routines.ts";
1314 import { keyOf } from "../../web/keymap.ts";
1415 import { costLine, dayCost } from "../../crew/captain_cost.ts";
@@ -79,7 +80,7 @@ export function captainScreen(f: Session, ctx: Ctx): Screen {
7980 };
8081 const screen: Screen = {
8182 title: "Captain",
82 keys: [binding(["j", "k"], "move"), binding(["a"], "add a rule"), binding(["enter"], "edit"), binding(["d"], "delete"), binding(["space"], "on/off"), binding(["p"], "post now / pause a watch"), binding(["w"], "add a watch"), binding(["e"], "end a watch now"), binding([keyOf("reread")], "refresh"), binding(["esc", "q"], "close")],
83 keys: [binding(["j", "k"], "move"), binding(["a"], "add a rule"), binding(["enter"], "edit"), binding(["d"], "delete"), binding(["o"], "on/off"), binding(["p"], "post now / pause a watch"), binding(["w"], "add a watch"), binding(["e"], "end a watch now"), binding([keyOf("reread")], "refresh"), binding(["esc", "q"], "close")],
8384 load: read,
8485 render(area, s) {
8586 drawList(s, area, ctx.theme.c, state, captainRows(lines));
@@ -137,7 +138,9 @@ export function captainScreen(f: Session, ctx: Ctx): Screen {
137138 removeMemory(f.app.db, f.user!.id, at.rule.id);
138139 ctx.toast("Forgotten.", "success");
139140 refresh();
140 } else if (e.key === " " && at?.kind === "routine") {
141 } else if (at?.kind === "routine" && movedKey(ctx, e, " ", "o turns it on or off now")) {
142 return true;
143 } else if (e.key === "o" && at?.kind === "routine") {
141144 const r = at.routine;
142145 setRoutine(f.app.db, f.user!.id, r.kind, { enabled: !r.enabled, everyMin: r.everyMin, atHour: r.atHour });
143146 refresh();
src/tui/screens/common.ts +3 −2
@@ -125,7 +125,8 @@ export class ListState {
125125 if (e.key === "pgup") return this.take(-this.height, length);
126126 if (e.key === "j" || e.key === "down") return this.take(1, length);
127127 if (e.key === "k" || e.key === "up") return this.take(-1, length);
128 if (e.key === "g" || e.key === "home") return this.jump(0, length);
128 // g opens a jump (the app's chord); g g, like Home, is the top.
129 if (e.key === "home") return this.jump(0, length);
129130 if (e.key === "G" || e.key === "end") return this.jump(length - 1, length);
130131 return false;
131132 }
@@ -166,7 +167,7 @@ export class Scroll {
166167 if (e.key === "pgup") return this.by(-this.height, total);
167168 if (e.key === "j" || e.key === "down") return this.by(1, total);
168169 if (e.key === "k" || e.key === "up") return this.by(-1, total);
169 if (e.key === "g" || e.key === "home") return this.by(-total, total);
170 if (e.key === "home") return this.by(-total, total);
170171 if (e.key === "G" || e.key === "end") return this.by(total, total);
171172 return false;
172173 }
src/tui/screens/crewfallback.ts +4 −2
@@ -6,6 +6,7 @@
66 * and the same two steps as the page (`crew/key_fallback.ts`). A forge admin who is a person only.
77 */
88
9 import { movedKey } from "./moved_key.ts";
910 import { capForecast, fallbackView, setFallback, setFallbackCap, type FallbackView } from "../../crew/key_fallback.ts";
1011 import type { Ctx, Screen } from "../app/app.ts";
1112 import { binding } from "../app/keys.ts";
@@ -51,7 +52,7 @@ export function crewFallbackScreen(f: Session, ctx: Ctx): Screen {
5152 };
5253 const screen: Screen = {
5354 title: "Metered fallback",
54 keys: [binding(["space"], "on/off"), binding(["c"], "set the cap"), binding(["u"], "undo the cap"), binding(["esc", "q"], "back")],
55 keys: [binding(["enter"], "on/off"), binding(["c"], "set the cap"), binding(["u"], "undo the cap"), binding(["esc", "q"], "back")],
5556 render(area, s) {
5657 const c = ctx.theme.c;
5758 const lines = [...fallbackLines(f), ...(note === "" ? [] : ["", note])];
@@ -60,7 +61,8 @@ export function crewFallbackScreen(f: Session, ctx: Ctx): Screen {
6061 key(e) {
6162 if (e.ctrl || e.alt) return true;
6263 if (e.key === "esc" || e.key === "q") ctx.pop();
63 else if (e.key === "space" && mayAct(f)) {
64 else if (movedKey(ctx, e, " ", "Enter turns it on or off now")) return true;
65 else if (e.key === "enter" && mayAct(f)) {
6466 const on = !fallbackView(f.app).on;
6567 if (setFallback(f.app, f.user, on).ok) note = on ? "The fallback is on." : "The fallback is off: crew runs wait for the first window to reset.";
6668 } else if (e.key === "u" && mayAct(f) && was !== undefined) {
src/tui/screens/crewswitch.ts +2 −2
@@ -32,7 +32,7 @@ export function crewSwitchLines(f: Session, repo: Repo): string[] {
3232 export function crewSwitchScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
3333 return {
3434 title: `${repo.ownerName}/${repo.name} — Crew builds here`,
35 keys: [binding(["enter", "space"], "turn on or off"), binding(["esc", "q"], "back")],
35 keys: [binding(["enter"], "turn on or off"), binding(["esc", "q"], "back")],
3636 async load(signal) {
3737 live(f, signal, { repoId: repo.id, where: (e) => e.kind === "repo.settings_updated" }, () => ctx.invalidate());
3838 },
@@ -43,7 +43,7 @@ export function crewSwitchScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
4343 key(e) {
4444 if (e.ctrl || e.alt) return true;
4545 if (e.key === "esc" || e.key === "q") ctx.pop();
46 else if (e.key === "enter" || e.key === " " || e.key === "space") {
46 else if (e.key === "enter") {
4747 const set = setCrewHere(f.app, f.user, repo, !crewBuildsHere(f.db, repo.id));
4848 if (set.ok) ctx.toast(crewHereSaid(set.value.on));
4949 else ctx.toast(NOT_YOURS, "danger");
src/tui/screens/dashboard.ts +12 −8
@@ -14,6 +14,7 @@
1414 * whole of this screen's design.
1515 */
1616
17 import { movedKey } from "./moved_key.ts";
1718 import { readyAsk } from "../../spawn/template_record.ts";
1819 import { keyOf } from "../../web/keymap.ts";
1920 import { DEFAULT_WEIGHTS, frontWeights, type FrontWeights } from "../../core/front.ts";
@@ -480,7 +481,7 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
480481
481482 const loadSinceLines = (): void => {
482483 const d = f.user ? sinceDigest(f.app.db, f.user, lastVisit(f.app.db, f.user.id), Date.now()) : undefined;
483 sinceLines = d === undefined ? [] : [d.heading, ...d.lines.map((l) => ` ${l.says}`), ` ${FEED_MORE} (v)`];
484 sinceLines = d === undefined ? [] : [d.heading, ...d.lines.map((l) => ` ${l.says}`), ` ${FEED_MORE} (Y)`];
484485 quiet = f.user !== undefined && quietFor({ app: f.app }, f.user, d !== undefined);
485486 ctx.invalidate();
486487 };
@@ -1260,7 +1261,7 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
12601261 ...(lastHand !== undefined ? [binding(["U"], "undo decider")] : []),
12611262 ...(focus === "onyou" && onYou.length > 0
12621263 ? [
1263 binding(["space"], "mark"),
1264 binding(["v"], "mark"),
12641265 binding(["x"], "close"),
12651266 binding(["m"], "mute"),
12661267 binding(["H"], HIDE_APP_DAY_WORDS.toLowerCase()),
@@ -1287,7 +1288,7 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
12871288 ...(clientNextSteps(f.user).some((s) => s.key === "i") ? [binding(["i"], "invite someone")] : []),
12881289 ]
12891290 : []),
1290 ...(sinceLines.length > 0 ? [binding(["v"], "feed link")] : []),
1291 ...(sinceLines.length > 0 ? [binding(["Y"], "feed link")] : []),
12911292 ...(clientLive.size > 0 ? [binding(["o"], "open the app")] : []),
12921293 ...(exploring() && explored?.next != null
12931294 ? [binding(["n"], "more results")]
@@ -1296,7 +1297,7 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
12961297 binding(["A"], "account", { disabled: !f.signedIn }),
12971298 binding(["s"], "sign in", { disabled: f.signedIn }),
12981299 ...(focus === "repos" && f.user !== undefined && shown().some(mayArchive)
1299 ? [binding(["space"], "mark"), ...(markedRepos.size > 0 ? [binding(["a"], "archive marked")] : [])]
1300 ? [binding(["v"], "mark"), ...(markedRepos.size > 0 ? [binding(["a"], "archive marked")] : [])]
13001301 : []),
13011302 binding([keyOf("reread")], "refresh"),
13021303 ];
@@ -1498,7 +1499,8 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
14981499 }
14991500 if (focus === "onyou" && f.user !== undefined) {
15001501 const item = onYou[at("onyou").index];
1501 if (e.key === "space" && item !== undefined && item.hand !== true) {
1502 if (movedKey(ctx, e, " ", "v marks now")) return true;
1503 if (e.key === "v" && item !== undefined && item.hand !== true) {
15021504 if (!marked.delete(item.issue.id)) marked.add(item.issue.id);
15031505 return true;
15041506 }
@@ -1515,13 +1517,14 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
15151517 if (e.key === "l") return actOnWave("later"), true;
15161518 }
15171519 if (e.key === "B" && f.user && asideWaves.length > 0) return bringBackWaves(), true;
1518 if (focus === "repos" && f.user !== undefined && exploring() && (e.key === "space" || e.key === "a" || e.key === "p")) {
1520 if (focus === "repos" && f.user !== undefined && exploring() && (e.key === "v" || e.key === "a" || e.key === "p")) {
15191521 ctx.toast("pin, mark and archive act on your repositories; esc clears the explorer line", "attn");
15201522 return true;
15211523 }
15221524 if (focus === "repos" && f.user !== undefined) {
15231525 const repo = shown()[at("repos").index];
1524 if (e.key === "space" && repo !== undefined && mayArchive(repo)) {
1526 if (movedKey(ctx, e, " ", "v marks now")) return true;
1527 if (e.key === "v" && repo !== undefined && mayArchive(repo)) {
15251528 if (!markedRepos.delete(repo.id)) markedRepos.add(repo.id);
15261529 ctx.invalidate();
15271530 return true;
@@ -1592,7 +1595,8 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
15921595 if (repo && clientRepoIds.has(repo.id)) askForSomething(f, ctx, () => screen, repo);
15931596 return true;
15941597 }
1595 if (e.key === "v" && sinceLines.length > 0) {
1598 if (sinceLines.length > 0 && movedKey(ctx, e, "v", "Y copies the feed link now")) return true;
1599 if (e.key === "Y" && sinceLines.length > 0) {
15961600 // The terminal's filter is the chips, kept per person and read by the feed itself; the link
15971601 // carries none.
15981602 ctx.push(linkScreen(ctx, `${publicOrigin(f.app.config.url, `http://localhost:${f.app.config.port}`)}/feed`, screen));
src/tui/screens/dutyswitch.ts +2 −2
@@ -60,7 +60,7 @@ export function dutySwitchScreen(session: Session, ctx: Ctx): Screen {
6060 const count = (): number => dutyStates(session.db).length;
6161 self = {
6262 title: "Maintenance duties",
63 keys: [binding(["j", "k"], "choose"), binding(["enter", "space"], "pause or resume"), binding(["d"], "dismiss 7 days"), binding(["esc", "q"], "back")],
63 keys: [binding(["j", "k"], "choose"), binding(["enter"], "pause or resume"), binding(["d"], "dismiss 7 days"), binding(["esc", "q"], "back")],
6464 render(area, s) {
6565 const c = ctx.theme.c;
6666 const lines = [...dutyLines(session, chosen), ...(note === "" ? [] : ["", note])];
@@ -82,7 +82,7 @@ export function dutySwitchScreen(session: Session, ctx: Ctx): Screen {
8282 return undefined;
8383 },
8484 }));
85 } else if (e.key === "enter" || e.key === " " || e.key === "space") note = flipDuty(session, chosen);
85 } else if (e.key === "enter") note = flipDuty(session, chosen);
8686 else return false;
8787 ctx.invalidate();
8888 return true;
src/tui/screens/fleet.ts +1 −1
@@ -168,7 +168,7 @@ export function fleetScreen(
168168 if (e.ctrl || e.alt) return scroll.key(e, Math.max(0, lines.length - 1));
169169 if (e.key === "esc" || e.key === "q") ctx.pop();
170170 else if (e.key === "/") ask();
171 else if ((e.key === "x" || e.key === " ") && view?.ok && mayAct(session.user)) mark(view.rows);
171 else if (e.key === "x" && view?.ok && mayAct(session.user)) mark(view.rows);
172172 else if (e.key === "v" && view?.ok && mayAct(session.user)) verb();
173173 else if (e.key === "u" && last !== undefined && mayAct(session.user)) undo();
174174 else if (e.key === "s" && view?.ok) sort = nextSort(view.kind, sort);
src/tui/screens/forges.ts +2 −1
@@ -402,6 +402,8 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses
402402 drawFacts(s, { x: inner.x + 1, y: inner.y, w: Math.max(0, inner.w - 1), h: inner.h }, c, shown, c.card);
403403 },
404404 key(e) {
405 // The old g says M (in the go panel it opens, or a toast), before anything takes the key.
406 if (e.key === "g") return movedKey(ctx, e, "g", "M moves it to a machine now");
405407 if (e.key === "esc" || e.key === "q") ctx.pop();
406408 else if (e.key === "f") {
407409 state = nextClientState(state);
@@ -456,7 +458,6 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses
456458 );
457459 } else if (e.key === "m") sandboxOne();
458460 else if (e.key === "M") machineOne(false);
459 else if (e.key === "g") movedKey(ctx, e, "g", "M moves it to a machine now");
460461 else if (e.key === "v") machineOne(true);
461462 else if (e.key === "e") upgradeOne();
462463 else if (e.key === "h") machinesSeen();
src/tui/screens/grants.ts +5 −3
@@ -7,6 +7,7 @@
77 * can be written. A subscription shows its name and kind, never its token.
88 */
99
10 import { movedKey } from "./moved_key.ts";
1011 import { listCrewRoles } from "../../core/agents.ts";
1112 import { canAdmin, type Repo } from "../../core/repos.ts";
1213 import { EVERYONE, listGrants, listSubscriptions, setGrants, type Subscription } from "../../core/subscriptions.ts";
@@ -63,7 +64,7 @@ export function grantsScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
6364 const screen: Screen = {
6465 title: "Crew grants",
6566 keys: admitted()
66 ? [binding(["j", "k"], "move cursor"), binding(["h", "l"], "choose subscription"), binding(["space"], "toggle"), binding(["esc"], "back")]
67 ? [binding(["j", "k"], "move cursor"), binding(["h", "l"], "choose subscription"), binding(["enter"], "toggle"), binding(["esc"], "back")]
6768 : [],
6869 render(area, s) {
6970 const c = ctx.theme.c;
@@ -74,7 +75,7 @@ export function grantsScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
7475 ? "Runs here work on the forge's own token. Add one on the Crew subscriptions screen first."
7576 : note !== ""
7677 ? note
77 : "h and l choose a subscription, space ticks it. Nothing ticked means the wider grant applies.";
78 : "h and l choose a subscription, Enter ticks it. Nothing ticked means the wider grant applies.";
7879 s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
7980 if (pool.length > 0) drawList(s, body!, c, state, listed);
8081 },
@@ -88,7 +89,8 @@ export function grantsScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
8889 if (e.ctrl || e.alt) return false;
8990 if (e.key === "h" || e.key === "left") at = Math.max(0, at - 1);
9091 else if (e.key === "l" || e.key === "right") at = Math.min(pool.length - 1, at + 1);
91 else if (e.key === " " || e.key === "space") {
92 else if (movedKey(ctx, e, " ", "Enter toggles now")) return true;
93 else if (e.key === "enter") {
9294 // Read at use, so a crew changed under the session is not written to.
9395 const fresh = [{ id: EVERYONE }, ...listCrewRoles(f.db, repo.id).map((c) => ({ id: c.agent.user.id }))];
9496 const row = who[state.index];
src/tui/screens/held.ts +4 −2
@@ -11,6 +11,7 @@
1111 * l lift (or revive, on a closed) enter open the issue
1212 */
1313
14 import { movedKey } from "./moved_key.ts";
1415 import { BAD_DATE, REVIVE_UNTIL } from "../../core/gate_snooze.ts";
1516 import { liftHold } from "../../actions/gate.ts";
1617 import { applyGateReview, reviewGate, type GateReview } from "../../actions/gate_review.ts";
@@ -154,7 +155,7 @@ export function heldScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
154155 title: `Held · ${repo.ownerName}/${repo.name}`,
155156 keys: [
156157 binding(["j", "k"], "move"),
157 binding(["space"], "tick"),
158 binding(["v"], "tick"),
158159 binding(["A"], "apply the ticked"),
159160 binding(["l"], "lift / revive"),
160161 binding(["u"], "lift until a date"),
@@ -176,7 +177,8 @@ export function heldScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
176177 },
177178 key(e) {
178179 if (e.key === "esc" || e.key === "q") ctx.pop();
179 else if (e.key === " " || e.key === "space") toggle(state.index);
180 else if (e.key === "v") toggle(state.index);
181 else if (movedKey(ctx, e, " ", "v ticks now")) return true;
180182 else if (e.key === "A") apply();
181183 else if (e.key === "l") void lift(state.index);
182184 else if (e.key === "u") snooze(state.index);
src/tui/screens/moved_key.ts +14 −4
@@ -4,16 +4,26 @@
44 * does nothing else.
55 *
66 * Screens give up `g` alone so that `g` can start a jump, as it does on the web: "read again"
7 * went to `R` (the map's `reread`, hinted by the app for every screen that refreshes on it), and
8 * each screen's own `g` went to a letter of its verb.
7 * went to `R` (the map's `reread`), and each screen's own `g` went to a letter of its verb. In the
8 * app the old `g` opens the go panel as everywhere, and the line is said in its title
9 * (`Ctx.hint`); without that panel it is a toast and the key stops here.
910 */
1011 import { oldKeysHinted } from "../../web/keymap.ts";
1112 import type { Ctx } from "../app/app.ts";
1213 import type { KeyEvent } from "../term/input.ts";
1314
14 /** True, after saying `says`, when `e` is the key `was` and the hint's date has not passed. */
15 /**
16 * When `e` is the key `was` and the hint's date has not passed: hands `says` to the panel the key
17 * opens and lets the key go on (false), or, where there is none, toasts it and stops the key
18 * (true).
19 */
1520 export function movedKey(ctx: Ctx, e: KeyEvent, was: string, says: string): boolean {
16 if (e.ctrl || e.alt || e.key !== was || !oldKeysHinted()) return false;
21 const key = e.key === "space" ? " " : e.key;
22 if (e.ctrl || e.alt || key !== was || !oldKeysHinted()) return false;
23 if (ctx.hint !== undefined) {
24 ctx.hint(`${says} (was ${was === " " ? "Space" : was})`);
25 return false;
26 }
1727 ctx.toast(says);
1828 return true;
1929 }
src/tui/screens/orggrants.ts +5 −3
@@ -12,6 +12,7 @@
1212 * `setGrants` call, made directly because `saveGrants` reads a request form.
1313 */
1414
15 import { movedKey } from "./moved_key.ts";
1516 import { listAgents } from "../../core/agents.ts";
1617 import { accessAllows, listOrgsForUser, orgAccess } from "../../core/orgs.ts";
1718 import { EVERYONE, listGrants, listSubscriptions, setGrants, type Subscription } from "../../core/subscriptions.ts";
@@ -73,11 +74,11 @@ function grantsScreen(f: Session, ctx: Ctx, org: User): Screen {
7374
7475 const screen: Screen = {
7576 title: `Grants of ${org.username}`,
76 keys: [binding(["j", "k"], "move row"), binding(["h", "l"], "move account"), binding(["space"], "toggle"), binding(["esc"], "back")],
77 keys: [binding(["j", "k"], "move row"), binding(["h", "l"], "move account"), binding(["enter"], "toggle"), binding(["esc"], "back")],
7778 render(area, s) {
7879 const c = ctx.theme.c;
7980 const [head, body] = split(area, "v", [len(1), fill(1)]);
80 const text = note !== "" ? note : "One decision for every repository here without a grant of its own. space toggles.";
81 const text = note !== "" ? note : "One decision for every repository here without a grant of its own. Enter toggles.";
8182 s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
8283 drawList(s, body!, c, state, rows());
8384 },
@@ -87,7 +88,8 @@ function grantsScreen(f: Session, ctx: Ctx, org: User): Screen {
8788 if (e.ctrl || e.alt) return false;
8889 if (e.key === "h" || e.key === "left") col = Math.max(0, col - 1);
8990 else if (e.key === "l" || e.key === "right") col = Math.max(0, Math.min(subs.length - 1, col + 1));
90 else if (e.key === " " || e.key === "space") {
91 else if (movedKey(ctx, e, " ", "Enter toggles now")) return true;
92 else if (e.key === "enter") {
9193 const w = who[state.index];
9294 const sub = subs[col];
9395 if (w === undefined || sub === undefined) return true;
src/tui/screens/runlog.ts +1 −1
@@ -76,7 +76,7 @@ export function runLogScreen(
7676 return [
7777 binding(["j", "k"], "scroll"),
7878 binding(["pgup", "pgdn"], "page"),
79 binding(["g", "G"], "top, end"),
79 binding(["g g", "G"], "top, end"),
8080 binding(["o"], "open on the web"),
8181 binding([keyOf("reread")], "refresh"),
8282 ...(offer() ? [binding(["a"], "start now on your own account")] : []),
src/tui/screens/system.ts +2 −1
@@ -479,11 +479,12 @@ export function systemScreen(ctx: Ctx, lines: readonly string[], session: Sessio
479479 buttons.forEach((rect) => ctx.hit(rect, () => ctx.pop()));
480480 },
481481 key(e) {
482 // The old g says T (in the go panel it opens, or a toast), before anything takes the key.
483 if (e.key === "g") return movedKey(ctx, e, "g", "T grants or takes back telemetry now");
482484 if (e.key === "h") {
483485 span = (span + 1) % WINDOWS.length;
484486 history = historyLines(session, WINDOWS[span]!);
485487 } else if (e.key === "T") askGrant();
486 else if (e.key === "g") movedKey(ctx, e, "g", "T grants or takes back telemetry now");
487488 else if (e.key === "x" && canSeeMemory(session.user)) later(ctx, () => seriesScreen(session, ctx));
488489 else if (e.key === "d" && reads) later(ctx, () => dbSizeScreen(session, ctx));
489490 else if (e.key === "a" && mayReadAtlas(session.user)) later(ctx, () => abstractionsScreen(session, ctx));
src/web/bridge_client.ts +87 −174
@@ -30,122 +30,84 @@
3030 * so the shell clicks them, `?` lists them, and no key is taken from a page without a selection
3131 * (`t` stays Tell the crew). A swapped lane keeps the selection: the tile with the same key is
3232 * selected again. The bar has no motion: it is what a person does many times a day.
33 *
34 * The bar, verbs, forecast and Undo, counts (3j), `.` and `v` are the shared focus layer's
35 * (`focus/core.ts`), which the pull and issue panes use too; this file is home's things, lanes and
36 * figures, as that layer's config.
3337 */
3438 import { html } from "./html.ts";
35 import { MOVES, verbsForScript } from "./keymap.ts";
39 import { focusCoreJs } from "./focus/core.ts";
3640
3741 /** The bar's one place on home: empty until a tile is selected. */
3842 export const bridgeBar = html`<div class="br-bar" id="bridge" role="region" aria-label="What you can do to the selected tile" hidden><div class="br-body" data-body></div><p class="br-said small" data-said aria-live="polite"></p></div>`;
3943
4044 export const bridgeJs = /* js */ `
45 ${focusCoreJs}
4146 (function () {
4247 var bar = document.getElementById('bridge');
43 if (!bar) return;
44 // What a verb did is said in the bar's one live region, which is on the page from the start, so a
45 // screen reader announces each answer; the rest of the bar is drawn into its body.
46 var body = bar.querySelector('[data-body]'), said = bar.querySelector('[data-said]');
47 var D = document, sel = null, armed = 0;
48 var coarse = window.matchMedia && window.matchMedia('(pointer: coarse)').matches;
48 if (!bar || !window.forgeFocus) return;
49 var D = document;
4950 var LANE = { asked: 'Asked', building: 'Building', checks: 'Checks', review: 'Review', landing: 'Landing', live: 'Live' };
5051 function tileOf(el) { return el && el.closest ? el.closest('.tile[data-key], .sl[data-nav]') : null; }
5152 function keyOf(t) { return t.classList.contains('sl') ? 'slots:' + t.getAttribute('data-kind') : t.getAttribute('data-key'); }
52 // The forge's own way to say a span (flow/pipeline.ts span): 45s, 12m, 3h 5m, 2d 4h.
53 function span(ms) {
54 var s = Math.max(0, Math.round(ms / 1000)); if (s < 60) return s + 's';
55 var m = Math.floor(s / 60); if (m < 60) return m + 'm';
56 var h = Math.floor(m / 60); if (h < 48) return m % 60 === 0 ? h + 'h' : h + 'h ' + (m % 60) + 'm';
57 return Math.floor(h / 24) + 'd ' + (h % 24) + 'h';
53 function findByKey(k) {
54 if (k.indexOf('slots:') === 0) return D.querySelector('.sl[data-nav][data-kind="' + k.slice(6) + '"]');
55 return D.querySelector('.tile[data-key="' + (window.CSS && CSS.escape ? CSS.escape(k) : k) + '"]');
5856 }
59 function el(tag, cls, text) { var e = D.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; }
60 // Every key and its word come from the forge's one keymap (keymap.ts): a verb is named, never typed.
61 var VERB = ${JSON.stringify(verbsForScript())};
62 var MOVE = { down: ${JSON.stringify(MOVES.down.key)}, up: ${JSON.stringify(MOVES.up.key)}, left: ${JSON.stringify(MOVES.left.key)}, right: ${JSON.stringify(MOVES.right.key)} };
63 function verb(id, act) {
64 var k = VERB[id][0], label = VERB[id][1];
65 var b = el(act.href ? 'a' : 'button', 'btn', null);
66 if (act.href) b.href = act.href; else b.type = 'button';
67 b.setAttribute('data-size', 'sm');
68 b.setAttribute('data-shortcut', k);
69 b.appendChild(el('kbd', null, k)); b.appendChild(D.createTextNode(' ' + label));
70 if (act.run) b.addEventListener('click', function (e) { e.preventDefault(); act.run(b); });
71 return b;
72 }
73 // The bar always says how to put it away: a Close button with its key, beside the head.
74 function top(head) {
75 var row = el('div', 'br-top', null), b = el('button', 'btn br-close', null);
76 b.type = 'button'; b.setAttribute('data-size', 'sm'); b.setAttribute('data-variant', 'ghost'); b.setAttribute('aria-label', 'Close the bar (Escape)'); b.setAttribute('aria-keyshortcuts', 'Escape');
77 b.appendChild(el('span', null, '\u00d7 Close')); b.appendChild(el('kbd', null, 'Esc'));
78 b.addEventListener('click', function () { clear(); if (D.activeElement && D.activeElement.blur) D.activeElement.blur(); });
79 row.appendChild(head); row.appendChild(b);
80 return row;
81 }
82 function say(text, extra) {
83 said.textContent = text;
84 if (extra) { said.appendChild(D.createTextNode(' ')); said.appendChild(extra); }
85 }
86 function act(op, ids, then) {
87 var body = new URLSearchParams();
88 body.set('op', op); body.set('phase', 'apply');
89 ids.forEach(function (id) { body.append('ids', id); });
90 say('Doing it…');
91 fetch('/home/act', { method: 'POST', body: body, credentials: 'same-origin', headers: { accept: 'application/json' } })
92 .then(function (r) { return r.json().catch(function () { return { ok: false, error: 'That did not go through (' + r.status + ').' }; }); })
93 .then(function (j) {
94 if (!j.ok) { say(j.error || 'That did not go through. Nothing changed.'); return; }
95 var a = null;
96 if (j.receipt) { a = el('a', null, j.reversible ? 'Receipt and Undo' : 'Receipt'); a.href = j.receipt; }
97 say(j.summary || 'Done.', a);
98 if (then) then();
99 })
100 .catch(function () { say('Could not reach the forge. Nothing changed.'); });
101 }
102 // A verb with a route of its own (Update): the form it already is, posted from here.
103 function post(url, done) {
104 say('Doing it…');
105 fetch(url, { method: 'POST', body: new URLSearchParams(), credentials: 'same-origin', headers: { accept: 'application/json' } })
106 .then(function (r) { return r.json().catch(function () { return {}; }).then(function (j) { say(r.ok && j.ok !== false ? (j.flash || done) : (j.error || 'That did not go through (' + r.status + '). Nothing changed.')); }); })
107 .catch(function () { say('Could not reach the forge. Nothing changed.'); });
108 }
109 function verbsFor(t) {
57 function verbsFor(t, f) {
11058 var d = t.dataset, out = [], base = '/' + d.repo;
11159 if (d.run) {
112 out.push(verb('watch', { href: base + '/runs/' + d.run }));
113 out.push(verb('wheel', { href: base + '/runs/' + d.run + '#run-steer' }));
114 out.push(verb('stop', { run: function () {
115 act('stop', [d.run], function () {
116 var again = verb('requeue', { run: function () { act('requeue', [d.run]); } });
117 bar.querySelector('[data-verbs]').appendChild(again);
60 out.push(f.verb('watch', { href: base + '/runs/' + d.run }));
61 out.push(f.verb('wheel', { href: base + '/runs/' + d.run + '#run-steer' }));
62 out.push(f.verb('stop', { run: function () {
63 f.act('stop', [d.run], function () {
64 var again = f.verb('requeue', { run: function () { f.act('requeue', [d.run]); } });
65 f.bar.querySelector('[data-verbs]').appendChild(again);
11866 });
11967 } }));
12068 }
12169 if (d.kind === 'issue' && d.number && d.issue) {
122 out.push(verb('assign', { href: base + '/issues/' + d.number + '#f-assignee' }));
123 out.push(verb('sharpen', { run: function () { act('replan', [d.issue]); } }));
124 out.push(verb('park', { run: function () { act('later', [d.issue]); } }));
70 out.push(f.verb('assign', { href: base + '/issues/' + d.number + '#f-assignee' }));
71 out.push(f.verb('sharpen', { run: function () { f.act('replan', [d.issue]); } }));
72 out.push(f.verb('park', { run: function () { f.act('later', [d.issue]); } }));
12573 }
12674 if (d.kind === 'pull' && d.number && d.issue) {
127 out.push(verb('merge', { run: function (b) {
128 if (Date.now() - armed < 5000) { armed = 0; act('ship', [d.issue]); return; }
129 armed = Date.now();
130 say('Press ' + VERB.merge[0] + ' again to merge #' + d.number + ': a merge is not undone.');
75 out.push(f.verb('merge', { run: function () {
76 if (f.armed('merge:' + d.issue, 'Press ' + f.VERB.merge[0] + ' again to merge #' + d.number + ': a merge is not undone.')) f.act('ship', [d.issue]);
13177 } }));
132 out.push(verb('close', { run: function () { act('close', [d.issue]); } }));
133 out.push(verb('update', { run: function () { post(base + '/pulls/' + d.number + '/update', 'Asked the crew to bring #' + d.number + ' up to date.'); } }));
134 out.push(verb('sendBack', { href: base + '/pulls/' + d.number + '#review' }));
78 out.push(f.verb('close', { run: function () { f.act('close', [d.issue]); } }));
79 out.push(f.verb('update', { run: function () { f.post(base + '/pulls/' + d.number + '/update', 'Asked the crew to bring #' + d.number + ' up to date.'); } }));
80 out.push(f.verb('sendBack', { href: base + '/pulls/' + d.number + '#review' }));
13581 }
13682 return out;
13783 }
84 // What applies to every picked tile at once (v): a run's stop and queue again, an issue's sharpen
85 // and park, a pull's close; a mix offers only what all of them take.
86 function bulk(items) {
87 var tiles = items.filter(function (t) { return t.classList.contains('tile'); });
88 if (tiles.length !== items.length || tiles.length === 0) return [];
89 var ds = tiles.map(function (t) { return t.dataset; });
90 var out = [];
91 if (ds.every(function (d) { return d.run; })) {
92 var runs = ds.map(function (d) { return d.run; });
93 out.push({ verb: 'stop', op: 'stop', ids: runs }, { verb: 'requeue', op: 'requeue', ids: runs });
94 }
95 var issues = ds.map(function (d) { return d.issue; });
96 if (ds.every(function (d) { return d.kind === 'issue' && d.issue; })) out.push({ verb: 'sharpen', op: 'replan', ids: issues }, { verb: 'park', op: 'later', ids: issues });
97 if (ds.every(function (d) { return d.kind === 'pull' && d.issue; })) out.push({ verb: 'close', op: 'close', ids: issues });
98 return out;
99 }
138100 // A figure (a slots line): its setting, turned here, with the estimate said before and recorded with
139101 // the change after, so what was promised can be held to what happens (flow/slots.ts estimateOf).
140 var WORD = { checks: 'check', crew: 'crew run' }, WORDS = { checks: 'checks', crew: 'crew runs' }, NAME = { checks: 'Checks', crew: 'Crew runs' }, KEY = { checks: 'checks.concurrency', crew: 'crew.concurrency' };
102 var WORD = { checks: 'check', crew: 'crew run' }, NAME = { checks: 'Checks', crew: 'Crew runs' }, KEY = { checks: 'checks.concurrency', crew: 'crew.concurrency' };
141103 // What n of a kind take from the machine is said by the server (flow/slots.ts roomSays), one line
142104 // per count, carried on the figure; here it is only picked.
143105 function roomSays(d, n) {
144106 var says = []; try { says = JSON.parse(d.room || '[]'); } catch (e) { says = []; }
145107 return says[n - 1] || { text: '', over: false };
146108 }
147 function figure(t) {
148 var d = t.dataset, kind = d.kind, from = Number(d.slots), n = from;
109 function figure(t, f) {
110 var d = t.dataset, kind = d.kind, from = Number(d.slots), n = from, el = f.el, span = f.span;
149111 var run = d.runMs === '' ? null : Number(d.runMs), waiting = Number(d.waiting);
150112 function est(k) { return run === null ? null : Math.round(waiting * run / k); }
151113 var head = el('p', 'br-head', null), verbs = el('div', 'br-verbs', null);
@@ -160,130 +122,81 @@ export const bridgeJs = /* js */ `
160122 room.textContent = r.text;
161123 if (r.over) room.setAttribute('data-over', ''); else room.removeAttribute('data-over');
162124 }
163 verbs.appendChild(verb('fewer', { run: function () { if (n > 1) { n--; show(); } } }));
164 verbs.appendChild(verb('more', { run: function () { if (n < 64) { n++; show(); } } }));
165 verbs.appendChild(verb('set', { run: function () {
166 if (n === from) { say('Nothing to change.'); return; }
125 verbs.appendChild(f.verb('fewer', { repeat: false, run: function () { if (n > 1) { n--; show(); } } }));
126 verbs.appendChild(f.verb('more', { repeat: false, run: function () { if (n < 64) { n++; show(); } } }));
127 verbs.appendChild(f.verb('set', { repeat: false, run: function () {
128 if (n === from) { f.say('Nothing to change.'); return; }
167129 var e = est(n), form = new URLSearchParams();
168130 form.set('key', KEY[kind]); form.set('value', String(n));
169131 if (e !== null) form.set('reason', 'Estimate: a new ' + WORD[kind] + ' waits ~' + span(e) + ' at ' + n + ' slots (' + Math.round(e / 1000) + ' s).');
170132 var was = from;
171 say('Setting it…');
133 f.say('Setting it…');
172134 fetch('/settings/capacity', { method: 'POST', body: form, credentials: 'same-origin', headers: { accept: 'application/json' } })
173135 .then(function (r) { return r.json().catch(function () { return { ok: false, flash: 'That did not go through (' + r.status + '). Nothing changed.' }; }); })
174136 .then(function (j) {
175 if (!j.ok) { say(j.flash || 'That did not go through. Nothing changed.'); return; }
137 if (!j.ok) { f.say(j.flash || 'That did not go through. Nothing changed.'); return; }
176138 from = n; d.slots = String(n); show();
177 var undo = verb('undo', { run: function () {
139 var undo = f.verb('undo', { run: function () {
178140 var back = new URLSearchParams(); back.set('key', KEY[kind]); back.set('value', String(was)); back.set('reason', 'Undone from home.');
179141 fetch('/settings/capacity', { method: 'POST', body: back, credentials: 'same-origin', headers: { accept: 'application/json' } })
180142 .then(function (r2) { return r2.json().catch(function () { return { ok: false }; }); })
181 .then(function (j2) { if (j2.ok) { from = n = was; d.slots = String(was); show(); say('Put back to ' + was + ' slots.'); } else say(j2.flash || 'That did not go through. It stays at ' + from + '.'); });
143 .then(function (j2) { if (j2.ok) { from = n = was; d.slots = String(was); show(); f.say('Put back to ' + was + ' slots.'); } else f.say(j2.flash || 'That did not go through. It stays at ' + from + '.'); });
182144 } });
183145 verbs.appendChild(undo);
184 say(NAME[kind] + ' slots ' + was + ' → ' + n + ': from the next run on. The estimate is kept with the change, to be checked against what happens.');
146 f.say(NAME[kind] + ' slots ' + was + ' → ' + n + ': from the next run on. The estimate is kept with the change, to be checked against what happens.');
185147 })
186 .catch(function () { say('Could not reach the forge. Nothing changed.'); });
148 .catch(function () { f.say('Could not reach the forge. Nothing changed.'); });
187149 } }));
188150 show();
189 body.replaceChildren(top(head), line, room, verbs); said.textContent = '';
190 bar.hidden = false;
151 f.show([f.top(head), line, room, verbs]);
191152 }
192 function draw(t) {
193 if (t.classList.contains('sl')) { figure(t); return; }
194 var d = t.dataset;
153 function draw(t, f) {
154 if (t.classList.contains('sl')) { figure(t, f); return; }
155 var d = t.dataset, el = f.el;
195156 var head = el('p', 'br-head', null);
196157 head.appendChild(el('strong', null, d.repo + (d.number ? ' #' + d.number : '')));
197158 head.appendChild(D.createTextNode(' · ' + (LANE[d.lane] || d.lane)));
198159 var verbs = el('div', 'br-verbs', null);
199160 verbs.setAttribute('data-verbs', '');
200 var list = verbsFor(t);
161 var list = verbsFor(t, f);
201162 if (list.length === 0) verbs.appendChild(el('span', 'muted small', 'Nothing to do from here: open it with Enter.'));
202163 list.forEach(function (b) { verbs.appendChild(b); });
203 body.replaceChildren(top(head), verbs); said.textContent = '';
204 bar.hidden = false;
164 f.show([f.top(head), verbs]);
205165 }
206 function select(t) {
207 if (!t) return;
208 if (sel !== keyOf(t)) { armed = 0; sel = keyOf(t); draw(t); }
209 D.querySelectorAll('[data-selected]').forEach(function (x) { if (x !== t) x.removeAttribute('data-selected'); });
210 t.setAttribute('data-selected', '');
211 }
212 function clear() {
213 sel = null; armed = 0; bar.hidden = true; body.replaceChildren(); said.textContent = '';
214 D.querySelectorAll('[data-selected]').forEach(function (x) { x.removeAttribute('data-selected'); });
215 }
216 D.addEventListener('focusin', function (e) {
217 var t = tileOf(e.target);
218 if (t) select(t);
219 else if (sel && !bar.contains(e.target)) clear();
220 });
221166 // The lanes as a grid. h and l (or the arrows) cross to the next lane at the same row, as near as it
222167 // has; j and k stay in the lane, and below its last tile j goes to the slots figures, k comes back.
223 // Read on the window before the shell's own j/k, and only while a tile or figure has the focus
224 // (h and l from nowhere start at the first tile); g then h is still the shell's go-home.
225168 function shown(root) { return Array.prototype.filter.call(root.querySelectorAll('.tile[data-key]'), function (t) { return t.getClientRects().length > 0; }); }
226169 function lanes() { return Array.prototype.filter.call(D.querySelectorAll('.lane[data-lane]'), function (l) { return shown(l).length > 0; }); }
227170 function figs() { return Array.prototype.slice.call(D.querySelectorAll('.sl[data-nav]')); }
228 // The selection follows the move itself, not only the focus event it brings.
229 function go(t) { var a = t.classList.contains('sl') ? t : t.querySelector('a[data-nav]') || t.querySelector('a'); if (a) { a.focus(); a.scrollIntoView({ block: 'nearest', inline: 'nearest' }); } select(t); }
230 var lastTile = null, prevKey = '', prevAt = 0;
231 function nextFor(at, k) {
232 if (at && at.classList.contains('sl')) {
171 var lastTile = null;
172 function next(at, k) {
173 var out;
174 if (at.classList.contains('sl')) {
233175 var fs = figs(), i = fs.indexOf(at);
234 if (k === 'left' || k === 'right') return fs[Math.min(Math.max(i + (k === 'right' ? 1 : -1), 0), fs.length - 1)];
235 return k === 'up' && lastTile && D.contains(lastTile) ? lastTile : at;
176 if (k === 'left' || k === 'right') out = fs[Math.min(Math.max(i + (k === 'right' ? 1 : -1), 0), fs.length - 1)];
177 else out = k === 'up' && lastTile && D.contains(lastTile) ? lastTile : at;
178 } else {
179 var ls = lanes(), lane = at.closest('.lane'), col = shown(lane), row = col.indexOf(at);
180 if (k === 'down') out = row < col.length - 1 ? col[row + 1] : figs()[0] || at;
181 else if (k === 'up') out = col[Math.max(row - 1, 0)];
182 else { var to = ls[ls.indexOf(lane) + (k === 'right' ? 1 : -1)]; if (!to) out = at; else { var c = shown(to); out = c[Math.min(row, c.length - 1)]; } }
236183 }
237 var ls = lanes();
238 if (!at) return ls[0] ? shown(ls[0])[0] : null;
239 var lane = at.closest('.lane'), col = shown(lane), row = col.indexOf(at);
240 if (k === 'down') return row < col.length - 1 ? col[row + 1] : figs()[0] || at;
241 if (k === 'up') return col[Math.max(row - 1, 0)];
242 var to = ls[ls.indexOf(lane) + (k === 'right' ? 1 : -1)];
243 if (!to) return at;
244 var c = shown(to);
245 return c[Math.min(row, c.length - 1)];
184 if (out && !out.classList.contains('sl')) lastTile = out;
185 return out;
246186 }
247 window.addEventListener('keydown', function (e) {
248 var afterG = prevKey === 'g' && Date.now() - prevAt < 1000;
249 prevKey = e.key; prevAt = Date.now();
250 if (e.metaKey || e.ctrlKey || e.altKey || e.defaultPrevented || afterG) return;
251 var k = e.key === 'ArrowLeft' ? 'left' : e.key === 'ArrowRight' ? 'right' : e.key === MOVE.left ? 'left' : e.key === MOVE.right ? 'right' : e.key === MOVE.down ? 'down' : e.key === MOVE.up ? 'up' : null;
252 if (k === null) return;
253 var t = e.target;
254 if (t && t.closest && t.closest('input, textarea, select, [contenteditable], dialog[open]')) return;
255 var at = tileOf(D.activeElement);
256 if (!at && (k === 'down' || k === 'up' || !D.querySelector('.lane[data-lane] .tile[data-key]'))) return;
257 var next = nextFor(at, k);
258 if (!next) return;
259 e.preventDefault(); e.stopImmediatePropagation();
260 if (!next.classList.contains('sl')) lastTile = next;
261 go(next);
262 }, true);
263 // A click or tap anywhere but the bar or a tile puts the bar away, as a focus elsewhere does.
264 D.addEventListener('click', function (e) {
265 if (!sel || bar.contains(e.target) || tileOf(e.target)) return;
266 clear();
187 function start() { var ls = lanes(); return ls[0] ? shown(ls[0])[0] : null; }
188 window.forgeFocus({
189 bar: bar,
190 item: tileOf,
191 keyOf: keyOf,
192 findByKey: findByKey,
193 focusEl: function (t) { return t.classList.contains('sl') ? t : t.querySelector('a[data-nav]') || t.querySelector('a'); },
194 draw: draw,
195 next: next,
196 start: start,
197 bulk: bulk,
198 root: D.querySelector('.hf-lanes') || D.body,
199 keep: function (k) { return k.indexOf('slots:') !== 0; },
267200 });
268 // On a phone the first tap selects and the second opens: the bar is where a thumb is. A real tap
269 // focuses the link before its click, and the focus selects, so the click asks what was selected
270 // when the finger came down; a click no touch began (Enter on a link) asks what is selected now.
271 var downSel;
272 D.addEventListener('pointerdown', function (e) { if (e.pointerType !== 'mouse' && tileOf(e.target)) downSel = sel; }, true);
273 D.addEventListener('click', function (e) {
274 var t = tileOf(e.target), was = downSel === undefined ? sel : downSel;
275 downSel = undefined;
276 if (!t || !coarse || e.metaKey || e.ctrlKey) return;
277 if (was !== keyOf(t)) { e.preventDefault(); select(t); }
278 }, true);
279 D.addEventListener('keydown', function (e) { if (e.key === 'Escape' && sel && !e.defaultPrevented) clear(); });
280 // A lane swapped by the live stream keeps the selection: the tile with the same key, wherever it moved.
281 new MutationObserver(function () {
282 if (!sel || sel.indexOf('slots:') === 0) return;
283 var t = D.querySelector('.tile[data-key="' + (window.CSS && CSS.escape ? CSS.escape(sel) : sel) + '"]');
284 if (!t) { clear(); return; }
285 t.setAttribute('data-selected', '');
286 if (!D.activeElement || D.activeElement === D.body) { var a = t.querySelector('a'); if (a) a.focus({ preventScroll: true }); }
287 }).observe(D.querySelector('.hf-lanes') || D.body, { childList: true, subtree: true });
288201 })();
289202 `;
src/web/client.ts +11 −2
@@ -11,6 +11,9 @@
1111 */
1212
1313 import { GO_MATCH_JS, goPagesData } from "./go_pages.ts";
14 import { whichStubJs } from "./focus/which.ts";
15 import { whichAsset } from "./which_asset.ts";
16 import { oldGo } from "./keymap.ts";
1417 import { keyDecisionJs } from "./key_decision.ts";
1518 import { actNowJs } from "./act_now.ts";
1619 import { FORM_BUSY_JS } from "./form_busy.ts";
@@ -1568,6 +1571,8 @@ const shellCore = /* js */ `
15681571 }
15691572 window.forgeSay = sayKey;
15701573 doc.addEventListener('keydown', function () { var old = doc.querySelector('.toast[data-key-says]'); if (old) old.remove(); }, true);
1574 var esc = function (k) { return window.CSS && CSS.escape ? CSS.escape(k) : k; };
1575 ${whichStubJs(whichAsset().path)}
15711576
15721577 // ---- keyboard: sequences from the DOM, so the help can never drift ----
15731578 ${keyDecisionJs}
@@ -1681,7 +1686,6 @@ const shellCore = /* js */ `
16811686 seq.push(e.key);
16821687 if (seq.length > 2) seq.splice(0, seq.length - 2);
16831688 var joined = seq.join(' ');
1684 var esc = function (k) { return window.CSS && CSS.escape ? CSS.escape(k) : k; };
16851689 // A key that moved (keymap.ts OLD_KEYS, drawn only for two weeks) says where it went.
16861690 var was = doc.querySelector('[data-was="' + esc(joined) + '"]');
16871691 if (was) { seq.length = 0; e.preventDefault(); sayKey(was.getAttribute('data-was-says') || ''); return; }
@@ -1701,9 +1705,13 @@ const shellCore = /* js */ `
17011705 return;
17021706 }
17031707 // \`g\` then a letter: a page from the one list (go_pages.ts), only if this viewer may open it.
1708 // A forge place a repository shadows is g and its capital there (keymap.ts GO); a g chord that
1709 // moved says where it went, when nothing took it (OLD_GO).
17041710 if (seq.length === 2 && seq[0] === 'g') {
1705 var gp = gotoPages().filter(function (p) { return p[3] !== '' && p[3] === e.key; })[0];
1711 var gp = gotoPages().filter(function (p) { return p[3] !== '' && (p[3] === e.key || p[3].toUpperCase() === e.key); })[0];
17061712 if (gp) { seq.length = 0; e.preventDefault(); location.assign(gp[1]); return; }
1713 var moved = OLD_GO.filter(function (o) { return o.was === joined; })[0];
1714 if (moved) { seq.length = 0; e.preventDefault(); sayKey(moved.says); return; }
17071715 }
17081716 if (row) { seq.length = 0; row[3](e); }
17091717 });
@@ -2008,6 +2016,7 @@ const shellCore = /* js */ `
20082016 var closeGoto = null;
20092017 // The pages ride in this script (cached once); the page wears only the viewer's level in data-go.
20102018 var GO_PAGES = ${JSON.stringify(goPagesData())};
2019 var OLD_GO = ${JSON.stringify(oldGo())};
20112020 function gotoPages() {
20122021 var lv = +(doc.body.getAttribute('data-go') || 0);
20132022 return GO_PAGES.filter(function (p) { return p[2] <= lv; });
src/web/focus/core.ts added +214
@@ -0,0 +1,214 @@
1 /**
2 * The focus and act layer every keyboard-first surface shares (the owner: "this keyboard driven
3 * flow and context aware interface could feel really great as it expands across the forge"): home's
4 * Bridge now, the pull and issue panes next, from this one code.
5 *
6 * `window.forgeFocus(cfg)` takes a page's bar and how to find, name, draw and move between its
7 * things, and gives back the verbs, the forecast and Undo, and the keys:
8 *
9 * - a focus or a tap selects a thing and its verbs fill the bar; Escape, the bar's Close or a
10 * click elsewhere put it away; on a phone the first tap selects and the second acts;
11 * - the moves come from the keymap (keymap.ts MOVES) through `cfg.next`, with a count before one
12 * (3j);
13 * - `.` presses the last verb again on the newly focused thing (a j . j .);
14 * - `v` starts a selection: the moves add to it, the bar offers what applies to every picked
15 * thing (`cfg.bulk`), and a verb says its forecast first and acts on the second press, with one
16 * receipt and Undo (POST /home/act, the fleet's preview and apply).
17 *
18 * No motion: these are keys a person presses many times a day. Idempotent: a second copy in one
19 * page finds the first.
20 */
21 import { MOVES, verbsForScript } from "../keymap.ts";
22
23 export const focusCoreJs = /* js */ `
24 (function () {
25 if (window.forgeFocus) return;
26 var VERB = ${JSON.stringify(verbsForScript())};
27 var MOVE = { down: ${JSON.stringify(MOVES.down.key)}, up: ${JSON.stringify(MOVES.up.key)}, left: ${JSON.stringify(MOVES.left.key)}, right: ${JSON.stringify(MOVES.right.key)}, select: ${JSON.stringify(MOVES.select.key)}, repeat: ${JSON.stringify(MOVES.repeat.key)} };
28 window.forgeFocus = function (cfg) {
29 var D = document, bar = cfg.bar;
30 // What a verb did is said in the bar's one live region, on the page from the start, so a screen
31 // reader announces each answer; the rest of the bar is drawn into its body.
32 var body = bar.querySelector('[data-body]'), said = bar.querySelector('[data-said]');
33 var sel = null, armedAt = 0, armedKey = '', lastVerb = '', picking = null;
34 var coarse = window.matchMedia && window.matchMedia('(pointer: coarse)').matches;
35 // The forge's own way to say a span (flow/pipeline.ts span): 45s, 12m, 3h 5m, 2d 4h.
36 function span(ms) {
37 var s = Math.max(0, Math.round(ms / 1000)); if (s < 60) return s + 's';
38 var m = Math.floor(s / 60); if (m < 60) return m + 'm';
39 var h = Math.floor(m / 60); if (h < 48) return m % 60 === 0 ? h + 'h' : h + 'h ' + (m % 60) + 'm';
40 return Math.floor(h / 24) + 'd ' + (h % 24) + 'h';
41 }
42 function el(tag, cls, text) { var e = D.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; }
43 // Every key and its word come from the forge's one keymap (keymap.ts): a verb is named, never typed.
44 function verb(id, act) {
45 var k = VERB[id][0], label = VERB[id][1];
46 var b = el(act.href ? 'a' : 'button', 'btn', null);
47 if (act.href) b.href = act.href; else b.type = 'button';
48 b.setAttribute('data-size', 'sm');
49 b.setAttribute('data-shortcut', k);
50 b.appendChild(el('kbd', null, k)); b.appendChild(D.createTextNode(' ' + label));
51 if (act.run) {
52 if (id !== 'undo' && act.repeat !== false) b.setAttribute('data-repeat', '');
53 b.addEventListener('click', function (e) { e.preventDefault(); if (b.hasAttribute('data-repeat')) lastVerb = k; act.run(b); });
54 }
55 return b;
56 }
57 // The bar always says how to put it away: a Close button with its key, beside the head.
58 function top(head) {
59 var row = el('div', 'br-top', null), b = el('button', 'btn br-close', null);
60 b.type = 'button'; b.setAttribute('data-size', 'sm'); b.setAttribute('data-variant', 'ghost'); b.setAttribute('aria-label', 'Close the bar (Escape)'); b.setAttribute('aria-keyshortcuts', 'Escape');
61 b.appendChild(el('span', null, '\\u00d7 Close')); b.appendChild(el('kbd', null, 'Esc'));
62 b.addEventListener('click', function () { clear(); if (D.activeElement && D.activeElement.blur) D.activeElement.blur(); });
63 row.appendChild(head); row.appendChild(b);
64 return row;
65 }
66 function say(text, extra) {
67 said.textContent = text;
68 if (extra) { said.appendChild(D.createTextNode(' ')); said.appendChild(extra); }
69 }
70 // A verb that is not undone asks for its key twice: the first press says so (and arms), the second acts.
71 function armed(key, words) {
72 if (armedKey === key && Date.now() - armedAt < 5000) { armedKey = ''; armedAt = 0; return true; }
73 armedKey = key; armedAt = Date.now(); say(words);
74 return false;
75 }
76 function answer(j, then) {
77 if (!j.ok) { say(j.error || 'That did not go through. Nothing changed.'); return; }
78 var a = null;
79 if (j.receipt) { a = el('a', null, j.reversible ? 'Receipt and Undo' : 'Receipt'); a.href = j.receipt; }
80 say(j.summary || 'Done.', a);
81 if (then) then();
82 }
83 function homeAct(op, ids, phase) {
84 var form = new URLSearchParams();
85 form.set('op', op); form.set('phase', phase);
86 ids.forEach(function (id) { form.append('ids', id); });
87 return fetch('/home/act', { method: 'POST', body: form, credentials: 'same-origin', headers: { accept: 'application/json' } })
88 .then(function (r) { return r.json().catch(function () { return { ok: false, error: 'That did not go through (' + r.status + ').' }; }); });
89 }
90 function act(op, ids, then) {
91 say('Doing it…');
92 homeAct(op, ids, 'apply').then(function (j) { answer(j, then); }).catch(function () { say('Could not reach the forge. Nothing changed.'); });
93 }
94 // A verb with a route of its own (Update): the form it already is, posted from here.
95 function post(url, done) {
96 say('Doing it…');
97 fetch(url, { method: 'POST', body: new URLSearchParams(), credentials: 'same-origin', headers: { accept: 'application/json' } })
98 .then(function (r) { return r.json().catch(function () { return {}; }).then(function (j) { say(r.ok && j.ok !== false ? (j.flash || done) : (j.error || 'That did not go through (' + r.status + '). Nothing changed.')); }); })
99 .catch(function () { say('Could not reach the forge. Nothing changed.'); });
100 }
101 var api = { el: el, verb: verb, top: top, say: say, act: act, post: post, span: span, armed: armed, VERB: VERB, body: body, said: said, bar: bar };
102 function show(nodes) { body.replaceChildren.apply(body, nodes); said.textContent = ''; bar.hidden = false; }
103 api.show = show;
104 // The picked things and what applies to all of them: one forecast, then one act and one receipt.
105 function drawPicked() {
106 var items = Array.from(picking.values());
107 var head = el('p', 'br-head', null);
108 head.appendChild(el('strong', null, items.length + ' picked'));
109 head.appendChild(D.createTextNode(' · v to stop picking'));
110 var verbs = el('div', 'br-verbs', null); verbs.setAttribute('data-verbs', '');
111 var all = cfg.bulk ? cfg.bulk(items) : [];
112 if (all.length === 0) verbs.appendChild(el('span', 'muted small', 'Nothing applies to all of these.'));
113 all.forEach(function (o) {
114 verbs.appendChild(verb(o.verb, { repeat: false, run: function () {
115 var key = 'bulk:' + o.op + ':' + o.ids.join(',');
116 if (armedKey === key && Date.now() - armedAt < 5000) { armedKey = ''; act(o.op, o.ids, function () { stopPicking(false); }); return; }
117 say('Working it out…');
118 homeAct(o.op, o.ids, 'preview').then(function (j) {
119 if (!j.ok) { say(j.error || 'That did not go through. Nothing changed.'); return; }
120 armedKey = key; armedAt = Date.now();
121 say(j.summary + ' Press ' + VERB[o.verb][0] + ' again to do it.');
122 }).catch(function () { say('Could not reach the forge. Nothing changed.'); });
123 } }));
124 });
125 show([top(head), verbs]);
126 }
127 function mark(t, on) { if (on) t.setAttribute('data-picked', ''); else t.removeAttribute('data-picked'); }
128 function startPicking() { picking = new Map(); if (sel) { var t = cfg.findByKey(sel); if (t) { picking.set(sel, t); mark(t, true); } } drawPicked(); }
129 function stopPicking(redraw) {
130 if (picking) picking.forEach(function (t) { mark(t, false); });
131 picking = null;
132 if (redraw && sel) { var t = cfg.findByKey(sel); if (t) cfg.draw(t, api); }
133 }
134 function select(t) {
135 if (!t) return;
136 var k = cfg.keyOf(t);
137 if (picking) { if (!picking.has(k)) { picking.set(k, t); mark(t, true); drawPicked(); } }
138 else if (sel !== k) { armedKey = ''; sel = k; cfg.draw(t, api); }
139 sel = k;
140 D.querySelectorAll('[data-selected]').forEach(function (x) { if (x !== t) x.removeAttribute('data-selected'); });
141 t.setAttribute('data-selected', '');
142 }
143 function clear() {
144 stopPicking(false);
145 sel = null; armedKey = ''; bar.hidden = true; body.replaceChildren(); said.textContent = '';
146 D.querySelectorAll('[data-selected]').forEach(function (x) { x.removeAttribute('data-selected'); });
147 }
148 api.select = select; api.clear = clear;
149 D.addEventListener('focusin', function (e) {
150 var t = cfg.item(e.target);
151 if (t) select(t);
152 else if (sel && !bar.contains(e.target)) clear();
153 });
154 // The selection follows the move itself, not only the focus event it brings.
155 function go(t) { var a = cfg.focusEl(t); if (a) { a.focus(); a.scrollIntoView({ block: 'nearest', inline: 'nearest' }); } select(t); }
156 api.go = go;
157 // Moves, counts, . and v, read on the window before the shell's own j/k, and only while a thing
158 // has the focus (h and l from nowhere start at the first); g then a letter is still the shell's.
159 var prevKey = '', prevAt = 0, count = '';
160 window.addEventListener('keydown', function (e) {
161 var afterG = prevKey === 'g' && Date.now() - prevAt < 1000;
162 prevKey = e.key; prevAt = Date.now();
163 if (e.metaKey || e.ctrlKey || e.altKey || e.defaultPrevented || afterG) return;
164 var t = e.target;
165 if (t && t.closest && t.closest('input, textarea, select, [contenteditable], dialog[open]')) return;
166 var at = cfg.item(D.activeElement);
167 if (at && /^[0-9]$/.test(e.key) && (count !== '' || e.key !== '0')) { count = (count + e.key).slice(-2); e.preventDefault(); e.stopImmediatePropagation(); return; }
168 if (at && e.key === MOVE.repeat && lastVerb !== '') {
169 var again = body.querySelector('[data-repeat][data-shortcut=' + JSON.stringify(lastVerb) + ']');
170 e.preventDefault(); e.stopImmediatePropagation();
171 if (again) again.click(); else say('Nothing here takes ' + lastVerb + ' again.');
172 return;
173 }
174 if (at && e.key === MOVE.select) { e.preventDefault(); e.stopImmediatePropagation(); if (picking) stopPicking(true); else startPicking(); return; }
175 var k = e.key === 'ArrowLeft' ? 'left' : e.key === 'ArrowRight' ? 'right' : e.key === MOVE.left ? 'left' : e.key === MOVE.right ? 'right' : e.key === MOVE.down ? 'down' : e.key === MOVE.up ? 'up' : null;
176 if (k === null) { count = ''; return; }
177 if (!at && (k === 'down' || k === 'up' || !cfg.start())) { count = ''; return; }
178 var times = Math.min(Math.max(Number(count) || 1, 1), 50), next = at;
179 count = '';
180 if (!at) next = cfg.start();
181 else for (var i = 0; i < times; i++) { var n2 = cfg.next(next, k); if (!n2 || n2 === next) break; next = n2; if (picking) select(next); }
182 if (!next) return;
183 e.preventDefault(); e.stopImmediatePropagation();
184 go(next);
185 }, true);
186 // A click or tap anywhere but the bar or a thing puts the bar away, as a focus elsewhere does.
187 D.addEventListener('click', function (e) {
188 if (!sel || bar.contains(e.target) || cfg.item(e.target)) return;
189 clear();
190 });
191 // On a phone the first tap selects and the second opens: the bar is where a thumb is. A real tap
192 // focuses the link before its click, and the focus selects, so the click asks what was selected
193 // when the finger came down; a click no touch began (Enter on a link) asks what is selected now.
194 var downSel;
195 D.addEventListener('pointerdown', function (e) { if (e.pointerType !== 'mouse' && cfg.item(e.target)) downSel = sel; }, true);
196 D.addEventListener('click', function (e) {
197 var t = cfg.item(e.target), was = downSel === undefined ? sel : downSel;
198 downSel = undefined;
199 if (!t || !coarse || e.metaKey || e.ctrlKey) return;
200 if (was !== cfg.keyOf(t)) { e.preventDefault(); select(t); }
201 }, true);
202 D.addEventListener('keydown', function (e) { if (e.key === 'Escape' && sel && !e.defaultPrevented) clear(); });
203 // A region swapped by the live stream keeps the selection: the thing with the same key, wherever it moved.
204 if (cfg.root) new MutationObserver(function () {
205 if (!sel || (cfg.keep && !cfg.keep(sel))) return;
206 var t = cfg.findByKey(sel);
207 if (!t) { clear(); return; }
208 t.setAttribute('data-selected', '');
209 if (!D.activeElement || D.activeElement === D.body) { var a = cfg.focusEl(t); if (a) a.focus({ preventScroll: true }); }
210 }).observe(cfg.root, { childList: true, subtree: true });
211 return api;
212 };
213 })();
214 `;
src/web/focus/which.ts added +197
@@ -0,0 +1,197 @@
1 /**

The Space leader excludes button, input, select, summary but not [role=button], [role=menuitem] or [role=tab] controls, so Space on those is taken from a keyboard or screen-reader user. Add [role] to wkControl and test it.

2 * The key tree in the browser (keymap.ts TREE, LEADER, GO): Space, a group and a leaf, and a quiet
3 * which-key panel. After a prefix (Space, a group, or g) a short pause shows the next keys and
4 * their words at the foot of the page; a fast typist never sees it. A key descends, Escape or
5 * Backspace goes up one level, and an unknown key says so and stops. The panel is static (no
6 * motion) and sticky at the foot of `main`, as the Bridge's bar is.
7 *
8 * Space is the leader only off a control: a button, an input, a select, editable text, or anything
9 * with a control's role (a role=button or menuitem, a tab, a checkbox…) keeps its own Space, and
10 * j/k and Page Down still scroll.
11 *
12 * Loaded when it is first wanted: the shell carries only {@link whichStubJs}, a few lines that, on
13 * the first Space off a control (or the first g), hold the keys and fetch this module
14 * (`whichAsset`, content-addressed like the shell). The module then takes over and plays the held
15 * keys, so Space p m typed before it arrived still merges. It reads the shell's helpers from
16 * `window`: `forgeGotoPages` (go_pages.ts, the forge's places this viewer may open) and
17 * `forgeSay`. A leaf that is a verb presses that verb's key on the page, the same button the key
18 * itself would click, so Space p m and m are one act.
19 */
20 import { GO_PREFIX, LEADER, treeForScript } from "../keymap.ts";
21
22 /** How long the shell waits for the module before it gives the keys back. */
23 const LOAD_GIVE_UP_MS = 3000;
24
25 /** What a control is, for Space: these keep their own Space and never start the tree. */
26 const CONTROLS = "input, textarea, select, button, summary, [contenteditable], dialog[open], [role=button], [role=menuitem], [role=menuitemcheckbox], [role=menuitemradio], [role=checkbox], [role=switch], [role=radio], [role=tab], [role=option], [role=slider], [role=combobox]";
27
28 /**
29 * The shell's part: on the first Space off a control, hold it and what follows, and fetch the
30 * module; on the first g, fetch it so the go panel is there for the next one. `src` is the module's
31 * address (`whichAsset().path`).
32 */
33 export const whichStubJs = (src: string): string => /* js */ `
34 // ---- the key tree, loaded when first wanted (focus/which.ts) ----
35 window.forgeGotoPages = gotoPages;
36 var wkLoading = false, wkHeld = null;
37 // A module that never arrives (offline, a hash gone after a deploy, a blocked request) must not
38 // keep the keys: on its error, or after ${String(LOAD_GIVE_UP_MS / 1000)} s without it, the held keys go and the
outdated

High: s has no onerror. If the fetch fails, wkHeld stays an array and the capture handler below swallows every key forever. Set s.onerror = function () { wkHeld = null; wkLoading = false; } and test it.

39 // keyboard is the page's again; the next Space tries once more.
40 var wkGiveUp = 0;
41 function wkRelease() { clearTimeout(wkGiveUp); if (!window.forgeWhich) { wkHeld = null; wkLoading = false; } }
42 function wkLoad() {
43 if (wkLoading) return;
44 wkLoading = true;
45 var s = doc.createElement('script');
46 s.src = ${JSON.stringify(src)};
47 s.onerror = wkRelease;
48 s.onload = function () { clearTimeout(wkGiveUp); };
49 wkGiveUp = setTimeout(wkRelease, ${String(LOAD_GIVE_UP_MS)});
50 var at = doc.head || doc.body;
51 if (at && at.appendChild) at.appendChild(s);
52 }
53 window.forgeWhichHeld = function () { var h = wkHeld || []; wkHeld = null; return h; };
54 doc.addEventListener('keydown', function (e) {
55 if (window.forgeWhich || e.metaKey || e.ctrlKey || e.altKey) return;
56 if (wkHeld !== null) { e.preventDefault(); e.stopImmediatePropagation(); wkHeld.push(e.key); return; }
57 var t = e.target, control = !!(t && t.closest && t.closest(${JSON.stringify(CONTROLS)}));
58 if (control) return;
59 if (e.key === ${JSON.stringify(LEADER)} && !doc.querySelector('dialog[open]')) { e.preventDefault(); e.stopImmediatePropagation(); wkHeld = [e.key]; wkLoad(); }
60 else if (e.key === ${JSON.stringify(GO_PREFIX)}) { window.forgeWhichG = Date.now(); wkLoad(); }
61 }, true);
62 `;
63
64 /** How long a prefix waits before the panel shows: a fast chord never sees it. */
65 const WHICH_DELAY_MS = 300;
66
67
68 export const whichJs = /* js */ `
69 (function () {
70 if (window.forgeWhich) return;
71 var doc = document;
72 var gotoPages = window.forgeGotoPages || function () { return []; };
73 var sayKey = function (t) { if (window.forgeSay) window.forgeSay(t); };
74 var esc = function (k) { return window.CSS && CSS.escape ? CSS.escape(k) : k; };
75 var TREE = ${JSON.stringify(treeForScript())};
76 var LEADER = ${JSON.stringify(LEADER)}, GO_PREFIX = ${JSON.stringify(GO_PREFIX)};
77 // A repository's tabs are its scope's g jumps; the topbar's own (g h, g t) are the forge's places.
78 var REPO_TABS = 'nav[aria-label="Repository"] [data-shortcut], .repo-nav [data-shortcut]';
79 var wkPath = null, wkTimer = 0, wkPanel = null, gTimer = 0;
80 function wkControl(t) { return !!(t && t.closest && t.closest(${JSON.stringify(CONTROLS)})); }
81 // The go panel, after a pause with no second key (the shell's own chord does the jump).
82 function goSoon(ms) {
83 clearTimeout(gTimer);
84 gTimer = setTimeout(function () { wkDraw('g · go (' + (doc.querySelector(REPO_TABS) ? 'this repository, then the forge' : 'the forge') + ')', wkGo()); }, ms);
85 }
86 function wkHide() { clearTimeout(wkTimer); clearTimeout(gTimer); if (wkPanel) wkPanel.hidden = true; }
87 function wkStop() { wkPath = null; wkHide(); }
88 // The go group: this scope's destinations, the page's own g tabs first (a repository's), then the
89 // forge's places, a shadowed one as its capital.
90 function wkGo() {
91 var out = [], taken = {};
92 Array.prototype.forEach.call(doc.querySelectorAll(REPO_TABS), function (el) {
93 var k = el.getAttribute('data-shortcut').slice(2);
94 if (k.length !== 1 || taken[k]) return;
95 taken[k] = true;
96 out.push({ k: k, l: (el.textContent || '').replace(/\\s+/g, ' ').trim() || k, el: el });
97 });
98 gotoPages().forEach(function (p) {
99 if (p[3] === '') return;
100 var k = taken[p[3]] ? p[3].toUpperCase() : p[3];
101 out.push({ k: k, l: p[0], href: p[1] });
102 });
103 return out;
104 }
105 function wkNode() {
106 if (wkPath === null) return null;
107 if (wkPath.length === 0) return { l: 'Space', leaves: TREE.map(function (g) { return { k: g.k, l: g.l, group: true }; }).concat([{ k: '?', l: 'the whole tree' }]) };
108 var g = TREE.filter(function (x) { return x.k === wkPath[0]; })[0];
109 if (!g) return null;
110 return { l: 'Space ' + g.k + ' · ' + g.l, leaves: g.k === 'g' ? wkGo() : g.leaves };
111 }
112 function wkDraw(title, leaves) {
113 if (!wkPanel) {
114 wkPanel = doc.createElement('div');
115 wkPanel.className = 'wk'; wkPanel.setAttribute('data-which', ''); wkPanel.setAttribute('aria-live', 'polite');
116 (doc.getElementById('main') || doc.body).appendChild(wkPanel);
117 }
118 wkPanel.replaceChildren();
119 var head = doc.createElement('p'); head.className = 'wk-head'; head.textContent = title;
120 var list = doc.createElement('ul'); list.className = 'wk-keys';
121 leaves.forEach(function (f) {
122 var li = doc.createElement('li'), kb = doc.createElement('kbd');
123 kb.textContent = f.k === ' ' ? 'Space' : f.k;
124 li.appendChild(kb); li.appendChild(doc.createTextNode(' ' + (f.group ? '+' : '') + f.l));
125 list.appendChild(li);
126 });
127 wkPanel.appendChild(head); wkPanel.appendChild(list);
128 wkPanel.hidden = false;
129 }
130 function wkLater() {
131 clearTimeout(wkTimer);
132 wkTimer = setTimeout(function () { var n = wkNode(); if (n) wkDraw(n.l, n.leaves); }, ${String(WHICH_DELAY_MS)});
133 }
134 function wkPress(k) {
135 var target = doc.querySelector('[data-shortcut=' + JSON.stringify(k) + ']');
136 if (target) { target.click(); return true; }
137 var mod = k.indexOf('Mod+') === 0;
138 var key = mod ? k.slice(4) : k;
139 var ev = new KeyboardEvent('keydown', { key: key, metaKey: mod, ctrlKey: false, bubbles: true, cancelable: true });
140 doc.dispatchEvent(ev);
141 return ev.defaultPrevented;
142 }
143 function wkCopy(what) {
144 var v = what === 'link' ? location.href : (doc.querySelector('[data-' + what + ']') || { getAttribute: function () { return null; } }).getAttribute('data-' + what);
145 if (!v) { sayKey('Nothing here has a ' + (what === 'sha' ? 'commit' : what) + ' to copy.'); return; }
146 if (navigator.clipboard) navigator.clipboard.writeText(v).then(function () { sayKey('Copied ' + v); }, function () { sayKey(v); });
147 else sayKey(v);
148 }
149 function wkDo(f) {
150 if (f.el) { f.el.click(); return; }
151 if (f.href) { location.assign(f.href); return; }
152 if (f.copy) { wkCopy(f.copy); return; }
153 var k = f.verb || f.press;
154 if (k && !wkPress(k)) sayKey('Nothing here takes ' + k + (f.l ? ' (' + f.l + ')' : '') + '.');
155 }
156 // The whole tree, at once, until Escape.
157 function wkAll() {
158 var rows = [];
159 TREE.forEach(function (g) {
160 rows.push({ k: g.k, l: g.l, group: true });
161 (g.k === 'g' ? wkGo() : g.leaves).forEach(function (f) { rows.push({ k: g.k + ' ' + f.k, l: f.l }); });
162 });
163 wkDraw('Space: the whole tree', rows);
164 }
165 doc.addEventListener('keydown', function (e) {
166 var t = e.target;
167 if (wkPath === null) {
168 if (e.key === LEADER && !e.metaKey && !e.ctrlKey && !e.altKey && !wkControl(t) && !doc.querySelector('dialog[open]')) {
169 e.preventDefault(); e.stopImmediatePropagation();
170 wkPath = []; wkLater();
171 return;
172 }
173 // g alone: the scope's destinations after a pause; the shell's own chord does the jump.
174 if (e.key === GO_PREFIX && !e.metaKey && !e.ctrlKey && !e.altKey && !wkControl(t)) goSoon(${String(WHICH_DELAY_MS)});
175 else if (wkPanel && !wkPanel.hidden && e.key !== 'Shift') wkHide();
176 return;
177 }
178 if (e.key === 'Shift' || e.key === 'Meta' || e.key === 'Control' || e.key === 'Alt') return;
179 e.preventDefault(); e.stopImmediatePropagation();
180 if (e.key === 'Escape') { wkStop(); return; }
181 if (e.key === 'Backspace') { if (wkPath.length === 0) wkStop(); else { wkPath.pop(); wkLater(); if (wkPanel && !wkPanel.hidden) { var n0 = wkNode(); wkDraw(n0.l, n0.leaves); } } return; }
182 if (wkPath.length === 0 && e.key === '?') { wkPath = null; clearTimeout(wkTimer); wkAll(); return; }
183 var n = wkNode();
184 var hit = n && n.leaves.filter(function (f) { return f.k === e.key; })[0];
185 if (!hit) { var said = 'Space ' + wkPath.concat([e.key]).join(' '); wkStop(); sayKey(said + ' is nothing here.'); return; }
186 if (wkPath.length === 0) { wkPath.push(hit.k); wkLater(); if (wkPanel && !wkPanel.hidden) { var n1 = wkNode(); wkDraw(n1.l, n1.leaves); } return; }
187 wkStop();
188 wkDo(hit);
189 }, true);
190 window.forgeWhich = true;
191 // A g that fetched this module, still alone: its panel comes when its pause is up.
192 var gAt = window.forgeWhichG || 0;
193 if (Date.now() - gAt < ${String(WHICH_DELAY_MS)}) goSoon(${String(WHICH_DELAY_MS)} - (Date.now() - gAt));
194 // The keys held while this loaded, played in order, as if typed now.
195 window.forgeWhichHeld().forEach(function (k) { doc.dispatchEvent(new KeyboardEvent('keydown', { key: k, bubbles: true, cancelable: true })); });
196 })();
197 `;
src/web/go_pages.ts +9 −6
@@ -5,6 +5,8 @@
55 * keeping its own. One list; a page added here appears in all three.
66 */
77
8 import { GO } from "./keymap.ts";
9
810 export interface GoPage {
911 /** The name typed to reach it. */
1012 readonly name: string;
@@ -18,23 +20,24 @@ export interface GoPage {
1820 }
1921
2022 export const GO_PAGES: readonly GoPage[] = [
21 { name: "Home", href: "/", who: "all", key: "h", palette: "Home" },
23 { name: "Home", href: "/", who: "all", key: GO.global.home, palette: "Home" },
2224 { name: "Apps", href: "/apps", who: "all", palette: "Apps" },
23 { name: "Explore", href: "/explore", who: "all", key: "e", palette: "Explore" },
25 { name: "Explore", href: "/explore", who: "all", key: GO.global.explore, palette: "Explore" },
2426 { name: "Packs", href: "/packs", who: "all", palette: "Forge packs" },
2527 { name: "Front page", href: "/front", who: "all", palette: "Front page" },
2628 { name: "Search", href: "/search", who: "all", palette: "Search" },
2729 { name: "Feed", href: "/feed", who: "user" },
2830 { name: "Board", href: "/board", who: "user" },
29 { name: "Boards", href: "/boards", who: "admin", palette: "Boards" },
30 { name: "Flow", href: "/flow", who: "admin", key: "f" },
31 { name: "Boards", href: "/boards", who: "admin", key: GO.global.boards, palette: "Boards" },
32 { name: "Flow", href: "/flow", who: "admin", key: GO.global.flow },
3133 { name: "Waiting", href: "/?waits=me", who: "user" },
3234 { name: "Notes", href: "/notes", who: "user", palette: "Notes" },
33 { name: "Talk", href: "/talk", who: "user", key: "t", palette: "Talk to the forge" },
35 { name: "Talk", href: "/talk", who: "user", key: GO.global.talk, palette: "Talk to the forge" },
36 { name: "Next up", href: "/next", who: "user", key: GO.global.next, palette: "Next up" },
3437 { name: "Map", href: "/map", who: "user", palette: "Map" },
3538 { name: "Displays", href: "/displays", who: "user", palette: "Displays" },
3639 { name: "Settings", href: "/settings", who: "user" },
37 { name: "System", href: "/system", who: "admin", key: "s" },
40 { name: "System", href: "/system", who: "admin", key: GO.global.system },
3841 { name: "Releases", href: "/releases", who: "admin" },
3942 { name: "Forges", href: "/forges", who: "admin" },
4043 { name: "Family", href: "/family", who: "admin" },
src/web/keymap.ts +172 −20
@@ -10,10 +10,24 @@
1010 * Pure data: the static client modules may read it. The g-letter jumps are go_pages.ts's one list;
1111 * the map reads its two from there.
1212 */
13 import { GO_PAGES } from "./go_pages.ts";
13 /**
14 * The g jumps, one table by scope (the owner: "if i do GF I go to forks … files should come
15 * first"). g and a letter is a destination in the scope the page is in: inside a repository its
16 * sections, code first; elsewhere the forge's places. A forge place a repository shadows is g and
17 * the capital there (g B boards), or Space g, or Cmd/Ctrl K. go_pages.ts and the repository's tabs
18 * read their letters from here, so changing a letter is one line; test/keymap.test.ts fails on a
19 * clash in a scope.
20 */
21 export const GO = {
22 global: { home: "h", explore: "e", flow: "f", talk: "t", next: "n", system: "y", boards: "b" },
23 repo: { code: "c", issues: "i", pulls: "p", runs: "r", map: "m", log: "l", branches: "b", forks: "k", settings: "s" },
24 } as const;
1425
15 /** The `g` sequence that jumps to `href`, from go_pages.ts. */
16 const go = (href: string): string => `g ${GO_PAGES.find((p) => p.href === href)?.key ?? ""}`;
26 /** The key that starts a g jump. */
27 export const GO_PREFIX = "g";
28
29 /** The g sequence for a forge-wide place. */
30 const go = (place: keyof typeof GO.global): string => `g ${GO.global[place]}`;
1731
1832 /** What a key acts on: a verb means one thing per kind, and a move works anywhere. */
1933 export type KeyKind = "any" | "pull" | "issue" | "run" | "figure" | "card" | "file" | "rank" | "space" | "table";
@@ -45,6 +59,8 @@ export const MOVES = {
4559 back: { key: "Escape", label: "Close", what: "Close what is on top, then clear the selection, then back out to the list", kinds: any },
4660 search: { key: "/", label: "Search", what: "Search, or filter the list (a terminal list's filter too)", kinds: any },
4761 // Read again: the terminal's refresh, named for what it does (a page is live and needs none).
62 select: { key: "v", label: "Select", what: "Start or stop picking things in a list; the moves add to it, and a verb acts on all", kinds: any },
63 repeat: { key: ".", label: "Again", what: "Do the last verb again on what has the focus", kinds: any },
4864 reread: { key: "R", label: "Refresh", what: "Read the screen again (the terminal; a page is live)", kinds: any },
4965 help: { key: "?", label: "Help", what: "List the keys this page answers", kinds: any },
5066 palette: { key: "Mod+k", label: "Jump", what: "Jump to anywhere, or act on what is focused", kinds: any },
@@ -52,8 +68,8 @@ export const MOVES = {
5268 tell: { key: "t", label: "Tell the crew", what: "Tell the crew what you want", kinds: any },
5369 create: { key: "c", label: "Write", what: "Write here: the page's box, else its New", kinds: any },
5470 newIssue: { key: "C", label: "New issue", what: "New issue from this page", kinds: any },
55 home: { key: go("/"), label: "Home", what: "Go home", kinds: any },
56 talk: { key: go("/talk"), label: "Talk", what: "Talk to the forge", kinds: any },
71 home: { key: go("home"), label: "Home", what: "Go home", kinds: any },
72 talk: { key: go("talk"), label: "Talk", what: "Talk to the forge", kinds: any },
5773 } as const satisfies Record<string, KeyDef>;
5874
5975 /** The verbs, one meaning each per kind of thing. */
@@ -92,23 +108,35 @@ export const VERBS = {
92108 find: { key: "f", label: "Go to file", what: "Find a file by name", kinds: ["file"] },
93109 } as const satisfies Record<string, KeyDef>;
94110
95 /**
96 * A repository's tabs, each a `g` jump on its pages. Two shadow a forge-wide jump there, by design:
97 * inside a repository `g f` is its Forks and `g s` its Settings (go_pages.ts's Front page and
98 * Settings stay a step away through `:` and Cmd/Ctrl K).
99 */
111 /** A repository's tabs, each a `g` jump on its pages, from {@link GO}'s repository scope. */
100112 export const REPO_TABS = {
101 code: "g c",
102 issues: "g i",
103 pulls: "g p",
104 map: "g a",
105 commits: "g m",
106 branches: "g b",
107 forks: "g f",
108 runs: "g r",
109 settings: "g s",
113 code: `g ${GO.repo.code}`,
114 issues: `g ${GO.repo.issues}`,
115 pulls: `g ${GO.repo.pulls}`,
116 map: `g ${GO.repo.map}`,
117 commits: `g ${GO.repo.log}`,
118 branches: `g ${GO.repo.branches}`,
119 forks: `g ${GO.repo.forks}`,
120 runs: `g ${GO.repo.runs}`,
121 settings: `g ${GO.repo.settings}`,
110122 } as const;
111123
124 /**
125 * The g chords that moved with {@link GO} (2026-12-01), each with what it says until
126 * {@link OLD_KEYS_UNTIL} when pressed where it now does nothing: the shell says it only when no tab
127 * and no place took the chord. g f in a repository now goes to Flow, and g m to its map, so those
128 * are not hinted: they go somewhere.
129 */
130 export const OLD_GO: readonly { readonly was: string; readonly says: string }[] = [
131 { was: "g a", says: `g ${GO.repo.map} is the map now` },
132 { was: "g s", says: `g ${GO.global.system} is System now (g s is a repository's settings)` },
133 ];
134
135 /** The moved g chords still hinted at `now`; none after the date. */
136 export function oldGo(now: Date = oldKeysClock ?? new Date()): readonly { readonly was: string; readonly says: string }[] {
137 return now.getTime() >= Date.parse(OLD_KEYS_UNTIL) ? [] : OLD_GO;
138 }
139
112140 /**
113141 * Keys that moved when the map took over, and what they say now. For two weeks the old key shows a
114142 * one-line hint instead of doing nothing; after {@link OLD_KEYS_UNTIL} no page draws them and the
@@ -139,7 +167,6 @@ export const OLD_KEYS: readonly OldKey[] = [
139167 { page: "runs", was: "S", now: "wheel" },
140168 { page: "runs", was: "a", now: "requeue" },
141169 { page: "terminal", was: "r", now: "reread" },
142 { page: "terminal", was: "g", now: "reread" },
143170 { page: "next", was: "t", now: "top" },
144171 { page: "next", was: "u", now: "raise" },
145172 { page: "next", was: "d", now: "lower" },
@@ -176,6 +203,131 @@ export function provideOldKeysClockForTest(now: Date | undefined): void {
176203 }
177204
178205 export const KEYMAP = { ...MOVES, ...VERBS } as const;
206
207 /**
208 * The leader: Space starts the tree, off a button, input or select (a control keeps its own Space).
209 */
210 export const LEADER = " ";
211
212 /** What a leaf of the tree does. */
213 export type TreeDoes =
214 | { readonly verb: VerbId }
215 | { readonly press: string }
216 | { readonly href: string }
217 | { readonly copy: "link" | "sha" | "branch" };
218
219 export interface TreeLeaf {
220 readonly key: string;
221 readonly label: string;
222 readonly does: TreeDoes;
223 }
224
225 export interface TreeGroup {
226 readonly key: string;
227 readonly label: string;
228 /** The leaves; the go group's come from the page's scope ({@link GO}), so it lists none here. */
229 readonly leaves: readonly TreeLeaf[];
230 }
231
232 /**
233 * The key tree (the owner: "like nvim hints … i want to start hitting COMBOS!!"): Space, a group,
234 * a leaf. A leaf that is a verb presses that verb on what has the focus, so Space p m and m on a
235 * focused pull are one act. Which-key, ? and Cmd/Ctrl K read this; test/keymap.test.ts fails on a
236 * path twice, a leaf without a label, or a verb the map does not have.
237 */
238 export const TREE: readonly TreeGroup[] = [
239 { key: "g", label: "go", leaves: [] },
240 {
241 key: "p",
242 label: "pull",
243 leaves: [
244 { key: "m", label: "merge", does: { verb: "merge" } },
245 { key: "a", label: "approve", does: { verb: "approve" } },
246 { key: "b", label: "send back", does: { verb: "sendBack" } },
247 { key: "u", label: "update", does: { verb: "update" } },
248 { key: "x", label: "close", does: { verb: "close" } },
249 ],
250 },
251 {
252 key: "i",
253 label: "issue",
254 leaves: [
255 { key: "a", label: "assign", does: { verb: "assign" } },
256 { key: "e", label: "sharpen", does: { verb: "sharpen" } },
257 { key: "p", label: "park", does: { verb: "park" } },
258 { key: "x", label: "close", does: { verb: "close" } },
259 ],
260 },
261 {
262 key: "r",
263 label: "runs",
264 leaves: [
265 { key: "r", label: "queue again", does: { verb: "requeue" } },
266 { key: "s", label: "stop", does: { verb: "stop" } },
267 { key: "i", label: "take the wheel", does: { verb: "wheel" } },
268 { key: "w", label: "watch", does: { verb: "watch" } },
269 ],
270 },
271 {
272 key: "c",
273 label: "crew",
274 leaves: [
275 { key: "t", label: "tell the crew", does: { press: "t" } },
276 { key: "s", label: "slots", does: { href: "/?view=lanes#slots" } },
277 { key: "f", label: "flow", does: { href: "/flow" } },
278 { key: "w", label: "the week", does: { href: "/settings/crew" } },
279 ],
280 },
281 {
282 key: "f",
283 label: "find",
284 leaves: [
285 { key: "f", label: "file", does: { press: "f" } },
286 { key: "c", label: "command", does: { press: "Mod+k" } },
287 { key: "/", label: "search", does: { press: "/" } },
288 { key: "g", label: "page by name", does: { press: ":" } },
289 ],
290 },
291 {
292 key: "t",
293 label: "talk",
294 leaves: [
295 { key: "t", label: "open Talk", does: { href: "/talk" } },
296 { key: "s", label: "say about this", does: { press: "t" } },
297 ],
298 },
299 {
300 key: "y",
301 label: "copy",
302 leaves: [
303 { key: "l", label: "link", does: { copy: "link" } },
304 { key: "s", label: "commit", does: { copy: "sha" } },
305 { key: "b", label: "branch", does: { copy: "branch" } },
306 ],
307 },
308 ];
309
310 /**
311 * The tree as the browser reads it: groups with their leaves' key, label and what each does as a
312 * key.
313 */
314 export function treeForScript(): { k: string; l: string; leaves: { k: string; l: string; verb?: string; press?: string; href?: string; copy?: string }[] }[] {
315 return TREE.map((g) => ({
316 k: g.key,
317 l: g.label,
318 leaves: g.leaves.map((f) => ({
319 k: f.key,
320 l: f.label,
321 ...("verb" in f.does ? { verb: VERBS[f.does.verb].key } : {}),
322 ...("press" in f.does ? { press: f.does.press } : {}),
323 ...("href" in f.does ? { href: f.does.href } : {}),
324 ...("copy" in f.does ? { copy: f.does.copy } : {}),
325 })),
326 }));
327 }
328
329 export type VerbId = keyof typeof VERBS;
330
179331 export type KeyId = keyof typeof KEYMAP;
180332
181333 /** The key for `id`: what a page passes as a button's `shortcut`. */
src/web/pages/home_flow_style.ts +1
@@ -60,6 +60,7 @@ export const homeFlowCss = /* css */ `
6060 .tile[data-state="done"] { border-left: 2px solid var(--success); }
6161 /* The bridge (bridge_client.ts): the selected tile, and the bar of its verbs under the lanes. No motion. */
6262 .tile[data-selected] { outline: 2px solid var(--accent); outline-offset: 1px; }
63 .tile[data-picked] { outline: 2px dashed var(--accent); outline-offset: 1px; }
6364 /* A line at the foot of the page, like a status line, not a sheet: one rule above it, the page's own ground. */
6465 .br-bar { position: sticky; bottom: 0; display: grid; gap: 4px; margin: 12px 0 0; padding: 8px 16px max(8px, env(safe-area-inset-bottom)); border-top: 1px solid var(--border); background: var(--bg); }
6566 .br-top { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
src/web/style/components.ts +7
@@ -996,6 +996,13 @@ a[data-palette] { display: none; }
996996 .palette { border-radius: 0; border: 0; }
997997 }
998998
999 /* ---- which-key: the key tree's next keys, at the foot (focus/which.ts) ---- */
1000 .wk { position: sticky; bottom: 0; margin: 16px 0 0; padding: 8px 16px max(8px, env(safe-area-inset-bottom)); border-top: 1px solid var(--border); background: var(--bg); font-size: 13px; }
1001 .wk[hidden] { display: none; }
1002 .wk-head { margin: 0 0 4px; color: var(--muted-fg); }
1003 .wk-keys { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 2px 16px; margin: 0; padding: 0; list-style: none; }
1004 .wk-keys kbd { min-width: 1.5em; text-align: center; }
1005
9991006 /* ---- toast / flash ---- */
10001007 .toast:not([hidden]) {
10011008 display: flex; align-items: flex-start; gap: 8px;
src/web/which_asset.ts added +19
@@ -0,0 +1,19 @@
1 /**
2 * The key tree's module (`focus/which.ts` whichJs), content-addressed like the shell and served
3 * immutable from `/assets/<name>.js`. The shell fetches it on the first Space or g a page sees, so
4 * a page no one types on never loads it.
5 */
6 import { whichJs } from "./focus/which.ts";
7 import type { BuiltAsset } from "./asset.ts";
8 import { sha256 } from "../kernel/hash.ts";
9
10 let which: BuiltAsset | null = null;
11
12 export function whichAsset(): BuiltAsset {
13 if (which === null) {
14 const hash = sha256(whichJs);
15 const name = `which-${hash.slice(0, 16)}`;
16 which = { path: `/assets/${name}.js`, name, code: whichJs, etag: `"${hash}"` };
17 }
18 return which;
19 }
test/bridge.test.ts +60
@@ -212,6 +212,66 @@ test.skipIf(skip)("the lanes are a grid: l and h cross lanes at the same row, j
212212 expect(s.typed, seen).toBe(true);
213213 }, 30_000);
214214
215 test.skipIf(skip)("combos: a count moves that many (2j), v picks as the moves go and offers what applies to all with one forecast, and . does the last verb again", async () => {
216 if (chromium === undefined) throw new Error("no Chromium starts in this check, so the bridge is not driven: the check's image must carry one (FORGE_CHROMIUM)");
217 const s = await inPage(1280, `(async () => {
218 ${WAIT} ${KEY} ${PICK}
219 { const f0 = HTMLElement.prototype.focus; HTMLElement.prototype.focus = function (o) { const was = document.activeElement; f0.call(this, o); if (document.activeElement === this && was !== this) this.dispatchEvent(new FocusEvent('focusin', { bubbles: true })); }; }
220 await wait(() => document.querySelector('.tile[data-key]'));
221 const bar = document.getElementById('bridge');
222 const shown = (l) => [...l.querySelectorAll('.tile[data-key]')].filter((t) => t.getClientRects().length > 0);
223 const lanes = [...document.querySelectorAll('.lane[data-lane]')].filter((l) => shown(l).length > 0);
224 const from = lanes.reduce((a, b) => (shown(b).length > shown(a).length ? b : a));
225 const col = shown(from);
226 const out = { rows: col.length };
227 pick(col[0]);
228 key('2'); key('j');
229 out.counted = document.querySelector('[data-selected]') === col[Math.min(2, col.length - 1)];
230 // v picks the focused tile, and each move adds the next.
231 pick(col[0]);
232 key('v');
233 out.one = bar.querySelector('.br-head')?.textContent ?? '';
234 key('j');
235 out.two = bar.querySelector('.br-head')?.textContent ?? '';
236 out.marked = document.querySelectorAll('[data-picked]').length;
237 out.offers = [...bar.querySelectorAll('[data-shortcut]')].map((b) => b.getAttribute('data-shortcut')).filter((k) => k !== null);
238 // A verb on the picked says its forecast first and waits for the second press.
239 if (out.offers.length > 0) {
240 key(out.offers[out.offers.length - 1]);
241 await wait(() => (bar.querySelector('[data-said]')?.textContent ?? '').includes('again to do it'));
242 out.forecast = bar.querySelector('[data-said]').textContent;
243 }
244 key('v');
245 out.stopped = document.querySelectorAll('[data-picked]').length;
246 // . does the last verb again on the newly focused tile: an issue's park, twice.
247 const issues = [...document.querySelectorAll('.tile[data-kind="issue"][data-issue]:not([data-issue=""])')].filter((t) => t.getClientRects().length > 0);
248 out.issues = issues.length;
249 if (issues.length >= 2) {
250 pick(issues[0]);
251 key('p');
252 await wait(() => (bar.querySelector('[data-said]')?.textContent ?? '').startsWith('Move to Later'));
253 out.first = bar.querySelector('[data-said]').textContent;
254 pick(issues[1]);
255 key('.');
256 await wait(() => (bar.querySelector('[data-said]')?.textContent ?? '').startsWith('Move to Later'));
257 out.again = bar.querySelector('[data-said]').textContent;
258 }
259 return JSON.stringify(out);
260 })()`);
261 const seen = JSON.stringify(s);
262 expect(s.rows, seen).toBeGreaterThanOrEqual(3);
263 expect(s.counted, seen).toBe(true);
264 expect(s.one, seen).toContain("1 picked");
265 expect(s.two, seen).toContain("2 picked");
266 expect(s.marked, seen).toBe(2);
267 expect(s.stopped, seen).toBe(0);
268 if (s.offers.length > 0) expect(s.forecast, seen).toMatch(/2 rows: .* Press \S+ again to do it\.$/);
269 if (s.issues >= 2) {
270 expect(s.first, seen).toMatch(/^Move to Later/);
271 expect(s.again, seen).toMatch(/^Move to Later/);
272 }
273 }, 30_000);
274
215275 test.skipIf(skip)("on a phone the first tap selects and the bar docks at the foot; the second tap opens", async () => {
216276 if (chromium === undefined) throw new Error("no Chromium starts in this check, so the bridge is not driven: the check's image must carry one (FORGE_CHROMIUM)");
217277 const s = await inPage(390, `(async () => {
test/crew-switch.test.ts +2 −2
@@ -200,7 +200,7 @@ describe("crew builds here, off: what carries on", () => {
200200 expect(crewBuildsHere(app.db, lib.value.id)).toBe(false);
201201 });
202202
203 test("the terminal: an admin flips it with space, the event the page follows is written, and a writer has no entry", async () => {
203 test("the terminal: an admin flips it with Enter, the event the page follows is written, and a writer has no entry", async () => {
204204 const key = (k: string) => ({ type: "key" as const, key: k, ctrl: false, alt: false, shift: false });
205205 const kinds: string[] = [];
206206 const off = app.bus.subscribe((e) => {
@@ -216,7 +216,7 @@ describe("crew builds here, off: what carries on", () => {
216216 await settleApp(tui);
217217 expect(tui.screen.toText()).toContain("Crew builds here: off");
218218 expect(crewSwitchCommands(session, tui.ctx, fresh())).toHaveLength(1);
219 tui.dispatch(key("space"));
219 tui.dispatch(key("enter"));
220220 await settleApp(tui);
221221 expect(crewBuildsHere(app.db, repo.id)).toBe(true);
222222 expect(kinds).toContain("repo.settings_updated");
test/digest-doors.test.ts +3 −2
@@ -86,8 +86,9 @@ test("web, terminal and MCP give identical digest lines for one seeded forge", a
8686 // Both doors end the same way: the web's link, the terminal's line and the key that shows its
8787 // address.
8888 expect(page).toContain(`${FEED_MORE}</a>`);
89 expect(text).toContain(`${FEED_MORE} (v)`);
90 terminal.feed("v");
89 expect(text).toContain(`${FEED_MORE} (Y)`);
90 // The feed link is Y on the dashboard (v marks now).
91 terminal.feed("Y");
9192 await settleApp(tui);
9293 expect(tui.screen.toText()).toContain(`${publicOrigin(app.config.url, `http://localhost:${app.config.port}`)}/feed`);
9394 tui.stop();
test/focus-tree.test.ts added +135
@@ -0,0 +1,135 @@
1 /**
2 * The key tree, pressed in a browser (keymap.ts TREE, focus/which.ts): Space then a group then a
3 * leaf acts; a pause after a prefix shows which-key, and a fast chord does not need it; an unknown
4 * key says so; Space on a button stays the button's; g alone shows this scope's destinations; and a
5 * moved g chord says where it went.
6 */
7 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { serve, type Servers } from "../src/http/server.ts";
13 import { findChromium } from "../src/looks/capture.ts";
14 import { OLD_KEYS_UNTIL, provideOldKeysClockForTest } from "../src/web/keymap.ts";
15 import { chromiumRuns, evaluateLoaded } from "./helpers/chrome.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17
18 quietLogs();
19 const found = findChromium();
20 const chromium = found !== undefined && chromiumRuns(found) ? found : undefined;
21 const skip = chromium === undefined && (process.env["FORGE_CHECK"] ?? "") === "";
22 if (skip) console.log("SKIPPING: no chromium that starts on this machine, so the key tree is not pressed");
23
24 let dir: string;
25 let app: App;
26 let servers: Servers;
27 beforeAll(async () => {
28 dir = await mkdtemp(join(tmpdir(), "forge-focus-tree-"));
29 app = createApp({ dataDir: dir, port: 0 });
30 // The shell is drawn with the old chords hinted, on a clock before their date.
31 provideOldKeysClockForTest(new Date(Date.parse(OLD_KEYS_UNTIL) - 86_400_000));
32 servers = await serve(app);
33 }, 30_000);
34 afterAll(async () => {
35 provideOldKeysClockForTest(undefined);
36 servers.stop();
37 app.close();
38 await rm(dir, { recursive: true, force: true });
39 });
40
41 const WAIT =
42 "const wait = (f, ms = 2000) => new Promise((ok) => { const t0 = performance.now(); const t = setInterval(() => { if (f() || performance.now() - t0 > ms) { clearInterval(t); ok(); } }, 25); });";
43 const KEY =
44 "const key = (k, at) => (at || document).dispatchEvent(new KeyboardEvent('keydown', { key: k, bubbles: true, cancelable: true }));";
45
46 test.skipIf(skip)(
47 "pressed: Space f c opens the palette; a pause shows which-key; z says it is nothing; a button keeps its Space; g shows the forge's places; g s says where System went",
48 async () => {
49 if (chromium === undefined)
50 throw new Error(
51 "no Chromium starts in this check, so the key tree is not pressed: the check's image must carry one (FORGE_CHROMIUM)",
52 );
53 const out = JSON.parse(
54 await evaluateLoaded(
55 chromium,
56 `${servers.url}/explore`,
57 { width: 1280, height: 900 },
58 [],
59 `(async () => {
60 ${WAIT} ${KEY}
61 const panel = () => document.querySelector('[data-which]');
62 const shown = () => !!panel() && !panel().hidden;
63 const said = () => document.querySelector('.toast[data-key-says]')?.textContent.trim() ?? null;
64 const out = {};
65 // Nothing of the tree is on the page until it is wanted (which_asset.ts).
66 out.lazy = !window.forgeWhich && !document.querySelector('script[src*="/assets/which-"]');
67 // A fast chord, typed before the tree arrived: held, then played: the palette opens and no panel was needed.
68 key(' '); key('f'); key('c');
69 await wait(() => document.querySelector('dialog[open]'));
70 out.palette = !!document.querySelector('dialog[open]');
71 out.fastPanel = shown();
72 key('Escape');
73 await wait(() => !document.querySelector('dialog[open]'));
74 // A pause after Space: the groups, with + on each.
75 key(' ');
76 await wait(shown);
77 out.groups = [...panel().querySelectorAll('li')].map((li) => li.textContent.trim());
78 // A group, then the pause: its leaves.
79 key('y');
80 await wait(() => (panel()?.textContent ?? '').includes('link'));
81 out.copyLeaves = [...panel().querySelectorAll('li')].map((li) => li.textContent.trim());
82 key('Escape');
83 out.closed = !shown();
84 // An unknown key says so and stops.
85 key(' '); key('z');
86 out.nothing = said();
87 // A button keeps its own Space: no tree starts.
88 const b = document.createElement('button'); b.type = 'button'; b.textContent = 'x'; document.getElementById('main').appendChild(b); b.focus();
89 key(' ', b); key('y', b); key('l', b);
90 out.buttonCopied = (said() ?? '').startsWith('Copied');
91 b.blur();
92 // A control by its role keeps its Space too (a menu item, a role=button).
93 const r = document.createElement('div'); r.setAttribute('role', 'button'); r.tabIndex = 0; r.textContent = 'y'; document.getElementById('main').appendChild(r); r.focus();
94 key(' ', r); key('y', r); key('l', r);
95 out.roleCopied = (said() ?? '').startsWith('Copied');
96 r.blur();
97 // g alone: this scope's destinations after a pause.
98 key('g');
99 await wait(shown);
100 out.go = panel().textContent;
101 key('x');
102 // A moved chord says where it went.
103 key('g'); key('s');
104 out.moved = said();
105 return JSON.stringify(out);
106 })()`,
107 ),
108 ) as {
109 palette: boolean;
110 fastPanel: boolean;
111 groups: string[];
112 copyLeaves: string[];
113 closed: boolean;
114 nothing: string | null;
115 buttonCopied: boolean;
116 roleCopied: boolean;
117 lazy: boolean;
118 go: string;
119 moved: string | null;
120 };
121 expect(out.palette).toBe(true);
122 expect(out.fastPanel).toBe(false);
123 expect(out.groups).toEqual(expect.arrayContaining(["g +go", "p +pull", "r +runs", "f +find", "y +copy", "? the whole tree"]));
124 expect(out.copyLeaves).toEqual(["l link", "s commit", "b branch"]);
125 expect(out.closed).toBe(true);
126 expect(out.nothing).toBe("Space z is nothing here.");
127 expect(out.buttonCopied).toBe(false);
128 expect(out.roleCopied).toBe(false);
129 expect(out.lazy).toBe(true);
130 expect(out.go).toContain("Explore");
131 expect(out.go).toContain("g · go (the forge)");
132 expect(out.moved).toBe("g y is System now (g s is a repository's settings)");
133 },
134 30_000,
135 );
test/keymap-terminal.test.ts +24 −5
@@ -94,13 +94,12 @@ const G_BINDING = /binding\(\[(?:"[^"]*",\s*)*"g"(?:,\s*"[^"]*")*\],\s*(["`])([^
9494
9595 /**
9696 * A handler that reads the key g itself (`e.key === "g"`). Not a moved key's hint (`movedKey`), a
97 * chord with Ctrl (`e.ctrl &&`), or the lists' own top, which reads g with Home until the
98 * terminal's jumps take `g g` for it.
97 * chord with Ctrl (`e.ctrl &&`), or the lists' Home (g g, through the go panel, is their top now).
9998 */
10099 const G_HANDLER = /^.*e\.key\s*===\s*"g".*$/gm;
101100 const G_ALLOWED = /movedKey|e\.ctrl\s*&&|"home"/;
102101
103 test("no terminal screen takes g for a verb of its own: g is to start a jump, as on the web", () => {
102 test("no terminal screen takes g at all: g opens the go panel, as on the web, and g g is the top", () => {
104103 const sources = terminalSources();
105104 const taken: string[] = [];
106105 for (const [path, text] of Object.entries(sources))
@@ -111,8 +110,7 @@ test("no terminal screen takes g for a verb of its own: g is to start a jump, as
111110 }
112111 for (const [path, text] of Object.entries(sources))
113112 for (const m of text.matchAll(G_BINDING))
114 // The lists' own top and end (g, G) stay until the jump arrives and takes g g for the top.
115 if (m[2] !== "top, end") taken.push(`${path}: g "${m[2]}": read again is ${keyOf("reread")}; any other verb takes a letter of its own`);
113 taken.push(`${path}: g "${m[2]}": read again is ${keyOf("reread")}; any other verb takes a letter of its own`);
116114 expect(taken).toEqual([]);
117115 });
118116
@@ -128,3 +126,24 @@ test("a screen's moved g says where it went until the date, and nothing after",
128126 provideOldKeysClockForTest(undefined);
129127 expect(said).toEqual(["G grants now"]);
130128 });
129
130 /** Screens whose Space belongs to a focused control, as a checkbox's does on the web: kept. */
131 const SPACE_IS_A_CONTROL: Record<string, string> = {
132 "src/tui/gallery.ts": "a control's state, cycled",
133 "src/tui/screens/migrate.ts": "a field's choice",
134 "src/tui/screens/common.ts": "a picker's tick",
135 "src/tui/screens/display.ts": "a form's tick",
136 "src/tui/screens/commit.ts": "a form's checkbox",
137 "src/tui/screens/configform.ts": "a form's checkbox",
138 "src/tui/screens/newrepo.ts": "a form's checkbox",
139 "src/tui/local/work.ts": "the git stage, as lazygit",
140 };
141 const SPACE_BINDING = /binding\(\[(?:"[^"]*",\s*)*"space"(?:,\s*"[^"]*")*\]/g;
142
143 test("Space is the leader off a control: only a control's screen binds it, and marking is v", () => {
144 const sources = terminalSources();
145 const binding = Object.keys(sources).filter((p) => [...sources[p]!.matchAll(SPACE_BINDING)].length > 0).sort();
146 const said = binding.filter((p) => !(p in SPACE_IS_A_CONTROL)).map((p) => `${p} binds Space: it is the leader; mark with v, toggle with Enter, or list it in SPACE_IS_A_CONTROL if a focused control owns it`);
147 expect(said).toEqual([]);
148 expect(Object.keys(SPACE_IS_A_CONTROL).filter((p) => !binding.includes(p))).toEqual([]);
149 });
test/keymap.test.ts +41 −11
@@ -12,7 +12,7 @@ import { readdirSync, readFileSync, statSync } from "node:fs";
1212 import { join, relative } from "node:path";
1313 import { decideKey } from "../src/web/key_decision.ts";
1414 import { GO_PAGES } from "../src/web/go_pages.ts";
15 import { KEYMAP, MOVES, OLD_KEYS, OLD_KEYS_UNTIL, REPO_TABS, VERBS, keyOf, oldKeys, provideOldKeysClockForTest, type KeyDef, type KeyKind } from "../src/web/keymap.ts";
15 import { GO, KEYMAP, LEADER, TREE, MOVES, OLD_KEYS, OLD_KEYS_UNTIL, REPO_TABS, oldGo, VERBS, keyOf, oldKeys, provideOldKeysClockForTest, type KeyDef, type KeyKind } from "../src/web/keymap.ts";
1616 import { bridgeJs } from "../src/web/bridge_client.ts";
1717 import { DISMISS_KEY, NEW_ISSUE_KEY } from "../src/web/script_keys.ts";
1818
@@ -125,11 +125,21 @@ test("the space's canvas and /system's sort take their keys from the map; /syste
125125 expect(oldKeys("next", new Date(Date.parse(OLD_KEYS_UNTIL) - 1)).map((o) => [o.was, o.key])).toEqual([["t", "T"], ["u", "K"], ["d", "J"], ["l", "p"]]);
126126 });
127127
128 test("a repository's tabs are g jumps of their own, and shadow a forge-wide one only where the map says", () => {
129 const tabs = Object.values(REPO_TABS);
130 expect(new Set(tabs).size).toBe(tabs.length);
131 const global = new Set(GO_PAGES.flatMap((p) => (p.key === undefined ? [] : [`g ${p.key}`])));
132 expect(tabs.filter((k) => global.has(k)).sort()).toEqual(["g f", "g s"]);
128 test("the g jumps are one table by scope: no letter twice in a scope, go_pages and the tabs read it, and a shadowed forge place is g and its capital", () => {
129 for (const scope of [GO.global, GO.repo]) {
130 const letters = Object.values(scope);
131 expect(letters.filter((l, i) => letters.indexOf(l) !== i)).toEqual([]);
132 for (const l of letters) expect(l).toMatch(/^[a-z]$/);
133 }
134 // go_pages.ts's letters are the global scope's, every one of them.
135 expect(GO_PAGES.flatMap((p) => (p.key === undefined ? [] : [p.key])).sort()).toEqual(Object.values(GO.global).sort());
136 expect((Object.values(REPO_TABS) as string[]).sort()).toEqual(Object.values(GO.repo).map((l) => `g ${l}`).sort());
137 // Inside a repository a forge place with the same letter is g and the capital (boards: g B).
138 const shadowed = Object.values(GO.global).filter((l) => (Object.values(GO.repo) as string[]).includes(l));
139 expect(shadowed).toEqual(["b"]);
140 // The moved chords say where they went, until the date.
141 expect(oldGo(new Date(Date.parse(OLD_KEYS_UNTIL) - 1)).map((o) => o.was)).toEqual(["g a", "g s"]);
142 expect(oldGo(new Date(OLD_KEYS_UNTIL))).toEqual([]);
133143 });
134144
135145 test("the shell says where a moved key went, and a quick second key still finds its button", () => {
@@ -143,11 +153,8 @@ test("both doors share one meaning per key: R refreshes a terminal screen, / fil
143153 // No terminal key differs from the web's: Next up's not now is p too, and its planner pause is P.
144154 expect((Object.entries(KEYMAP) as [string, KeyDef][]).filter(([, d]) => d.terminal !== undefined).map(([id]) => id)).toEqual([]);
145155 expect([keyOf("park"), keyOf("pausePlanner")]).toEqual(["p", "P"]);
146 // g read again too, on the screens that took g for it (slice 4a): g is to start a jump.
147 expect(oldKeys("terminal", new Date(Date.parse(OLD_KEYS_UNTIL) - 1))).toEqual([
148 { was: "r", key: "R", says: "R is refresh now" },
149 { was: "g", key: "R", says: "R is refresh now" },
150 ]);
156 // g, which read again on a few screens, opens the go panel now (which.ts), so it says nothing.
157 expect(oldKeys("terminal", new Date(Date.parse(OLD_KEYS_UNTIL) - 1))).toEqual([{ was: "r", key: "R", says: "R is refresh now" }]);
151158 });
152159
153160 test("the g jumps the map names are go_pages.ts's", () => {
@@ -183,3 +190,26 @@ test("the bridge is handed its verbs from the map, and names them, never types t
183190 for (const [id, d] of Object.entries(VERBS)) expect(bridgeJs).toContain(`"${id}":[${JSON.stringify(d.key)},${JSON.stringify(d.label)}]`);
184191 expect(bridgeJs).not.toMatch(/verb\('.{1,5}', '/);
185192 });
193
194 test("the key tree is one table: no path twice, every leaf has words and does something the map has, and the leader is no single key", () => {
195 expect(LEADER).toBe(" ");
196 const groups = TREE.map((g) => g.key);
197 expect(groups.filter((k, i) => groups.indexOf(k) !== i)).toEqual([]);
198 expect(groups).not.toContain("?");
199 const known = new Set<string>([...Object.values(KEYMAP).map((d) => d.key), "Mod+k"]);
200 for (const g of TREE) {
201 expect(g.label.length).toBeGreaterThan(1);
202 const leaves = g.leaves.map((f) => f.key);
203 expect({ group: g.key, twice: leaves.filter((k, i) => leaves.indexOf(k) !== i) }).toEqual({ group: g.key, twice: [] });
204 for (const f of g.leaves) {
205 expect(f.label.length).toBeGreaterThan(1);
206 if ("verb" in f.does) expect(Object.keys(VERBS)).toContain(f.does.verb);
207 if ("press" in f.does) expect(known.has(f.does.press)).toBe(true);
208 if ("href" in f.does) expect(f.does.href.startsWith("/")).toBe(true);
209 }
210 }
211 // The go group lists none of its own: its leaves are the page's scope (GO).
212 expect(TREE.find((g) => g.key === "g")?.leaves).toEqual([]);
213 // No single key is the leader, so Space never shadows a move or a verb.
214 expect(Object.values(KEYMAP).map((d) => d.key)).not.toContain(LEADER);
215 });
test/keys-goto.test.ts +6 −6
@@ -10,12 +10,12 @@ test("every g-letter is one lowercase letter, bound once", () => {
1010 expect(new Set(letters).size).toBe(letters.length);
1111 });
1212
13 test("the main pages are bound: g h, g f, g e, g s", () => {
13 test("the main pages are bound: g h, g f, g e, g y (keymap.ts GO)", () => {
1414 const at = (k: string) => keyed.find((p) => p.key === k)?.href;
1515 expect(at("h")).toBe("/");
1616 expect(at("f")).toBe("/flow");
1717 expect(at("e")).toBe("/explore");
18 expect(at("s")).toBe("/system");
18 expect(at("y")).toBe("/system");
1919 });
2020
2121 test("a page has one binding; every target is a page of the list", () => {
@@ -26,8 +26,8 @@ test("a page has one binding; every target is a page of the list", () => {
2626 test("a viewer is offered only the targets they can open", () => {
2727 const keys = (v: { signedIn: boolean; admin: boolean }) => goPagesFor(v).filter((p) => p.key).map((p) => p.key);
2828 expect(keys({ signedIn: false, admin: false })).toEqual(["h", "e"]);
29 expect(keys({ signedIn: true, admin: false })).not.toContain("s");
30 expect(keys({ signedIn: true, admin: true })).toContain("s");
29 expect(keys({ signedIn: true, admin: false })).not.toContain("y");
30 expect(keys({ signedIn: true, admin: true })).toContain("y");
3131 });
3232
3333 // The real keys script, run against a minimal fake document: it records the listeners
@@ -72,14 +72,14 @@ test("the script: a stranger's or a user's g f does nothing, an admin's goes to
7272 user.press("g");
7373 user.press("f");
7474 user.press("g");
75 user.press("s");
75 user.press("y");
7676 expect(user.assigned).toEqual([]);
7777 const admin = keys(2);
7878 admin.press("g");
7979 admin.press("f");
8080 expect(admin.assigned).toEqual(["/flow"]);
8181 admin.press("g");
82 admin.press("s");
82 admin.press("y");
8383 expect(admin.assigned).toEqual(["/flow", "/system"]);
8484 Date.now = realNow;
8585 });
test/tui-archive-many.test.ts +2 −2
@@ -70,7 +70,7 @@ describe("archive many repositories from the terminal home", () => {
7070 try {
7171 await settleUntil(h.app, "alice/one");
7272 // Rows are newest first or by name; mark whichever two are under the cursor.
73 await h.press("space", "j", "space");
73 await h.press("v", "j", "v");
7474 expect(h.text().match(/\[x\]/g)?.length).toBe(2);
7575 await h.press("a");
7676 expect(h.text()).toContain("Archive 2 repositories?");
@@ -94,7 +94,7 @@ describe("archive many repositories from the terminal home", () => {
9494 for (const ch of "alice/") await h.press(ch);
9595 await h.press("enter");
9696 await settleUntil(h.app, "alice/one");
97 await h.press("space", "a");
97 await h.press("v", "a");
9898 expect(h.text()).not.toContain("[x]");
9999 expect(h.text()).not.toContain("Archive");
100100 expect(["one", "two", "three"].filter(archived)).toEqual([]);
test/tui-archive.test.ts +2 −1
@@ -214,7 +214,8 @@ describe("a terminal archive and the web home", () => {
214214 const h = boot(admin);
215215 try {
216216 await settleUntil(h.app, "keeper/alpha");
217 await h.press("space", "j", "space");
217 // Marking is v (Space is the leader).
218 await h.press("v", "j", "v");
218219 await h.press("a");
219220 await h.press("enter");
220221 await settleUntil(h.app, "archived 2");
test/tui-asks-admin.test.ts +1 −1
@@ -176,7 +176,7 @@ describe("what stands in the way, in the terminal", () => {
176176 const to = async (h: ReturnType<typeof boot>, kind: AskRow["kind"]) => {
177177 const at = rowsOf(h).indexOf(kind);
178178 expect(at).toBeGreaterThanOrEqual(0);
179 await h.press("g");
179 await h.press("home");
180180 for (let i = 0; i < at; i++) await h.press("j");
181181 };
182182 // His row was put aside above: on it, a asks nothing new, o opens nothing, n is not his.
test/tui-grants.test.ts +5 −5
@@ -116,11 +116,11 @@ describe("crew grants in the terminal", () => {
116116 expect(h.text()).toContain("Everyone on the crew");
117117 expect(h.text()).toContain("bot1");
118118 expect(h.text()).not.toContain(SECRET);
119 await h.feed(" ");
119 await h.feed("\r");
120120 expect(own(EVERYONE)).toEqual([subA]);
121 await h.feed("l", " ");
121 await h.feed("l", "\r");
122122 expect(own(EVERYONE).sort()).toEqual([subA, subB].sort());
123 await h.feed("j", " ");
123 await h.feed("j", "\r");
124124 expect(own(bot.id)).toEqual([subB]);
125125 expect(own(EVERYONE).length).toBe(2);
126126 h.stop();
@@ -134,7 +134,7 @@ describe("crew grants in the terminal", () => {
134134 setGrants(app.db, repo.id, bot.id, [subB]);
135135 const g = open(alice);
136136 await grants(g);
137 await g.feed("j", "l", " ");
137 await g.feed("j", "l", "\r");
138138 expect(own(bot.id)).toEqual([]);
139139 expect(g.text()).toContain("the wider grant applies");
140140 g.stop();
@@ -146,7 +146,7 @@ describe("crew grants in the terminal", () => {
146146 await grants(h);
147147 await h.feed("j"); // the cursor is on bot1
148148 removeCrew(app.db, repo.id, bot.id);
149 await h.feed(" ");
149 await h.feed("\r");
150150 expect(own(bot.id)).toEqual([]);
151151 expect(h.text()).toContain("That row is no longer on the crew.");
152152 h.stop();
test/tui-held.test.ts +3 −3
@@ -113,7 +113,7 @@ describe("the Later gate, in the terminal", () => {
113113 expect(h.text()).not.toContain("[x]");
114114 await h.press("l");
115115 expect(h.text()).toContain(THREAD_SAYS.planForbidden);
116 await h.press("space", "A");
116 await h.press("v", "A");
117117 expect(held(idea) && held(other)).toBe(true);
118118 expect(current(idea).state).toBe("open");
119119 h.stop();
@@ -125,7 +125,7 @@ describe("the Later gate, in the terminal", () => {
125125 expect(h.text()).toContain("Unchosen idea about colours");
126126 await h.press("l");
127127 expect(held(idea) && held(other)).toBe(true);
128 await h.press("space", "A");
128 await h.press("v", "A");
129129 expect(current(idea).state).toBe("open");
130130 h.stop();
131131 });
@@ -148,7 +148,7 @@ describe("the Later gate, in the terminal", () => {
148148 const h = boot(getUserByName(forge.db, "alice")!);
149149 await h.toHeld("alice/plan");
150150 // Nothing is ticked until the writer ticks: the first line is the newest.
151 await h.press("space");
151 await h.press("v");
152152 expect(h.text()).toContain("[x]");
153153 await h.press("A");
154154 expect(current(other).state).toBe("closed");
test/tui-mouse.test.ts +2 −2
@@ -218,7 +218,7 @@ describe("the pointer", () => {
218218 await h.settle();
219219 // Put the cursor on the first row, then aim at the second one — so the
220220 // click under test is demonstrably on a row that was *not* selected.
221 await h.press("g");
221 await h.press("home");
222222 const LEFT = 70; // the repo pane; the feed names repos too
223223 const first = Math.min(
224224 h.rowOf("alice/beacon", LEFT),
@@ -253,7 +253,7 @@ describe("the pointer", () => {
253253 const h = boot();
254254 try {
255255 await h.settle();
256 await h.press("g");
256 await h.press("home");
257257 const LEFT = 70;
258258 const second = Math.max(
259259 h.rowOf("alice/beacon", LEFT),
test/tui-onyou.test.ts +1 −1
@@ -109,7 +109,7 @@ describe("terminal On you: mutes and many in one move", () => {
109109 issueIn(lamp, "Lamp hums");
110110 const h = await boot();
111111 expect(h.text()).toContain("Lamp flickers");
112 await h.press("space", "j", "space");
112 await h.press("v", "j", "v");
113113 expect(h.text()).toContain("2 marked");
114114 await h.press("x");
115115 await h.type("done for now");
test/tui-org-grants.test.ts +6 −6
@@ -115,13 +115,13 @@ describe("organization grants in the terminal", () => {
115115 expect(screen).toContain("@bot1");
116116 expect(screen).toContain("[ ] starter");
117117 expect(screen).not.toContain("secretstarter");
118 await h.press(" ");
118 await h.press("enter");
119119 expect(h.text()).toContain("Saved. Every repository here without a grant of its own follows it.");
120120 expect(h.text()).toContain("[x] starter");
121121 expect(listGrants(forge.db, orgId)).toEqual([{ scopeId: orgId, agentId: EVERYONE, subscriptionId: starterId }]);
122122 expect(standing()).toContain("starter");
123123
124 await h.press(" ");
124 await h.press("enter");
125125 expect(listGrants(forge.db, orgId)).toEqual([]);
126126 h.stop();
127127 });
@@ -129,10 +129,10 @@ describe("organization grants in the terminal", () => {
129129 test("a row other than everyone is saved on its own", async () => {
130130 const h = boot("rooty");
131131 await palette(h);
132 await h.press("enter", "enter", "j", " ");
132 await h.press("enter", "enter", "j", "enter");
133133 const bot = getUserByName(forge.db, "bot1")!;
134134 expect(listGrants(forge.db, orgId)).toEqual([{ scopeId: orgId, agentId: bot.id, subscriptionId: starterId }]);
135 await h.press(" ");
135 await h.press("enter");
136136 h.stop();
137137 });
138138
@@ -152,7 +152,7 @@ describe("organization grants in the terminal", () => {
152152 await palette(h);
153153 await h.press("enter", "enter");
154154 forge.db.query("UPDATE user SET is_admin = 0 WHERE username = 'rooty'").run();
155 await h.press(" ");
155 await h.press("enter");
156156 expect(h.text()).toContain("Only an admin of this organization");
157157 expect(listGrants(forge.db, orgId)).toEqual([]);
158158 forge.db.query("UPDATE user SET is_admin = 1 WHERE username = 'rooty'").run();
@@ -165,7 +165,7 @@ describe("organization grants in the terminal", () => {
165165 await palette(h);
166166 await h.press("enter", "enter");
167167 expect(h.text()).toContain("No subscription yet.");
168 await h.press("l", "l", "h", " ");
168 await h.press("l", "l", "h", "enter");
169169 expect(h.text()).toContain("No subscription yet.");
170170 expect(listGrants(forge.db, orgId)).toEqual([]);
171171 h.stop();
test/tui-runlog.test.ts +3 −2
@@ -71,7 +71,8 @@ test("a finished run shows its state and its last 200 lines, at the end", async
7171 expect(text).toContain("BOOM-SUMMARY");
7272 expect(text).toContain("line-300");
7373 expect(text).not.toContain("\nline-2\n");
74 app.dispatch({ type: "key", key: "g", ctrl: false, alt: false, shift: false });
74 // The top is Home (or g g): g alone opens the go panel now.
75 app.dispatch({ type: "key", key: "home", ctrl: false, alt: false, shift: false });
7576 await settleApp(app);
7677 expect(app.screen.toText()).toContain("line-101");
7778 expect(app.screen.toText()).not.toContain("\nline-100\n");
@@ -159,7 +160,7 @@ test("a viewer at the end follows new lines; one who scrolled up keeps their pla
159160 appendRunLog(dir, run.id, "row-101");
160161 await settleApp(app);
161162 expect(app.screen.toText()).toContain("row-101");
162 await key(app, "g");
163 await key(app, "home");
163164 expect(app.screen.toText()).toContain("\nrow-1\n");
164165 appendRunLog(dir, run.id, "row-102");
165166 await settleApp(app);
test/tui-screens.test.ts +1 −1
@@ -420,7 +420,7 @@ describe("the terminal UI, against a real forge", () => {
420420 // refresh it (the merged pull has left the open segment), open the top.
421421 await h.press("esc");
422422 await h.press("r");
423 await h.press("g");
423 await h.press("home");
424424 await h.press("enter");
425425 expect(h.text()).toContain("Clash");
426426 expect(h.text()).toContain("conflicts");
test/tui-subscriptions-windows.test.ts +1 −1
@@ -194,7 +194,7 @@ describe("windows on the terminal's subscriptions screen", () => {
194194
195195 test("an account with no window seen says so, whichever row the cursor is on", async () => {
196196 const h = await open();
197 await h.press("g");
197 await h.press("home");
198198 await h.press("j");
199199 expect(h.text()).toContain("windows not seen yet");
200200 h.stop();
test/tui-which.test.ts added +118
@@ -0,0 +1,118 @@
1 /**
2 * The key tree in the terminal (src/tui/app/which.ts): Space opens the groups, a group its
3 * leaves, a key that is nothing says so; g opens the forge's places and g h goes home; g g is the
4 * top of a list; a screen's old g says where it went in the go panel's title.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { createUser, type User } from "../src/core/users.ts";
12 import { createForgeApp } from "../src/tui/forge.ts";
13 import { headlessTerminal } from "../src/tui/term/terminal.ts";
14 import { OLD_KEYS_UNTIL, provideOldKeysClockForTest } from "../src/web/keymap.ts";
15 import { whichRows, whichStep } from "../src/tui/app/which.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17 import { settleApp } from "./helpers/tui.ts";
18
19 quietLogs();
20 let dir: string;
21 let app: App;
22 let alice: User;
23 beforeAll(async () => {
24 dir = await mkdtemp(join(tmpdir(), "forge-tui-which-"));
25 app = createApp({ dataDir: dir, port: 0 });
26 const made = await createUser(app.db, {
27 origin: "seed",
28 trusted: true,
29 username: "alice",
30 email: "[email protected]",
31 password: "a-good-passphrase",
32 adminIfFirst: true,
33 });
34 if (!made.ok) throw new Error(made.error);
35 alice = made.value;
36 }, 30_000);
37 afterAll(async () => {
38 app.close();
39 await rm(dir, { recursive: true, force: true });
40 });
41
42 const boot = async () => {
43 const { app: tui } = createForgeApp(
44 app,
45 { sshUsername: "alice", remoteAddress: "127.0.0.1", user: alice },
46 { terminal: headlessTerminal(140, 40), exitHooks: false },
47 );
48 tui.start();
49 await settleApp(tui);
50 const press = async (...keys: string[]) => {
51 for (const key of keys) {
52 tui.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
53 await settleApp(tui);
54 }
55 };
56 return { tui, press, text: () => tui.screen.toText() };
57 };
58
59 test("Space opens the groups, a group its leaves, Backspace goes up, and a key that is nothing says so", async () => {
60 const h = await boot();
61 try {
62 await h.press(" ");
63 expect(h.text()).toContain("+pull");
64 expect(h.text()).toContain("+copy");
65 await h.press("y");
66 expect(h.text()).toContain("Space y · copy");
67 expect(h.text()).toContain("link");
68 await h.press("backspace");
69 expect(h.text()).toContain("+runs");
70 await h.press("z");
71 expect(h.text()).toContain("Space z is nothing here.");
72 expect(h.text()).not.toContain("+runs");
73 } finally {
74 h.tui.stop();
75 }
76 });
77
78 test("g opens the forge's places in the terminal's words, and a leaf for a web page says so", () => {
79 const here = new Set(["home", "explore", "flow", "conversations", "system"]);
80 const go = whichRows({ kind: "go", path: [] }, here);
81 expect(go.rows.map((r) => `${r.key} ${r.label}`)).toEqual(["g top of the list", "h Home", "e Explore", "f Flow", "t Talk", "y System"]);
82 expect(whichStep({ kind: "go", path: [] }, "h", here)).toEqual({ act: { command: "home" } });
83 expect(whichStep({ kind: "go", path: [] }, "g", here)).toEqual({ act: { press: "home" } });
84 expect(whichStep({ kind: "go", path: [] }, "b", here)).toEqual({ miss: "g b is nothing here." });
85 expect(whichStep({ kind: "leader", path: ["p"] }, "m", here)).toEqual({ act: { press: "m" } });
86 expect(whichStep({ kind: "leader", path: ["c"] }, "w", here)).toEqual({ act: { say: "That is a page on the web: /settings/crew" } });
87 expect(whichStep({ kind: "leader", path: ["f"] }, "c", here)).toEqual({ act: { press: "k", ctrl: true } });
88 });
89
90 test("g y, pressed, opens System; Escape closes an open chord", async () => {
91 const h = await boot();
92 try {
93 await h.press("g");
94 expect(h.text()).toContain("g · go");
95 await h.press("escape");
96 expect(h.text()).not.toContain("g · go");
97 await h.press("g", "y");
98 expect(h.text()).toContain("alice › System");
99 } finally {
100 h.tui.stop();
101 }
102 });
103
104 test("before the date, a screen's moved key says where it went in the panel the key opens", async () => {
105 const { movedKey } = await import("../src/tui/screens/moved_key.ts");
106 provideOldKeysClockForTest(new Date(Date.parse(OLD_KEYS_UNTIL) - 1));
107 try {
108 const hinted: string[] = [];
109 const ctx = { toast: () => {}, hint: (t: string) => void hinted.push(t) } as unknown as Parameters<typeof movedKey>[0];
110 const e = { key: "g", ctrl: false, alt: false, shift: false } as Parameters<typeof movedKey>[1];
111 // The key goes on to open the go panel, which says the line.
112 expect(movedKey(ctx, e, "g", "t sets the range now")).toBe(false);
113 expect(movedKey(ctx, { ...e, key: "space" }, " ", "v marks now")).toBe(false);
114 expect(hinted).toEqual(["t sets the range now (was g)", "v marks now (was Space)"]);
115 } finally {
116 provideOldKeysClockForTest(undefined);
117 }
118 });
test/tui-workspace.test.ts +1 −1
@@ -170,7 +170,7 @@ describe("the terminal workspace", () => {
170170 expect(h.text()).toContain("L01");
171171 await h.press("G");
172172 expect(h.text()).toContain("L60");
173 await h.press("g");
173 await h.press("home");
174174 expect(h.text()).toContain("# Lighthouse");
175175 } finally {
176176 h.stop();
test/which-stub.test.ts added +89
@@ -0,0 +1,89 @@
1 /**
2 * The shell's stub for the key tree (focus/which.ts whichStubJs), run against a minimal fake
3 * document: Space holds the keys while the module loads, and a module that never arrives gives them
4 * back, on its error or when the wait gives up, so the keyboard is never lost until a reload.
5 */
6 import { expect, test } from "bun:test";
7 import { shellJs } from "../src/web/client.ts";
8
9 /** Whether a listener held the key: took it and stopped every listener after it. */
10 type Key = { key: string; held: boolean };
11 type Script = { src?: string; onerror?: () => void; onload?: () => void };
12
13 /** The real shell script, with the loader's script element and the clock caught. */
14 function shell() {
15 const handlers: ((e: unknown) => void)[] = [];
16 const scripts: Script[] = [];
17 const timers: (() => void)[] = [];
18 const el: any = new Proxy(function () {}, { get: (_t, k) => (k === "length" ? 0 : el), apply: () => el });
19 const doc: any = {
20 head: { appendChild: (s: Script) => void scripts.push(s) },
21 body: { getAttribute: (n: string) => (n === "data-go" ? "2" : null) },
22 documentElement: { classList: { add() {} }, setAttribute() {}, removeAttribute() {}, hasAttribute: () => false },
23 activeElement: null,
24 currentScript: null,
25 addEventListener: (t: string, f: (e: unknown) => void) => t === "keydown" && handlers.push(f),
26 querySelector: () => null,
27 querySelectorAll: () => [],
28 getElementById: () => null,
29 createElement: (tag: string) => (tag === "script" ? ({} as Script) : el),
30 };
31 const win: any = { addEventListener() {}, matchMedia: () => ({ matches: false, addEventListener() {} }) };
32 const loc: any = { pathname: "/", search: "", assign() {} };
33 const setTimeout = (f: () => void) => timers.push(f);
34 new Function("document", "window", "location", "sessionStorage", "CSS", "setTimeout", "clearTimeout", shellJs)(
35 doc,
36 win,
37 loc,
38 undefined,
39 undefined,
40 setTimeout,
41 () => {},
42 );
43 const press = (key: string): Key => {
44 const out: Key = { key, held: false };
45 const e = {
46 key,
47 target: null,
48 metaKey: false,
49 ctrlKey: false,
50 altKey: false,
51 defaultPrevented: false,
52 preventDefault() {},
53 stopImmediatePropagation: () => void (out.held = true),
54 };
55 // In order, as the browser calls them; a listener that stops the key stops the rest.
56 for (const h of handlers) {
57 h(e);
58 if (out.held) break;
59 }
60 return out;
61 };
62 return { press, scripts, timers };
63 }
64
65 test("Space holds the keys and fetches the module once", () => {
66 const s = shell();
67 expect(s.press(" ").held).toBe(true);
68 expect(s.press("x").held).toBe(true);
69 expect(s.scripts).toHaveLength(1);
70 expect(s.scripts[0]!.src).toMatch(/^\/assets\/which-[0-9a-f]{16}\.js$/);
71 });
72
73 test("a module that fails to load gives the keys back, and the next Space tries again", () => {
74 const s = shell();
75 s.press(" ");
76 s.scripts[0]!.onerror!();
77 expect(s.press("x").held).toBe(false);
78 expect(s.press("Escape").held).toBe(false);
79 expect(s.press(" ").held).toBe(true);
80 expect(s.scripts).toHaveLength(2);
81 });
82
83 test("a module that hangs gives the keys back when the wait gives up", () => {
84 const s = shell();
85 s.press(" ");
86 expect(s.press("x").held).toBe(true);
87 for (const t of s.timers.splice(0)) t();
88 expect(s.press("x").held).toBe(false);
89 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs