press() and actions.ts: what the mouse offers, from one place

press(key) sends a synthetic keydown through the page's key handler, so a
mouse control does exactly what its key does. actions.ts builds the items of
the selection bar, the ⋯ menus and the right-click menu from a context for
each kind of target (words, a node, a page, a pane, an article's row, the top
bar); each item names its key and runs by pressing it, or runs a command of
the command bar. Unit tests check every item presses its own key and that the
key handler takes that key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab
This commit is contained in:
thalladaandClaude Opus 5.5 committed 2026-11-16 02:12:06 -05:00
1 parent abf79c14cc
commit 9b73cdb15e
3 files changed
+443

No files matched your search

+289
View File
@@ -0,0 +1,289 @@
/**
* What the mouse can do, by what it points at: the items of the selection bar, of the ⋯ menus and
* of the right-click menu, built here and only here so the three never drift apart. Every item
* that has a key runs by pressing it (press.ts), so it does exactly what the key does; the few that
* have none run a command of the command bar, or copy. Builders are pure: what they need to know
* about the target comes in a context, and how to act in `Act`, so they can be tested without a page.
*/
import { press } from "./press";
export interface Item {
t: "item";
label: string;
/** The key it presses (as KeyboardEvent.key), shown beside it. */
key?: string;
/** What to show for the key when it is not the key itself (⇧⏎, /research, Ctrl C). */
keyText?: string;
/** A quiet second line. */
sub?: string;
disabled?: boolean;
/** A setting or a state that is on (shown with a tick). */
checked?: boolean;
/** The label on the selection bar, where it differs. */
short?: string;
/** Press the key with Shift (Shift+Enter: open in place). */
shift?: boolean;
run: () => void;
}
export interface Choice {
label: string;
key?: string;
on?: boolean;
run: () => void;
}
export type Entry = Item | { t: "sep" } | { t: "head"; text: string } | { t: "choices"; label: string; options: Choice[] };
/** How items act. The page passes the real thing; the tests a recorder. */
export interface Act {
press(key: string, shift?: boolean): void;
/** Run a command of the command bar at once (`/view panes`). */
command(text: string): void;
/** Open the command bar with this already typed (`/research `). */
prompt(prefill: string): void;
copy(text: string): void;
}
const SEP = { t: "sep" } as const;
/** How the system's copy key is written. */
const COPY = typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(navigator.platform) ? "⌘C" : "Ctrl C";
const head = (text: string): Entry => ({ t: "head", text });
/** An item that presses its key. */
const key = (act: Act, label: string, k: string, more: Partial<Item> = {}): Item => ({ t: "item", label, key: k, run: () => act.press(k, !!more.shift), ...more });
/** Separators only between groups that have something in them, never two together or at an end. */
export function tidy(es: (Entry | false | null | undefined | "")[]): Entry[] {
const out: Entry[] = [];
for (const e of es) {
if (!e) continue;
if (e.t === "sep" && (!out.length || out[out.length - 1].t === "sep")) continue;
out.push(e);
}
while (out.length && out[out.length - 1].t === "sep") out.pop();
return out;
}
const quote = (s: string, n = 60) => {
const t = s.replace(/\s+/g, " ").trim();
return `“${t.length > n ? `${t.slice(0, n - 1)}…` : t}”`;
};
// ---- words selected ----
export interface SelCtx {
/** The words, for Copy and the menu's head. */
text: string;
/** In Wikipedia's text: no linking by hand, no Related. */
article: boolean;
/** A link on exactly these words: where it goes. */
link?: "wiki" | "node" | "url";
/** A note (with text of its own) on exactly these words. */
note?: boolean;
/** A suggested link on these words: what it would link to. */
suggestion?: string;
/** The node's Related list, numbered 1–5. */
related?: { title: string; doc?: string }[];
panes: boolean;
}
/** The lenses, as the bar shows them and the menus list them. */
function lenses(act: Act): Item[] {
return [
key(act, "Expand", "e", { short: "expand" }),
key(act, "Define", "d", { short: "define" }),
key(act, "Why?", "y", { short: "why" }),
key(act, "An example", "x", { short: "example" }),
key(act, "An objection", "c", { short: "challenge" }),
key(act, "Ask your own question…", ":", { short: "ask…" }),
];
}
/** The selection bar: the lenses, then linking (not in an article). Its ⋯ opens `selectionEntries`. */
export function barItems(c: SelCtx, act: Act): Item[][] {
const ls = lenses(act);
return c.article ? [ls] : [ls, [key(act, "Link to…", "w", { short: "link…" })]];
}
/** Words selected, by a click, a drag or the keys: the bar's ⋯ and the right-click menu. */
export function selectionEntries(c: SelCtx, act: Act): Entry[] {
const related = c.article ? [] : (c.related ?? []).slice(0, 5);
return tidy([
head(quote(c.text)),
c.text && { t: "item", label: "Copy", keyText: COPY, run: () => act.copy(c.text) },
SEP,
c.link && key(act, c.panes ? "Open the link beside" : "Open the link", "Enter"),
c.link && c.panes && key(act, "Open it in place", "Enter", { keyText: "⇧⏎", shift: true, sub: "instead of the pane there" }),
c.link === "wiki" && key(act, "Open on wikipedia.org", "W"),
c.note && key(act, "Open the note", "Enter"),
c.suggestion && key(act, `Link to ${c.suggestion}`, "y", { sub: "a suggested link" }),
c.suggestion && key(act, "Decline the suggestion", "n"),
(c.link || c.note) && !c.article && key(act, c.link ? "Retarget…" : "Link it…", "w"),
(c.link || c.note) && key(act, c.link && !c.note ? "Remove the link" : "Delete the note", "D"),
SEP,
...lenses(act),
SEP,
!c.article && !c.link && !c.note && key(act, "Link to…", "w"),
related.length > 0 && head("Link to a related section"),
...related.map((r, i) => key(act, r.title, String(i + 1), { sub: r.doc })),
SEP,
{ t: "choices", label: "Select", options: [{ label: "less", key: "H", run: () => act.press("H") }, { label: "more", key: "L", run: () => act.press("L") }] },
]);
}
// ---- a node: a section's row, a note's box, a pane's head, a page's head ----
export interface NodeCtx {
title: string;
/** Its title and text, for Copy. */
text: string;
note: boolean;
/** Its parent changed, or its sections did. */
stale?: "parent" | "sections";
locked: boolean;
/** It has a target of its own (L opens it). */
target: boolean;
/** The library itself: nothing around it to add after, move among or delete it from. */
library: boolean;
/** A document's top. */
doc: boolean;
generating: boolean;
}
export function nodeEntries(c: NodeCtx, act: Act): Entry[] {
const fixed = c.library;
return tidy([
head(c.stale ? `${c.title} · ${c.stale === "parent" ? "its parent changed" : "its sections changed"}` : c.title),
c.stale && key(act, "Bring it in line", "R", { sub: c.locked ? "locked: the model will not rewrite it" : "the model rewrites it to match", disabled: c.locked || !c.generating }),
c.stale && key(act, "Accept as it stands", "b"),
SEP,
c.text && { t: "item", label: "Copy", keyText: COPY, sub: "its title and text", run: () => act.copy(c.text) },
SEP,
key(act, "Write more", "e"),
key(act, "Edit text", "c"),
key(act, "Rename", "r"),
key(act, c.library ? "Add a document" : "Add a section inside", "a"),
!fixed && !c.note && key(act, c.doc ? "Add a document after" : "Add a section after", "A"),
SEP,
key(act, "Ask the editor…", ":"),
c.generating && { t: "item", label: "Research on the web…", keyText: "/research", run: () => act.prompt("/research ") },
key(act, c.note ? "Link this note to…" : "Link this section to…", "w"),
c.target && key(act, "Open its target", "L"),
SEP,
!fixed && { t: "choices", label: "Move", options: [{ label: "up", key: "K", run: () => act.press("K") }, { label: "down", key: "J", run: () => act.press("J") }, { label: "in", key: ">", run: () => act.press(">") }, { label: "out", key: "<", run: () => act.press("<") }] },
c.note && key(act, "Change its form", "f", { sub: "inline · margin · inset" }),
key(act, "Open everything below", "o"),
key(act, "Collapse everything", "O"),
!fixed && key(act, "Lock", "p", { checked: c.locked, sub: "the model will not rewrite it" }),
!c.library && key(act, "Show only this", "z", { sub: "hoist it: h or Esc at its top steps out" }),
SEP,
!fixed && key(act, "Delete", "D", { sub: "u undoes" }),
]);
}
/** A document's own head: the node's items, and the document's. */
export function pageEntries(c: NodeCtx, act: Act): Entry[] {
return tidy([
...nodeEntries(c, act),
SEP,
c.doc && { t: "item", label: "Save a copy", keyText: "/duplicate", run: () => act.command("/duplicate") },
c.doc && { t: "item", label: "Export as .md", keyText: "/export", run: () => act.command("/export") },
]);
}
// ---- a pane ----
export interface PaneCtx {
/** A node's pane: its node; none for an article's. */
node?: NodeCtx;
/** An article's pane: its title. */
article?: string;
pinned: boolean;
}
export function paneEntries(c: PaneCtx, act: Act): Entry[] {
const own = c.node ? (c.node.doc || c.node.library ? pageEntries(c.node, act) : nodeEntries(c.node, act)) : [head(c.article ?? "Wikipedia"), key(act, "Open on wikipedia.org", "W")];
return tidy([
...own,
SEP,
key(act, "Pin this pane", "P", { checked: c.pinned, sub: "it stays when what opened it closes" }),
key(act, "Close this pane", "q", { sub: "with what was opened from it" }),
key(act, "Show as one column", "v"),
]);
}
/** A row of an article (a section, a sense): open it. */
export function articleRowEntries(title: string, panes: boolean, act: Act): Entry[] {
return tidy([
head(title),
key(act, panes ? "Open beside" : "Open", "Enter"),
panes && key(act, "Open in place", "Enter", { keyText: "⇧⏎", shift: true, sub: "instead of the pane there" }),
key(act, "Open on wikipedia.org", "W"),
]);
}
// ---- the top bar's menu ----
export interface TopCtx {
view: "auto" | "column" | "panes";
autolink: "suggest" | "on" | "off";
auto: boolean;
speculate: boolean;
curves: boolean;
panes: boolean;
/** A document is open (its links can be looked for and reviewed). */
doc: boolean;
canRedo: boolean;
}
export function topEntries(c: TopCtx, act: Act): Entry[] {
const view = (v: TopCtx["view"]): Choice => ({ label: v, on: c.view === v, run: () => act.command(`/view ${v}`) });
const auto = (v: TopCtx["autolink"], label: string): Choice => ({ label, on: c.autolink === v, run: () => act.command(`/autolink ${v}`) });
const setting = (label: string, name: string, on: boolean, sub?: string): Item => ({ t: "item", label, sub, keyText: `/${name}`, checked: on, run: () => act.command(`/${name} ${on ? "off" : "on"}`) });
return tidy([
key(act, "Documents…", "m"),
key(act, "Jump to a section…", "/"),
key(act, "History and branches", "g"),
SEP,
key(act, "Undo", "u"),
key(act, "Redo", "U", { disabled: !c.canRedo }),
SEP,
c.doc && key(act, "Review suggested links", "S"),
c.doc && { t: "item", label: "Find links in this document", keyText: "/linkdoc", run: () => act.command("/linkdoc") },
SEP,
{ t: "choices", label: "Layout", options: [view("auto"), view("column"), view("panes")] },
{ t: "choices", label: "Links found", options: [auto("suggest", "suggest"), auto("on", "link sure"), auto("off", "off")] },
setting("Reconcile after edits", "auto", c.auto),
setting("Write ahead while reading", "speculate", c.speculate),
c.panes && setting("Curves between panes", "curves", c.curves),
SEP,
key(act, "Command line…", ":"),
key(act, "Keys and help", "?"),
]);
}
/** The page's own `Act`: keys through the key handler, commands through the command bar's handler. */
export function pageAct(hooks: { command(text: string): void; prompt(prefill: string): void }): Act {
return {
press,
command: hooks.command,
prompt: hooks.prompt,
copy(text) {
if (navigator.clipboard) navigator.clipboard.writeText(text).catch(() => fallbackCopy(text));
else fallbackCopy(text);
},
};
}
function fallbackCopy(text: string) {
const t = document.createElement("textarea");
t.value = text;
t.style.position = "fixed";
t.style.opacity = "0";
document.body.appendChild(t);
t.select();
try {
document.execCommand("copy");
} finally {
t.remove();
}
}
+9
View File
@@ -0,0 +1,9 @@
/**
* The one way a mouse control acts: it presses the key it names. A synthetic keydown goes to the
* window, where the page's key handler (keys.ts `handleKey`, listened for by App.tsx) takes it as
* it takes a real one, so a button, a menu item or the selection bar does exactly what its key does
* and no action has a second implementation.
*/
export function press(key: string, shift = false) {
window.dispatchEvent(new KeyboardEvent("keydown", { key, shiftKey: shift, bubbles: true, cancelable: true }));
}
+145
View File
@@ -0,0 +1,145 @@
/** What the mouse offers (src/ui/actions.ts): every item does what its key does, and the bar, the ⋯ menus and the right-click menu are built from one place. */
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { articleRowEntries, barItems, nodeEntries, pageEntries, paneEntries, selectionEntries, tidy, topEntries, type Act, type Entry, type Item, type NodeCtx, type SelCtx, type TopCtx } from "../src/ui/actions";
/** An Act that records what was asked of it. */
function recorder() {
const calls: string[] = [];
const act: Act = {
press: (k, shift) => void calls.push(`press ${shift ? "S-" : ""}${k}`),
command: (t) => void calls.push(`command ${t}`),
prompt: (p) => void calls.push(`prompt ${p}`),
copy: (t) => void calls.push(`copy ${t}`),
};
return { act, calls };
}
const items = (es: Entry[]): Item[] => es.filter((e): e is Item => e.t === "item");
const labels = (es: Entry[]) => es.map((e) => (e.t === "item" ? e.label : e.t === "head" ? `# ${e.text}` : e.t === "choices" ? `[${e.label}: ${e.options.map((o) => o.label).join(" ")}]` : "--"));
const find = (es: Entry[], label: string) => items(es).find((i) => i.label === label)!;
const node = (more: Partial<NodeCtx> = {}): NodeCtx => ({ title: "Training", text: "Training\n\nIt is trained.", note: false, locked: false, target: false, library: false, doc: false, generating: true, ...more });
const sel = (more: Partial<SelCtx> = {}): SelCtx => ({ text: "a probability for each possible next piece", article: false, panes: false, ...more });
const top = (more: Partial<TopCtx> = {}): TopCtx => ({ view: "auto", autolink: "suggest", auto: true, speculate: false, curves: true, panes: false, doc: true, canRedo: false, ...more });
/** Every key the page's handler takes, read from keys.ts: an item's key must be one of them. */
const handled = new Set([...readFileSync(new URL("../src/ui/keys.ts", import.meta.url), "utf8").matchAll(/case "([^"]+)":/g)].map((m) => m[1]));
describe("actions", () => {
it("every item with a key runs by pressing exactly that key, which the key handler takes", () => {
const { act, calls } = recorder();
const all = [
...barItems(sel(), act).flat(),
...items(selectionEntries(sel({ link: "wiki", note: true, suggestion: "Hoyle state", related: [{ title: "Nodes" }], panes: true }), act)),
...items(nodeEntries(node({ stale: "parent", target: true, note: true }), act)),
...items(pageEntries(node({ doc: true }), act)),
...items(paneEntries({ node: node(), pinned: false }, act)),
...items(paneEntries({ article: "Octopus", pinned: true }, act)),
...items(articleRowEntries("Octopus", true, act)),
...items(topEntries(top({ canRedo: true }), act)),
];
const keyed = all.filter((i) => i.key);
expect(keyed.length).toBeGreaterThan(50);
for (const it of keyed) {
calls.length = 0;
it.run();
expect(calls).toEqual([`press ${it.shift ? "S-" : ""}${it.key}`]);
expect(handled.has(it.key!) || it.key === "Escape", `${it.label}: ${it.key}`).toBe(true);
}
});
it("the bar offers the lenses and linking, each with its key; in an article, no linking", () => {
const { act } = recorder();
expect(barItems(sel(), act).map((g) => g.map((i) => `${i.short} ${i.key}`))).toEqual([["expand e", "define d", "why y", "example x", "challenge c", "ask… :"], ["link… w"]]);
expect(barItems(sel({ article: true }), act).flat().map((i) => i.key)).toEqual(["e", "d", "y", "x", "c", ":"]);
});
it("the selection menu puts Copy first, then what the words carry, then the lenses, linking and Related", () => {
const { act, calls } = recorder();
const plain = selectionEntries(sel({ related: [{ title: "Expansion by depth", doc: "Infinispand" }, { title: "Nodes" }] }), act);
expect(labels(plain)).toEqual([
"# “a probability for each possible next piece”",
"Copy",
"--",
"Expand",
"Define",
"Why?",
"An example",
"An objection",
"Ask your own question…",
"--",
"Link to…",
"# Link to a related section",
"Expansion by depth",
"Nodes",
"--",
"[Select: less more]",
]);
find(plain, "Copy").run();
expect(calls).toEqual(["copy a probability for each possible next piece"]);
// A Wikipedia link on the words, in panes: open beside or in place, on wikipedia.org, retarget, remove.
const link = selectionEntries(sel({ link: "wiki", panes: true }), act);
expect(labels(link).slice(1, 8)).toEqual(["Copy", "--", "Open the link beside", "Open it in place", "Open on wikipedia.org", "Retarget…", "Remove the link"]);
expect(find(link, "Open it in place")).toMatchObject({ key: "Enter", shift: true, keyText: "⇧⏎" });
expect(labels(link)).not.toContain("Link to…");
// In an article: no linking by hand, no Related.
const art = selectionEntries(sel({ article: true, related: [{ title: "Nodes" }] }), act);
expect(labels(art)).not.toContain("Link to…");
expect(labels(art)).not.toContain("# Link to a related section");
// A suggestion on the words: link it or decline it.
expect(items(selectionEntries(sel({ suggestion: "Hoyle state" }), act)).map((i) => i.key)).toEqual(expect.arrayContaining(["y", "n"]));
});
it("a node's menu: its remedies first when stale, Lock checked when locked, and nothing a library cannot do", () => {
const { act, calls } = recorder();
const stale = nodeEntries(node({ stale: "parent" }), act);
expect(labels(stale).slice(0, 3)).toEqual(["# Training · its parent changed", "Bring it in line", "Accept as it stands"]);
const locked = nodeEntries(node({ stale: "parent", locked: true }), act);
expect(find(locked, "Bring it in line").disabled).toBe(true);
expect(find(locked, "Lock")).toMatchObject({ key: "p", checked: true });
expect(find(nodeEntries(node(), act), "Lock").checked).toBe(false);
expect(labels(nodeEntries(node(), act)).join("|")).not.toMatch(/pin/i);
const lib = labels(nodeEntries(node({ library: true }), act));
for (const l of ["Delete", "Lock", "Add a section after", "[Move: up down in out]", "Show only this"]) expect(lib).not.toContain(l);
expect(lib).toContain("Add a document");
expect(labels(nodeEntries(node({ note: true }), act))).toContain("Change its form");
find(nodeEntries(node(), act), "Research on the web…").run();
expect(calls).toEqual(["prompt /research "]);
expect(labels(nodeEntries(node({ generating: false }), act))).not.toContain("Research on the web…");
});
it("a page adds the document's own items; a pane adds pin, close and the column", () => {
const { act, calls } = recorder();
const page = pageEntries(node({ doc: true }), act);
expect(labels(page).slice(-2)).toEqual(["Save a copy", "Export as .md"]);
find(page, "Export as .md").run();
expect(calls).toEqual(["command /export"]);
const pane = paneEntries({ node: node(), pinned: true }, act);
expect(labels(pane).slice(-3)).toEqual(["Pin this pane", "Close this pane", "Show as one column"]);
expect(find(pane, "Pin this pane").checked).toBe(true);
expect(labels(paneEntries({ article: "Octopus", pinned: false }, act)).slice(0, 2)).toEqual(["# Octopus", "Open on wikipedia.org"]);
});
it("the top menu: documents, history, undo and redo, links, the layout and settings as commands", () => {
const { act, calls } = recorder();
const es = topEntries(top(), act);
expect(find(es, "Redo").disabled).toBe(true);
expect(find(topEntries(top({ canRedo: true }), act), "Redo").disabled).toBeFalsy();
const layout = es.find((e) => e.t === "choices" && e.label === "Layout") as Extract<Entry, { t: "choices" }>;
expect(layout.options.map((o) => `${o.label}${o.on ? "*" : ""}`)).toEqual(["auto*", "column", "panes"]);
layout.options[2].run();
find(es, "Reconcile after edits").run();
find(es, "Write ahead while reading").run();
expect(calls).toEqual(["command /view panes", "command /auto off", "command /speculate on"]);
expect(labels(es)).not.toContain("Curves between panes");
expect(labels(topEntries(top({ panes: true }), act))).toContain("Curves between panes");
expect(labels(topEntries(top({ doc: false }), act))).not.toContain("Review suggested links");
});
it("tidy leaves no separator at an end or next to another", () => {
const s = { t: "sep" } as const;
const h = { t: "head", text: "x" } as const;
expect(tidy([s, h, s, false, s, null, h, s, ""]).map((e) => e.t)).toEqual(["head", "sep", "head"]);
});
});