diff --git a/apps/desktop/src/components/editor/QueryEditor.vue b/apps/desktop/src/components/editor/QueryEditor.vue index 4b2b908d7e..3a228154ff 100644 --- a/apps/desktop/src/components/editor/QueryEditor.vue +++ b/apps/desktop/src/components/editor/QueryEditor.vue @@ -57,7 +57,7 @@ import { createColumnReferencePayload, tableReferenceInsertText } from "@/lib/ed import { clearRememberedFocusedQueryEditorView, focusedQueryEditorView, queryEditorInsertContext, registerQueryEditorInsertContext, rememberFocusedQueryEditorView, unregisterQueryEditorInsertContext } from "@/lib/editor/focusedQueryEditorView"; import { loadObjectMetadataFacet } from "@/lib/metadata/objectMetadataCache"; import { structurePeekPanelId } from "@/lib/editor/structurePeekPanel"; -import { parkEditorNativeSelection, type EditorNativeSelectionPark } from "@/lib/editor/queryEditorNativeSelection"; +import { createQueryEditorNativeSelectionGuard, parkEditorNativeSelection, type EditorNativeSelectionPark } from "@/lib/editor/queryEditorNativeSelection"; import CodeSnapshotDialog from "@/components/codeSnapshot/CodeSnapshotDialog.vue"; import QueryEditorContextMenu, { type QueryEditorContextMenuState, type QueryEditorContextMenuActions } from "./QueryEditorContextMenu.vue"; @@ -134,6 +134,7 @@ import { supportsQueryEditorBlockComments, supportsSqlInListPaste } from "@/lib/ import { queryContextObjectRoute, queryTableCandidateAtSqlPosition, resolveQueryContextCandidateDatabase, resolveQueryContextObjectTarget, type QueryContextObjectAction } from "@/lib/sql/queryCursorTableTarget"; import * as api from "@/lib/backend/api"; import { isTauriRuntime } from "@/lib/backend/tauriRuntime"; +import { isMacOS } from "@/lib/backend/platform"; import { resolveSqlDialectId } from "@/lib/sql/semantic/dialect"; import type { SqlCompletionColumn, SqlCompletionContext, SqlCompletionReferencedTable } from "@/lib/sql/sqlCompletion"; @@ -1929,6 +1930,7 @@ const codeMirrorLifecycle = useQueryEditorCodeMirror({ // keystroke maps the boundary view to the new doc before any lineMarker // callback reads it, otherwise the gutter would trigger a full parse. statementBoundariesTrackingPlugin, + createQueryEditorNativeSelectionGuard(ViewPlugin, { enabled: isTauriRuntime() && isMacOS(), inputHandler: EditorView.inputHandler, finalizeClipboardText: (text) => clipboardLineEndings(text) }), initializedRuntime.runGutterComp.of(runStatementGutterExtension()), initializedRuntime.lineNumbersComp.of(lineNumbersExtension(initialSettings.showLineNumbers)), createQueryEditorLineNumberAlignmentExtension(ViewPlugin), diff --git a/apps/desktop/src/lib/editor/__tests__/queryEditorNativeSelectionGuard.spec.ts b/apps/desktop/src/lib/editor/__tests__/queryEditorNativeSelectionGuard.spec.ts new file mode 100644 index 0000000000..6846fd0e96 --- /dev/null +++ b/apps/desktop/src/lib/editor/__tests__/queryEditorNativeSelectionGuard.spec.ts @@ -0,0 +1,267 @@ +// @vitest-environment happy-dom +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { EditorSelection, EditorState, StateEffect } from "@codemirror/state"; +import { EditorView, ViewPlugin, keymap } from "@codemirror/view"; +import { defaultKeymap, history, selectAll, undo } from "@codemirror/commands"; +import { createQueryEditorNativeSelectionGuard, keepNativeSelectionParkedDuringDrag, parkEditorNativeSelection } from "../queryEditorNativeSelection"; + +const SQL = Array.from({ length: 200 }, (_, index) => `CREATE TABLE example_${index} (id INTEGER);`).join("\n"); +const views: EditorView[] = []; + +beforeEach(() => { + // Browsers queue selectionchange; happy-dom dispatches it during collapse. + const dispatch = document.dispatchEvent.bind(document); + let selectionChangePending = false; + vi.spyOn(document, "dispatchEvent").mockImplementation((event) => { + if (event.type !== "selectionchange") return dispatch(event); + if (!selectionChangePending) { + selectionChangePending = true; + queueMicrotask(() => { + selectionChangePending = false; + dispatch(event); + }); + } + return true; + }); +}); + +function createView(options: { enabled?: boolean; readOnly?: boolean } = {}) { + const execute = vi.fn((view: EditorView) => { + view.focus(); + return view.state.sliceDoc(view.state.selection.main.from, view.state.selection.main.to); + }); + const parent = document.body.appendChild(document.createElement("div")); + const view = new EditorView({ + parent, + state: EditorState.create({ + doc: SQL, + extensions: [ + history(), + EditorState.readOnly.of(options.readOnly ?? false), + EditorView.clipboardOutputFilter.of((text) => text.replaceAll("\n", "\r\n")), + createQueryEditorNativeSelectionGuard(ViewPlugin, { enabled: options.enabled ?? true, inputHandler: EditorView.inputHandler, finalizeClipboardText: (text) => text.replaceAll("\n", "\r\n") }), + keymap.of([{ key: "Meta-a", run: selectAll }, { key: "Meta-Enter", run: (currentView) => !!execute(currentView) }, ...defaultKeymap]), + ], + }), + }); + views.push(view); + view.focus(); + return { view, execute }; +} + +function press(view: EditorView, key: string, options: KeyboardEventInit = {}) { + const event = new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...options }); + view.contentDOM.dispatchEvent(event); + return event; +} + +function clipboard(view: EditorView, type: "copy" | "cut" | "paste", text = "") { + const data = { clearData: vi.fn(), setData: vi.fn(), getData: vi.fn(() => text) }; + const event = new Event(type, { bubbles: true, cancelable: true }); + Object.defineProperty(event, "clipboardData", { value: data }); + view.contentDOM.dispatchEvent(event); + return { data, event }; +} + +function expectParked(view: EditorView) { + expect(document.getSelection()?.anchorNode === view.contentDOM).toBe(true); + expect(document.getSelection()?.isCollapsed).toBe(true); + expect(view.state.selection.main.to - view.state.selection.main.from).toBe(SQL.length); +} + +afterEach(() => { + for (const view of views.splice(0)) view.destroy(); + document.body.replaceChildren(); + vi.restoreAllMocks(); +}); + +describe("macOS long native selection guard", () => { + it("parks Cmd+A before CodeMirror publishes the long DOM range and keeps execution intact", () => { + const { view, execute } = createView(); + const extend = vi.spyOn(document.getSelection()!, "extend"); + + expect(press(view, "a", { metaKey: true }).defaultPrevented).toBe(true); + expectParked(view); + expect(extend).not.toHaveBeenCalled(); + + for (let attempt = 0; attempt < 3; attempt++) { + expect(press(view, "Enter", { metaKey: true }).defaultPrevented).toBe(true); + view.dispatch({ selection: view.state.selection }); + expectParked(view); + } + expect(execute).toHaveBeenCalledTimes(3); + expect(execute.mock.results.every((result) => result.value === SQL)).toBe(true); + expect(extend).not.toHaveBeenCalled(); + }); + + it("keeps native selection behavior when disabled", () => { + const { view } = createView({ enabled: false }); + const extend = vi.spyOn(document.getSelection()!, "extend"); + selectAll(view); + expect(extend).toHaveBeenCalled(); + expect(document.getSelection()?.toString()).not.toBe(""); + }); + + it("leaves an incompatible selection implementation alone", () => { + const { view } = createView(); + const internals = view as unknown as { docView: { updateSelection: () => void } }; + const original = internals.docView.updateSelection; + const foreignWrite = vi.fn(() => original.call(internals.docView)); + internals.docView.updateSelection = foreignWrite; + selectAll(view); + expect(foreignWrite).toHaveBeenCalled(); + expect(internals.docView.updateSelection).toBe(foreignWrite); + expect(document.getSelection()?.isCollapsed).toBe(false); + expect(view.state.selection.main.to).toBe(SQL.length); + }); + + it("protects a long selection immediately on refocus", () => { + const { view } = createView(); + selectAll(view); + const other = document.body.appendChild(document.createElement("input")); + other.focus(); + const extend = vi.spyOn(document.getSelection()!, "extend"); + view.focus(); + expectParked(view); + expect(extend).not.toHaveBeenCalled(); + }); + + it("restores small selections and the caret without a frame delay", () => { + const { view } = createView(); + selectAll(view); + view.dispatch({ selection: { anchor: 0, head: 6 } }); + expect(document.getSelection()?.toString()).toBe("CREATE"); + view.dispatch({ selection: { anchor: 3 } }); + const selection = document.getSelection()!; + expect(view.posAtDOM(selection.anchorNode!, selection.anchorOffset)).toBe(3); + expect(selection.isCollapsed).toBe(true); + }); + + it("copies the exact selected SQL with configured line endings", () => { + const { view } = createView(); + selectAll(view); + const { data, event } = clipboard(view, "copy"); + expect(event.defaultPrevented).toBe(true); + expect(data.setData).toHaveBeenCalledWith("text/plain", SQL.replaceAll("\n", "\r\n")); + expectParked(view); + }); + + it("cuts and pastes from editor state and preserves undo", () => { + const { view } = createView(); + selectAll(view); + clipboard(view, "cut"); + expect(view.state.doc.length).toBe(0); + expect(undo(view)).toBe(true); + expect(view.state.doc.toString()).toBe(SQL); + selectAll(view); + expect(clipboard(view, "paste", "SELECT 42;").event.defaultPrevented).toBe(true); + expect(view.state.doc.toString()).toBe("SELECT 42;"); + expect(undo(view)).toBe(true); + expect(view.state.doc.toString()).toBe(SQL); + }); + + it("does not cut a read-only document", () => { + const { view } = createView({ readOnly: true }); + selectAll(view); + const { data } = clipboard(view, "cut"); + expect(data.setData).toHaveBeenCalledWith("text/plain", SQL.replaceAll("\n", "\r\n")); + expect(view.state.doc.toString()).toBe(SQL); + }); + + it("restores a reversed selection before typing without changing its direction", () => { + const { view } = createView(); + view.dispatch({ selection: EditorSelection.single(SQL.length, 0) }); + expectParked(view); + press(view, "x"); + const selection = document.getSelection()!; + expect(view.posAtDOM(selection.anchorNode!, selection.anchorOffset)).toBe(SQL.length); + expect(view.posAtDOM(selection.focusNode!, selection.focusOffset)).toBe(0); + view.dispatch(view.state.replaceSelection("x")); + expect(view.state.doc.toString()).toBe("x"); + expect(view.contentDOM.contains(document.getSelection()?.anchorNode ?? null)).toBe(true); + }); + + it("replaces the logical selection for native input without a keyboard event", () => { + const { view } = createView(); + selectAll(view); + const event = new InputEvent("beforeinput", { inputType: "insertText", data: "中文", bubbles: true, cancelable: true }); + view.contentDOM.dispatchEvent(event); + expect(event.defaultPrevented).toBe(true); + expect(view.contentDOM.contains(document.getSelection()?.anchorNode ?? null)).toBe(true); + expect(view.state.doc.toString()).toBe("中文"); + expect(undo(view)).toBe(true); + expect(view.state.doc.toString()).toBe(SQL); + }); + + it("preserves registered input handlers for native replacement text", () => { + const { view } = createView(); + const handler = vi.fn((currentView: EditorView) => { + currentView.dispatch(currentView.state.replaceSelection("handled")); + return true; + }); + view.dispatch({ effects: StateEffect.appendConfig.of(EditorView.inputHandler.of(handler)) }); + selectAll(view); + view.contentDOM.dispatchEvent(new InputEvent("beforeinput", { inputType: "insertReplacementText", data: "replacement", bubbles: true, cancelable: true })); + expect(handler).toHaveBeenCalledWith(view, 0, SQL.length, "replacement", expect.any(Function)); + expect(view.state.doc.toString()).toBe("handled"); + }); + + it.each([ + ["insertParagraph", "\n"], + ["insertLineBreak", "\n"], + ["deleteContentBackward", ""], + ])("applies native %s to the logical selection", (inputType, expected) => { + const { view } = createView(); + selectAll(view); + const event = new InputEvent("beforeinput", { inputType, bubbles: true, cancelable: true }); + view.contentDOM.dispatchEvent(event); + expect(event.defaultPrevented).toBe(true); + expect(view.state.doc.toString()).toBe(expected); + expect(undo(view)).toBe(true); + expect(view.state.doc.toString()).toBe(SQL); + }); + + it("leaves the native selection available throughout IME composition", () => { + const { view } = createView(); + selectAll(view); + view.contentDOM.dispatchEvent(new CompositionEvent("compositionstart", { bubbles: true })); + view.dispatch({ selection: view.state.selection }); + expect(view.contentDOM.contains(document.getSelection()?.anchorNode ?? null)).toBe(true); + view.dispatch(view.state.replaceSelection("中文")); + view.contentDOM.dispatchEvent(new CompositionEvent("compositionend", { bubbles: true, data: "中文" })); + expect(view.state.doc.toString()).toBe("中文"); + }); + + it.each(["menu-first", "drag-first"])("retains protection across overlapping menu and drag parks (%s)", (order) => { + const { view, execute } = createView(); + selectAll(view); + const drag = keepNativeSelectionParkedDuringDrag(view); + const menu = parkEditorNativeSelection(view)!; + expect(menu).not.toBeNull(); + if (order === "menu-first") { + menu.release(); + drag.release(); + } else { + drag.release(); + menu.release(); + } + view.focus(); + press(view, "Enter", { metaKey: true }); + expectParked(view); + expect(execute).toHaveReturnedWith(SQL); + }); + + it("does not reclaim selection from another focused control or during teardown", () => { + const { view } = createView(); + selectAll(view); + const other = document.body.appendChild(document.createElement("div")); + other.contentEditable = "true"; + other.textContent = "Other editor"; + other.focus(); + document.getSelection()!.selectAllChildren(other); + view.dispatch({ selection: view.state.selection }); + expect(document.getSelection()?.toString()).toBe("Other editor"); + view.destroy(); + expect(document.getSelection()?.toString()).toBe("Other editor"); + }); +}); diff --git a/apps/desktop/src/lib/editor/queryEditorNativeSelection.ts b/apps/desktop/src/lib/editor/queryEditorNativeSelection.ts index 40b8ec23a0..564296acd8 100644 --- a/apps/desktop/src/lib/editor/queryEditorNativeSelection.ts +++ b/apps/desktop/src/lib/editor/queryEditorNativeSelection.ts @@ -1,4 +1,4 @@ -import type { EditorView } from "@codemirror/view"; +import type { EditorView, ViewPlugin, ViewUpdate } from "@codemirror/view"; import { appendDebugLog } from "@/lib/backend/debugLog"; /** @@ -17,7 +17,11 @@ import { appendDebugLog } from "@/lib/backend/debugLog"; * selection parked outside its content element. So the browser selection is * parked on the editor chrome while an overlay menu covers the editor, and for * as long as a pointer gesture is dragging a long selection out, and restored - * as soon as the menu closes or the pointer is released. + * as soon as the menu closes or the pointer is released. On macOS desktop a + * view plugin also holds long keyboard selections, including during execution. + * Its collapsed caret stays inside the editable so native input without a + * keydown still arrives. The observer cache is updated together with that caret + * so CodeMirror does not mistake the parked position for a user selection. * * The drag is the case that is easiest to misread from a bug report: sweeping * the pointer to the edge of the editor autoscrolls and never leaves the @@ -47,8 +51,8 @@ export function isLargeEditorSelection(currentView: EditorView): boolean { } export interface EditorNativeSelectionPark { - /** Put the browser selection back where the editor state has it. */ - release(): void; + /** Release ownership; skip restoration during view updates or teardown. */ + release(restoreSelection?: boolean): void; } export interface EditorNativeSelectionDragParkOptions extends EditorNativeSelectionParkOptions { @@ -59,8 +63,8 @@ export interface EditorNativeSelectionDragParkOptions extends EditorNativeSelect shouldKeepParked?: () => boolean; /** * Whether CodeMirror's own browser-selection writes are suspended while the - * park holds. Only the drag park wants this, because only the drag park is - * re-collapsed in a frame loop that CodeMirror then writes against. See + * park holds. Dragging and persistent keyboard selections need this to avoid + * re-collapsing ranges that CodeMirror writes back on each update. See * `suppressEditorSelectionWrites`. */ suppressEditorSelectionWrites?: boolean; @@ -88,17 +92,22 @@ export function editorRootSelection(currentView: EditorView): Selection | null { return root.ownerDocument?.getSelection() ?? null; } -function isParkedOutsideContent(currentView: EditorView, selection: Selection): boolean { - const anchor = selection.anchorNode; - return !!anchor && !currentView.contentDOM.contains(anchor); +function isParkedEditorSelection(currentView: EditorView, selection: Selection): boolean { + return (selection.anchorNode === currentView.dom || selection.anchorNode === currentView.contentDOM) && selection.focusNode === selection.anchorNode && selection.anchorOffset === 0 && selection.focusOffset === 0; } interface EditorViewSelectionInternals { docView?: { updateSelection?: (mustRead?: boolean, fromPointer?: boolean) => void }; - observer?: { selectionRange: { focusNode: Node | null }; readSelectionRange: () => boolean }; + observer?: { + selectionRange: { focusNode: Node | null }; + readSelectionRange: () => boolean; + ignore?: (write: () => void) => void; + setSelectionRange?: (anchor: { node: Node; offset: number }, head: { node: Node; offset: number }) => void; + }; } const UPDATE_SELECTION = "updateSelection"; +const selectionWriteSuppressions = new WeakMap void }>(); /** * Stops CodeMirror from writing its selection into the browser while parked. @@ -119,6 +128,11 @@ const UPDATE_SELECTION = "updateSelection"; * the ones it was written against. */ function suppressEditorSelectionWrites(currentView: EditorView): (() => void) | null { + const existing = selectionWriteSuppressions.get(currentView); + if (existing) { + existing.users++; + return () => releaseSelectionWriteSuppression(currentView); + } const internals = currentView as unknown as EditorViewSelectionInternals; const docView = internals.docView; const observer = internals.observer; @@ -130,18 +144,40 @@ function suppressEditorSelectionWrites(currentView: EditorView): (() => void) | if (mustRead || !observer.selectionRange.focusNode) observer.readSelectionRange(); }; docView[UPDATE_SELECTION] = suppressed; - return () => { - if (docView[UPDATE_SELECTION] === suppressed) delete docView[UPDATE_SELECTION]; - }; + selectionWriteSuppressions.set(currentView, { + users: 1, + restore: () => { + if (docView[UPDATE_SELECTION] === suppressed) delete docView[UPDATE_SELECTION]; + }, + }); + return () => releaseSelectionWriteSuppression(currentView); } -function parkSelection(currentView: EditorView, selection: Selection): void { +function releaseSelectionWriteSuppression(currentView: EditorView) { + const suppression = selectionWriteSuppressions.get(currentView); + if (!suppression || --suppression.users > 0) return; + suppression.restore(); + selectionWriteSuppressions.delete(currentView); +} + +function canGuardNativeSelection(currentView: EditorView) { + const { docView, observer } = currentView as unknown as EditorViewSelectionInternals; + return ( + !!docView && + typeof docView.updateSelection === "function" && + !!observer && + typeof observer.ignore === "function" && + typeof observer.setSelectionRange === "function" && + typeof observer.readSelectionRange === "function" && + (!Object.prototype.hasOwnProperty.call(docView, UPDATE_SELECTION) || selectionWriteSuppressions.has(currentView)) + ); +} + +function parkSelection(currentView: EditorView, selection: Selection, insideContent: boolean): void { try { - // `view.dom` (the editor element) sits outside `view.contentDOM`, so - // CodeMirror treats the parked selection as somebody else's and leaves the - // editor state alone. It is also far from the highlighted text, which is - // what keeps the attributed string cheap. - selection.collapse(currentView.dom, 0); + // Menus and drags use the editor chrome; persistent keyboard selections + // keep an editable caret so WebKit still delivers native beforeinput. + ignoreEditorSelectionChange(currentView, () => selection.collapse(insideContent ? currentView.contentDOM : currentView.dom, 0)); } catch { // WebKit rejects a collapse whose node disappeared between layout passes. } @@ -150,16 +186,31 @@ function parkSelection(currentView: EditorView, selection: Selection): void { function restoreSelectionFromState(currentView: EditorView, selection: Selection): void { try { const main = currentView.state.selection.main; - const anchor = currentView.domAtPos(main.from); - const head = main.empty ? anchor : currentView.domAtPos(main.to); - selection.collapse(anchor.node, anchor.offset); - if (!main.empty) selection.extend(head.node, head.offset); + const anchor = currentView.domAtPos(main.anchor); + const head = main.empty ? anchor : currentView.domAtPos(main.head); + ignoreEditorSelectionChange(currentView, () => { + selection.collapse(anchor.node, anchor.offset); + if (!main.empty) selection.extend(head.node, head.offset); + }); } catch { // WebKit refuses `extend` when the target moved in the meantime; the next // selection change makes CodeMirror rewrite the browser selection anyway. } } +function ignoreEditorSelectionChange(currentView: EditorView, write: () => void) { + const observer = (currentView as unknown as EditorViewSelectionInternals).observer; + if (observer?.ignore) { + observer.ignore(() => { + write(); + const selection = editorRootSelection(currentView); + // Reading instead of setting can invoke CodeMirror's focus repair and + // publish the long selection again during the first 200ms after focus. + if (selection?.anchorNode && selection.focusNode) observer.setSelectionRange?.({ node: selection.anchorNode, offset: selection.anchorOffset }, { node: selection.focusNode, offset: selection.focusOffset }); + }); + } else write(); +} + /** * The text CodeMirror would put on the clipboard for the current state. * @@ -210,7 +261,7 @@ function handleParkedClipboardEvent(currentView: EditorView, finalizeClipboardTe } /** - * The machinery both parking windows share. + * The machinery the menu, drag and keyboard parking windows share. * * Parking is idempotent and self-healing: the browser can put a selection back * into the editor on its own (focus, a redraw, the platform moving a caret), so @@ -226,6 +277,7 @@ interface NativeSelectionParkConfig { finalizeClipboardText: (text: string) => string; /** See `suppressEditorSelectionWrites`. */ suppressWrites?: boolean; + insideContent?: boolean; /** * Restore the browser selection on the next frame instead of inside * `release()`, and skip the restore when the browser selection is no longer @@ -246,16 +298,17 @@ interface NativeSelectionParkConfig { } /** - * Which park most recently took the browser selection. A deferred restore only - * acts while its own park is still the newest one: a park that starts before the - * microtask runs owns the browser selection, and restoring under it would hand - * the selection back to the text services for a frame. + * Overlapping windows share ownership. Restore only after the last one ends, + * and never let a deferred restore run underneath a newer parking window. */ -let latestParkSequence = 0; +const editorParks = new WeakMap void>; outside: number }>(); function createNativeSelectionPark(currentView: EditorView, config: NativeSelectionParkConfig): EditorNativeSelectionPark { - const { shouldKeepParked, finalizeClipboardText, suppressWrites = false, deferReleaseRestore = false } = config; - const sequence = ++latestParkSequence; + const { shouldKeepParked, finalizeClipboardText, suppressWrites = false, deferReleaseRestore = false, insideContent = false } = config; + let parks = editorParks.get(currentView); + if (!parks) editorParks.set(currentView, (parks = { generation: 0, active: new Set(), outside: 0 })); + parks.generation++; + if (!insideContent) parks.outside++; const doc = currentView.dom.ownerDocument; const win = doc.defaultView ?? window; let released = false; @@ -267,12 +320,15 @@ function createNativeSelectionPark(currentView: EditorView, config: NativeSelect const park = () => { if (released || !shouldKeepParked()) return; const selection = editorRootSelection(currentView); - if (!selection || isParkedOutsideContent(currentView, selection)) return; - parkSelection(currentView, selection); + if (!selection || (!currentView.hasFocus && (!selection.anchorNode || !currentView.dom.contains(selection.anchorNode)))) return; + if (suppressWrites && !restoreWrites) restoreWrites = suppressEditorSelectionWrites(currentView); + if (insideContent && !restoreWrites) return; + const parkInsideContent = insideContent && parks.outside === 0; + const target = parkInsideContent ? currentView.contentDOM : currentView.dom; + if (!isParkedEditorSelection(currentView, selection) || selection.anchorNode !== target) parkSelection(currentView, selection, parkInsideContent); if (!parkedOnce) { parkedOnce = true; parkedSince = performance.now(); - if (suppressWrites) restoreWrites = suppressEditorSelectionWrites(currentView); // Kept for field diagnosis: it only writes while debug logging is // switched on, and it is the one line that shows whether the parking // window was even entered when somebody reports the editor stuttering. @@ -282,6 +338,7 @@ function createNativeSelectionPark(currentView: EditorView, config: NativeSelect }); } }; + parks.active.add(park); park(); const onCopy = (event: ClipboardEvent) => handleParkedClipboardEvent(currentView, finalizeClipboardText, () => released, event); @@ -298,7 +355,7 @@ function createNativeSelectionPark(currentView: EditorView, config: NativeSelect frame = win.requestAnimationFrame(keepParked); return { - release() { + release(restoreSelection = true) { if (released) return; released = true; doc.removeEventListener("copy", onCopy); @@ -306,13 +363,19 @@ function createNativeSelectionPark(currentView: EditorView, config: NativeSelect win.cancelAnimationFrame(frame); restoreWrites?.(); restoreWrites = null; + parks.active.delete(park); + if (!insideContent) parks.outside--; + for (const refreshPark of parks.active) refreshPark(); + const generation = parks.generation; const restore = () => { - if (sequence !== latestParkSequence) return; + if (parks.active.size || generation !== parks.generation) return; const live = editorRootSelection(currentView); - if (live && isParkedOutsideContent(currentView, live)) restoreSelectionFromState(currentView, live); + if (live && isParkedEditorSelection(currentView, live)) restoreSelectionFromState(currentView, live); }; - if (deferReleaseRestore) win.requestAnimationFrame(restore); - else restore(); + if (restoreSelection) { + if (deferReleaseRestore) win.requestAnimationFrame(restore); + else restore(); + } if (parkedOnce) { // Field diagnosis for "the selection took seconds to clear": how long a // park lived says whether a gesture was still parked while the user @@ -361,3 +424,125 @@ export function keepNativeSelectionParkedDuringDrag(currentView: EditorView, opt deferReleaseRestore: true, }); } + +export function createQueryEditorNativeSelectionGuard(plugin: typeof ViewPlugin, options: EditorNativeSelectionParkOptions & { enabled: boolean; inputHandler: typeof EditorView.inputHandler }) { + if (!options.enabled) return []; + return plugin.fromClass( + class { + private park: EditorNativeSelectionPark | null = null; + private frame = 0; + private nativeInputPending = false; + private composing = false; + private win: Window; + + constructor(private currentView: EditorView) { + this.win = currentView.dom.ownerDocument.defaultView ?? window; + const content = currentView.contentDOM; + content.addEventListener("keydown", this.onKeyDown, true); + content.addEventListener("beforeinput", this.onBeforeInput, true); + content.addEventListener("compositionstart", this.onCompositionStart, true); + content.addEventListener("compositionend", this.onCompositionEnd, true); + content.addEventListener("focus", this.onFocus); + content.addEventListener("blur", this.onBlur); + this.scheduleSync(); + } + + update(update: ViewUpdate) { + if (update.docChanged || update.selectionSet) this.nativeInputPending = false; + this.sync(); + } + + private canPark = () => this.currentView.hasFocus && !this.nativeInputPending && !this.composing && !this.currentView.compositionStarted && isLargeEditorSelection(this.currentView); + + private sync() { + if (!this.canPark() || !canGuardNativeSelection(this.currentView)) { + this.release(false); + return; + } + // ViewPlugin.update runs before DocView publishes the new selection; + // an updateListener would allow the first expensive native write. + this.park ??= createNativeSelectionPark(this.currentView, { + shouldKeepParked: this.canPark, + finalizeClipboardText: options.finalizeClipboardText ?? ((text: string) => text), + suppressWrites: true, + insideContent: true, + }); + } + + private release(restoreSelection: boolean) { + this.park?.release(restoreSelection); + this.park = null; + } + + private scheduleSync = () => { + this.win.cancelAnimationFrame(this.frame); + this.frame = this.win.requestAnimationFrame(() => { + this.frame = 0; + this.nativeInputPending = false; + this.sync(); + }); + }; + + private onNativeInput = () => { + this.nativeInputPending = true; + this.release(true); + this.scheduleSync(); + }; + + private onBeforeInput = (event: InputEvent) => { + if (event.defaultPrevented) return; + const replacementText = event.inputType === "insertText" || event.inputType === "insertReplacementText" ? event.data : event.inputType === "insertLineBreak" || event.inputType === "insertParagraph" ? "\n" : event.inputType.startsWith("delete") ? "" : null; + if (this.park && event.cancelable && !event.isComposing && !this.currentView.state.readOnly && replacementText !== null) { + event.preventDefault(); + // WebKit snapshots the native target before beforeinput. Restoring + // here is too late for dictation/emoji input without a keydown. + const view = this.currentView; + const text = replacementText; + const selection = view.state.selection.main; + const userEvent = event.inputType.startsWith("delete") ? "delete.selection" : "input.type"; + const insert = () => view.state.update({ ...view.state.replaceSelection(text), scrollIntoView: true, userEvent }); + if (!view.state.facet(options.inputHandler).some((handler) => handler(view, selection.from, selection.to, text, insert))) view.dispatch(insert()); + return; + } + this.onNativeInput(); + }; + + private onKeyDown = (event: KeyboardEvent) => { + if (event.defaultPrevented || ((event.metaKey || event.ctrlKey) && !event.getModifierState("AltGraph"))) return; + if (event.key.length === 1 || ["Enter", "Backspace", "Delete", "Dead", "Process", "Unidentified"].includes(event.key) || event.isComposing || event.keyCode === 229) this.onNativeInput(); + }; + + private onCompositionStart = () => { + this.composing = true; + this.onNativeInput(); + }; + + private onCompositionEnd = () => { + this.composing = false; + this.scheduleSync(); + }; + + private onBlur = () => { + this.nativeInputPending = false; + this.release(false); + }; + + private onFocus = () => { + this.sync(); + this.scheduleSync(); + }; + + destroy() { + this.win.cancelAnimationFrame(this.frame); + const content = this.currentView.contentDOM; + content.removeEventListener("keydown", this.onKeyDown, true); + content.removeEventListener("beforeinput", this.onBeforeInput, true); + content.removeEventListener("compositionstart", this.onCompositionStart, true); + content.removeEventListener("compositionend", this.onCompositionEnd, true); + content.removeEventListener("focus", this.onFocus); + content.removeEventListener("blur", this.onBlur); + this.release(false); + } + }, + ); +}