import { tr } from "../i18n/index.ts"; 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"; import { externalLinkText, workspaceLinkText } from "./linkCommands"; import { documentLinkAt } from "./documentLinks"; import { linkMenuItems, type DocumentLinkActions } from "./linkMenu"; import { htmlToMarkdown } from "../workspace/htmlToMarkdown"; import { cellFormats, type TableContextActions } from "./tableCellActions"; import { FORMAT_KEYS, LINK_KEY } from "./formatKeys"; import { keys } from "../ui/shortcuts"; import { formatText, insertBlock, paragraphText, replacement, type MarkdownEdit, type TextSelection, type ParagraphStyle, type InsertBlock } from "./markdownCommands"; export type MarkdownMenuEditor = { snapshot: () => { source: string; selection: TextSelection; valid: () => boolean }; apply: (edit: MarkdownEdit) => void; selectAll: () => void; focus: () => void; select: (from: number, to: number) => void; undo?: () => void; redo?: () => void; canUndo?: () => boolean; canRedo?: () => boolean; }; // 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 menu: MenuHandle | undefined, destroyed = false; const pending = new AbortController(); const restore = () => { if (!destroyed) editor.focus(); }; function close(focus = true) { menu?.close(); menu = undefined; if (focus) restore(); } 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); const snapshot = editor.snapshot(), { source, selection } = snapshot; const text = source.slice(selection.from, selection.to); const selectedLink = documentLinkAt(source, linkOffset ?? selection.from); const valid = () => !destroyed && snapshot.valid(); function apply(edit: MarkdownEdit) { if (!valid()) return; close(); editor.apply(edit); editor.focus(); } async function request(run: () => Promise) { close(false); try { await run(); } catch (error) { if (!destroyed) report(error instanceof Error ? error.message : String(error)); } finally { if (valid()) editor.focus(); } } function link(external: boolean) { if (external) { apply(externalLinkText(source, selection)); return; } void request(async () => { const target = await pickLinkDocument(pending.signal); if (!target || !valid()) return; apply(workspaceLinkText(source, selection, target)); }); } function clipboard(kind: "cut" | "copy" | "paste" | "plain") { void request(async () => { try { if (kind === "cut" || kind === "copy") { await navigator.clipboard.writeText(text); if (kind === "cut") apply(replacement(selection, "")); } else { let value = ""; if (kind === "paste" && navigator.clipboard.read) { try { const data = await navigator.clipboard.read(); const rich = data.find(item => item.types.includes("text/html")); if (rich) value = htmlToMarkdown(await (await rich.getType("text/html")).text()); } catch { /* Fall back to the text clipboard on older WebViews. */ } } if (!value) value = await navigator.clipboard.readText(); if (value) apply(replacement(selection, value.replace(/\r?\n/g, source.includes("\r\n") ? "\r\n" : "\n"))); } } catch { report(tr("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste.")); } }); } const paragraph = (label: string, style: ParagraphStyle, icon: "bullet" | "number" | "task" | "heading" | "paragraph" | "quote"): ActionMenuItem => ({ label, icon, run: () => apply(paragraphText(source, selection, style)) }); const insert = (label: string, kind: InsertBlock, icon: "footnote" | "table" | "quote" | "rule" | "code" | "math"): ActionMenuItem => ({ label, icon, run: () => apply(insertBlock(source, selection, kind)) }); const items: ActionMenuItem[] = [ ...(selectedLink ? [...linkMenuItems(selectedLink, linkActions(), () => close(false), report, () => { if (!valid()) return; editor.select(selectedLink.targetFrom, selectedLink.targetTo); editor.focus(); }), { 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", shortcut: keys(LINK_KEY), run: () => link(true) }, { separator: true }, 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()}]]`)); }) }, { label: tr("Format"), icon: "format", children: cellFormats.flatMap(([label, kind]) => [ ...(kind === "code" || kind === "clear" ? [{ separator: true } as const] : []), { label: tr(label), icon: kind, ...(FORMAT_KEYS[kind] ? { shortcut: keys(FORMAT_KEYS[kind]) } : {}), disabled: kind === "clear" && !text, run: () => apply(formatText(source, selection, kind)) }, ]) }, { label: tr("Paragraph"), icon: "paragraph", children: [ paragraph(tr("Bullet list"), "bullet", "bullet"), paragraph(tr("Numbered list"), "number", "number"), paragraph(tr("Task list"), "task", "task"), { separator: true }, ...([1, 2, 3, 4, 5, 6] as const).map(level => paragraph(tr("Heading {level}", { level }), level, "heading")), paragraph(tr("Body"), "body", "paragraph"), { separator: true }, paragraph(tr("Quote"), "quote", "quote"), ] }, { label: tr("Insert"), icon: "insert", children: [ insert(tr("Footnote"), "footnote", "footnote"), insert(tr("Table"), "table", "table"), insert(tr("Callout"), "callout", "quote"), insert(tr("Horizontal rule"), "rule", "rule"), { separator: true }, insert(tr("Code block"), "code", "code"), insert(tr("Math block"), "math", "math"), ] }, { separator: true }, ...clipboardItems({ selected: !!text, cut: () => clipboard("cut"), copy: () => clipboard("copy"), paste: () => clipboard("paste"), pastePlain: () => clipboard("plain"), selectAll: () => editor.selectAll(), }), ]; 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 || 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(tr("Could not add the word to the dictionary."))); } }); 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(":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); } }; }