Use one menu lifecycle and shared menu rows in the editors

Phase 4c. The Markdown, code, Read, and image menus open through
showActionMenu. It closes a menu on an outside press, an outside scroll,
a resize, and window blur. A host surface now gives its own focus
return, so four copies of the listener code are gone.

- menuItems.ts builds Undo, Redo, the clipboard rows, and the search
  row. The Markdown, code, Read, table cell, and table range menus use
  it. The Markdown and table menus now show the shortcuts for Cut,
  Copy, Paste, and Select all, as the other menus did.
- writerSearch.ts is now editorSearch.ts, because it serves Write and
  Source.
- Plugins still get only close() from api.ui.showActionMenu. The SDK
  menu types do not change.
- The table range menu and the native spelling menu keep their own
  lifecycle, because their open state drives table editing and the
  native spelling protocol.
- docs/ui-design.md names the shared rows and the search modules. The
  menu inventory has the new count for markdownMenu.ts.

pnpm check, pnpm test (341 of 341), and the full smoke suite pass, except
tables/formulas, which failed one time under load and passed on retry.
This commit is contained in:
Knotty Wyvern
2026-10-28 11:09:09 -07:00
parent 724402729e
commit 6cd9195370
17 changed files with 152 additions and 135 deletions
+21 -34
View File
@@ -1,5 +1,7 @@
import { tr } from "../i18n/index.ts";
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
import type { ActionMenuItem } from "../ui/actionMenu";
import { showActionMenu, type MenuHandle } from "../ui/managedActionMenu";
import { clipboardItems, historyItems, searchItem } from "../ui/menuItems";
import { invoke, isTauri } from "@tauri-apps/api/core";
import { wordAt } from "./spellingWord";
import { pickLinkDocument } from "./documentPicker";
@@ -25,18 +27,14 @@ export type MarkdownMenuEditor = {
// A shared controller keeps menus, async selection guards, and clipboard behavior
// identical in the writing editor and the source editor.
export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextActions, report: (message: string) => void, linkActions: () => DocumentLinkActions = () => ({})) {
let root: HTMLElement | undefined, destroyed = false;
let menu: MenuHandle | undefined, destroyed = false;
const pending = new AbortController();
const restore = () => { if (!destroyed) editor.focus(); };
function close(focus = true) {
root?.remove(); root = undefined;
if (focus && !destroyed) editor.focus();
menu?.close(); menu = undefined;
if (focus) restore();
}
const outside = (event: MouseEvent) => { if (root && !root.contains(event.target as Node)) close(false); };
const scroll = (event: Event) => { if (root && event.target instanceof Node && !root.contains(event.target)) close(false); };
const resize = () => close(false);
document.addEventListener("mousedown", outside, true);
document.addEventListener("scroll", scroll, true);
window.addEventListener("resize", resize);
const show = (x: number, y: number, items: ActionMenuItem[]) => menu = showActionMenu({ x, y, items, label: tr("Markdown text actions") }, undefined, restore);
function open(x: number, y: number, spellingOffset?: number, linkOffset?: number) {
close(false);
@@ -89,15 +87,11 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc
if (!valid()) return;
editor.select(selectedLink.targetFrom, selectedLink.targetTo); editor.focus();
}), { separator: true as const }] : []),
...(editor.undo ? [
{ label: tr("Undo"), icon: "undo" as const, shortcut: "Ctrl+Z", disabled: !editor.canUndo?.(), run: () => { close(); editor.undo?.(); } },
{ label: tr("Redo"), icon: "redo" as const, shortcut: "Ctrl+Shift+Z", disabled: !editor.canRedo?.(), run: () => { close(); editor.redo?.(); } },
{ separator: true as const },
] : []),
...(editor.undo ? historyItems({ canUndo: !!editor.canUndo?.(), canRedo: !!editor.canRedo?.(), undo: () => editor.undo?.(), redo: () => editor.redo?.() }) : []),
{ label: tr("Add link"), icon: "link", run: () => link(false) },
{ label: tr("Add external link"), icon: "external", run: () => link(true) },
{ separator: true },
{ label: text ? tr("Search for “{text}”", { text: text.length > 32 ? text.slice(0, 32) + "…" : text }) : tr("Search selection"), icon: "search", disabled: !text || !actions.onSearch, run: () => { close(); actions.onSearch?.(text); } },
searchItem(text, actions.onSearch),
{ label: tr("Extract current selection…"), icon: "extract", disabled: !text || !actions.onExtract, run: () => void request(async () => {
const target = await actions.onExtract?.(text, text, valid);
if (target) apply(replacement(selection, `[[${target}|${text.replace(/[\[\]|]/g, "").replace(/\s+/g, " ").trim()}]]`));
@@ -117,36 +111,29 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc
{ separator: true }, insert(tr("Code block"), "code", "code"), insert(tr("Math block"), "math", "math"),
] },
{ separator: true },
{ label: tr("Cut"), icon: "cut", disabled: !text, run: () => clipboard("cut") },
{ label: tr("Copy"), icon: "copy", disabled: !text, run: () => clipboard("copy") },
{ label: tr("Paste"), icon: "paste", run: () => clipboard("paste") },
{ label: tr("Paste as plain text"), icon: "paste-text", run: () => clipboard("plain") },
{ label: tr("Select all"), icon: "select", run: () => { close(); editor.selectAll(); } },
...clipboardItems({
selected: !!text, cut: () => clipboard("cut"), copy: () => clipboard("copy"), paste: () => clipboard("paste"),
pastePlain: () => clipboard("plain"), selectAll: () => editor.selectAll(),
}),
];
root = actionMenu(x, y, items, close, tr("Markdown text actions"));
const opened = root;
const opened = show(x, y, items);
const word = spellingOffset === undefined ? null : wordAt(source, spellingOffset);
if (word && isTauri()) {
const languages = [...new Set([document.documentElement.lang, ...navigator.languages].filter(Boolean))];
void invoke<{ language: string; words: string[]; misspelled: boolean }>("spelling_suggestions", { word: word.word, languages }).then(result => {
if (!result.misspelled || root !== opened || !valid()) return;
if (!result.misspelled || menu !== opened || !opened.open || !valid()) return;
const suggestions: ActionMenuItem[] = result.words.map(value => ({ label: value, run: () => apply(replacement(word, value)) }));
if (!suggestions.length) suggestions.push({ label: tr("No spelling suggestions"), disabled: true });
suggestions.push({ label: tr("Add to dictionary"), icon: "book", run: () => {
close();
void invoke("spelling_suggestions", { word: word.word, languages: [result.language], add: true }).catch(() => report("Could not add the word to the dictionary."));
} });
const focusedLabel = opened.contains(document.activeElement) ? document.activeElement?.querySelector(".action-label")?.textContent : undefined;
opened.remove();
root = actionMenu(x, y, [...suggestions, { separator: true }, ...items], close, tr("Markdown text actions"));
if (focusedLabel) [...root.querySelectorAll<HTMLButtonElement>(":scope > button")].find(button => button.querySelector(".action-label")?.textContent === focusedLabel)?.focus();
const focusedLabel = opened.element.contains(document.activeElement) ? document.activeElement?.querySelector(".action-label")?.textContent : undefined;
opened.close();
const next = show(x, y, [...suggestions, { separator: true }, ...items]);
if (focusedLabel) [...next.element.querySelectorAll<HTMLButtonElement>(":scope > button")].find(button => button.querySelector(".action-label")?.textContent === focusedLabel)?.focus();
}).catch(() => { /* Editing actions remain available without spelling suggestions. */ });
}
}
return { open, close, destroy() {
destroyed = true; pending.abort(); close(false);
document.removeEventListener("mousedown", outside, true);
document.removeEventListener("scroll", scroll, true);
window.removeEventListener("resize", resize);
} };
return { open, close, destroy() { destroyed = true; pending.abort(); close(false); } };
}