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

The terminal's keys are tested: pull the key handling out of the pty and characterize it #29

Merged opened this

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

Merged

mason/tempo:mason/22-the-terminal-s-keys-are-tested-pull-the → main 7 commits fork 2 threads · 2 unresolved

  • Merged. mason/22-the-terminal-s-keys-are-tested-pull-the was merged into main as e888c44.

Review

Sign in to review this change.
6 files changed +684 −185
AGENTS.md +3
@@ -27,6 +27,9 @@ preview at its own address, deployed from your branch as you push.
2727 `src/server.ts` stops fitting in one read, split it — `src/db.ts` for
2828 the schema and queries, `src/pages/<page>.ts` for rendering,
2929 `src/routes.ts` for the table of paths — and keep the pattern you find.
30 The terminal is split the same way: `src/tty.ts` is raw mode, drawing and
31 exiting, `src/keys.ts` is what a key does — a state and a key in, the next
32 state and whether to quit out — so the keys are tested without a tty.
3033 - Security: every input is validated at the boundary and every output is
3134 escaped; every response carries the security floor in `src/server.ts`
3235 (keep it, extend it); a POST that is not same-origin is refused; secrets
README.md +2 −1
@@ -80,7 +80,8 @@ background, reverting if it fails.
8080 the server, so it can't be used to go discover a board by guessing.
8181 - Undo is board-wide, not per-visitor, and unaffected by who's signed
8282 in.
83 - The terminal (`src/tty.ts`) mirrors the board actions with a
83 - The terminal (`src/tty.ts` draws it, `src/keys.ts` decides what each
84 key does) mirrors the board actions with a
8485 letter-key scheme (`j/k/h/l` move, `H/J/K/L` move the focused card,
8586 `a`/`e`/`d` add/edit/delete, `c`/`r`/`D` add/rename/delete a column,
8687 `f` filter, `u` undo) rather than drag-and-drop, since a terminal has
src/keys.ts added +228
@@ -0,0 +1,228 @@
1 /**

probe

2 * What a key does to the terminal's cursor, prompt and board.
3 *
4 * Plain data in, plain data out: `handleKey` takes the terminal's state,
5 * the bytes one keypress produced, and the board store to read and write
6 * through; it returns the next state and whether the person asked to quit.
7 * Nothing here touches a tty — no raw mode, no stdout — so the same key
8 * sequence a person types can be driven from a test.
9 *
10 * A prompt is a plain record too (a kind plus the ids it captured), not a
11 * closure, so the whole state stays serialisable and a later addition —
12 * a revision to poll, say — is one more field, not a reshuffle.
13 */
14
15 import type { Board, Card, Column } from "./db.ts";
16 import { MAX_CARDS_PER_BOARD, MAX_COLUMNS_PER_BOARD } from "./limits.ts";
17
18 /** The `src/db.ts` functions the keys reach for, passed in rather than imported. */
19 export type BoardStore = {
20 listBoardsForOwner(ownerId: string | null): Board[];
21 getBoard(boardId: string): Board | null;
22 listColumns(boardId: string): Column[];
23 listCards(boardId: string): Card[];
24 createBoard(name: string): Board;
25 createColumn(boardId: string, name: string): Column | "full";
26 renameColumn(boardId: string, columnId: string, name: string): boolean;
27 deleteColumn(boardId: string, columnId: string): boolean;
28 moveColumn(boardId: string, columnId: string, direction: "left" | "right"): boolean;
29 createCard(boardId: string, columnId: string, title: string): Card | "not_found" | "full";
30 editCard(boardId: string, cardId: string, title: string): boolean;
31 deleteCard(boardId: string, cardId: string): boolean;
32 moveCard(boardId: string, cardId: string, columnId: string, index: number): boolean;
33 undo(boardId: string): boolean;
34 };
35
36 export type Mode = "boards" | "board";
37
38 /** What a submitted prompt does, and the ids it captured when it opened. */
39 export type Prompt =
40 | { kind: "newBoard"; label: string; value: string }
41 | { kind: "openById"; label: string; value: string }
42 | { kind: "newCard"; label: string; value: string; columnId: string }
43 | { kind: "editCard"; label: string; value: string; cardId: string }
44 | { kind: "newColumn"; label: string; value: string }
45 | { kind: "renameColumn"; label: string; value: string; columnId: string }
46 | { kind: "filter"; label: string; value: string };
47
48 export type State = {
49 mode: Mode;
50 boardsCursor: number;
51 boardId?: string;
52 columnCursor: number;
53 cardCursor: number;
54 filter: string;
55 message: string;
56 prompt?: Prompt;
57 };
58
59 export type Outcome = { state: State; quit: boolean };
60
61 export function initialState(): State {
62 return { mode: "boards", boardsCursor: 0, columnCursor: 0, cardCursor: 0, filter: "", message: "" };
63 }
64
65 // The terminal has no verified identity — nothing here plays the part of
66 // the forge's signed x-forge-identity header — so it can't tell who is
67 // typing and must not mint ownership on their behalf. A board it creates
68 // is unowned, exactly like a guest's on the web; the picker lists only
69 // unowned boards, and a kept board is reached by its id (press o), the
70 // same way a shared link works on the page.
71 export function visibleBoards(board: BoardStore): Board[] {
72 return board.listBoardsForOwner(null);
73 }
74
75 /** A board id as `src/db.ts` mints them: the only text `o` will look up. */
76 const boardIdRe = /^[a-z0-9]{8}$/;
77
78 /** The cards of one column that the current filter leaves showing. */
79 export function visibleCards(board: BoardStore, state: State, columnId: string): Card[] {
80 const q = state.filter.trim().toLowerCase();
81 return board
82 .listCards(state.boardId!)
83 .filter((c) => c.column_id === columnId)
84 .filter((c) => q === "" || c.title.toLowerCase().includes(q));
85 }
86
87 export function handleKey(state: State, key: string, board: BoardStore): Outcome {
88 if (state.prompt) return handlePromptKey(state, key, board);
89 if (state.mode === "boards") return handleBoardsKey(state, key, board);
90 return handleBoardKey(state, key, board);
91 }
92
93 // The cursor may not point outside the board: a column that was deleted, a
94 // card that was filtered away or removed, an empty board at all.
95 function clampCursors(state: State, board: BoardStore): State {
96 const columns = board.listColumns(state.boardId!);
97 const columnCursor = Math.max(0, Math.min(state.columnCursor, columns.length - 1));
98 const at = { ...state, columnCursor };
99 const cards = columns[columnCursor] ? visibleCards(board, at, columns[columnCursor].id) : [];
100 return { ...at, cardCursor: Math.max(0, Math.min(state.cardCursor, cards.length - 1)) };
101 }
102
103 function handlePromptKey(state: State, key: string, board: BoardStore): Outcome {
104 const prompt = state.prompt!;
105 if (key === "\r") {
106 let next = submitPrompt({ ...state, prompt: undefined }, prompt, prompt.value.trim(), board);
107 if (next.mode === "board") next = clampCursors(next, board);
108 return { state: next, quit: false };
109 }
outdated

probe

110 if (key === "\x1b") return { state: { ...state, prompt: undefined }, quit: false };
111 if (key === "\x7f") return { state: { ...state, prompt: { ...prompt, value: prompt.value.slice(0, -1) } }, quit: false };
112 // Anything below a space — an arrow key's escape sequence included, as it
113 // starts with ESC — is not text and is ignored.
114 if (key >= " ") return { state: { ...state, prompt: { ...prompt, value: prompt.value + key } }, quit: false };
115 return { state, quit: false };
116 }
117
118 function submitPrompt(state: State, prompt: Prompt, text: string, board: BoardStore): State {
119 switch (prompt.kind) {
120 case "newBoard": {
121 const created = board.createBoard(text || "New board");
122 return { ...state, boardId: created.id, mode: "board", columnCursor: 0, cardCursor: 0 };
123 }
124 case "openById": {
125 const found = boardIdRe.test(text) ? board.getBoard(text) : null;
126 if (!found) return state;
127 return { ...state, boardId: found.id, mode: "board", columnCursor: 0, cardCursor: 0, filter: "" };
128 }
129 case "newCard": {
130 if (!text) return state;
131 const created = board.createCard(state.boardId!, prompt.columnId, text);
132 return created === "full" ? { ...state, message: `this board is full — ${MAX_CARDS_PER_BOARD} cards` } : state;
133 }
134 case "editCard":
135 if (text) board.editCard(state.boardId!, prompt.cardId, text);
136 return state;
137 case "newColumn": {
138 if (!text) return state;
139 const created = board.createColumn(state.boardId!, text);
140 return created === "full" ? { ...state, message: `this board is full — ${MAX_COLUMNS_PER_BOARD} columns` } : state;
141 }
142 case "renameColumn":
143 if (text) board.renameColumn(state.boardId!, prompt.columnId, text);
144 return state;
145 case "filter":
146 return { ...state, filter: text, cardCursor: 0 };
147 }
148 }
149
150 function handleBoardsKey(state: State, key: string, board: BoardStore): Outcome {
151 const boards = visibleBoards(board);
152 const next = { ...state };
153 if (key === "j" || key === "\x1b[B") next.boardsCursor = Math.min(state.boardsCursor + 1, Math.max(0, boards.length - 1));
154 else if (key === "k" || key === "\x1b[A") next.boardsCursor = Math.max(state.boardsCursor - 1, 0);
155 else if (key === "n") next.prompt = { kind: "newBoard", label: "New board name", value: "" };
156 else if (key === "o") next.prompt = { kind: "openById", label: "Open board id", value: "" };
157 else if (key === "\r" && boards[state.boardsCursor]) {
158 next.boardId = boards[state.boardsCursor].id;
159 next.mode = "board";
160 next.columnCursor = 0;
161 next.cardCursor = 0;
162 next.filter = "";
163 } else if (key === "q" || key === "\x03") return { state, quit: true };
164 return { state: next, quit: false };
165 }
166
167 function handleBoardKey(state: State, key: string, board: BoardStore): Outcome {
168 const columns = board.listColumns(state.boardId!);
169 const column = columns[state.columnCursor];
170 const cards = column ? visibleCards(board, state, column.id) : [];
171 const card = cards[state.cardCursor];
172 const next: State = { ...state, message: "" };
173
174 if (key === "b") {
175 next.mode = "boards";
176 } else if (key === "q" || key === "\x03") {
177 return { state, quit: true };
178 } else if (key === "h" || key === "\x1b[D") {
179 next.columnCursor = Math.max(0, state.columnCursor - 1);
180 next.cardCursor = 0;
181 } else if (key === "l" || key === "\x1b[C") {
182 next.columnCursor = Math.min(columns.length - 1, state.columnCursor + 1);
183 next.cardCursor = 0;
184 } else if (key === "j" || key === "\x1b[B") {
185 next.cardCursor = Math.min(cards.length - 1, state.cardCursor + 1);
186 } else if (key === "k" || key === "\x1b[A") {
187 next.cardCursor = Math.max(0, state.cardCursor - 1);
188 } else if (key === "a" && column) {
189 next.prompt = { kind: "newCard", label: "New card", value: "", columnId: column.id };
190 } else if (key === "e" && card) {
191 next.prompt = { kind: "editCard", label: "Edit card", value: card.title, cardId: card.id };
192 } else if (key === "d" && card) {
193 board.deleteCard(state.boardId!, card.id);
194 } else if (key === "K" && card) {
195 board.moveCard(state.boardId!, card.id, column.id, Math.max(0, state.cardCursor - 1));
196 next.cardCursor = Math.max(0, state.cardCursor - 1);
197 } else if (key === "J" && card) {
198 board.moveCard(state.boardId!, card.id, column.id, state.cardCursor + 1);
199 next.cardCursor = Math.min(cards.length - 1, state.cardCursor + 1);
200 } else if (key === "H" && card && state.columnCursor > 0) {
201 const target = columns[state.columnCursor - 1];
202 const index = Math.min(state.cardCursor, visibleCards(board, state, target.id).length);
203 board.moveCard(state.boardId!, card.id, target.id, index);
204 next.columnCursor = state.columnCursor - 1;
205 next.cardCursor = index;
206 } else if (key === "L" && card && state.columnCursor < columns.length - 1) {
207 const target = columns[state.columnCursor + 1];
208 const index = Math.min(state.cardCursor, visibleCards(board, state, target.id).length);
209 board.moveCard(state.boardId!, card.id, target.id, index);
210 next.columnCursor = state.columnCursor + 1;
211 next.cardCursor = index;
212 } else if (key === "c") {
213 next.prompt = { kind: "newColumn", label: "New column", value: "" };
214 } else if (key === "r" && column) {
215 next.prompt = { kind: "renameColumn", label: "Rename column", value: column.name, columnId: column.id };
216 } else if (key === "D" && column) {
217 board.deleteColumn(state.boardId!, column.id);
218 } else if (key === "[" && column) {
219 if (board.moveColumn(state.boardId!, column.id, "left")) next.columnCursor = state.columnCursor - 1;
220 } else if (key === "]" && column) {
221 if (board.moveColumn(state.boardId!, column.id, "right")) next.columnCursor = state.columnCursor + 1;
222 } else if (key === "f") {
223 next.prompt = { kind: "filter", label: "Filter (empty clears)", value: state.filter };
224 } else if (key === "u") {
225 next.message = board.undo(state.boardId!) ? "" : "nothing to undo";
226 }
227 return { state: clampCursors(next, board), quit: false };
228 }
src/live-refresh.test.ts +23 −3
@@ -25,6 +25,23 @@ const base = `http://${server.hostname}:${server.port}`;
2525 const post = (path: string, body: Record<string, string> = {}) =>
2626 fetch(base + path, { method: "POST", body: new URLSearchParams(body) });
2727
28 /**
29 * A refresh is a fetch and a parse, so it lands a turn or several of the
30 * event loop later — how many depends on the machine. Waiting for what the
31 * refresh does, rather than for a number of milliseconds, keeps the test
32 * about behaviour instead of about how fast the box is.
33 */
34 async function waitFor(condition: () => boolean, what: string): Promise<void> {
35 const deadline = Date.now() + 5000;
36 while (!condition()) {
37 if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`);
38 await new Promise((resolve) => setTimeout(resolve, 5));
39 }
40 }
41
42 /** Long enough that a refresh would have landed, for asserting one has not. */
43 const settle = () => new Promise((resolve) => setTimeout(resolve, 100));
44
2845 let restoreEventSource: (() => void) | undefined;
2946 let restoreDOMParser: (() => void) | undefined;
3047 beforeEach(() => {
@@ -90,14 +107,14 @@ test("a live refresh does not wipe an in-progress add-card title", async () => {
90107 const hasNewCard = () => document.querySelector('.card[data-title="From elsewhere"]') !== null;
91108
92109 latestSource!.onmessage!({ data: JSON.stringify({ by: "someone-else" }) });
93 await new Promise((resolve) => setTimeout(resolve, 20));
110 await settle();
94111
95112 expect((document.querySelector(".add-card input") as unknown as HTMLInputElement).value).toBe("half-typed");
96113 expect(hasNewCard()).toBe(false);
97114
98115 // Leaving the input lets the deferred refresh through.
99116 addInput.blur();
100 await new Promise((resolve) => setTimeout(resolve, 20));
117 await waitFor(hasNewCard, "the deferred refresh to bring in the other tab's card");
101118 expect(hasNewCard()).toBe(true);
102119
103120 await window.close();
@@ -116,7 +133,10 @@ test("a live refresh restores focus to a keyboard-focused card instead of deferr
116133
117134 await post(`/b/${boardId}/columns/${columnId}/cards`, { title: "From elsewhere" });
118135 latestSource!.onmessage!({ data: JSON.stringify({ by: "someone-else" }) });
119 await new Promise((resolve) => setTimeout(resolve, 20));
136 await waitFor(
137 () => document.querySelector('.card[data-title="From elsewhere"]') !== null,
138 "the refresh to bring in the other tab's card",
139 );
120140
121141 expect(document.querySelector('.card[data-title="From elsewhere"]')).not.toBeNull();
122142 const refocused = document.querySelector(`[data-card-id="${cardId}"]`);
src/tty.test.ts added +403
@@ -0,0 +1,403 @@
1 /**
2 * Characterizes the terminal's keys as they behave today. Every test drives
3 * `src/keys.ts` the way `src/tty.ts` does — one keypress at a time, against
4 * a real database under a temporary FORGE_APP_DATA — and asserts through
5 * `db.listCards`/`db.listColumns`, so a test fails if what a key does to the
6 * board or the cursor changes. Nothing here needs a tty.
7 */
8 import { expect, test } from "bun:test";
9 import { mkdtempSync } from "node:fs";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import type { State } from "./keys.ts";
13 import { MAX_CARDS_PER_BOARD, MAX_COLUMNS_PER_BOARD } from "./limits.ts";
14
15 process.env.FORGE_APP_DATA = mkdtempSync(join(tmpdir(), "app-"));
16 const db = await import("./db.ts");
17 const { handleKey, initialState, visibleBoards, visibleCards } = await import("./keys.ts");
18
19 /** One keypress after another, the way the tty feeds them in. */
20 function press(state: State, ...keys: string[]): State {
21 return keys.reduce((s, key) => handleKey(s, key, db).state, state);
22 }
23
24 const type = (text: string): string[] => [...text];
25
26 /** A board opened in board mode, with the cursor at its first column. */
27 function openBoard(name = "Board"): { state: State; boardId: string } {
28 const board = db.createBoard(name);
29 return { state: { ...initialState(), mode: "board", boardId: board.id }, boardId: board.id };
30 }
31
32 const columnsOf = (boardId: string): string[] => db.listColumns(boardId).map((c) => c.name);
33 const titlesIn = (boardId: string, index: number): string[] => {
34 const column = db.listColumns(boardId)[index];
35 return db
36 .listCards(boardId)
37 .filter((c) => c.column_id === column.id)
38 .map((c) => c.title);
39 };
40
41 test("j/k and the arrow keys move the board-list cursor and clamp at both ends", () => {
42 db.createBoard("One");
43 db.createBoard("Two");
44 db.createBoard("Three");
45 const last = visibleBoards(db).length - 1;
46
47 expect(press(initialState(), "k").boardsCursor).toBe(0);
48 expect(press(initialState(), "\x1b[A").boardsCursor).toBe(0);
49 expect(press(initialState(), "j").boardsCursor).toBe(1);
50 expect(press(initialState(), "\x1b[B", "\x1b[B").boardsCursor).toBe(2);
51
52 const bottom = press(initialState(), ...Array(last + 3).fill("j"));
53 expect(bottom.boardsCursor).toBe(last);
54 expect(press(bottom, "j", "k").boardsCursor).toBe(last - 1);
55 });
56
57 test("enter opens the board under the cursor and b goes back to the list", () => {
58 db.createBoard("Openable");
59 const boards = visibleBoards(db);
60
61 const opened = press(initialState(), "j", "\r");
62 expect(opened.mode).toBe("board");
63 expect(opened.boardId).toBe(boards[1].id);
64 expect(opened.columnCursor).toBe(0);
65 expect(opened.cardCursor).toBe(0);
66 expect(opened.filter).toBe("");
67
68 const back = press(opened, "b");
69 expect(back.mode).toBe("boards");
70 expect(back.boardId).toBe(boards[1].id);
71 });
72
73 test("the picker lists unowned boards only, and o opens a kept one by its id", () => {
74 const kept = db.createBoard("Kept", { id: "owner-1", name: "Owner" });
75 expect(visibleBoards(db).map((b) => b.id)).not.toContain(kept.id);
76
77 const prompted = press(initialState(), "o");
78 expect(prompted.prompt).toEqual({ kind: "openById", label: "Open board id", value: "" });
79
80 const opened = press(prompted, ...type(kept.id), "\r");
81 expect(opened.mode).toBe("board");
82 expect(opened.boardId).toBe(kept.id);
83 });
84
85 test("o with an id that is not a board, or not an id at all, stays in the list", () => {
86 for (const text of ["", "nosuchbd", "../../etc", "'; drop table board--"]) {
87 const after = press(initialState(), "o", ...type(text), "\r");
88 expect(after.mode).toBe("boards");
89 expect(after.boardId).toBeUndefined();
90 }
91 });
92
93 test("enter on an empty board list does nothing", () => {
94 const empty = { ...initialState(), boardsCursor: 999 };
95 expect(press(empty, "\r").mode).toBe("boards");
96 });
97
98 test("n prompts for a name and creates the board, then opens it", () => {
99 const prompted = press(initialState(), "n");
100 expect(prompted.prompt).toEqual({ kind: "newBoard", label: "New board name", value: "" });
101
102 const created = press(prompted, ...type("Fresh"), "\r");
103 expect(created.prompt).toBeUndefined();
104 expect(created.mode).toBe("board");
105 expect(db.getBoard(created.boardId!)!.name).toBe("Fresh");
106 expect(columnsOf(created.boardId!)).toEqual(["To do", "Doing", "Done"]);
107 });
108
109 test("n with an empty name creates a board called New board", () => {
110 const created = press(initialState(), "n", "\r");
111 expect(db.getBoard(created.boardId!)!.name).toBe("New board");
112 });
113
114 test("hjkl and the arrow keys move the board cursors and clamp at both ends", () => {
115 const { state, boardId } = openBoard();
116 const [todo] = db.listColumns(boardId);
117 db.createCard(boardId, todo.id, "one");
118 db.createCard(boardId, todo.id, "two");
119
120 expect(press(state, "h").columnCursor).toBe(0);
121 expect(press(state, "l").columnCursor).toBe(1);
122 expect(press(state, "l", "l", "l", "l").columnCursor).toBe(2);
123 expect(press(state, "\x1b[C", "\x1b[D").columnCursor).toBe(0);
124
125 expect(press(state, "k").cardCursor).toBe(0);
126 expect(press(state, "j").cardCursor).toBe(1);
127 expect(press(state, "j", "j", "j").cardCursor).toBe(1);
128 expect(press(state, "\x1b[B", "\x1b[A").cardCursor).toBe(0);
129
130 // Moving between columns puts the card cursor back at the top.
131 expect(press(state, "j", "l").cardCursor).toBe(0);
132 });
133
134 test("a adds a card to the column under the cursor", () => {
135 const { state, boardId } = openBoard();
136 const prompted = press(state, "l", "a");
137 expect(prompted.prompt).toMatchObject({ kind: "newCard", label: "New card", value: "" });
138
139 const added = press(prompted, ...type("Write it down"), "\r");
140 expect(added.prompt).toBeUndefined();
141 expect(titlesIn(boardId, 1)).toEqual(["Write it down"]);
142 expect(titlesIn(boardId, 0)).toEqual([]);
143 });
144
145 test("a with an empty title creates nothing", () => {
146 const { state, boardId } = openBoard();
147 press(state, "a", " ", "\r");
148 expect(db.listCards(boardId)).toEqual([]);
149 });
150
151 test("a and c on a board at its limit say the board is full instead of failing silently", () => {
152 const { state, boardId } = openBoard();
153 const column = db.listColumns(boardId)[0];
154 for (let i = db.listCards(boardId).length; i < MAX_CARDS_PER_BOARD; i++) db.createCard(boardId, column.id, `Card ${i}`);
155 const full = press(state, "a", ...type("One too many"), "\r");
156 expect(full.message).toBe(`this board is full — ${MAX_CARDS_PER_BOARD} cards`);
157 expect(db.listCards(boardId).length).toBe(MAX_CARDS_PER_BOARD);
158
159 for (let i = db.listColumns(boardId).length; i < MAX_COLUMNS_PER_BOARD; i++) db.createColumn(boardId, `Column ${i}`);
160 const noRoom = press(state, "c", ...type("One too many"), "\r");
161 expect(noRoom.message).toBe(`this board is full — ${MAX_COLUMNS_PER_BOARD} columns`);
162 expect(db.listColumns(boardId).length).toBe(MAX_COLUMNS_PER_BOARD);
163 });
164
165 test("e edits the card under the cursor, starting from its current title", () => {
166 const { state, boardId } = openBoard();
167 const [todo] = db.listColumns(boardId);
168 db.createCard(boardId, todo.id, "Draft");
169
170 const prompted = press(state, "e");
171 expect(prompted.prompt).toMatchObject({ kind: "editCard", label: "Edit card", value: "Draft" });
172
173 const edited = press(prompted, "\x7f", "\x7f", ...type("ft it"), "\r");
174 expect(edited.prompt).toBeUndefined();
175 expect(titlesIn(boardId, 0)).toEqual(["Draft it"]);
176 });
177
178 test("d deletes the card under the cursor", () => {
179 const { state, boardId } = openBoard();
180 const [todo] = db.listColumns(boardId);
181 db.createCard(boardId, todo.id, "keep");
182 db.createCard(boardId, todo.id, "drop");
183
184 const after = press(state, "j", "d");
185 expect(titlesIn(boardId, 0)).toEqual(["keep"]);
186 expect(after.cardCursor).toBe(0);
187 });
188
189 test("H and L move the card under the cursor between columns, carrying the cursor with it", () => {
190 const { state, boardId } = openBoard();
191 const [todo] = db.listColumns(boardId);
192 db.createCard(boardId, todo.id, "travels");
193
194 const right = press(state, "L");
195 expect(titlesIn(boardId, 0)).toEqual([]);
196 expect(titlesIn(boardId, 1)).toEqual(["travels"]);
197 expect([right.columnCursor, right.cardCursor]).toEqual([1, 0]);
198
199 const back = press(right, "H");
200 expect(titlesIn(boardId, 0)).toEqual(["travels"]);
201 expect([back.columnCursor, back.cardCursor]).toEqual([0, 0]);
202
203 // The first column has nothing to its left, the last nothing to its right.
204 expect(press(back, "H").columnCursor).toBe(0);
205 expect(titlesIn(boardId, 0)).toEqual(["travels"]);
206 const far = press(back, "L", "L", "L");
207 expect(far.columnCursor).toBe(2);
208 expect(titlesIn(boardId, 2)).toEqual(["travels"]);
209 });
210
211 test("K and J move the card under the cursor within its column", () => {
212 const { state, boardId } = openBoard();
213 const [todo] = db.listColumns(boardId);
214 for (const title of ["a", "b", "c"]) db.createCard(boardId, todo.id, title);
215
216 const down = press(state, "J");
217 expect(titlesIn(boardId, 0)).toEqual(["b", "a", "c"]);
218 expect(down.cardCursor).toBe(1);
219
220 const up = press(down, "K");
221 expect(titlesIn(boardId, 0)).toEqual(["a", "b", "c"]);
222 expect(up.cardCursor).toBe(0);
223
224 // Clamped at the ends: K at the top and J at the bottom leave the order alone.
225 expect(press(up, "K").cardCursor).toBe(0);
226 expect(titlesIn(boardId, 0)).toEqual(["a", "b", "c"]);
227 const bottom = press(up, "j", "j", "J");
228 expect(bottom.cardCursor).toBe(2);
229 expect(titlesIn(boardId, 0)).toEqual(["a", "b", "c"]);
230 });
231
232 test("c creates a column, r renames it and D deletes it", () => {
233 const { state, boardId } = openBoard();
234
235 const prompted = press(state, "c");
236 expect(prompted.prompt).toMatchObject({ kind: "newColumn", label: "New column", value: "" });
237 const created = press(prompted, ...type("Later"), "\r");
238 expect(columnsOf(boardId)).toEqual(["To do", "Doing", "Done", "Later"]);
239
240 const renaming = press(created, "l", "r");
241 expect(renaming.prompt).toMatchObject({ kind: "renameColumn", label: "Rename column", value: "Doing" });
242 press(renaming, ...type("!"), "\r");
243 expect(columnsOf(boardId)).toEqual(["To do", "Doing!", "Done", "Later"]);
244
245 const deleted = press(created, "l", "l", "l", "D");
246 expect(columnsOf(boardId)).toEqual(["To do", "Doing!", "Done"]);
247 expect(deleted.columnCursor).toBe(2);
248 });
249
250 test("[ and ] reorder the column under the cursor and clamp at both ends", () => {
251 const { state, boardId } = openBoard();
252
253 const left = press(state, "l", "[");
254 expect(columnsOf(boardId)).toEqual(["Doing", "To do", "Done"]);
255 expect(left.columnCursor).toBe(0);
256
257 const right = press(left, "]");
258 expect(columnsOf(boardId)).toEqual(["To do", "Doing", "Done"]);
259 expect(right.columnCursor).toBe(1);
260
261 const stuckLeft = press(right, "[", "[");
262 expect(columnsOf(boardId)).toEqual(["Doing", "To do", "Done"]);
263 expect(stuckLeft.columnCursor).toBe(0);
264 const stuckRight = press(stuckLeft, "]", "]", "]");
265 expect(columnsOf(boardId)).toEqual(["To do", "Done", "Doing"]);
266 expect(stuckRight.columnCursor).toBe(2);
267 });
268
269 test("f sets the filter and the card cursor stays inside the filtered list", () => {
270 const { state, boardId } = openBoard();
271 const [todo] = db.listColumns(boardId);
272 for (const title of ["alpha", "beta", "gamma"]) db.createCard(boardId, todo.id, title);
273
274 const atGamma = press(state, "j", "j");
275 expect(atGamma.cardCursor).toBe(2);
276
277 const prompted = press(atGamma, "f");
278 expect(prompted.prompt).toMatchObject({ kind: "filter", label: "Filter (empty clears)", value: "" });
279
280 const filtered = press(prompted, ...type("BET"), "\r");
281 expect(filtered.filter).toBe("BET");
282 expect(filtered.cardCursor).toBe(0);
283 expect(visibleCards(db, filtered, todo.id).map((c) => c.title)).toEqual(["beta"]);
284 expect(press(filtered, "j", "j").cardCursor).toBe(0);
285
286 // Reopening the filter starts from the current one; an empty value clears it.
287 expect(press(filtered, "f").prompt).toMatchObject({ kind: "filter", value: "BET" });
288 const cleared = press(filtered, "f", "\x7f", "\x7f", "\x7f", "\r");
289 expect(cleared.filter).toBe("");
290 expect(visibleCards(db, cleared, todo.id).map((c) => c.title)).toEqual(["alpha", "beta", "gamma"]);
291 });
292
293 test("J with a filter on counts the index among all the cards, not the visible ones", () => {
294 // Today's behaviour, recorded rather than fixed, and a bug: the cursor
295 // index comes from the filtered list but db.moveCard reads it as an index
296 // among every card in the column, so a hidden card absorbs the move and
297 // the visible order does not change. #33 fixes it and rewrites this test;
298 // until then this is a marker, not a contract.
299 const { state, boardId } = openBoard();
300 const [todo] = db.listColumns(boardId);
301 for (const title of ["x-one", "hidden", "x-two"]) db.createCard(boardId, todo.id, title);
302
303 const filtered = { ...state, filter: "x-" };
304 expect(visibleCards(db, filtered, todo.id).map((c) => c.title)).toEqual(["x-one", "x-two"]);
305
306 const moved = press(filtered, "J");
307 expect(moved.cardCursor).toBe(1);
308 expect(titlesIn(boardId, 0)).toEqual(["hidden", "x-one", "x-two"]);
309 expect(visibleCards(db, moved, todo.id).map((c) => c.title)).toEqual(["x-one", "x-two"]);
310 });
311
312 test("u undoes the last change", () => {
313 const { state, boardId } = openBoard();
314 const [todo] = db.listColumns(boardId);
315 db.createCard(boardId, todo.id, "precious");
316
317 const deleted = press(state, "d");
318 expect(titlesIn(boardId, 0)).toEqual([]);
319
320 const undone = press(deleted, "u");
321 expect(titlesIn(boardId, 0)).toEqual(["precious"]);
322 expect(undone.message).toBe("");
323 });
324
325 test("u with nothing left to undo says so, and the next key clears the message", () => {
326 const { state, boardId } = openBoard();
327 while (db.undo(boardId)) {
328 // A new board's three columns are three logged actions; drain them.
329 }
330
331 const said = press(state, "u");
332 expect(said.message).toBe("nothing to undo");
333 expect(press(said, "j").message).toBe("");
334 });
335
336 test("esc cancels a prompt and backspace deletes one character from it", () => {
337 const { state, boardId } = openBoard();
338
339 const typing = press(state, "a", ...type("half"));
340 expect(typing.prompt).toMatchObject({ value: "half" });
341 expect(press(typing, "\x7f").prompt).toMatchObject({ value: "hal" });
342 expect(press(typing, "\x7f", "\x7f", "\x7f", "\x7f", "\x7f").prompt).toMatchObject({ value: "" });
343
344 const cancelled = press(typing, "\x1b");
345 expect(cancelled.prompt).toBeUndefined();
346 expect(db.listCards(boardId)).toEqual([]);
347 });
348
349 test("an arrow key inside a prompt is ignored, not typed into it", () => {
350 const { state } = openBoard();
351 const typing = press(state, "a", ...type("ok"), "\x1b[A", "\x1b[D");
352 expect(typing.prompt).toMatchObject({ value: "ok" });
353 });
354
355 test("q and ctrl-c ask to quit instead of exiting, and leave the state alone", () => {
356 const { state } = openBoard();
357 for (const key of ["q", "\x03"]) {
358 expect(handleKey(initialState(), key, db)).toEqual({ state: initialState(), quit: true });
359 expect(handleKey(state, key, db)).toEqual({ state, quit: true });
360 }
361 // In a prompt, q is text.
362 expect(press(state, "a", "q").prompt).toMatchObject({ value: "q" });
363 });
364
365 test("the cursor cannot point outside the board after the last card in a column is deleted", () => {
366 const { state, boardId } = openBoard();
367 const [todo] = db.listColumns(boardId);
368 db.createCard(boardId, todo.id, "only");
369
370 const emptied = press(state, "d");
371 expect(emptied.cardCursor).toBe(0);
372 expect(db.listCards(boardId)).toEqual([]);
373 // Every key that reaches for the card under the cursor still answers.
374 const after = press(emptied, "j", "k", "d", "e", "K", "J", "H", "L", "u");
375 expect(after.cardCursor).toBe(0);
376 });
377
378 test("the cursor cannot point outside the board after a filter hides everything", () => {
379 const { state, boardId } = openBoard();
380 const [todo] = db.listColumns(boardId);
381 for (const title of ["alpha", "beta"]) db.createCard(boardId, todo.id, title);
382
383 const hidden = press(state, "j", "f", ...type("zzz"), "\r");
384 expect(hidden.cardCursor).toBe(0);
385 expect(visibleCards(db, hidden, todo.id)).toEqual([]);
386 const after = press(hidden, "j", "k", "d", "e", "K", "J", "L");
387 expect(after.cardCursor).toBe(0);
388 expect(titlesIn(boardId, 0)).toEqual(["alpha", "beta"]);
389
390 // u is not a cursor key: it undoes the last change whether or not the
391 // filter shows what it touches.
392 expect(press(after, "u").cardCursor).toBe(0);
393 expect(titlesIn(boardId, 0)).toEqual(["alpha"]);
394 });
395
396 test("the cursor cannot point outside a board with no columns at all", () => {
397 const { state, boardId } = openBoard();
398 for (const column of db.listColumns(boardId)) db.deleteColumn(boardId, column.id);
399
400 const after = press({ ...state, columnCursor: 2, cardCursor: 4 }, "h", "l", "j", "k", "a", "d", "r", "D", "[", "]");
401 expect([after.columnCursor, after.cardCursor]).toEqual([0, 0]);
402 expect(after.prompt).toBeUndefined();
403 });
src/tty.ts +25 −181
@@ -3,59 +3,33 @@
33 * same data. Pick a board, then: arrows/hjkl move the cursor between
44 * columns and cards; shift+that moves the card under the cursor, the
55 * keyboard-only alternative to dragging it. Plain ANSI, no dependencies.
6 *
7 * This file is the terminal itself: raw mode, reading keys, drawing, and
8 * exiting. What a key means lives in `src/keys.ts`, which never touches a
9 * tty, so it can be tested without one.
610 */
711
812 import * as db from "./db.ts";
9 import { MAX_CARDS_PER_BOARD, MAX_COLUMNS_PER_BOARD } from "./limits.ts";
10
11 // The terminal has no verified identity — nothing here plays the part of
12 // the forge's signed x-forge-identity header — so it can't tell who is
13 // typing and must not mint ownership on their behalf. A board it creates
14 // is unowned, exactly like a guest's on the web; the picker lists only
15 // unowned boards, and a kept board is reached by its id (press o), the
16 // same way a shared link works on the page.
17 const visibleBoards = (): db.Board[] => db.listBoardsForOwner(null);
18 const boardIdRe = /^[a-z0-9]{8}$/;
13 import { handleKey, initialState, visibleBoards, visibleCards, type State } from "./keys.ts";
1914
2015 const esc = "\x1b[";
2116 const out = (s: string): void => {
2217 process.stdout.write(s);
2318 };
2419
25 type Mode = "boards" | "board";
26 type Prompt = { label: string; value: string; onSubmit: (text: string) => void };
27
28 let mode: Mode = "boards";
29 let boardsCursor = 0;
30 let boardId: string | undefined;
31 let columnCursor = 0;
32 let cardCursor = 0;
33 let filter = "";
34 let message = "";
35 let prompt: Prompt | undefined;
36
37 const visibleCards = (columnId: string): db.Card[] => {
38 const q = filter.trim().toLowerCase();
39 return db
40 .listCards(boardId!)
41 .filter((c) => c.column_id === columnId)
42 .filter((c) => q === "" || c.title.toLowerCase().includes(q));
43 };
44
45 function startPrompt(label: string, value: string, onSubmit: (text: string) => void): void {
46 prompt = { label, value, onSubmit };
47 }
20 let state: State = initialState();
4821
4922 function draw(): void {
5023 const lines: string[] = [];
51 if (mode === "boards") {
52 const boards = visibleBoards();
24 const prompt = state.prompt;
25 if (state.mode === "boards") {
26 const boards = visibleBoards(db);
5327 lines.push(`${esc}1mtempo${esc}0m ${esc}2mpick a board${esc}0m`);
5428 lines.push("");
5529 if (boards.length === 0) lines.push(`${esc}2mNo boards yet. Press n to create one.${esc}0m`);
5630 boards.forEach((b, i) => {
57 const mark = i === boardsCursor ? "▸" : " ";
58 const name = i === boardsCursor ? `${esc}1m${b.name}${esc}0m` : b.name;
31 const mark = i === state.boardsCursor ? "▸" : " ";
32 const name = i === state.boardsCursor ? `${esc}1m${b.name}${esc}0m` : b.name;
5933 lines.push(`${mark} ${name} ${esc}2m/b/${b.id}${esc}0m`);
6034 });
6135 lines.push("");
@@ -65,15 +39,15 @@ function draw(): void {
6539 : `${esc}2mj/k move · enter open · n new board · o open by id · q quit${esc}0m`,
6640 );
6741 } else {
68 const board = db.getBoard(boardId!)!;
69 const columns = db.listColumns(boardId!);
70 lines.push(`${esc}1mtempo${esc}0m ${esc}2m${board.name}${esc}0m${filter ? ` ${esc}2mfilter: ${filter}${esc}0m` : ""}`);
42 const board = db.getBoard(state.boardId!)!;
43 const columns = db.listColumns(state.boardId!);
44 lines.push(`${esc}1mtempo${esc}0m ${esc}2m${board.name}${esc}0m${state.filter ? ` ${esc}2mfilter: ${state.filter}${esc}0m` : ""}`);
7145 lines.push("");
7246 const columnLines = columns.map((col, ci) => {
73 const cards = visibleCards(col.id);
74 const header = ci === columnCursor ? `${esc}1m${col.name}${esc}0m` : col.name;
47 const cards = visibleCards(db, state, col.id);
48 const header = ci === state.columnCursor ? `${esc}1m${col.name}${esc}0m` : col.name;
7549 const body = cards.map((c, i) => {
76 const focused = ci === columnCursor && i === cardCursor;
50 const focused = ci === state.columnCursor && i === state.cardCursor;
7751 const mark = focused ? "▸" : " ";
7852 return `${mark} ${focused ? `${esc}1m${c.title}${esc}0m` : c.title}`;
7953 });
@@ -93,7 +67,7 @@ function draw(): void {
9367 lines.push(
9468 prompt
9569 ? `${prompt.label}: ${prompt.value}${esc}7m ${esc}0m`
96 : message || `${esc}2mhjkl move · a add · e edit · d delete · H/L/K/J move card · c column · r rename · D delete col · [ ] reorder col · f filter · u undo · b back · q quit${esc}0m`,
70 : state.message || `${esc}2mhjkl move · a add · e edit · d delete · H/L/K/J move card · c column · r rename · D delete col · [ ] reorder col · f filter · u undo · b back · q quit${esc}0m`,
9771 );
9872 }
9973 out(`${esc}2J${esc}H` + lines.join("\r\n"));
@@ -104,147 +78,17 @@ function visibleLength(s: string): number {
10478 return s.replace(/\x1b\[[0-9]*m/g, "").length;
10579 }
10680
107 function clampCursors(): void {
108 const columns = db.listColumns(boardId!);
109 columnCursor = Math.max(0, Math.min(columnCursor, columns.length - 1));
110 const cards = columns[columnCursor] ? visibleCards(columns[columnCursor].id) : [];
111 cardCursor = Math.max(0, Math.min(cardCursor, cards.length - 1));
112 }
113
114 function handlePromptKey(key: string): void {
115 if (!prompt) return;
116 if (key === "\r") {
117 const text = prompt.value.trim();
118 const onSubmit = prompt.onSubmit;
119 prompt = undefined;
120 onSubmit(text);
121 if (mode === "board") clampCursors();
122 } else if (key === "\x1b") prompt = undefined;
123 else if (key === "\x7f") prompt.value = prompt.value.slice(0, -1);
124 else if (key >= " ") prompt.value += key;
125 draw();
126 }
127
128 function handleBoardsKey(key: string): void {
129 const boards = visibleBoards();
130 if (key === "j" || key === "\x1b[B") boardsCursor = Math.min(boardsCursor + 1, Math.max(0, boards.length - 1));
131 else if (key === "k" || key === "\x1b[A") boardsCursor = Math.max(boardsCursor - 1, 0);
132 else if (key === "n") startPrompt("New board name", "", (name) => {
133 const board = db.createBoard(name || "New board");
134 boardId = board.id;
135 mode = "board";
136 columnCursor = 0;
137 cardCursor = 0;
138 });
139 else if (key === "o") startPrompt("Open board id", "", (text) => {
140 const found = boardIdRe.test(text) ? db.getBoard(text) : null;
141 if (!found) return;
142 boardId = found.id;
143 mode = "board";
144 columnCursor = 0;
145 cardCursor = 0;
146 filter = "";
147 });
148 else if (key === "\r" && boards[boardsCursor]) {
149 boardId = boards[boardsCursor].id;
150 mode = "board";
151 columnCursor = 0;
152 cardCursor = 0;
153 filter = "";
154 } else if (key === "q" || key === "\x03") {
155 out(`${esc}2J${esc}H`);
156 process.exit(0);
157 }
158 draw();
159 }
160
161 function handleBoardKey(key: string): void {
162 const columns = db.listColumns(boardId!);
163 const column = columns[columnCursor];
164 const cards = column ? visibleCards(column.id) : [];
165 const card = cards[cardCursor];
166 message = "";
167
168 if (key === "b") {
169 mode = "boards";
170 } else if (key === "q" || key === "\x03") {
171 out(`${esc}2J${esc}H`);
172 process.exit(0);
173 } else if (key === "h" || key === "\x1b[D") {
174 columnCursor = Math.max(0, columnCursor - 1);
175 cardCursor = 0;
176 } else if (key === "l" || key === "\x1b[C") {
177 columnCursor = Math.min(columns.length - 1, columnCursor + 1);
178 cardCursor = 0;
179 } else if (key === "j" || key === "\x1b[B") {
180 cardCursor = Math.min(cards.length - 1, cardCursor + 1);
181 } else if (key === "k" || key === "\x1b[A") {
182 cardCursor = Math.max(0, cardCursor - 1);
183 } else if (key === "a" && column) {
184 startPrompt("New card", "", (title) => {
185 if (!title) return;
186 const result = db.createCard(boardId!, column.id, title);
187 if (result === "full") message = `this board is full — ${MAX_CARDS_PER_BOARD} cards`;
188 });
189 } else if (key === "e" && card) {
190 startPrompt("Edit card", card.title, (title) => {
191 if (title) db.editCard(boardId!, card.id, title);
192 });
193 } else if (key === "d" && card) {
194 db.deleteCard(boardId!, card.id);
195 } else if (key === "K" && card) {
196 db.moveCard(boardId!, card.id, column.id, Math.max(0, cardCursor - 1));
197 cardCursor = Math.max(0, cardCursor - 1);
198 } else if (key === "J" && card) {
199 db.moveCard(boardId!, card.id, column.id, cardCursor + 1);
200 cardCursor = Math.min(cards.length - 1, cardCursor + 1);
201 } else if (key === "H" && card && columnCursor > 0) {
202 const target = columns[columnCursor - 1];
203 const index = Math.min(cardCursor, visibleCards(target.id).length);
204 db.moveCard(boardId!, card.id, target.id, index);
205 columnCursor -= 1;
206 cardCursor = index;
207 } else if (key === "L" && card && columnCursor < columns.length - 1) {
208 const target = columns[columnCursor + 1];
209 const index = Math.min(cardCursor, visibleCards(target.id).length);
210 db.moveCard(boardId!, card.id, target.id, index);
211 columnCursor += 1;
212 cardCursor = index;
213 } else if (key === "c") {
214 startPrompt("New column", "", (name) => {
215 if (!name) return;
216 const result = db.createColumn(boardId!, name);
217 if (result === "full") message = `this board is full — ${MAX_COLUMNS_PER_BOARD} columns`;
218 });
219 } else if (key === "r" && column) {
220 startPrompt("Rename column", column.name, (name) => {
221 if (name) db.renameColumn(boardId!, column.id, name);
222 });
223 } else if (key === "D" && column) {
224 db.deleteColumn(boardId!, column.id);
225 } else if (key === "[" && column) {
226 if (db.moveColumn(boardId!, column.id, "left")) columnCursor -= 1;
227 } else if (key === "]" && column) {
228 if (db.moveColumn(boardId!, column.id, "right")) columnCursor += 1;
229 } else if (key === "f") {
230 startPrompt("Filter (empty clears)", filter, (text) => {
231 filter = text;
232 cardCursor = 0;
233 });
234 } else if (key === "u") {
235 message = db.undo(boardId!) ? "" : "nothing to undo";
236 }
237 clampCursors();
238 draw();
239 }
240
24181 process.stdin.setRawMode?.(true);
24282 process.stdin.resume();
24383 process.stdin.setEncoding("utf8");
24484 draw();
24585 process.stdin.on("data", (key: string) => {
246 if (prompt) handlePromptKey(key);
247 else if (mode === "boards") handleBoardsKey(key);
248 else handleBoardKey(key);
86 const outcome = handleKey(state, key, db);
87 if (outcome.quit) {
88 out(`${esc}2J${esc}H`);
89 process.exit(0);
90 }
91 state = outcome.state;
92 draw();
24993 });
25094 process.stdout.on("resize", draw);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs