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:
@@ -54,7 +54,7 @@
|
||||
},
|
||||
"RuneStone/src/lib/editor/markdownMenu.ts": {
|
||||
"counts": {
|
||||
"action": 2
|
||||
"action": 1
|
||||
},
|
||||
"design": "Shared action menu",
|
||||
"check": "tests/smoke/menus/consistency.smoke.mjs; tests/smoke/links/linkEditing.smoke.mjs; tests/smoke/editor/surfaces.smoke.mjs"
|
||||
|
||||
+4
-2
@@ -27,9 +27,10 @@ Do not copy feature-specific colors into a shared control.
|
||||
| Icons | `src/lib/ui/Icon.svelte` and `src/lib/ui/actionIcons.ts` (one 24-pixel grid and stroke weight) |
|
||||
| Tooltip on a DOM control | `attachTooltip` in `src/lib/ui/tooltip.ts` |
|
||||
| Action menu | `src/lib/ui/actionMenu.ts`. Svelte callers can use `src/lib/layout/ContextMenu.svelte`. |
|
||||
| Menu with dismissal and focus return | `showActionMenu` in `src/lib/ui/managedActionMenu.ts`. Plugins call it as `api.ui.showActionMenu`. |
|
||||
| Menu with dismissal and focus return | `showActionMenu` in `src/lib/ui/managedActionMenu.ts`. Editor surfaces give their own focus return. Plugins call it as `api.ui.showActionMenu`. |
|
||||
| Undo, Redo, clipboard, and search rows | `src/lib/ui/menuItems.ts` |
|
||||
| Menu and picker presentation | `src/lib/ui/menu.css` |
|
||||
| Find | `src/lib/editor/FindPanel.svelte` and `src/lib/ui/find.css` |
|
||||
| Find | `src/lib/editor/FindPanel.svelte` and `src/lib/ui/find.css`. Write and Source search with `editorSearch.ts`. Read and plugin views search with `readingSearch.ts`. |
|
||||
| Dimensions and colors | `src/lib/theme/tokens.css` |
|
||||
|
||||
| Token | Default | Use |
|
||||
@@ -100,6 +101,7 @@ Use one menu design for context menus, action menus, and their submenus in the h
|
||||
- Give a recognizable action an icon and a short label. Use the same icon for the same function in every menu.
|
||||
- A menu with only text choices omits the icon column. A mixed menu reserves the icon column on every row.
|
||||
- Shortcut text and submenu arrows use separate trailing columns.
|
||||
- A common text action has the same label, icon, and shortcut in every menu. Build Undo, Redo, the clipboard rows, and the search row with `menuItems.ts`.
|
||||
- Use inset separators between related groups.
|
||||
- Enabled rows share one hover fill and one keyboard focus fill.
|
||||
- Disabled rows stay readable. Keyboard navigation skips them, and they do not run.
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
import { foldedRanges, indentUnit, unfoldEffect } from "@codemirror/language";
|
||||
import { closeSearchPanel, findNext, findPrevious, openSearchPanel, searchKeymap } from "@codemirror/search";
|
||||
import { htmlToMarkdown } from "$lib/workspace/htmlToMarkdown";
|
||||
import { writerSearch } from "./writerSearch";
|
||||
import { editorSearch } from "./editorSearch";
|
||||
import type { Chrome, OpenBuffer } from "$lib/workspace/types";
|
||||
import { workspaceReadDataUrl, workspaceReveal } from "$lib/workspace/api";
|
||||
import { linkCandidates } from "$lib/workspace/markdownLinks";
|
||||
@@ -206,7 +206,7 @@
|
||||
modeConfig.of(modeExtensions(shown)),
|
||||
history(), drawSelection(), indentUnit.of(" "), EditorState.tabSize.of(4),
|
||||
EditorView.theme({}, { dark: true }),
|
||||
writerSearch,
|
||||
editorSearch,
|
||||
imageDrops,
|
||||
keymap.of([...searchKeymap, ...historyKeymap, ...defaultKeymap]),
|
||||
EditorView.updateListener.of(update => {
|
||||
|
||||
+14
-28
@@ -3,21 +3,17 @@ import { EditorSelection } from "@codemirror/state";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { redo, redoDepth, undo, undoDepth } from "@codemirror/commands";
|
||||
import { selectSelectionMatches } from "@codemirror/search";
|
||||
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
|
||||
import { showActionMenu, type MenuHandle } from "../ui/managedActionMenu";
|
||||
import { clipboardItems, historyItems } from "../ui/menuItems";
|
||||
|
||||
/** Keep source editing commands in the host's shared action menu. */
|
||||
export function codeMenu(view: EditorView, report: (message: string) => void) {
|
||||
let root: HTMLElement | undefined;
|
||||
let menu: MenuHandle | undefined;
|
||||
const restore = () => view.focus();
|
||||
function close(focus = true) {
|
||||
root?.remove(); root = undefined;
|
||||
if (focus) view.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);
|
||||
function open(x: number, y: number) {
|
||||
close(false);
|
||||
const state = view.state, main = state.selection.main;
|
||||
@@ -30,35 +26,25 @@ export function codeMenu(view: EditorView, report: (message: string) => void) {
|
||||
view.focus();
|
||||
};
|
||||
const clipboard = async (kind: "cut" | "copy" | "paste") => {
|
||||
close();
|
||||
try {
|
||||
if (kind === "paste") replace(await navigator.clipboard.readText());
|
||||
else { await navigator.clipboard.writeText(selected); if (kind === "cut") replace(""); }
|
||||
} catch { report("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste."); }
|
||||
};
|
||||
const changeAll = () => {
|
||||
close();
|
||||
if (!valid() || !word) return;
|
||||
if (main.empty) view.dispatch({ selection: EditorSelection.single(word.from, word.to) });
|
||||
selectSelectionMatches(view);
|
||||
};
|
||||
const items: ActionMenuItem[] = [
|
||||
{ label: tr("Undo"), icon: "undo", shortcut: "Ctrl+Z", disabled: !undoDepth(state), run: () => { close(); undo(view); } },
|
||||
{ label: tr("Redo"), icon: "redo", shortcut: "Ctrl+Shift+Z", disabled: !redoDepth(state), run: () => { close(); redo(view); } },
|
||||
{ separator: true },
|
||||
menu = showActionMenu({ x, y, label: tr("Code text actions"), items: [
|
||||
...historyItems({ canUndo: undoDepth(state) > 0, canRedo: redoDepth(state) > 0, undo: () => undo(view), redo: () => redo(view) }),
|
||||
{ label: tr("Change all occurrences"), icon: "select", shortcut: "Ctrl+Shift+L", disabled: !word || word.empty, run: changeAll },
|
||||
{ separator: true },
|
||||
{ label: tr("Cut"), icon: "cut", shortcut: "Ctrl+X", disabled: !selected, run: () => void clipboard("cut") },
|
||||
{ label: tr("Copy"), icon: "copy", shortcut: "Ctrl+C", disabled: !selected, run: () => void clipboard("copy") },
|
||||
{ label: tr("Paste"), icon: "paste", shortcut: "Ctrl+V", run: () => void clipboard("paste") },
|
||||
{ label: tr("Select all"), icon: "select", shortcut: "Ctrl+A", run: () => { close(); view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } }); } },
|
||||
];
|
||||
root = actionMenu(x, y, items, close, tr("Code text actions"));
|
||||
...clipboardItems({
|
||||
selected: !!selected, cut: () => void clipboard("cut"), copy: () => void clipboard("copy"), paste: () => void clipboard("paste"),
|
||||
selectAll: () => view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } }),
|
||||
}),
|
||||
] }, undefined, restore);
|
||||
}
|
||||
return { open, close, destroy() {
|
||||
close(false);
|
||||
document.removeEventListener("mousedown", outside, true);
|
||||
document.removeEventListener("scroll", scroll, true);
|
||||
window.removeEventListener("resize", resize);
|
||||
} };
|
||||
return { open, close, destroy() { close(false); } };
|
||||
}
|
||||
|
||||
@@ -3,11 +3,12 @@ import { runScopeHandlers } from "@codemirror/view";
|
||||
import { closeSearchPanel, findNext, findPrevious, getSearchQuery, replaceAll, replaceNext, search, selectMatches, setSearchQuery, type SearchQuery } from "@codemirror/search";
|
||||
import FindPanel from "./FindPanel.svelte";
|
||||
|
||||
export const writerSearch = search({
|
||||
/** CodeMirror search for Write and Source, shown in the shared Find panel. */
|
||||
export const editorSearch = search({
|
||||
top: true,
|
||||
createPanel(view) {
|
||||
const dom = document.createElement("div");
|
||||
dom.className = "rs-writer-search";
|
||||
dom.className = "rs-editor-search";
|
||||
let panel: { sync(query: SearchQuery): void } | undefined;
|
||||
return {
|
||||
dom,
|
||||
@@ -2,7 +2,8 @@ import { tr } from '../i18n/index.ts';
|
||||
import { actionIcon, type ActionIcon } from "../ui/actionIcons";
|
||||
import { attachTooltip } from "../ui/tooltip";
|
||||
const tooltipCleanups = new WeakMap<HTMLElement, () => void>();
|
||||
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
|
||||
import type { ActionMenuItem } from "../ui/actionMenu";
|
||||
import { showActionMenu, type MenuHandle } from "../ui/managedActionMenu";
|
||||
|
||||
export type ImageActions = {
|
||||
edit?: () => void;
|
||||
@@ -107,9 +108,10 @@ export function imageControls(root: HTMLElement, actions: ImageActions = {}, mea
|
||||
if (actions.edit) toolbar.append(button(actions.editing ? tr("Hide image source") : tr("Edit image source"), "code", actions.editing && actions.done ? actions.done : actions.edit));
|
||||
frame.append(toolbar);
|
||||
cleanup.push(() => toolbar.querySelectorAll<HTMLButtonElement>("button").forEach(button => tooltipCleanups.get(button)?.()));
|
||||
let menu: HTMLElement | undefined;
|
||||
let menu: MenuHandle | undefined;
|
||||
let openingMenu = false;
|
||||
function closeMenu(focus = true) { menu?.remove(); menu = undefined; if (focus && frame.isConnected) frame.focus({ preventScroll: true }); }
|
||||
const restore = () => { if (frame.isConnected) frame.focus({ preventScroll: true }); };
|
||||
function closeMenu(focus = true) { menu?.close(); menu = undefined; if (focus) restore(); }
|
||||
async function run(action: () => void | Promise<void>) {
|
||||
closeMenu(false);
|
||||
try { await action(); } catch (error) {
|
||||
@@ -138,7 +140,7 @@ export function imageControls(root: HTMLElement, actions: ImageActions = {}, mea
|
||||
...(actions.reveal && !/^https?:/i.test(image.dataset.mdSrc || "") ? [{ label: tr("Show in Explorer"), icon: "external" as const, run: () => void run(() => actions.reveal!(image)) }] : []),
|
||||
];
|
||||
openingMenu = true;
|
||||
try { menu = actionMenu(x, y, items, closeMenu, tr("Image actions")); }
|
||||
try { menu = showActionMenu({ x, y, items, label: tr("Image actions") }, undefined, restore); }
|
||||
finally { openingMenu = false; }
|
||||
}
|
||||
frame.addEventListener("mousedown", event => { if (!(event.target as Element).closest("button")) { event.preventDefault(); event.stopPropagation(); select(); } });
|
||||
@@ -155,15 +157,12 @@ export function imageControls(root: HTMLElement, actions: ImageActions = {}, mea
|
||||
});
|
||||
const outside = (event: Event) => {
|
||||
if (openingMenu) return;
|
||||
if (event.target instanceof Node && !frame.contains(event.target) && !menu?.contains(event.target)) { closeMenu(false); frame.classList.remove("is-selected"); }
|
||||
if (event.target instanceof Node && !frame.contains(event.target) && !menu?.element.contains(event.target)) { closeMenu(false); frame.classList.remove("is-selected"); }
|
||||
};
|
||||
const dismiss = () => closeMenu(false);
|
||||
const scroll = (event: Event) => { if (menu && event.target instanceof Node && !menu.contains(event.target)) closeMenu(false); };
|
||||
// The shared menu closes itself. This handler also clears the image selection.
|
||||
document.addEventListener("mousedown", outside, true);
|
||||
document.addEventListener("focusin", outside, true);
|
||||
window.addEventListener("resize", dismiss);
|
||||
document.addEventListener("scroll", scroll, true);
|
||||
cleanup.push(() => { closeMenu(false); document.removeEventListener("mousedown", outside, true); document.removeEventListener("focusin", outside, true); window.removeEventListener("resize", dismiss); document.removeEventListener("scroll", scroll, true); });
|
||||
cleanup.push(() => { closeMenu(false); document.removeEventListener("mousedown", outside, true); document.removeEventListener("focusin", outside, true); });
|
||||
if (measure) {
|
||||
image.addEventListener("load", measure);
|
||||
image.addEventListener("error", measure);
|
||||
|
||||
@@ -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); } };
|
||||
}
|
||||
|
||||
@@ -1,20 +1,18 @@
|
||||
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, searchItem } from "../ui/menuItems";
|
||||
import { linkMenuItems, type DocumentLinkActions } from "./linkMenu";
|
||||
|
||||
/** Preserve the DOM range while the shared menu owns keyboard focus. */
|
||||
export function readingMenu(host: HTMLElement, actions: DocumentLinkActions, search: ((text: string) => void) | undefined, report: (message: string) => void) {
|
||||
let root: HTMLElement | undefined;
|
||||
let menu: MenuHandle | undefined;
|
||||
let previousFocus: HTMLElement | null = null;
|
||||
let range: Range | undefined;
|
||||
function close(restore = true) {
|
||||
if (!root) return;
|
||||
root.remove(); root = undefined;
|
||||
if (restore) {
|
||||
(previousFocus?.isConnected ? previousFocus : host).focus({ preventScroll: true });
|
||||
if (range?.startContainer.isConnected && range.endContainer.isConnected) {
|
||||
const selection = window.getSelection(); selection?.removeAllRanges(); selection?.addRange(range);
|
||||
}
|
||||
function restore() {
|
||||
(previousFocus?.isConnected ? previousFocus : host).focus({ preventScroll: true });
|
||||
if (range?.startContainer.isConnected && range.endContainer.isConnected) {
|
||||
const selection = window.getSelection(); selection?.removeAllRanges(); selection?.addRange(range);
|
||||
}
|
||||
}
|
||||
function open(event: MouseEvent | KeyboardEvent) {
|
||||
@@ -28,32 +26,25 @@ export function readingMenu(host: HTMLElement, actions: DocumentLinkActions, sea
|
||||
const target = event.target instanceof Element ? event.target : null;
|
||||
const anchor = target?.closest("a") ?? (keyboard && selection?.anchorNode ? (selection.anchorNode.parentElement?.closest("a") ?? null) : null);
|
||||
if (!text && !anchor) return;
|
||||
event.preventDefault(); event.stopPropagation(); close(false);
|
||||
event.preventDefault(); event.stopPropagation(); menu?.close();
|
||||
previousFocus = document.activeElement instanceof HTMLElement && host.contains(document.activeElement) ? document.activeElement : host;
|
||||
const items: ActionMenuItem[] = [];
|
||||
if (text) items.push(
|
||||
{ label: tr("Copy"), icon: "copy", shortcut: "Ctrl+C", run: () => { close(); void navigator.clipboard.writeText(text).catch(() => report(tr("Clipboard unavailable. Use Ctrl+C to copy."))); } },
|
||||
{ label: tr("Search for “{text}”", { text: text.length > 32 ? text.slice(0, 32) + "…" : text }), icon: "search", disabled: !search, run: () => { close(false); search?.(text); } },
|
||||
...clipboardItems({ selected: true, copy: () => void navigator.clipboard.writeText(text).catch(() => report(tr("Clipboard unavailable. Use Ctrl+C to copy."))) }),
|
||||
searchItem(text, search),
|
||||
);
|
||||
if (anchor) {
|
||||
if (items.length) items.push({ separator: true });
|
||||
if (anchor.hasAttribute("data-footnote-link")) items.push({ label: tr("Open link"), icon: "link", run: () => { close(false); (anchor as HTMLElement).click(); } });
|
||||
else items.push(...linkMenuItems({ kind: anchor.getAttribute("data-kind") === "wiki" ? "wiki" : "md", target: anchor.getAttribute("href") ?? "" }, actions, () => close(false), report));
|
||||
if (anchor.hasAttribute("data-footnote-link")) items.push({ label: tr("Open link"), icon: "link", run: () => (anchor as HTMLElement).click() });
|
||||
else items.push(...linkMenuItems({ kind: anchor.getAttribute("data-kind") === "wiki" ? "wiki" : "md", target: anchor.getAttribute("href") ?? "" }, actions, () => menu?.close(), report));
|
||||
}
|
||||
const rect = keyboard ? (range?.getBoundingClientRect() ?? anchor?.getBoundingClientRect() ?? host.getBoundingClientRect()) : null;
|
||||
root = actionMenu(rect?.left ?? (event as MouseEvent).clientX, rect?.bottom ?? (event as MouseEvent).clientY, items, close, tr("Reading actions"));
|
||||
menu = showActionMenu({ x: rect?.left ?? (event as MouseEvent).clientX, y: rect?.bottom ?? (event as MouseEvent).clientY, items, label: tr("Reading actions") }, undefined, restore);
|
||||
}
|
||||
const outside = (event: Event) => { if (root && event.target instanceof Node && !root.contains(event.target)) close(false); };
|
||||
const resize = () => close(false);
|
||||
host.addEventListener("contextmenu", open);
|
||||
host.addEventListener("keydown", open);
|
||||
document.addEventListener("mousedown", outside, true);
|
||||
document.addEventListener("scroll", outside, true);
|
||||
window.addEventListener("resize", resize);
|
||||
return () => {
|
||||
close(false);
|
||||
menu?.close();
|
||||
host.removeEventListener("contextmenu", open); host.removeEventListener("keydown", open);
|
||||
document.removeEventListener("mousedown", outside, true); document.removeEventListener("scroll", outside, true);
|
||||
window.removeEventListener("resize", resize);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { getMarkRange, type Editor, type JSONContent } from "@tiptap/core";
|
||||
import { requestText } from "../workspace/dialogs.svelte";
|
||||
import { extractedCellMarkdown } from "./tableCellMarkdown";
|
||||
import type { ActionMenuItem } from "../ui/actionMenu";
|
||||
import { clipboardItems, searchItem } from "../ui/menuItems";
|
||||
import { linkMenuItems, type DocumentLinkActions } from "./linkMenu";
|
||||
import { documentLinkAt } from "./documentLinks";
|
||||
|
||||
@@ -97,7 +98,7 @@ export function tableTextItems(editor: Editor, actions: TableContextActions, clo
|
||||
{ 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 && (value => { close(); actions.onSearch?.(value); })),
|
||||
{ label: tr("Extract current selection…"), icon: "extract", disabled: !text || !actions.onExtract, run: () => void request(async () => {
|
||||
const selected = doc.slice(selection.from, selection.to).content.toJSON() as JSONContent[] | null;
|
||||
const markdown = extractedCellMarkdown(selected || []);
|
||||
@@ -110,11 +111,10 @@ export function tableTextItems(editor: Editor, actions: TableContextActions, clo
|
||||
{ label: tr("Paragraph"), icon: "paragraph", disabled: true, title: tr("Markdown table cells contain inline text") },
|
||||
{ label: tr("Insert"), icon: "insert", disabled: true, title: tr("Use the Row and Column menus to change the table") },
|
||||
{ separator: true },
|
||||
{ label: tr("Cut"), icon: "cut", disabled: selection.empty, run: () => void clipboard("cut") },
|
||||
{ label: tr("Copy"), icon: "copy", disabled: selection.empty, run: () => void clipboard("copy") },
|
||||
{ label: tr("Paste"), icon: "paste", run: () => void clipboard("paste") },
|
||||
{ label: tr("Paste as plain text"), icon: "paste-text", run: () => void clipboard("plain") },
|
||||
{ label: tr("Select all"), icon: "select", run: () => { close(); editor.commands.selectAll(); editor.view.focus(); } },
|
||||
...clipboardItems({
|
||||
selected: !selection.empty, cut: () => void clipboard("cut"), copy: () => void clipboard("copy"), paste: () => void clipboard("paste"),
|
||||
pastePlain: () => void clipboard("plain"), selectAll: () => { close(); editor.commands.selectAll(); editor.view.focus(); },
|
||||
}),
|
||||
];
|
||||
return sourceEditing ? [
|
||||
...(selectedLink ? [...linkMenuItems(selectedLink, actions.linkActions?.() || {}, close, report, editLink), { separator: true as const }] : []),
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { Editor } from "@tiptap/core";
|
||||
import { useSpellingMenu } from "./spellingMenu";
|
||||
import { changeTableStructure, sortTableColumn, type TableAxis, type TableOperation } from "./tableStructure";
|
||||
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
|
||||
import { clipboardItems } from "../ui/menuItems";
|
||||
import { cellFormats, tableTextItems, type TableContextActions } from "./tableCellActions";
|
||||
import { alignTableCells, bounds, copyTableCells, copyTableMarkdown, deleteTableCells, formatTableCells, mapTableCells, pasteTableCells, type CellFormat, type CellPoint, type CellRange } from "./tableSelection";
|
||||
import { renderMarkdownHtml } from "../workspace/noteHtml";
|
||||
@@ -120,7 +121,7 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
|
||||
const items: ActionMenuItem[] = textEditor ? tableTextItems(textEditor, actions, closeMenu, run => {
|
||||
view.dispatch({ annotations: isolateHistory.of("before") }); run(); view.dispatch({ annotations: isolateHistory.of("after") });
|
||||
}, value => { pending = value; }, report, rich.editSource) : [
|
||||
...(["cut", "copy", "paste"] as const).map(action => ({ label: tr(action[0].toUpperCase() + action.slice(1)), icon: action, run: () => void clipboard(action) })),
|
||||
...clipboardItems({ selected: true, cut: () => void clipboard("cut"), copy: () => void clipboard("copy"), paste: () => void clipboard("paste") }),
|
||||
sep,
|
||||
{ label: tr("Format"), icon: "format", children: cellFormats.map(([label, kind]) => ({ label: tr(label), icon: kind, run: () => format(kind) })) },
|
||||
...alignmentItems,
|
||||
|
||||
@@ -87,7 +87,7 @@ export class ExternalSession {
|
||||
return cleanup;
|
||||
},
|
||||
} } : {}),
|
||||
ui: { showActionMenu: options => { this.check(); return showActionMenu(options, this.controller.signal); } },
|
||||
ui: { showActionMenu: options => { this.check(); const menu = showActionMenu(options, this.controller.signal); return { close: () => menu.close() }; } },
|
||||
...(this.services.git ? { git: {
|
||||
status: () => { this.check(); return this.services.git!.status(); },
|
||||
diff: (path: string, staged: boolean) => { this.check(); return this.services.git!.diff(path, staged); },
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import { actionMenu, type ActionMenuItem } from "./actionMenu.ts";
|
||||
|
||||
export type MenuOptions = { x: number; y: number; items: ActionMenuItem[]; label?: string; parent?: HTMLElement };
|
||||
export type MenuHandle = { close(restore?: boolean): void; readonly element: HTMLElement; readonly open: boolean };
|
||||
|
||||
export function showActionMenu(options: MenuOptions, signal?: AbortSignal): { close(): void } {
|
||||
/**
|
||||
* Show the shared action menu. It closes on a press outside it, a scroll outside it, a window resize, and window blur.
|
||||
* A choice and Escape return focus to the element that had focus. A host surface can give `restore` to return focus itself.
|
||||
*/
|
||||
export function showActionMenu(options: MenuOptions, signal?: AbortSignal, restore?: () => void): MenuHandle {
|
||||
const origin = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
||||
// Focus can scroll a trigger before its queued scroll event reaches this menu.
|
||||
const scrollPositions = new Map<EventTarget, [number, number]>();
|
||||
@@ -10,20 +15,24 @@ export function showActionMenu(options: MenuOptions, signal?: AbortSignal): { cl
|
||||
scrollPositions.set(node, [node.scrollLeft, node.scrollTop]);
|
||||
}
|
||||
scrollPositions.set(document, [window.scrollX, window.scrollY]);
|
||||
let root: HTMLElement | undefined;
|
||||
const close = (restore = false) => {
|
||||
root?.remove();
|
||||
let open = true;
|
||||
const close = (back = false) => {
|
||||
if (!open) return;
|
||||
open = false;
|
||||
root.remove();
|
||||
window.removeEventListener("pointerdown", outside, true);
|
||||
window.removeEventListener("resize", dismiss);
|
||||
window.removeEventListener("blur", dismiss);
|
||||
document.removeEventListener("scroll", scroll, true);
|
||||
signal?.removeEventListener("abort", dismiss);
|
||||
if (restore && origin?.isConnected) origin.focus({ preventScroll: true });
|
||||
if (!back) return;
|
||||
if (restore) restore();
|
||||
else if (origin?.isConnected) origin.focus({ preventScroll: true });
|
||||
};
|
||||
const dismiss = () => close();
|
||||
const outside = (event: PointerEvent) => { if (!root?.contains(event.target as Node)) close(); };
|
||||
const outside = (event: PointerEvent) => { if (!root.contains(event.target as Node)) close(); };
|
||||
const scroll = (event: Event) => {
|
||||
if (root?.contains(event.target as Node)) return;
|
||||
if (root.contains(event.target as Node)) return;
|
||||
const before = event.target && scrollPositions.get(event.target);
|
||||
const current = event.target === document ? [window.scrollX, window.scrollY]
|
||||
: event.target instanceof HTMLElement ? [event.target.scrollLeft, event.target.scrollTop] : undefined;
|
||||
@@ -34,12 +43,12 @@ export function showActionMenu(options: MenuOptions, signal?: AbortSignal): { cl
|
||||
...(item.children ? { children: wrap(item.children) } : {}),
|
||||
...(!item.children || item.run ? { run: () => { close(true); if (!signal?.aborted) item.run?.(); } } : {}),
|
||||
});
|
||||
root = actionMenu(options.x, options.y, wrap(options.items), () => close(true), options.label ?? "Actions", options.parent);
|
||||
const root = actionMenu(options.x, options.y, wrap(options.items), () => close(true), options.label ?? "Actions", options.parent);
|
||||
window.addEventListener("pointerdown", outside, true);
|
||||
window.addEventListener("resize", dismiss);
|
||||
window.addEventListener("blur", dismiss);
|
||||
document.addEventListener("scroll", scroll, true);
|
||||
signal?.addEventListener("abort", dismiss, { once: true });
|
||||
if (signal?.aborted) close();
|
||||
return { close: () => close() };
|
||||
return { close, element: root, get open() { return open; } };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { tr } from "../i18n/index.ts";
|
||||
import type { ActionMenuItem } from "./actionMenu.ts";
|
||||
|
||||
// The common text actions of the editor and reading menus. Each menu supplies only its commands.
|
||||
|
||||
/** Undo and Redo, then a separator. */
|
||||
export function historyItems(history: { canUndo: boolean; canRedo: boolean; undo(): void; redo(): void }): ActionMenuItem[] {
|
||||
return [
|
||||
{ label: tr("Undo"), icon: "undo", shortcut: "Ctrl+Z", disabled: !history.canUndo, run: history.undo },
|
||||
{ label: tr("Redo"), icon: "redo", shortcut: "Ctrl+Shift+Z", disabled: !history.canRedo, run: history.redo },
|
||||
{ separator: true },
|
||||
];
|
||||
}
|
||||
|
||||
/** Search the workspace for the selected text. The label quotes at most 32 characters. */
|
||||
export function searchItem(text: string, search?: (text: string) => void): ActionMenuItem {
|
||||
return {
|
||||
label: text ? tr("Search for “{text}”", { text: text.length > 32 ? text.slice(0, 32) + "…" : text }) : tr("Search selection"),
|
||||
icon: "search", disabled: !text || !search, run: () => search?.(text),
|
||||
};
|
||||
}
|
||||
|
||||
export type ClipboardActions = {
|
||||
selected: boolean;
|
||||
copy(): void;
|
||||
cut?(): void;
|
||||
paste?(): void;
|
||||
pastePlain?(): void;
|
||||
selectAll?(): void;
|
||||
};
|
||||
|
||||
/** The clipboard actions in their shared order. A menu leaves out an action that it does not supply. */
|
||||
export function clipboardItems(actions: ClipboardActions): ActionMenuItem[] {
|
||||
const items: ActionMenuItem[] = [];
|
||||
if (actions.cut) items.push({ label: tr("Cut"), icon: "cut", shortcut: "Ctrl+X", disabled: !actions.selected, run: actions.cut });
|
||||
items.push({ label: tr("Copy"), icon: "copy", shortcut: "Ctrl+C", disabled: !actions.selected, run: actions.copy });
|
||||
if (actions.paste) items.push({ label: tr("Paste"), icon: "paste", shortcut: "Ctrl+V", run: actions.paste });
|
||||
if (actions.pastePlain) items.push({ label: tr("Paste as plain text"), icon: "paste-text", run: actions.pastePlain });
|
||||
if (actions.selectAll) items.push({ label: tr("Select all"), icon: "select", shortcut: "Ctrl+A", run: actions.selectAll });
|
||||
return items;
|
||||
}
|
||||
@@ -35,9 +35,9 @@ await runSmoke("editor/emptyMenu", async ({ page }) => {
|
||||
await setSource('');
|
||||
await page.locator('.cm-line').first().click({button:'right'});
|
||||
await menu().waitFor();
|
||||
for (const label of ['Add link','Add external link','Format','Paragraph','Insert','Paste','Paste as plain text','Select all']) assert.equal(await menu().getByRole('menuitem', {name:label,exact:true}).count(),1,label);
|
||||
assert.equal(await menu().getByRole('menuitem',{name:'Cut',exact:true}).isDisabled(),true);
|
||||
assert.equal(await menu().getByRole('menuitem',{name:'Copy',exact:true}).isDisabled(),true);
|
||||
for (const label of ['Add link','Add external link','Format','Paragraph','Insert','Paste Ctrl+V','Paste as plain text','Select all Ctrl+A']) assert.equal(await menu().getByRole('menuitem', {name:label,exact:true}).count(),1,label);
|
||||
assert.equal(await menu().getByRole('menuitem',{name:'Cut Ctrl+X',exact:true}).isDisabled(),true);
|
||||
assert.equal(await menu().getByRole('menuitem',{name:'Copy Ctrl+C',exact:true}).isDisabled(),true);
|
||||
await page.screenshot({path:`${output}/empty-${theme}.png`});
|
||||
await menu().getByRole('menuitem',{name:'Format',exact:true}).focus();
|
||||
await page.keyboard.press('ArrowRight');
|
||||
|
||||
@@ -49,7 +49,7 @@ await runSmoke("editor/surfaces", async ({ page }) => {
|
||||
await text.click({ button: 'right', position: { x: 20, y: 8 } });
|
||||
const writer = menu('Markdown text actions');
|
||||
assert.deepEqual(await styles(writer), reference);
|
||||
for (const name of ['Add link', 'Add external link', 'Format', 'Paragraph', 'Insert', 'Paste', 'Select all']) assert.equal(await item(name).count(), 1);
|
||||
for (const name of ['Add link', 'Add external link', 'Format', 'Paragraph', 'Insert', 'Paste Ctrl+V', 'Select all Ctrl+A']) assert.equal(await item(name).count(), 1);
|
||||
await item('Corrected').waitFor();
|
||||
assert.equal(await item('Spelling').count(), 0, 'Corrections appear directly in the main menu');
|
||||
assert.equal(await writer.locator(':scope > button').first().textContent(), 'Corrected');
|
||||
|
||||
@@ -44,8 +44,8 @@ await runSmoke("find/searchPanel", async ({ page }) => {
|
||||
const find = page.getByRole("textbox", { name: "Find in document", exact: true });
|
||||
await find.waitFor();
|
||||
assert.equal(await find.evaluate(el => document.activeElement === el), true);
|
||||
assert.equal(await page.locator(".cm-panels-top .rs-writer-search").count(), 1);
|
||||
const panelBounds = await page.locator(".rs-writer-search").boundingBox();
|
||||
assert.equal(await page.locator(".cm-panels-top .rs-editor-search").count(), 1);
|
||||
const panelBounds = await page.locator(".rs-editor-search").boundingBox();
|
||||
const scrollBounds = await page.locator(".cm-scroller").boundingBox();
|
||||
assert.ok(panelBounds.y + panelBounds.height <= scrollBounds.y + 1);
|
||||
await find.fill("Alpha");
|
||||
@@ -110,7 +110,7 @@ await runSmoke("find/searchPanel", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 880, height: 760 });
|
||||
await find.focus();
|
||||
await page.screenshot({ path: path.join(output, "find-bars-narrow.png") });
|
||||
for (const selector of [".rs-writer-search", ".outline-search"]) {
|
||||
for (const selector of [".rs-editor-search", ".outline-search"]) {
|
||||
assert.equal(await page.locator(selector).evaluate(el => el.scrollWidth <= el.clientWidth), true, selector);
|
||||
}
|
||||
console.log("PASS: Top search panel, shortcuts, replacement, query sync, invalid regex, focus tooltip, outline filtering, focus return and narrow layout.");
|
||||
|
||||
@@ -497,12 +497,12 @@ await runSmoke("layout/workbench", async ({ page }) => {
|
||||
}
|
||||
await cellAction('Clear formatting', true);
|
||||
await page.waitForFunction(() => document.querySelectorAll('.live-writer table strong').length === 0);
|
||||
await cellAction('Copy');
|
||||
await cellAction('Copy Ctrl+C');
|
||||
// clipboard.write resolves its items asynchronously.
|
||||
await page.waitForFunction(expected => window.__TEST__.clipboard === expected, 'one\ttwo\nfour\tfive');
|
||||
await cellAction('Cut');
|
||||
await cellAction('Cut Ctrl+X');
|
||||
await page.waitForFunction(() => [...document.querySelectorAll('.is-cell-selected')].every(cell => !cell.textContent.trim()));
|
||||
await cellAction('Paste');
|
||||
await cellAction('Paste Ctrl+V');
|
||||
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'one');
|
||||
await cellAction('Align centre');
|
||||
await page.waitForFunction(() => [...document.querySelectorAll('.is-cell-selected')].every(cell => cell.style.textAlign === 'center'));
|
||||
@@ -617,7 +617,7 @@ await runSmoke("layout/workbench", async ({ page }) => {
|
||||
}
|
||||
await selectBrokers();
|
||||
await actionCell(1, 0).click({ button: 'right' });
|
||||
assert.equal(await page.getByRole('menuitem', { name: 'Copy', exact: true }).isDisabled(), false);
|
||||
assert.equal(await page.getByRole('menuitem', { name: 'Copy Ctrl+C', exact: true }).isDisabled(), false);
|
||||
assert.ok(await page.locator('.table-cell-menu button').evaluateAll(buttons => buttons.every(button => button.querySelector('svg[aria-hidden="true"]'))));
|
||||
await page.getByRole('menuitem', { name: 'Row', exact: true }).hover();
|
||||
await page.screenshot({ path: path.join(output, 'table-text-row-menu.png') });
|
||||
@@ -666,18 +666,18 @@ await runSmoke("layout/workbench", async ({ page }) => {
|
||||
await page.evaluate(() => {
|
||||
navigator.clipboard.read = async () => [{ types: ['text/html', 'text/plain'], getType: async type => new Blob([type === 'text/html' ? '<em>Rich paste</em>' : 'Rich paste'], { type }) }];
|
||||
});
|
||||
await actionItem('Paste');
|
||||
await actionItem('Paste Ctrl+V');
|
||||
await page.waitForFunction(() => document.querySelector('.live-writer td em')?.textContent === 'Rich paste');
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.evaluate(() => { delete navigator.clipboard.read; });
|
||||
await selectBrokers();
|
||||
await actionItem('Copy');
|
||||
await actionItem('Copy Ctrl+C');
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.clipboard), 'Brokers');
|
||||
await actionItem('Cut');
|
||||
await actionItem('Cut Ctrl+X');
|
||||
await page.waitForFunction(() => !document.querySelector('.live-writer td').textContent.includes('Brokers'));
|
||||
await page.keyboard.press('Control+z');
|
||||
await selectBrokers();
|
||||
await actionItem('Select all');
|
||||
await actionItem('Select all Ctrl+A');
|
||||
assert.equal(await page.evaluate(() => getSelection().toString()), 'Interactive Brokers Group');
|
||||
await page.setViewportSize({ width: 800, height: 600 });
|
||||
await actionCell(1, 0).click({ button: 'right' });
|
||||
|
||||
Reference in New Issue
Block a user