Skip to content

Build your personal knowledge base with Trilium Notes

client/collections/board: add keyboard accessibility support

Adorian Doranb892f8df10ce
diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.ts
index cfc9384260..757230fd85 100644
--- a/apps/client/src/widgets/collections/board/api.spec.ts
+++ b/apps/client/src/widgets/collections/board/api.spec.ts
@@ -411,6 +411,22 @@ describe("BoardApi card operations", () => {
.toHaveBeenCalledWith([ first.branch.branchId ], third.branch.branchId);
});
+ /**
+ * Nothing waits for the board to redraw between two keystrokes, so the column map the API holds
+ * still shows the target as it was before the first card arrived.
+ */
+ it("sends each card past the one it sent before, without waiting for a redraw", async () => {
+ const { api, items } = createBoardWithCards();
+ const [ first, second ] = items;
+
+ await api.moveToColumnEnd(first.note.noteId, first.branch.branchId, "To Do");
+ expect(branches.moveAfterBranch).not.toHaveBeenCalled();
+
+ await api.moveToColumnEnd(second.note.noteId, second.branch.branchId, "To Do");
+ expect(branches.moveAfterBranch)
+ .toHaveBeenLastCalledWith([ second.branch.branchId ], first.branch.branchId);
+ });
+
it("moves nothing for a card dropped where it is, or one it cannot find", async () => {
const { api, items } = createBoardWithCards();
const [ first ] = items;
diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.ts
index ef6bc26d2c..b4969e7665 100644
--- a/apps/client/src/widgets/collections/board/api.ts
+++ b/apps/client/src/widgets/collections/board/api.ts
@@ -18,6 +18,8 @@ import { ColumnMap } from "./data";
export default class BoardApi {
private isRelationMode: boolean;
+ /** The branch last sent to the end of each column, by {@link moveToColumnEnd}. */
+ private sentToColumnEnd = new Map<string, string>();
statusAttribute: string;
constructor(
@@ -479,6 +481,30 @@ export default class BoardApi {
return attributes.removeOwnedLabelByName(note, this.statusAttribute);
}
+ /**
+ * Moves a card to the end of another column, where a new one would go.
+ *
+ * {@link moveWithinBoard} leaves a card crossing columns where the tree already had it, which
+ * is where a drop between two cards wants it. A card sent across by the keyboard is aimed at no
+ * card in particular, so it goes where the reader would look for it.
+ */
+ async moveToColumnEnd(noteId: string, branchId: string, targetColumn: string) {
+ // What is already at the end, as far as this instance can know: nothing waits for the board
+ // to redraw between two keystrokes, so the column map still shows the target as it was
+ // before the card the last press sent. Anything sent since is remembered here instead, and
+ // the memory lasts exactly as long as the map it stands in for, both being rebuilt by the
+ // refresh that catches up.
+ const last = this.sentToColumnEnd.get(targetColumn)
+ ?? (this.byColumn?.get(targetColumn) ?? []).at(-1)?.branch.branchId;
+
+ await this.changeColumn(noteId, targetColumn);
+ if (last && last !== branchId) {
+ await branches.moveAfterBranch([ branchId ], last);
+ }
+
+ this.sentToColumnEnd.set(targetColumn, branchId);
+ }
+
async moveWithinBoard(noteId: string, sourceBranchId: string, sourceIndex: number, targetIndex: number, sourceColumn: string, targetColumn: string) {
const targetItems = this.byColumn?.get(targetColumn) ?? [];
diff --git a/apps/client/src/widgets/collections/board/card.tsx b/apps/client/src/widgets/collections/board/card.tsx
index 63caacff78..42f607a477 100644
--- a/apps/client/src/widgets/collections/board/card.tsx
+++ b/apps/client/src/widgets/collections/board/card.tsx
@@ -105,6 +105,7 @@ function Card({
return (
<div
className={`board-note ${colorClass} ${isDragging ? 'dragging' : ''} ${isEditing ? "editing" : ""} ${isArchived ? "archived" : ""}`}
+ data-note-id={note.noteId}
draggable
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsx
index 17df0e95a8..310b86203e 100644
--- a/apps/client/src/widgets/collections/board/column.tsx
+++ b/apps/client/src/widgets/collections/board/column.tsx
@@ -120,6 +120,7 @@ export default function Column({
return (
<div
+ data-column={column}
className={clsx("board-column", {
"drag-over": dropTarget === column && draggedCard?.fromColumn !== column,
// The class the themes key a hue off, worn here as anywhere else that carries one.
diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsx
index bc9ec45589..655cab8e09 100644
--- a/apps/client/src/widgets/collections/board/index.tsx
+++ b/apps/client/src/widgets/collections/board/index.tsx
@@ -21,6 +21,7 @@ import BoardApi from "./api";
import { DEFAULT_GROUP_BY, getStatusDefinition } from "./columns";
import Column from "./column";
import { ColumnMap, getBoardData } from "./data";
+import { useBoardKeyboard } from "./keyboard";
export interface BoardViewData {
columns?: BoardColumnData[];
@@ -168,6 +169,8 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
includeArchived || !storedColumns.get(column)?.archived),
[ columns, storedColumns, includeArchived ]);
+ const containerRef = useRef<HTMLDivElement>(null);
+
const boardDragState = useMemo<BoardDragState>(() => ({
branchIdToEdit,
columnNameToEdit,
@@ -233,6 +236,14 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
setColumnDropPosition(null);
}, [ api, columns, shownColumns ]);
+ const handleKeyDown = useBoardKeyboard({
+ containerRef,
+ columns: shownColumns,
+ byColumn,
+ api,
+ moveColumn: handleColumnDrop
+ });
+
useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
// The column list is read off the definition, which may be edited from the attribute panel,
// another split, or a synced instance. Re-reading it re-runs the refresh through the effect.
@@ -278,7 +289,9 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
<BoardActionsContext.Provider value={boardActions}>
<BoardDragStateContext.Provider value={boardDragState}>
{byColumn && columns && <div
+ ref={containerRef}
className="board-view-container"
+ onKeyDown={handleKeyDown}
onDragOver={handleColumnDragOver}
onDrop={handleContainerDrop}
onWheel={onWheelHorizontalScroll}
diff --git a/apps/client/src/widgets/collections/board/keyboard.spec.tsx b/apps/client/src/widgets/collections/board/keyboard.spec.tsx
new file mode 100644
index 0000000000..39f6ab6241
--- /dev/null
+++ b/apps/client/src/widgets/collections/board/keyboard.spec.tsx
@@ -0,0 +1,565 @@
+/**
+ * The board's keyboard: the arrows, Home and End walk it, the same with Alt move what is focused,
+ * and Space opens a card. Driven through the rendered board rather than the hook, since where focus
+ * lands and what it lands on is the whole of what these keys do.
+ */
+import $ from "jquery";
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import appContext from "../../../components/app_context";
+import Component from "../../../components/component";
+import branches from "../../../services/branches";
+import froca from "../../../services/froca";
+import server from "../../../services/server";
+import { buildNote } from "../../../test/easy-froca";
+import { ParentComponent } from "../../react/react_utils";
+import BoardView, { BoardViewData } from ".";
+
+vi.mock("../../../services/branches", () => ({
+ default: {
+ moveBeforeBranch: vi.fn(async () => {}),
+ moveAfterBranch: vi.fn(async () => {}),
+ cloneNoteToParentNote: vi.fn(async () => {}),
+ cloneNoteAfter: vi.fn(async () => {})
+ }
+}));
+
+vi.mock("../../../services/i18n", () => ({
+ t: (key: string) => key,
+ translationsInitializedPromise: $.Deferred().resolve()
+}));
+
+describe("Board keyboard", () => {
+ let container: HTMLElement | undefined;
+ const saved: BoardViewData[] = [];
+
+ beforeEach(() => {
+ saved.length = 0;
+ vi.restoreAllMocks();
+ // A mocked module is not a spy, so restoring leaves its calls where the last test left.
+ vi.mocked(branches.moveBeforeBranch).mockClear();
+ vi.mocked(branches.moveAfterBranch).mockClear();
+ vi.spyOn(server, "put").mockResolvedValue(undefined);
+ });
+
+ afterEach(() => {
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+ });
+
+ describe("moving about", () => {
+ it("walks a column from its header, through its cards, to its button", async () => {
+ const board = await renderBoard();
+ focusHeader(board, 0);
+
+ expect(press(board, "ArrowDown")).toBe("First");
+ expect(press(board, "ArrowDown")).toBe("Second");
+ expect(press(board, "ArrowDown")).toBe("board_view.new-item");
+
+ // The button under the column is the end of it.
+ press(board, "ArrowDown");
+ expect(focusedName(board)).toBe("board_view.new-item");
+
+ expect(press(board, "ArrowUp")).toBe("Second");
+ expect(press(board, "ArrowUp")).toBe("First");
+ expect(press(board, "ArrowUp")).toBe("To Do");
+
+ // And its header is the start.
+ press(board, "ArrowUp");
+ expect(focusedName(board)).toBe("To Do");
+ });
+
+ it("crosses to the first card of the next column rather than to its header", async () => {
+ const board = await renderBoard();
+ focusHeader(board, 0);
+
+ expect(press(board, "ArrowRight")).toBe("Third");
+ expect(press(board, "ArrowLeft")).toBe("First");
+ });
+
+ it("offers the button of an empty column, and the one that adds a column", async () => {
+ const board = await renderBoard();
+ focusHeader(board, 2);
+
+ // The third column is empty, so its button is what crossing into it reaches.
+ expect(press(board, "ArrowLeft")).toBe("Third");
+ expect(press(board, "ArrowRight")).toBe("board_view.new-item");
+ expect(press(board, "ArrowRight")).toBe("board_view.add-column");
+ expect(press(board, "ArrowRight")).toBe("board_view.add-column");
+ expect(press(board, "ArrowLeft")).toBe("board_view.new-item");
+ });
+
+ it("jumps to the ends of a column with Home and End", async () => {
+ const board = await renderBoard();
+ focusHeader(board, 0);
+
+ expect(press(board, "End")).toBe("Second");
+ expect(press(board, "Home")).toBe("First");
+ });
+
+ /**
+ * `Alt+Left` and `Alt+Right` are the app's own back and forward in note history, bound on
+ * the document. A key the board answers must not also navigate away from it.
+ */
+ it("keeps the keys it answers from reaching what else is bound to them", async () => {
+ const board = await renderBoard();
+ const reachedDocument: string[] = [];
+ const listener = (e: Event) => reachedDocument.push((e as KeyboardEvent).key);
+ document.addEventListener("keydown", listener);
+
+ try {
+ focusCard(board, 0, 0);
+ press(board, "ArrowDown");
+ press(board, "ArrowRight", { ctrlKey: true });
+ // Even at an edge it moves nothing from: the board owns the key while focused.
+ focusCard(board, 0, 0);
+ press(board, "ArrowLeft", { ctrlKey: true });
+ press(board, "PageDown", { ctrlKey: true });
+ press(board, "ArrowRight", { ctrlKey: true, altKey: true });
+ press(board, " ");
+
+ expect(reachedDocument).toEqual([]);
+ } finally {
+ document.removeEventListener("keydown", listener);
+ }
+ });
+
+ /**
+ * Going back and forward through notes is bound on the document with Alt and an arrow. A
+ * board is no reason for it to stop working, so the board answers to Ctrl instead.
+ */
+ it("lets Alt and an arrow through to the app's own back and forward", async () => {
+ const board = await renderBoard();
+ const reachedDocument: string[] = [];
+ const listener = (e: Event) => reachedDocument.push((e as KeyboardEvent).key);
+ document.addEventListener("keydown", listener);
+
+ try {
+ focusCard(board, 0, 0);
+ press(board, "ArrowLeft", { altKey: true });
+ press(board, "ArrowRight", { altKey: true });
+
+ expect(reachedDocument).toEqual([ "ArrowLeft", "ArrowRight" ]);
+ expect(saved).toHaveLength(0);
+ } finally {
+ document.removeEventListener("keydown", listener);
+ }
+ });
+
+ it("leaves the keys alone while a title is being edited", async () => {
+ const board = await renderBoard();
+ const header = board.querySelectorAll<HTMLElement>(".board-column h3")[0];
+
+ await act(async () => {
+ header.focus();
+ header.dispatchEvent(new KeyboardEvent("keydown", { key: "F2", bubbles: true }));
+ await flush();
+ });
+
+ const editor = header.querySelector<HTMLInputElement>("input");
+ if (!editor) throw new Error("expected the title editor");
+ editor.focus();
+
+ editor.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }));
+ expect(document.activeElement).toBe(editor);
+ });
+ });
+
+ describe("moving what is focused", () => {
+ it("moves a card up and down its own column", async () => {
+ const board = await renderBoard();
+ focusCard(board, 0, 1);
+
+ press(board, "ArrowUp", { ctrlKey: true });
+ expect(branches.moveBeforeBranch)
+ .toHaveBeenCalledWith([ branchOf(board, "Second") ], branchOf(board, "First"));
+
+ focusCard(board, 0, 0);
+ press(board, "ArrowDown", { ctrlKey: true });
+ // Placed past the card below it, which is the last, so it goes after that one.
+ expect(branches.moveAfterBranch)
+ .toHaveBeenCalledWith([ branchOf(board, "First") ], branchOf(board, "Second"));
+ });
+
+ it("sends a card to the end of the column beside it, keeping focus", async () => {
+ const board = await renderBoard();
+ focusCard(board, 0, 0);
+
+ press(board, "ArrowRight", { ctrlKey: true });
+ await act(async () => { await flush(); });
+
+ const [ url, body ] = vi.mocked(server.put).mock.calls.at(-1) ?? [];
+ expect(url).toBe(`notes/${noteOf(board, "First")}/set-attribute`);
+ expect(body).toMatchObject({ name: "status", value: "Doing" });
+ expect(branches.moveAfterBranch)
+ .toHaveBeenCalledWith([ branchOf(board, "First") ], branchOf(board, "Third"));
+ });
+
+ /**
+ * The card is drawn again under another parent, so its element is a new one and whatever
+ * held focus is gone. Two writes go out, each landing a redraw of its own, and the card is
+ * only where it was asked to be after the second.
+ */
+ it("keeps focus on a card once it has actually crossed to the other column", async () => {
+ const board = await renderBoard();
+ focusCard(board, 0, 0);
+ const moved = noteOf(board, "First");
+
+ press(board, "ArrowRight", { ctrlKey: true });
+
+ // The first redraw arrives before the label the move writes has been applied.
+ await redraw();
+ expect(focusedName(board)).toBe("First");
+
+ // The second carries it, and the card is drawn afresh in the column beside it.
+ setStatus(moved, "Doing");
+ await redraw();
+
+ expect(columnOf(board, "First")).toBe(1);
+ expect(focusedName(board)).toBe("First");
+ });
+
+ it("keeps focus on a card sent to the column on its left", async () => {
+ const board = await renderBoard();
+ focusCard(board, 1, 0);
+ const moved = noteOf(board, "Third");
+
+ press(board, "ArrowLeft", { ctrlKey: true });
+
+ await redraw();
+ setStatus(moved, "To Do");
+ await redraw();
+
+ expect(columnOf(board, "Third")).toBe(0);
+ expect(focusedName(board)).toBe("Third");
+ });
+
+ it("carries the column from its header, which holds no card of its own", async () => {
+ const board = await renderBoard();
+ focusHeader(board, 0);
+
+ press(board, "ArrowRight", { ctrlKey: true });
+
+ expect(saved.at(-1)?.columns?.map(column => column.value))
+ .toEqual([ "Doing", "To Do", "Done" ]);
+ expect(focusedName(board)).toBe("To Do");
+ });
+
+ /**
+ * A move still settling holds focus until its card arrives. Opening a note takes focus away
+ * on purpose, and the hold would pull it straight back.
+ */
+ it("stops holding focus once the reader opens a note", async () => {
+ const board = await renderBoard();
+ const open = vi.spyOn(appContext, "triggerCommand").mockReturnValue(undefined);
+
+ focusCard(board, 0, 0);
+ press(board, "ArrowRight", { ctrlKey: true });
+ press(board, " ");
+ expect(open).toHaveBeenCalled();
+
+ // Focus is let go of, so redrawing around the move does not take it back.
+ const elsewhere = document.createElement("input");
+ document.body.appendChild(elsewhere);
+ elsewhere.focus();
+
+ await redraw();
+ expect(document.activeElement).toBe(elsewhere);
+ elsewhere.remove();
+ });
+
+ it("keeps focus through the redraws that follow a card arriving", async () => {
+ const board = await renderBoard();
+ focusCard(board, 0, 0);
+ const moved = noteOf(board, "First");
+
+ press(board, "ArrowRight", { ctrlKey: true });
+ setStatus(moved, "Doing");
+ await redraw();
+ expect(focusedName(board)).toBe("First");
+
+ // The second write lands its own redraw, and more arrive from elsewhere.
+ await redraw();
+ await redraw();
+ expect(focusedName(board)).toBe("First");
+ });
+
+ it("keeps focus on a card sent across and then straight back", async () => {
+ const board = await renderBoard();
+ focusCard(board, 0, 0);
+ const moved = noteOf(board, "First");
+
+ press(board, "ArrowRight", { ctrlKey: true });
+ setStatus(moved, "Doing");
+ await redraw();
+ expect(columnOf(board, "First")).toBe(1);
+ expect(focusedName(board)).toBe("First");
+
+ press(board, "ArrowLeft", { ctrlKey: true });
+ setStatus(moved, "To Do");
+ await redraw();
+
+ expect(columnOf(board, "First")).toBe(0);
+ expect(focusedName(board)).toBe("First");
+ });
+
+ /**
+ * Reordering keeps the card's element and moves it, and a browser blurs an element it
+ * moves. happy-dom does not, so the blur is made here; without it the test would pass on
+ * a board that loses focus in every browser there is.
+ */
+ it("takes focus back after a redraw has left it on nothing", async () => {
+ const board = await renderBoard();
+ focusCard(board, 0, 1);
+
+ press(board, "ArrowUp", { ctrlKey: true });
+ (document.activeElement as HTMLElement | null)?.blur();
+ await redraw();
+
+ expect(focusedName(board)).toBe("Second");
+ });
+
+ it("leaves focus where the reader has since put it", async () => {
+ const board = await renderBoard();
+ focusCard(board, 0, 1);
+
+ press(board, "ArrowUp", { ctrlKey: true });
+ focusHeader(board, 2);
+ await redraw();
+
+ expect(focusedName(board)).toBe("Done");
+ });
+
+ it("does nothing at the edges it cannot move past", async () => {
+ const board = await renderBoard();
+
+ focusCard(board, 0, 0);
+ press(board, "ArrowUp", { ctrlKey: true });
+ press(board, "PageUp", { ctrlKey: true });
+ press(board, "ArrowLeft", { ctrlKey: true });
+
+ focusButton(board, 1);
+ press(board, "ArrowUp", { ctrlKey: true });
+ press(board, "ArrowLeft", { ctrlKey: true });
+
+ expect(branches.moveBeforeBranch).not.toHaveBeenCalled();
+ expect(branches.moveAfterBranch).not.toHaveBeenCalled();
+ expect(saved).toHaveLength(0);
+ });
+
+ it("moves the column from anywhere within it, keeping focus where it was", async () => {
+ const board = await renderBoard();
+
+ focusCard(board, 0, 1);
+ press(board, "ArrowRight", { ctrlKey: true, altKey: true });
+ expect(saved.at(-1)?.columns?.map(column => column.value))
+ .toEqual([ "Doing", "To Do", "Done" ]);
+ expect(focusedName(board)).toBe("Second");
+
+ focusButton(board, 1);
+ press(board, "ArrowLeft", { ctrlKey: true, altKey: true });
+ expect(saved.at(-1)?.columns?.map(column => column.value))
+ .toEqual([ "To Do", "Doing", "Done" ]);
+ expect(focusedName(board)).toBe("board_view.new-item");
+ });
+
+ it("moves no column past either end, and none from the button that adds one", async () => {
+ const board = await renderBoard();
+
+ focusCard(board, 0, 0);
+ press(board, "ArrowLeft", { ctrlKey: true, altKey: true });
+
+ board.querySelector<HTMLElement>(".board-add-column")?.focus();
+ press(board, "ArrowRight", { ctrlKey: true, altKey: true });
+
+ expect(saved).toHaveLength(0);
+ });
+
+ it("moves the column its header stands on, keeping focus on that header", async () => {
+ const board = await renderBoard();
+ focusHeader(board, 0);
+
+ press(board, "ArrowRight", { ctrlKey: true, altKey: true });
+ await act(async () => { await flush(); });
+
+ expect(saved.at(-1)?.columns?.map(column => column.value))
+ .toEqual([ "Doing", "To Do", "Done" ]);
+ expect(focusedName(board)).toBe("To Do");
+ });
+
+ it("sends a column to either end with the page keys", async () => {
+ const board = await renderBoard();
+
+ focusHeader(board, 1);
+ press(board, "PageUp", { ctrlKey: true, altKey: true });
+ await act(async () => { await flush(); });
+ expect(saved.at(-1)?.columns?.map(column => column.value))
+ .toEqual([ "Doing", "To Do", "Done" ]);
+
+ focusHeader(board, 0);
+ press(board, "PageDown", { ctrlKey: true, altKey: true });
+ await act(async () => { await flush(); });
+ expect(saved.at(-1)?.columns?.map(column => column.value))
+ .toEqual([ "To Do", "Done", "Doing" ]);
+ });
+ });
+
+ it("opens the card under the cursor with Space", async () => {
+ const board = await renderBoard();
+ const open = vi.spyOn(appContext, "triggerCommand").mockReturnValue(undefined);
+
+ focusCard(board, 0, 0);
+ press(board, " ");
+
+ expect(open).toHaveBeenCalledWith("openInPopup", { noteIdOrPath: noteOf(board, "First") });
+ });
+
+ /** Which column a card is drawn in, counted as the reader sees them. */
+ function columnOf(board: HTMLElement, title: string) {
+ return [ ...board.querySelectorAll(".board-column") ]
+ .findIndex(column => [ ...column.querySelectorAll(".board-note") ]
+ .some(card => card.textContent?.includes(title)));
+ }
+
+ /** Applies a move the way the server's answer would, which nothing here waits for. */
+ function setStatus(noteId: string | undefined, value: string) {
+ for (const attribute of froca.getNoteFromCache(noteId ?? "")?.getAttributes() ?? []) {
+ if (attribute.name === "status") {
+ attribute.value = value;
+ }
+ }
+ }
+
+ /** Draws the board again, as the refresh that follows a write does. */
+ async function redraw() {
+ await act(async () => {
+ render(
+ <ParentComponent.Provider value={new Component()}>
+ <BoardView
+ note={boardNote}
+ notePath={`root/${boardNote.noteId}`}
+ noteIds={[ ...boardNote.getChildNoteIds() ]}
+ highlightedTokens={null}
+ viewConfig={{
+ columns: [ { value: "To Do" }, { value: "Doing" }, { value: "Done" } ]
+ }}
+ saveConfig={(config) => saved.push(config)}
+ media="screen"
+ onReady={() => {}}
+ />
+ </ParentComponent.Provider>,
+ container as HTMLElement
+ );
+ await flush();
+ });
+ await act(async () => { await flush(); });
+ }
+
+ /** Presses a key on whatever holds focus, answering with what holds it afterwards. */
+ function press(
+ board: HTMLElement,
+ key: string,
+ options: { altKey?: boolean, ctrlKey?: boolean } = {}
+ ) {
+ act(() => {
+ document.activeElement?.dispatchEvent(new KeyboardEvent("keydown", {
+ key,
+ altKey: options.altKey ?? false,
+ ctrlKey: options.ctrlKey ?? false,
+ bubbles: true,
+ cancelable: true
+ }));
+ });
+
+ return focusedName(board);
+ }
+
+ /**
+ * What holds focus, named the way the reader would name it. Its own title where it has one, so
+ * that a header is not read together with the count beside it.
+ */
+ function focusedName(board: HTMLElement) {
+ const active = document.activeElement;
+ if (!active || !board.contains(active)) return null;
+
+ const named = active.querySelector(".title") ?? active;
+ return named.textContent?.trim() ?? null;
+ }
+
+ function focusHeader(board: HTMLElement, column: number) {
+ board.querySelectorAll<HTMLElement>(".board-column h3")[column].focus();
+ }
+
+ function focusCard(board: HTMLElement, column: number, item: number) {
+ board.querySelectorAll(".board-column")[column]
+ .querySelectorAll<HTMLElement>(".board-note")[item].focus();
+ }
+
+ function focusButton(board: HTMLElement, column: number) {
+ board.querySelectorAll(".board-column")[column]
+ .querySelector<HTMLElement>(".board-new-item")?.focus();
+ }
+
+ function noteOf(board: HTMLElement, title: string) {
+ return [ ...board.querySelectorAll<HTMLElement>(".board-note") ]
+ .find(card => card.textContent?.includes(title))?.dataset.noteId;
+ }
+
+ function branchOf(board: HTMLElement, title: string) {
+ const noteId = noteOf(board, title);
+ return [ ...boardNote.getChildBranches() ]
+ .find(branch => branch.noteId === noteId)?.branchId;
+ }
+
+ let boardNote: ReturnType<typeof buildNote>;
+
+ /** Two columns of cards, one empty column, and the button that adds another. */
+ async function renderBoard() {
+ boardNote = buildNote({
+ title: "Board",
+ "#collection": "",
+ "#viewType": "board",
+ children: [
+ { title: "First", "#status": "To Do" },
+ { title: "Second", "#status": "To Do" },
+ { title: "Third", "#status": "Doing" }
+ ]
+ });
+
+ const mountPoint = document.createElement("div");
+ container = mountPoint;
+ document.body.appendChild(mountPoint);
+
+ await act(async () => {
+ render(
+ <ParentComponent.Provider value={new Component()}>
+ <BoardView
+ note={boardNote}
+ notePath={`root/${boardNote.noteId}`}
+ noteIds={[ ...boardNote.getChildNoteIds() ]}
+ highlightedTokens={null}
+ viewConfig={{
+ columns: [ { value: "To Do" }, { value: "Doing" }, { value: "Done" } ]
+ }}
+ saveConfig={(config) => saved.push(config)}
+ media="screen"
+ onReady={() => {}}
+ />
+ </ParentComponent.Provider>,
+ mountPoint
+ );
+ });
+ await act(async () => { await flush(); });
+
+ return mountPoint;
+ }
+
+ function flush() {
+ return new Promise((resolve) => setTimeout(resolve));
+ }
+});
diff --git a/apps/client/src/widgets/collections/board/keyboard.ts b/apps/client/src/widgets/collections/board/keyboard.ts
new file mode 100644
index 0000000000..c7cd701142
--- /dev/null
+++ b/apps/client/src/widgets/collections/board/keyboard.ts
@@ -0,0 +1,367 @@
+import { RefObject } from "preact";
+import { useCallback, useLayoutEffect, useRef } from "preact/hooks";
+
+import BoardApi from "./api";
+import { ColumnMap } from "./data";
+
+/** Plain, these walk the board. */
+const NAVIGATION_KEYS = [ "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Home", "End" ];
+
+/** With Ctrl, these carry the focused card: a step, a column across, or all the way to an end. */
+const ITEM_MOVE_KEYS = [ "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "PageUp", "PageDown" ];
+
+/** With Ctrl and Alt, these carry the column focus is in, from wherever inside it focus sits. */
+const COLUMN_MOVE_KEYS = [ "ArrowLeft", "ArrowRight", "PageUp", "PageDown" ];
+
+/**
+ * A place on the board that can hold focus.
+ *
+ * Columns and items are named by position rather than by value, since that is what the arrows walk
+ * and what the DOM can be asked for; the value is looked up only when something has to be moved.
+ */
+type Spot =
+ | { kind: "header"; column: number }
+ | { kind: "item"; column: number; item: number }
+ | { kind: "add-item"; column: number }
+ | { kind: "add-column" };
+
+/**
+ * What to put focus back on once the board has redrawn around a move. A card is named by the note
+ * it stands for and everything else by its column, since only a card is drawn anywhere else.
+ */
+type FocusIntent =
+ | { noteId: string }
+ | { column: string; part: "header" | "add-item" };
+
+/**
+ * What focus belongs to while a move is under way.
+ *
+ * Held rather than restored once, because a move takes focus away more than once and at times the
+ * board cannot foresee. A card crossing columns is drawn afresh under its new one; a card merely
+ * reordered keeps its element, but the browser moves that element, and moving a focused one blurs
+ * it. Both leave focus on nothing at all, which is the one state worth stepping into.
+ *
+ * So it is given up not on any sign of having landed, but when the reader has plainly gone
+ * elsewhere: another key, or focus resting on something other than the card.
+ */
+interface PendingFocus {
+ intent: FocusIntent;
+}
+
+export interface BoardKeyboardOptions {
+ containerRef: RefObject<HTMLDivElement>;
+ /** The columns as shown, which is what the arrows count and what `moveColumn` is told about. */
+ columns: string[];
+ byColumn: ColumnMap | undefined;
+ api: BoardApi;
+ /** Moves a column to sit before the given position, as a drag onto that position would. */
+ moveColumn: (fromIndex: number, toIndex: number) => void;
+}
+
+/**
+ * The board's keyboard: the arrows, Home and End walk it, Ctrl with them carries the focused card,
+ * Ctrl and Alt together carry its column, and Space opens the card under the cursor.
+ *
+ * Alt on its own is left alone throughout, since that is how a reader goes back and forward through
+ * notes and a board is no reason for it to stop working.
+ *
+ * One handler on the board rather than one per element, because every key here is about the board
+ * as a whole: where the next thing is, and where what is focused should go. The per-element
+ * handlers keep what is theirs (F2 to rename, Enter to open, typing to start a card).
+ *
+ * Focus follows what is under it rather than where it sits: a card moved to another column is
+ * drawn as a new element, and columns are drawn unkeyed, so a header would otherwise be left
+ * focused on whichever column took its place.
+ */
+export function useBoardKeyboard({
+ containerRef, columns, byColumn, api, moveColumn
+}: BoardKeyboardOptions) {
+ const pendingFocus = useRef<PendingFocus | null>(null);
+
+ // Every render, since a redraw is the only thing that takes focus away here and more than one
+ // of them follows a move.
+ useLayoutEffect(() => {
+ const pending = pendingFocus.current;
+ const container = containerRef.current;
+ if (!pending || !container) return;
+
+ if (!("noteId" in pending.intent)) {
+ // The columns are drawn unkeyed, so what was focused is now over whichever column took
+ // the old one's place. Focus is pointed at the right one and the hold is done with.
+ const element = findInColumn(container, pending.intent.column, pending.intent.part);
+ if (element) {
+ element.focus();
+ pendingFocus.current = null;
+ }
+ return;
+ }
+
+ // Focus is resting somewhere of the reader's choosing, so it is not this move's to take
+ // back. Only what a redraw leaves behind is, which is nothing holding focus at all.
+ const element = findCard(container, pending.intent.noteId);
+ const active = document.activeElement;
+ if (active && active !== document.body && active !== element) {
+ pendingFocus.current = null;
+ return;
+ }
+
+ element?.focus();
+ });
+
+ return useCallback((e: KeyboardEvent) => {
+ const container = containerRef.current;
+ const target = e.target as HTMLElement | null;
+ if (!container || e.metaKey || e.shiftKey) return;
+
+ // An editor is open on the thing that is focused, and every key belongs to it.
+ if (target?.closest("input, textarea")) return;
+
+ // Alt on its own is how a reader goes back and forward through notes, which is expected to
+ // work over a board as over anything else.
+ if (e.altKey && !e.ctrlKey) return;
+
+ const spot = spotOf(container, document.activeElement);
+ if (!spot) return;
+
+ if (e.ctrlKey) {
+ // A header holds no card, so the key carries the column it heads. Alt says so from
+ // anywhere within a column, for a reader who is standing on one of its cards.
+ const carriesColumn = e.altKey || spot.kind === "header";
+
+ // Taken whether or not it leads anywhere: a card already at the end of its column is no
+ // reason to let the key mean something else instead.
+ if (!(carriesColumn ? COLUMN_MOVE_KEYS : ITEM_MOVE_KEYS).includes(e.key)) return;
+ take(e);
+
+ if (carriesColumn) {
+ const shifted = shiftColumn(spot, e.key, { columns, byColumn, moveColumn });
+ if (shifted) {
+ pendingFocus.current = { intent: shifted };
+ }
+ return;
+ }
+
+ const moved = move(spot, e.key, { columns, byColumn, api });
+ if (moved) {
+ const pending: PendingFocus = { intent: moved.intent };
+ pendingFocus.current = pending;
+
+ // Nothing is going to arrive, so focus is not held for it any longer.
+ moved.done.catch(() => {
+ if (pendingFocus.current === pending) {
+ pendingFocus.current = null;
+ }
+ });
+ }
+ return;
+ }
+
+ // Every other key says the reader has moved on, so a move still settling stops holding
+ // focus: it would otherwise pull it back out of whatever the key opened.
+ pendingFocus.current = null;
+
+ if (NAVIGATION_KEYS.includes(e.key)) {
+ // The plain arrows would otherwise scroll the page past the end of a column.
+ take(e);
+ walk(container, spot, e.key);
+ return;
+ }
+
+ if (e.key === " " && spot.kind === "item") {
+ const item = itemAt(columns, byColumn, spot);
+ if (item) {
+ take(e);
+ api.openNote(item.note.noteId);
+ }
+ }
+ }, [ containerRef, columns, byColumn, api, moveColumn ]);
+}
+
+/** Keeps a key the board has answered from also reaching whatever else is bound to it. */
+function take(e: KeyboardEvent) {
+ e.preventDefault();
+ e.stopPropagation();
+}
+
+/** Where the board is focused, or null where the keyboard has nothing to say about it. */
+function spotOf(container: HTMLElement, element: Element | null): Spot | null {
+ if (!element || !container.contains(element)) return null;
+ if (element.closest(".board-add-column")) return { kind: "add-column" };
+
+ const columnElement = element.closest(".board-column");
+ if (!columnElement) return null;
+
+ const column = columnsOf(container).indexOf(columnElement as HTMLElement);
+ if (element.closest("h3")) return { kind: "header", column };
+ if (element.closest(".board-new-item")) return { kind: "add-item", column };
+
+ const card = element.closest(".board-note");
+ if (!card) return null;
+
+ return { kind: "item", column, item: cardsOf(columnElement).indexOf(card as HTMLElement) };
+}
+
+/**
+ * Moves focus, answering with whether the key led anywhere.
+ *
+ * Up and down walk one column, from its header through its cards to the button under them. Left and
+ * right cross to the next column's first card, or to its button where it holds none: its header is
+ * reached by pressing up from there, which is the only way a header is reached at all.
+ */
+function walk(container: HTMLElement, from: Spot, key: string) {
+ const next = destination(container, from, key);
+ if (!next) return false;
+
+ elementAt(container, next)?.focus();
+ return true;
+}
+
+function destination(container: HTMLElement, from: Spot, key: string): Spot | null {
+ const columnCount = columnsOf(container).length;
+
+ if (key === "ArrowLeft" || key === "ArrowRight") {
+ const step = key === "ArrowRight" ? 1 : -1;
+ const column = (from.kind === "add-column" ? columnCount : from.column) + step;
+
+ if (column < 0) return null;
+ if (column >= columnCount) {
+ return from.kind === "add-column" ? null : { kind: "add-column" };
+ }
+ return entryOf(container, column);
+ }
+
+ if (from.kind === "add-column") return null;
+
+ const items = cardsOf(columnsOf(container)[from.column]).length;
+ if (key === "Home") return entryOf(container, from.column);
+ if (key === "End") {
+ return items
+ ? { kind: "item", column: from.column, item: items - 1 }
+ : entryOf(container, from.column);
+ }
+
+ // Down the column: its header, then each card, then the button under them.
+ const row = from.kind === "header" ? 0 : from.kind === "item" ? from.item + 1 : items + 1;
+ const next = row + (key === "ArrowDown" ? 1 : -1);
+ if (next < 0 || next > items + 1) return null;
+
+ if (next === 0) return { kind: "header", column: from.column };
+ if (next === items + 1) return { kind: "add-item", column: from.column };
+ return { kind: "item", column: from.column, item: next - 1 };
+}
+
+/** The first thing a column offers on the way in, which is never its header. */
+function entryOf(container: HTMLElement, column: number): Spot {
+ return cardsOf(columnsOf(container)[column]).length
+ ? { kind: "item", column, item: 0 }
+ : { kind: "add-item", column };
+}
+
+/**
+ * Moves the focused card, answering with what to focus once the board has redrawn, or false where
+ * the key led nowhere. A header and the button under a column hold no card, so nothing moves from
+ * either: the column itself is moved with Alt held as well.
+ */
+function move(
+ spot: Spot,
+ key: string,
+ { columns, byColumn, api }: Pick<BoardKeyboardOptions, "columns" | "byColumn" | "api">
+): { intent: FocusIntent; done: Promise<unknown> } | false {
+ const item = itemAt(columns, byColumn, spot);
+ if (!item || spot.kind !== "item") return false;
+
+ const column = columns[spot.column];
+ const items = byColumn?.get(column) ?? [];
+ const { noteId } = item.note;
+ const { branchId } = item.branch;
+
+ if (key === "ArrowLeft" || key === "ArrowRight") {
+ const target = columns[spot.column + (key === "ArrowRight" ? 1 : -1)];
+ if (!target) return false;
+
+ return { intent: { noteId }, done: api.moveToColumnEnd(noteId, branchId, target) };
+ }
+
+ const last = items.length - 1;
+ // A card is placed before a position too, so moving one down means passing the one below it.
+ const to = key === "ArrowUp" && spot.item > 0 ? spot.item - 1
+ : key === "ArrowDown" && spot.item < last ? spot.item + 2
+ : key === "PageUp" && spot.item > 0 ? 0
+ : key === "PageDown" && spot.item < last ? items.length
+ : null;
+
+ if (to === null) return false;
+
+ return {
+ intent: { noteId },
+ done: api.moveWithinBoard(noteId, branchId, spot.item, to, column, column)
+ };
+}
+
+/**
+ * Moves the column focus is in, answering with what to put focus back on. Whatever was focused
+ * stays focused: the columns are drawn unkeyed, so the element would otherwise be left standing
+ * over whichever column took the old one's place.
+ */
+function shiftColumn(
+ spot: Spot,
+ key: string,
+ { columns, byColumn, moveColumn }:
+ Pick<BoardKeyboardOptions, "columns" | "byColumn" | "moveColumn">
+): FocusIntent | false {
+ if (spot.kind === "add-column") return false;
+
+ const last = columns.length - 1;
+ // A column is placed before a position, so passing one to the right means passing two.
+ const to = key === "ArrowRight" && spot.column < last ? spot.column + 2
+ : key === "ArrowLeft" && spot.column > 0 ? spot.column - 1
+ : key === "PageDown" && spot.column < last ? columns.length
+ : key === "PageUp" && spot.column > 0 ? 0
+ : null;
+
+ if (to === null) return false;
+
+ const card = itemAt(columns, byColumn, spot);
+ moveColumn(spot.column, to);
+
+ if (card) return { noteId: card.note.noteId };
+ return {
+ column: columns[spot.column],
+ part: spot.kind === "header" ? "header" : "add-item"
+ };
+}
+
+function itemAt(columns: string[], byColumn: ColumnMap | undefined, spot: Spot) {
+ if (spot.kind !== "item") return undefined;
+ return byColumn?.get(columns[spot.column])?.[spot.item];
+}
+
+function elementAt(container: HTMLElement, spot: Spot): HTMLElement | null {
+ if (spot.kind === "add-column") return container.querySelector(".board-add-column");
+
+ const column = columnsOf(container)[spot.column];
+ if (!column) return null;
+
+ if (spot.kind === "header") return column.querySelector("h3");
+ if (spot.kind === "add-item") return column.querySelector(".board-new-item");
+ return cardsOf(column)[spot.item] ?? null;
+}
+
+/** Found by what it stands for rather than by where it sits, which a move is about to change. */
+function findCard(container: HTMLElement, noteId: string) {
+ return container.querySelector<HTMLElement>(`.board-note[data-note-id="${noteId}"]`);
+}
+
+function findInColumn(container: HTMLElement, column: string, part: "header" | "add-item") {
+ const element = columnsOf(container).find(candidate => candidate.dataset.column === column);
+ return element?.querySelector<HTMLElement>(
+ part === "header" ? "h3" : ".board-new-item") ?? null;
+}
+
+function columnsOf(container: HTMLElement) {
+ return [ ...container.querySelectorAll<HTMLElement>(".board-column") ];
+}
+
+function cardsOf(column: Element | undefined) {
+ return column ? [ ...column.querySelectorAll<HTMLElement>(".board-note") ] : [];
+}