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.
124 lines
7.5 KiB
TypeScript
124 lines
7.5 KiB
TypeScript
import { tr } from '../i18n/index.ts';
|
|
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";
|
|
|
|
export type TableContextActions = {
|
|
linkActions?: () => DocumentLinkActions;
|
|
onSearch?: (text: string) => void;
|
|
onExtract?: (markdown: string, label: string, valid: () => boolean) => Promise<string | null>;
|
|
};
|
|
|
|
export const cellFormats = [
|
|
["Bold", "bold"], ["Italic", "italic"], ["Strikethrough", "strike"], ["Highlight", "highlight"],
|
|
["Code", "code"], ["Math", "math"], ["Comment", "comment"], ["Clear formatting", "clear"],
|
|
] as const;
|
|
|
|
export function tableTextItems(editor: Editor, actions: TableContextActions, close: () => void, transaction: (run: () => void) => void, pending: (value: boolean) => void, report: (message: string) => void, editSource: (range: { from: number; to: number }) => void): ActionMenuItem[] {
|
|
const selection = editor.state.selection, doc = editor.state.doc;
|
|
const sourceEditing = editor.view.dom.parentElement?.classList.contains("is-source-editing");
|
|
const text = doc.textBetween(selection.from, selection.to, "\n");
|
|
const valid = () => !editor.isDestroyed && editor.state.doc === doc && editor.state.selection.eq(selection);
|
|
function run(command: () => void) { if (!valid()) return; close(); transaction(() => { editor.view.focus(); command(); }); }
|
|
async function request(command: () => Promise<void>) {
|
|
pending(true); close();
|
|
try { await command(); } catch (error) { report(error instanceof Error ? error.message : String(error)); }
|
|
finally { pending(false); if (!editor.isDestroyed) editor.view.focus(); }
|
|
}
|
|
function link(external: boolean) {
|
|
void request(async () => {
|
|
const target = await requestText(external ? tr("External link URL") : tr("Link to note (name or workspace path)"), external ? "https://" : text);
|
|
if (!target || !valid()) return;
|
|
if (external) {
|
|
try {
|
|
const url = new URL(target);
|
|
if (!(["http:", "https:"].includes(url.protocol) && url.hostname || url.protocol === "mailto:" && url.pathname.includes("@")) || /\s/.test(target)) throw new Error("Invalid URL");
|
|
} catch { report(tr("Enter a valid http, https, or mailto link.")); return; }
|
|
}
|
|
if (!external && /[\[\]|\r\n]|^[a-z][a-z\d+.-]*:/i.test(target)) { report(tr("Enter a note name or path without brackets or pipes.")); return; }
|
|
run(() => {
|
|
const attrs = { href: target, "data-kind": external ? "md" : "wiki" };
|
|
if (selection.empty) editor.commands.insertContent({ type: "text", text: target, marks: [{ type: "link", attrs }] });
|
|
else editor.commands.setMark("link", attrs);
|
|
});
|
|
});
|
|
}
|
|
const at = doc.resolve(selection.from);
|
|
const mark = [...at.marks(), ...(at.nodeAfter?.marks || [])].find(mark => mark.type.name === "link");
|
|
const linkRange = mark && getMarkRange(doc.resolve(selection.from), mark.type, mark.attrs);
|
|
const sourceLink = sourceEditing ? documentLinkAt(doc.textContent, selection.from - 1)
|
|
|| documentLinkAt(doc.textContent, selection.from - 2) : undefined;
|
|
const selectedLink = sourceLink || (mark && linkRange ? { kind: mark.attrs["data-kind"] === "wiki" ? "wiki" as const : "md" as const, target: String(mark.attrs.href) } : undefined);
|
|
function editLink() {
|
|
if (!selectedLink) return;
|
|
if (!valid()) return;
|
|
close();
|
|
if (sourceLink) {
|
|
editor.commands.setTextSelection({ from: sourceLink.targetFrom + 1, to: sourceLink.targetTo + 1 });
|
|
editor.view.focus();
|
|
} else if (linkRange) editSource(linkRange);
|
|
}
|
|
async function clipboard(action: "cut" | "copy" | "paste" | "plain") {
|
|
await request(async () => {
|
|
try {
|
|
if (action === "copy" || action === "cut") {
|
|
await navigator.clipboard.writeText(text);
|
|
if (action === "cut") run(() => { editor.commands.deleteSelection(); });
|
|
} else {
|
|
let html = "", value = "";
|
|
if (!sourceEditing && action === "paste" && navigator.clipboard.read) {
|
|
try {
|
|
const data = await navigator.clipboard.read();
|
|
const rich = data.find(item => item.types.includes("text/html"));
|
|
if (rich) html = await (await rich.getType("text/html")).text();
|
|
const plain = data.find(item => item.types.includes("text/plain"));
|
|
if (plain) value = await (await plain.getType("text/plain")).text();
|
|
} catch { /* Text clipboard is also supported on older WebViews. */ }
|
|
}
|
|
if (!html && !value) value = await navigator.clipboard.readText();
|
|
if (!html && !value) return;
|
|
run(() => {
|
|
if (html) editor.commands.insertContent(html);
|
|
else {
|
|
const nodes: JSONContent[] = [];
|
|
value.replace(/\r\n?/g, "\n").split("\n").forEach((line, i) => { if (i) nodes.push({ type: "hardBreak" }); if (line) nodes.push({ type: "text", text: line, marks: [] }); });
|
|
editor.commands.insertContent(nodes);
|
|
}
|
|
});
|
|
}
|
|
} catch { report(tr("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste.")); }
|
|
});
|
|
}
|
|
const items: ActionMenuItem[] = [
|
|
...(selectedLink ? [...linkMenuItems(selectedLink, actions.linkActions?.() || {}, close, report, editLink), { separator: true as const }] : []),
|
|
{ label: tr("Add link"), icon: "link", run: () => link(false) },
|
|
{ label: tr("Add external link"), icon: "external", run: () => link(true) },
|
|
{ separator: true },
|
|
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 || []);
|
|
const target = await actions.onExtract?.(markdown, text, valid);
|
|
if (target) run(() => { editor.commands.insertContent({ type: "text", text: text.replace(/\s+/g, " ").trim(), marks: [{ type: "link", attrs: { href: target, "data-kind": "wiki" } }] }); });
|
|
}) },
|
|
{ label: tr("Format"), icon: "format", children: cellFormats.map(([label, kind]) => ({ label: tr(label), icon: kind, disabled: selection.empty, run: () => run(() => {
|
|
if (kind === "clear") editor.commands.unsetAllMarks(); else editor.commands.toggleMark(kind);
|
|
}) })) },
|
|
{ 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 },
|
|
...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 }] : []),
|
|
...items.slice(items.findIndex(item => "label" in item && item.label === tr("Cut"))),
|
|
] : items;
|
|
}
|