/** * Read-only text the user can select and copy, like IDEA's Markdown preview, * Quick Documentation and message panes. The workbench body is unselectable * (chrome); content opts back in with `selectableText`. A right-click on a * selection, or anywhere in such content, offers Copy (`copyMenuFor`). */ import { readClipboardPlainText, writeClipboardText } from "@/platform/clipboard"; import { isTauri } from "@/platform/ipc"; import type { KeyboardEvent } from "react"; import { hasPrimaryModifier, formatBinding } from "@/platform/keymap"; import type { MenuItem } from "./Menu"; import styles from "./SelectableText.module.css"; export const selectableText = styles.selectable!; const EDITABLE = "input, textarea, [contenteditable=''], [contenteditable='true'], [contenteditable='plaintext-only']"; /** Input types that hold editable text. */ const TEXT_INPUTS = new Set(["text", "search", "url", "tel", "email", "password", "number"]); function selectionCovers(sel: Selection | null, target: Node): boolean { if (!sel || sel.isCollapsed || !sel.toString()) return false; for (let i = 0; i < sel.rangeCount; i++) { const range = sel.getRangeAt(i); if (range.intersectsNode(target) || target.contains(range.commonAncestorContainer)) return true; } return false; } /** * The Copy menu for a right-click on `target`, or null when it is not on readable text. On a link * it also offers Copy Link Address, as browsers do; Copy keeps copying the selected text. */ export function copyMenuFor(target: EventTarget | null): MenuItem[] | null { const el = target instanceof Element ? target : target instanceof Node ? target.parentElement : null; if (!el || el.closest(EDITABLE)) return null; const sel = window.getSelection(); const text = selectionCovers(sel, el) ? sel!.toString() : ""; const href = el.closest("a[href]")?.getAttribute("href") ?? ""; const link = href.startsWith("#") ? "" : href; if (!text && !link && !el.closest(`.${selectableText}`)) return null; const items: MenuItem[] = [ { id: "copy", label: "Copy", icon: "copy", shortcut: formatBinding("Meta+C"), disabled: !text, run: () => void copyText(text), }, ]; if (link) items.push({ id: "copy-link", label: "Copy Link Address", run: () => void copyText(link) }); return items; } type TextField = HTMLInputElement | HTMLTextAreaElement; /** The text selected in a text field; empty when its type has no text selection (number, email…). */ function fieldSelection(el: TextField): string { try { const { selectionStart: from, selectionEnd: to } = el; return from == null || to == null ? "" : el.value.slice(from, to); } catch { return ""; } } /** * Cut / Copy / Paste / Select All for a right-click in a text field or other editable * text no component gave a menu of its own, as desktop text fields offer; null elsewhere. * Edits go through the field's own editing commands, so its undo and input events follow. */ export function textFieldMenuFor(target: EventTarget | null): MenuItem[] | null { const node = target instanceof Element ? target : target instanceof Node ? target.parentElement : null; const el = node?.closest(EDITABLE); if (!el) return null; const field = el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement ? el : null; if (field instanceof HTMLInputElement && !TEXT_INPUTS.has(field.type)) return null; const editable = field ? !field.disabled && !field.readOnly : el.isContentEditable; const secret = field instanceof HTMLInputElement && field.type === "password"; const selected = field ? fieldSelection(field) : (window.getSelection()?.toString() ?? ""); const focus = () => el.focus({ preventScroll: true }); return [ { id: "cut", label: "Cut", icon: "cut", shortcut: formatBinding("Meta+X"), disabled: !editable || secret || !selected, run: () => { focus(); void copyText(selected).then(() => document.execCommand("delete")); }, }, { id: "copy", label: "Copy", icon: "copy", shortcut: formatBinding("Meta+C"), disabled: secret || !selected, run: () => void copyText(selected), }, { id: "paste", label: "Paste", icon: "paste", shortcut: formatBinding("Meta+V"), disabled: !editable, run: () => void readClipboardPlainText() .then((text) => { focus(); if (text) document.execCommand("insertText", false, text.replace(/\r\n?/g, "\n")); }) .catch(() => {}), }, { kind: "separator" }, { id: "selectAll", label: "Select All", shortcut: formatBinding("Meta+A"), disabled: field ? !field.value : !el.textContent, run: () => { focus(); if (field) field.select(); else document.execCommand("selectAll"); }, }, ]; } /** Writes `text` to the clipboard; falls back to copying the live selection. */ export async function copyText(text: string): Promise { try { if (isTauri() || typeof navigator.clipboard?.writeText === "function") { await writeClipboardText(text); return; } } catch { // Clipboard API refused (permissions): the selection is still there. } document.execCommand("copy"); } /** Copy a DOM output selection locally, leaving editable children and other views alone. */ export function copySelectionOnKeyDown( e: Pick< KeyboardEvent, | "key" | "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "defaultPrevented" | "nativeEvent" | "target" | "currentTarget" | "preventDefault" | "stopPropagation" >, /** Text to copy instead of `selection.toString()`, for views that do not mount all their text. */ textOf: (selection: Selection) => string = (selection) => selection.toString(), ): boolean { if (e.defaultPrevented || e.nativeEvent.isComposing || e.altKey || e.shiftKey) return false; const copy = (e.key.toLowerCase() === "c" && (e.ctrlKey || hasPrimaryModifier(e))) || (e.key === "Insert" && e.ctrlKey && !e.metaKey); if (!copy || (e.target instanceof Element && e.target.closest(EDITABLE))) return false; const selection = window.getSelection(); if ( !selection || selection.isCollapsed || !selection.toString() || !e.currentTarget.contains(selection.anchorNode) || !e.currentTarget.contains(selection.focusNode) ) return false; e.preventDefault(); e.stopPropagation(); void copyText(textOf(selection)); return true; }