import { tr } from '../i18n/index.ts'; import { keys } from "../ui/shortcuts"; 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 { 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 menu: MenuHandle | undefined; const restore = () => view.focus(); function close(focus = true) { menu?.close(); menu = undefined; if (focus) restore(); } function open(x: number, y: number) { close(false); const state = view.state, main = state.selection.main; const valid = () => view.state.doc === state.doc && view.state.selection.eq(state.selection); const selected = state.sliceDoc(main.from, main.to); const word = main.empty ? state.wordAt(main.head) : main; const replace = (text: string) => { if (!valid()) return; view.dispatch(view.state.replaceSelection(text), { userEvent: "input", scrollIntoView: true }); view.focus(); }; const clipboard = async (kind: "cut" | "copy" | "paste") => { try { if (kind === "paste") replace(await navigator.clipboard.readText()); else { await navigator.clipboard.writeText(selected); if (kind === "cut") replace(""); } } catch { report(tr("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste.")); } }; const changeAll = () => { if (!valid() || !word) return; if (main.empty) view.dispatch({ selection: EditorSelection.single(word.from, word.to) }); selectSelectionMatches(view); }; 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: keys("Mod+Shift+L"), disabled: !word || word.empty, run: changeAll }, { separator: true }, ...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); } }; }