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

One keymap (a): every key from one map, the shell and home read it, a test refuses strays #16965

Merged opened this

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

Merged

keymap-a → main 0 commits

  • Merged. keymap-a was merged into main as 7524834.

Review

Sign in to review this change.
9 files changed +289 −32
docs/features/keymap.md added +18
@@ -0,0 +1,18 @@
1 ---
2 topic: Getting around: keys, the palette and search
3 row: One keymap: the same key means the same thing everywhere
4 ---
5
6 # One keymap
7
8 The owner, after the bridge: "tying together all the keybinds is really what im looking for". The forge has one keymap, lazygit-style, in `src/web/keymap.ts`: the same key means the same thing on every page, and a page never chooses a key of its own.
9
10 - **Moves, everywhere:** `j` / `k` along a list or lane, `h` / `l` across columns or tabs, Enter (or `o`) opens, Escape closes what is on top, then clears the selection, then backs out to the list; `/` search, `?` help, Cmd/Ctrl K jump, `:` go to a page, `t` tell the crew, `c` write here, `C` new issue, `g` and a letter to a page (`go_pages.ts`, the one list of those).
11 - **Verbs, one meaning per kind of thing:** a pull: `m` merge (asks for a second `m`), `x` close, `b` send back, `u` update, `a` approve. An issue: `a` assign, `e` sharpen, `p` park, `x` close. A run: `s` stop, `r` queue it again, `w` watch, `i` take the wheel. A figure: `-` / `+` turn it, Enter sets it. `z` undoes, `x` dismisses a card.
12 - **Never while typing:** in a box every key is the box's; Escape leaves it.
13 - **One source:** pages take a key with `keyOf(id)`, the bridge's script is handed the verbs from the map, `?` and Cmd/Ctrl K list what a page carries, and the shell's own keys are held to the map's moves. `test/keymap.test.ts` refuses a key literal outside the map, one key with two meanings on one kind of thing, and a key that fires while typing; the files not yet moved are listed there with the pull that moves them.
14 - **In the terminal** (`src/tui`) the same acts are meant to answer the same keys. Where the terminal still answers another key, the map says which and why (the run list's `x` stop, `a` queue again and `S` steer, which move with the runs pull).
15
16 Coming, one pull each: the pull lists, the pull page and the review page (where `c` and `r` become `x` and `b`, and the verdicts `v a`, `v r`, `v c` become `a`, `b`, `x`, with a two-week hint on the old key); issues and runs (and the terminal's run list); /boards, /flow and Talk.
17
18 Proof: `test/keymap.test.ts`, `test/bridge.test.ts`.
src/web/bridge_client.ts +30 −25
@@ -32,6 +32,7 @@
3232 * selected again. The bar has no motion: it is what a person does many times a day.
3333 */
3434 import { html } from "./html.ts";
35 import { MOVES, verbsForScript } from "./keymap.ts";
3536
3637 /** The bar's one place on home: empty until a tile is selected. */
3738 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>`;
@@ -56,7 +57,11 @@ export const bridgeJs = /* js */ `
5657 return Math.floor(h / 24) + 'd ' + (h % 24) + 'h';
5758 }
5859 function el(tag, cls, text) { var e = D.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; }
59 function verb(k, label, act) {
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];
6065 var b = el(act.href ? 'a' : 'button', 'btn', null);
6166 if (act.href) b.href = act.href; else b.type = 'button';
6267 b.setAttribute('data-size', 'sm');
@@ -104,29 +109,29 @@ export const bridgeJs = /* js */ `
104109 function verbsFor(t) {
105110 var d = t.dataset, out = [], base = '/' + d.repo;
106111 if (d.run) {
107 out.push(verb('w', 'Watch live', { href: base + '/runs/' + d.run }));
108 out.push(verb('i', 'Take the wheel', { href: base + '/runs/' + d.run + '#run-steer' }));
109 out.push(verb('s', 'Stop', { run: function () {
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 () {
110115 act('stop', [d.run], function () {
111 var again = verb('r', 'Queue it again', { run: function () { act('requeue', [d.run]); } });
116 var again = verb('requeue', { run: function () { act('requeue', [d.run]); } });
112117 bar.querySelector('[data-verbs]').appendChild(again);
113118 });
114119 } }));
115120 }
116121 if (d.kind === 'issue' && d.number && d.issue) {
117 out.push(verb('a', 'Assign', { href: base + '/issues/' + d.number + '#f-assignee' }));
118 out.push(verb('e', 'Sharpen', { run: function () { act('replan', [d.issue]); } }));
119 out.push(verb('p', 'Park', { run: function () { act('later', [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]); } }));
120125 }
121126 if (d.kind === 'pull' && d.number && d.issue) {
122 out.push(verb('m', 'Merge', { run: function (b) {
127 out.push(verb('merge', { run: function (b) {
123128 if (Date.now() - armed < 5000) { armed = 0; act('ship', [d.issue]); return; }
124129 armed = Date.now();
125 say('Press m again to merge #' + d.number + ': a merge is not undone.');
130 say('Press ' + VERB.merge[0] + ' again to merge #' + d.number + ': a merge is not undone.');
126131 } }));
127 out.push(verb('x', 'Close', { run: function () { act('close', [d.issue]); } }));
128 out.push(verb('u', 'Update', { run: function () { post(base + '/pulls/' + d.number + '/update', 'Asked the crew to bring #' + d.number + ' up to date.'); } }));
129 out.push(verb('b', 'Send back', { href: base + '/pulls/' + d.number + '#review' }));
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' }));
130135 }
131136 return out;
132137 }
@@ -167,9 +172,9 @@ export const bridgeJs = /* js */ `
167172 room.textContent = r.text;
168173 if (r.over) room.setAttribute('data-over', ''); else room.removeAttribute('data-over');
169174 }
170 verbs.appendChild(verb('-', 'Fewer', { run: function () { if (n > 1) { n--; show(); } } }));
171 verbs.appendChild(verb('+', 'More', { run: function () { if (n < 64) { n++; show(); } } }));
172 verbs.appendChild(verb('Enter', 'Set', { run: function () {
175 verbs.appendChild(verb('fewer', { run: function () { if (n > 1) { n--; show(); } } }));
176 verbs.appendChild(verb('more', { run: function () { if (n < 64) { n++; show(); } } }));
177 verbs.appendChild(verb('set', { run: function () {
173178 if (n === from) { say('Nothing to change.'); return; }
174179 var e = est(n), form = new URLSearchParams();
175180 form.set('key', KEY[kind]); form.set('value', String(n));
@@ -181,7 +186,7 @@ export const bridgeJs = /* js */ `
181186 .then(function (j) {
182187 if (!j.ok) { say(j.flash || 'That did not go through. Nothing changed.'); return; }
183188 from = n; d.slots = String(n); show();
184 var undo = verb('z', 'Undo', { run: function () {
189 var undo = verb('undo', { run: function () {
185190 var back = new URLSearchParams(); back.set('key', KEY[kind]); back.set('value', String(was)); back.set('reason', 'Undone from home.');
186191 fetch('/settings/capacity', { method: 'POST', body: back, credentials: 'same-origin', headers: { accept: 'application/json' } })
187192 .then(function (r2) { return r2.json().catch(function () { return { ok: false }; }); })
@@ -238,15 +243,15 @@ export const bridgeJs = /* js */ `
238243 function nextFor(at, k) {
239244 if (at && at.classList.contains('sl')) {
240245 var fs = figs(), i = fs.indexOf(at);
241 if (k === 'h' || k === 'l') return fs[Math.min(Math.max(i + (k === 'l' ? 1 : -1), 0), fs.length - 1)];
242 return k === 'k' && lastTile && D.contains(lastTile) ? lastTile : at;
246 if (k === 'left' || k === 'right') return fs[Math.min(Math.max(i + (k === 'right' ? 1 : -1), 0), fs.length - 1)];
247 return k === 'up' && lastTile && D.contains(lastTile) ? lastTile : at;
243248 }
244249 var ls = lanes();
245250 if (!at) return ls[0] ? shown(ls[0])[0] : null;
246251 var lane = at.closest('.lane'), col = shown(lane), row = col.indexOf(at);
247 if (k === 'j') return row < col.length - 1 ? col[row + 1] : figs()[0] || at;
248 if (k === 'k') return col[Math.max(row - 1, 0)];
249 var to = ls[ls.indexOf(lane) + (k === 'l' ? 1 : -1)];
252 if (k === 'down') return row < col.length - 1 ? col[row + 1] : figs()[0] || at;
253 if (k === 'up') return col[Math.max(row - 1, 0)];
254 var to = ls[ls.indexOf(lane) + (k === 'right' ? 1 : -1)];
250255 if (!to) return at;
251256 var c = shown(to);
252257 return c[Math.min(row, c.length - 1)];
@@ -255,12 +260,12 @@ export const bridgeJs = /* js */ `
255260 var afterG = prevKey === 'g' && Date.now() - prevAt < 1000;
256261 prevKey = e.key; prevAt = Date.now();
257262 if (e.metaKey || e.ctrlKey || e.altKey || e.defaultPrevented || afterG) return;
258 var k = e.key === 'ArrowLeft' ? 'h' : e.key === 'ArrowRight' ? 'l' : e.key;
259 if (k !== 'h' && k !== 'l' && k !== 'j' && k !== 'k') return;
263 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;
264 if (k === null) return;
260265 var t = e.target;
261266 if (t && t.closest && t.closest('input, textarea, select, [contenteditable], dialog[open]')) return;
262267 var at = tileOf(D.activeElement);
263 if (!at && (k === 'j' || k === 'k' || !D.querySelector('.lane[data-lane] .tile[data-key]'))) return;
268 if (!at && (k === 'down' || k === 'up' || !D.querySelector('.lane[data-lane] .tile[data-key]'))) return;
264269 var next = nextFor(at, k);
265270 if (!next) return;
266271 e.preventDefault(); e.stopImmediatePropagation();
src/web/keymap.ts added +103
@@ -0,0 +1,103 @@
1 /**
2 * The forge's one keymap (the owner: "tying together all the keybinds is really what im looking
3 * for"), lazygit-style: the same key means the same thing on every page and in the terminal. A page
4 * never invents a key: it takes one from here (`keyOf`), the bridge's script is handed the verbs
5 * from here, and `?` and Cmd+K list what the page carries, which can only be these. The shell's own
6 * keys (client.ts STATIC_KEYS) are held to the moves below by test/keymap.test.ts, which also
7 * refuses a key literal outside this file, two meanings for one key on one kind of thing, and a key
8 * that fires while typing.
9 *
10 * Pure data: the static client modules may read it. The g-letter jumps are go_pages.ts's one list;
11 * the map reads its two from there.
12 */
13 import { GO_PAGES } from "./go_pages.ts";
14
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 ?? ""}`;
17
18 /** What a key acts on: a verb means one thing per kind, and a move works anywhere. */
19 export type KeyKind = "any" | "pull" | "issue" | "run" | "figure" | "card";
20
21 export interface KeyDef {
22 /** The `KeyboardEvent.key` it answers; a sequence is written with a space ("g h"). */
23 readonly key: string;
24 /** The word on its button, beside the key. */
25 readonly label: string;
26 /** What it does, as the help says it. */
27 readonly what: string;
28 readonly kinds: readonly KeyKind[];
29 /**
30 * Where the terminal (src/tui) answers another key for the same act, that key and why; absent,
31 * the terminal answers the same key or has no such act.
32 */
33 readonly terminal?: { readonly key: string; readonly reason: string };
34 }
35
36 const any: readonly KeyKind[] = ["any"];
37
38 /** Moving, opening and leaving: the same on every page. */
39 export const MOVES = {
40 down: { key: "j", label: "Down", what: "Move down a list or lane", kinds: any },
41 up: { key: "k", label: "Up", what: "Move up a list or lane", kinds: any },
42 left: { key: "h", label: "Left", what: "Move to the column or tab on the left", kinds: any },
43 right: { key: "l", label: "Right", what: "Move to the column or tab on the right", kinds: any },
44 open: { key: "Enter", label: "Open", what: "Open the focused row (o does too)", kinds: any },
45 back: { key: "Escape", label: "Close", what: "Close what is on top, then clear the selection, then back out to the list", kinds: any },
46 search: { key: "/", label: "Search", what: "Focus search", kinds: any },
47 help: { key: "?", label: "Help", what: "List the keys this page answers", kinds: any },
48 palette: { key: "Mod+k", label: "Jump", what: "Jump to anywhere, or act on what is focused", kinds: any },
49 goto: { key: ":", label: "Go to", what: "Go to a page by name", kinds: any },
50 tell: { key: "t", label: "Tell the crew", what: "Tell the crew what you want", kinds: any },
51 create: { key: "c", label: "Write", what: "Write here: the page's box, else its New", kinds: any },
52 newIssue: { key: "C", label: "New issue", what: "New issue from this page", kinds: any },
53 home: { key: go("/"), label: "Home", what: "Go home", kinds: any },
54 talk: { key: go("/talk"), label: "Talk", what: "Talk to the forge", kinds: any },
55 } as const satisfies Record<string, KeyDef>;
56
57 /** The verbs, one meaning each per kind of thing. */
58 export const VERBS = {
59 merge: { key: "m", label: "Merge", what: "Merge it; asks for a second m, since a merge is not undone", kinds: ["pull"] },
60 close: { key: "x", label: "Close", what: "Close it, or dismiss a card", kinds: ["pull", "issue", "card"] },
61 sendBack: { key: "b", label: "Send back", what: "Send it back with what to change", kinds: ["pull"] },
62 update: { key: "u", label: "Update", what: "Bring it up to date with its base", kinds: ["pull"] },
63 approve: { key: "a", label: "Approve", what: "Approve it", kinds: ["pull"] },
64 assign: { key: "a", label: "Assign", what: "Give it to someone", kinds: ["issue"] },
65 sharpen: { key: "e", label: "Sharpen", what: "Have the planner plan it again", kinds: ["issue"] },
66 park: { key: "p", label: "Park", what: "Park it behind the Later gate", kinds: ["issue"] },
67 stop: {
68 key: "s",
69 label: "Stop",
70 what: "Stop the run",
71 kinds: ["run"],
72 terminal: { key: "x", reason: "the terminal's run list cycles its state filter on s; it moves to s with the runs pull" },
73 },
74 requeue: {
75 key: "r",
76 label: "Queue it again",
77 what: "Queue a stopped run again",
78 kinds: ["run"],
79 terminal: { key: "a", reason: "the terminal's run list refreshes on r; it moves to r with the runs pull" },
80 },
81 watch: { key: "w", label: "Watch live", what: "Watch the run live", kinds: ["run"] },
82 wheel: {
83 key: "i",
84 label: "Take the wheel",
85 what: "Take the wheel: steer the running agent",
86 kinds: ["run"],
87 terminal: { key: "S", reason: "the terminal's run list steers on S; it moves to i with the runs pull" },
88 },
89 fewer: { key: "-", label: "Fewer", what: "Turn the figure down", kinds: ["figure"] },
90 more: { key: "+", label: "More", what: "Turn the figure up", kinds: ["figure"] },
91 set: { key: "Enter", label: "Set", what: "Set the figure to what it shows", kinds: ["figure"] },
92 undo: { key: "z", label: "Undo", what: "Put back what was just done", kinds: ["any"] },
93 } as const satisfies Record<string, KeyDef>;
94
95 export const KEYMAP = { ...MOVES, ...VERBS } as const;
96 export type KeyId = keyof typeof KEYMAP;
97
98 /** The key for `id`: what a page passes as a button's `shortcut`. */
99 export const keyOf = (id: KeyId): string => KEYMAP[id].key;
100
101 /** The verbs as the bridge's script reads them: `{ id: [key, label] }`. */
102 export const verbsForScript = (): Record<string, readonly [string, string]> =>
103 Object.fromEntries(Object.entries(VERBS).map(([id, d]) => [id, [d.key, d.label] as const]));
src/web/layout.ts +3 −2
@@ -8,6 +8,7 @@
88 */
99
1010 import { repoOnRequest } from "../http/request_repo.ts";
11 import { keyOf } from "./keymap.ts";
1112 import { requestHolds } from "../http/conditional.ts";
1213 import { sshOn } from "../settings/ssh.ts";
1314 import { hereAddress, returnTo, withReturn } from "./return_to.ts";
@@ -698,7 +699,7 @@ export function signUpHref(ctx: Ctx): string | undefined {
698699 function talkButton(ctx: Ctx, user: User, about?: string): Html {
699700 const waiting = waitingCount(ctx, user);
700701 const label = waiting > 0 ? `Talk to the forge, ${waiting} waiting` : "Talk to the forge";
701 return html`<a class="btn btn-icon talk-btn" href="${talkHref(about)}" aria-label="${label}" data-shortcut="g t" ${hintAttr("g t", "Talk to the forge")}
702 return html`<a class="btn btn-icon talk-btn" href="${talkHref(about)}" aria-label="${label}" data-shortcut="${keyOf("talk")}" ${hintAttr(keyOf("talk"), "Talk to the forge")}
702703 >${icon("comment")}${waiting > 0 ? html`<span class="talk-count" aria-hidden="true">${waiting > 9 ? "9+" : String(waiting)}</span>` : null}</a
703704 >`;
704705 }
@@ -714,7 +715,7 @@ function topbar(
714715 const user = ctx.auth.user;
715716 return html`<a class="skip" href="#main">Skip to content</a>
716717 <header class="topbar" role="banner">
717 <a href="/" class="wordmark" data-shortcut="g h" ${hintAttr("g h")}
718 <a href="/" class="wordmark" data-shortcut="${keyOf("home")}" ${hintAttr(keyOf("home"))}
718719 ><span class="mark"></span>forge</a
719720 >
720721 ${when(
src/web/pages/apps.ts +2 −1
@@ -13,6 +13,7 @@
1313 */
1414
1515 import { appsStanding } from "../studio/standing.ts";
16 import { keyOf } from "../keymap.ts";
1617 import { stepsOf } from "../../core/review_steps.ts";
1718 import { USERNAME_PATTERN } from "../username_pattern.ts";
1819 import { sshOn } from "../../settings/ssh.ts";
@@ -217,7 +218,7 @@ export async function appsList(ctx: Ctx): Promise<Response> {
217218 variant: "primary",
218219 size: "sm",
219220 icon: "plus",
220 shortcut: "c",
221 shortcut: keyOf("create"),
221222 })
222223 : btn("Sign in to make one", { href: withReturn("/signin", returnTo(ctx)), size: "sm" });
223224 const filters =
src/web/script_keys.ts +5 −3
@@ -6,6 +6,8 @@
66 * `keyHint(key)` beside the action, and the test walks the list and fails on a page whose action shows no hint.
77 */
88
9 import { keyOf } from "./keymap.ts";
10
911 export interface ScriptKey {
1012 key: string;
1113 /** What it does, as the help overlay and the test name it. */
@@ -16,14 +18,14 @@ export interface ScriptKey {
1618 label: string;
1719 }
1820
19 /** Dismiss the focused feed card. */
20 export const DISMISS_KEY = "x";
21 /** Dismiss the focused feed card: the keymap's close, on a card. */
22 export const DISMISS_KEY = keyOf("close");
2123 /**
2224 * New issue from the page, on any page. `c` does it too where the page has no
2325 * box of its own (there it focuses the box), so the hint names the one key that
2426 * always works.
2527 */
26 export const NEW_ISSUE_KEY = "C";
28 export const NEW_ISSUE_KEY = keyOf("newIssue");
2729
2830 export const SCRIPT_KEYS: readonly ScriptKey[] = [
2931 { key: DISMISS_KEY, action: "Dismiss a feed card", page: "/feed", label: "Dismiss" },
src/web/studio/lists.ts +2 −1
@@ -10,6 +10,7 @@
1010 */
1111
1212 import { securityLine } from "../pages/reports.ts";
13 import { keyOf } from "../keymap.ts";
1314 import { sealedScope } from "../../core/sealed.ts";
1415 import { appsRuntime } from "../../apps/runtime.ts";
1516 import { getAppByRepo } from "../../core/apps.ts";
@@ -542,7 +543,7 @@ export async function tellsList(ctx: Ctx): Promise<Response> {
542543 href: `${base}/issues/new`,
543544 size: "sm",
544545 variant: "primary",
545 shortcut: "c",
546 shortcut: keyOf("create"),
546547 }),
547548 );
548549 // A stranger can still say something is wrong on a public repository;
test/bridge.test.ts +14
@@ -139,6 +139,10 @@ test.skipIf(skip)("the lanes are a grid: l and h cross lanes at the same row, j
139139 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)");
140140 const s = await inPage(1280, `(async () => {
141141 ${WAIT} ${KEY} ${PICK}
142 // A page with the window's focus (a Linux check runner's) sends focusin when an element takes
143 // the focus; a headless one here may not. Send it as the focused page would, so the test runs the
144 // same on both.
145 { 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 })); }; }
142146 await wait(() => document.querySelector('.tile[data-key]'));
143147 const bar = document.getElementById('bridge');
144148 const shown = (l) => [...l.querySelectorAll('.tile[data-key]')].filter((t) => t.getClientRects().length > 0);
@@ -171,6 +175,15 @@ test.skipIf(skip)("the lanes are a grid: l and h cross lanes at the same row, j
171175 pick(shown(from)[0]);
172176 key('Escape');
173177 out.escaped = bar.hidden;
178 // Typing in a box moves nothing: the keys are the box's. Focusing the box clears the selection,
179 // as any focus elsewhere does, and the keys typed then select no tile.
180 pick(shown(from)[0]);
181 const box = document.querySelector('main input[type="text"], main input:not([type]), main textarea');
182 if (box) {
183 box.focus();
184 for (const k of ['l', 'j', 'h']) box.dispatchEvent(new KeyboardEvent('keydown', { key: k, bubbles: true, cancelable: true }));
185 }
186 out.typed = box ? where() === null && bar.hidden : 'no box';
174187 return JSON.stringify(out);
175188 })()`);
176189 const seen = JSON.stringify(s);
@@ -193,6 +206,7 @@ test.skipIf(skip)("the lanes are a grid: l and h cross lanes at the same row, j
193206 expect(s.reopened, seen).toBe(true);
194207 expect(s.outside, seen).toBe(true);
195208 expect(s.escaped, seen).toBe(true);
209 expect(s.typed, seen).toBe(true);
196210 }, 30_000);
197211
198212 test.skipIf(skip)("on a phone the first tap selects and the bar docks at the foot; the second tap opens", async () => {
test/keymap.test.ts added +112
@@ -0,0 +1,112 @@
1 /**
2 * The forge's one keymap (src/web/keymap.ts) is the only place a key is chosen. This holds it: a
3 * key literal in src/web outside the map fails (files not yet moved are listed with the pull that
4 * moves them), one key never means two things on one kind of thing, the shell's own keys are the
5 * map's moves, no key fires while typing, and the bridge is handed its verbs from the map.
6 */
7 import { expect, test } from "bun:test";
8 import { readdirSync, readFileSync, statSync } from "node:fs";
9 import { join, relative } from "node:path";
10 import { decideKey } from "../src/web/key_decision.ts";
11 import { KEYMAP, MOVES, VERBS, keyOf, type KeyDef, type KeyKind } from "../src/web/keymap.ts";
12 import { bridgeJs } from "../src/web/bridge_client.ts";
13 import { DISMISS_KEY, NEW_ISSUE_KEY } from "../src/web/script_keys.ts";
14
15 const ROOT = join(import.meta.dir, "..");
16
17 /**
18 * Files that still choose their own keys, each with the pull of the keymap work that moves it onto
19 * the map. This list only shrinks; a file here that no longer has a literal must leave it.
20 */
21 const PENDING: Record<string, string> = {
22 "src/web/pages/pull.ts": "(b) pulls and the pull page: the verdicts v a, v r, v c become a, b, x",
23 "src/web/studio/review_page.ts": "(b) pulls and the pull page: c and r become x and b",
24 "src/web/repo_steps.ts": "(b) pulls and the pull page: the repository's g-letter tabs",
25 "src/web/pages/repo.ts": "(b) pulls and the pull page: e to propose a change",
26 "src/web/pages/explorer.ts": "(c) issues and runs: t finds a file here, which Tell the crew owns everywhere else",
27 };
28
29 /**
30 * Key literals a page could choose for itself. The shell (client.ts) is held to the map below
31 * instead.
32 */
33 const LITERAL = [
34 /data-shortcut="([^"$]+)"/g,
35 /shortcut: "([^"]+)"/g,
36 /hintAttr\("([^"]+)"/g,
37 /verb\('([^']+)', '/g,
38 /\bkey: "([a-zA-Z](?: [a-zA-Z])?)",/g,
39 /\$\{key\("([^"]{1,3})", /g,
40 ];
41
42 function sources(dir: string): string[] {
43 return readdirSync(dir).flatMap((name) => {
44 const path = join(dir, name);
45 return statSync(path).isDirectory() ? sources(path) : path.endsWith(".ts") ? [path] : [];
46 });
47 }
48
49 test("no page in src/web chooses a key: every key comes from the keymap, and the not-yet-moved list only shrinks", () => {
50 const found = new Map<string, string[]>();
51 for (const path of sources(join(ROOT, "src/web"))) {
52 const file = relative(ROOT, path);
53 // The map, the shell (held to the map below) and the g-letter jumps' one list, which the map
54 // reads.
55 if (file === "src/web/keymap.ts" || file === "src/web/client.ts" || file === "src/web/go_pages.ts") continue;
56 const text = readFileSync(path, "utf8");
57 const keys = LITERAL.flatMap((re) => [...text.matchAll(re)].map((m) => m[1]!));
58 if (keys.length > 0) found.set(file, keys);
59 }
60 const offenders = [...found.keys()].filter((f) => PENDING[f] === undefined).map((f) => `${f}: ${found.get(f)!.join(", ")}`);
61 expect(offenders).toEqual([]);
62 const moved = Object.keys(PENDING).filter((f) => !found.has(f));
63 expect(moved).toEqual([]);
64 });
65
66 test("one key, one meaning: no two verbs share a key on one kind of thing, and no verb takes a move's key", () => {
67 const verbs = Object.entries(VERBS) as [string, KeyDef][];
68 const kinds = new Set<KeyKind>(verbs.flatMap(([, d]) => d.kinds));
69 for (const kind of kinds) {
70 const on = verbs.filter(([, d]) => d.kinds.includes(kind) || d.kinds.includes("any"));
71 const keys = on.map(([, d]) => d.key);
72 expect({ kind, keys: keys.filter((k, i) => keys.indexOf(k) !== i) }).toEqual({ kind, keys: [] });
73 }
74 const moveKeys = new Set<string>(Object.values(MOVES).map((d) => d.key));
75 // A figure's Enter is its open: setting it to what it shows.
76 expect(verbs.filter(([id, d]) => moveKeys.has(d.key) && id !== "set").map(([id]) => id)).toEqual([]);
77 for (const [, d] of Object.entries(KEYMAP)) if ("terminal" in d) expect(d.terminal.reason.length).toBeGreaterThan(20);
78 });
79
80 test("the g jumps the map names are go_pages.ts's", () => {
81 expect([keyOf("home"), keyOf("talk")]).toEqual(["g h", "g t"]);
82 });
83
84 test("the shell's own keys are the map's moves, and the feed's and New issue's keys are the map's", () => {
85 const client = readFileSync(join(ROOT, "src/web/client.ts"), "utf8");
86 const rows = client.slice(client.indexOf("var STATIC_KEYS = ["), client.indexOf("];", client.indexOf("var STATIC_KEYS = [")));
87 const keysOf = (list: string) => list.split(",").map((k) => k.trim().replace(/^'|'$/g, ""));
88 const lists = [...rows.matchAll(/^ {4}\['[^']*', '[^']*', \[([^\]]*)\]/gm)].map((m) => keysOf(m[1]!));
89 expect(lists).toContainEqual([keyOf("down"), keyOf("up")]);
90 expect(lists).toContainEqual(["o", keyOf("open")]);
91 for (const id of ["search", "tell", "goto", "help", "palette", "back"] as const) expect(lists).toContainEqual([keyOf(id)]);
92 expect(client).toContain(`var PAGE_KEYS = ['${keyOf("create")}', '${keyOf("newIssue")}', 'Mod+Enter'];`);
93 expect(DISMISS_KEY).toBe(keyOf("close"));
94 expect(NEW_ISSUE_KEY).toBe(keyOf("newIssue"));
95 });
96
97 test("no key fires while typing: in a box every key is the box's (Escape leaves it), and the bridge's own keys check for one", () => {
98 for (const d of Object.values(KEYMAP)) {
99 if (d.key.startsWith("Mod+")) continue;
100 for (const key of d.key.split(" ")) {
101 const what = decideKey({ ctrl: false, meta: false, alt: false, key, hasChord: false, inDialog: false, inField: true });
102 expect({ key, what }).toEqual({ key, what: key === "Escape" ? "blur" : null });
103 }
104 }
105 // The bridge reads keys on the window ahead of the shell; it leaves a box's typing alone.
106 expect(bridgeJs).toContain("t.closest('input, textarea, select, [contenteditable], dialog[open]')");
107 });
108
109 test("the bridge is handed its verbs from the map, and names them, never types them", () => {
110 for (const [id, d] of Object.entries(VERBS)) expect(bridgeJs).toContain(`"${id}":[${JSON.stringify(d.key)},${JSON.stringify(d.label)}]`);
111 expect(bridgeJs).not.toMatch(/verb\('.{1,5}', '/);
112 });

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

Keyboard shortcuts

Docs