perf(editor): fix long SQL scroll jank after select all

This commit is contained in:
zipg authored and GitHub committed 2026-10-02 23:44:28 +08:00
1 parent 92da1bcbee
commit ef16749339
6 files changed
+460 -4

No files matched your search

@@ -99,6 +99,7 @@ import { createQueryEditorSqlShortcutDomHandler, isCharacterProducingShortcut }
import { createQueryEditorReplaceShortcutBindings, createQueryEditorReplaceShortcutHandler, createQueryEditorSearchKeymap } from "@/lib/editor/queryEditorSearchKeymap";
import { createQueryEditorEscapeHandler } from "@/lib/editor/queryEditorEscape";
import { buildQueryEditorLineNumbersExtension, createQueryEditorLineNumberAlignmentExtension } from "@/lib/editor/queryEditorLineNumbers";
import { keepGuttersAttachedDuringSync } from "@/lib/editor/codemirrorGutterSync";
import { searchKeymapWithoutModD } from "@/lib/editor/codemirrorSearchKeymap";
import { defaultKeymapForGlobalShortcuts } from "@/lib/editor/codemirrorDefaultKeymap";
import { createShowWhitespaceExtension } from "@/lib/editor/codemirrorShowWhitespace";
@@ -545,7 +546,7 @@ const {
const hoverContent = createQueryEditorHoverContent({ isDark, t, toast });
const { resolveSqlHoverTooltip } = useQueryEditorHover({ props, contextMenuOpen, settingsStore, connectionStore, metadata: completionMetadata, createHoverDom: hoverContent.createHoverDom, semanticCompletionEnabled: SEMANTIC_SQL_COMPLETION_ENABLED, maxCompletionTables: MAX_COMPLETION_TABLES });
const pointerInteractions = useQueryEditorPointer({ props, clearTableNavigationHover: () => clearTableNavigationHover(), emit });
const { registerEditorScrollbarPointerGuard, registerEditorNativeSelectionDragGuard, startEditorSelectionDrag } = pointerInteractions;
const { registerEditorScrollbarPointerGuard, registerEditorNativeSelectionDragGuard, registerEditorNativeSelectionScrollGuard, startEditorSelectionDrag } = pointerInteractions;
const tableDrop = useQueryEditorTableDrop({ props, view, editorRef, settingsStore });
const { hasDroppedTableReference, insertDroppedTableReference, queryEditorDropCaret, queryEditorDropCaretStyle, showQueryEditorDropCaretAt, hideQueryEditorDropCaret, registerTableReferenceDropListener, unregisterTableReferenceDropListener } = tableDrop;
const objectNavigation = useQueryEditorObjectNavigation({
@@ -1936,6 +1937,7 @@ const codeMirrorLifecycle = useQueryEditorCodeMirror({
createQueryEditorLineNumberAlignmentExtension(ViewPlugin),
currentStatementFrameExtension,
highlightActiveLineGutter(),
keepGuttersAttachedDuringSync(ViewPlugin),
highlightSpecialChars(),
initializedRuntime.historyResetComp.of(history()),
foldGutter({
@@ -2188,6 +2190,10 @@ const codeMirrorLifecycle = useQueryEditorCodeMirror({
// such a copy happens rather than here, because that is the only moment
// the normalizer is used.
registerEditorNativeSelectionDragGuard(view.value, { finalizeClipboardText: (text) => clipboardLineEndings(text) });
// The same park, held for the length of a scroll burst: scrolling a
// long selection costs macOS 26/27 the same per-run serialization on
// every scroll event that a drag pays per pointer move.
registerEditorNativeSelectionScrollGuard(view.value, { finalizeClipboardText: (text) => clipboardLineEndings(text) });
view.value.scrollDOM.addEventListener("scroll", scheduleEditorViewportEmit, {
passive: true,
});
@@ -1,6 +1,6 @@
import type { EditorView as EditorViewType } from "@codemirror/view";
import { startsQueryEditorSelectionDrag } from "@/lib/editor/queryEditorPointerSelection";
import { keepNativeSelectionParkedDuringDrag, type EditorNativeSelectionPark } from "@/lib/editor/queryEditorNativeSelection";
import { keepNativeSelectionParkedDuringDrag, keepNativeSelectionParkedWhileScrolling, type EditorNativeSelectionPark } from "@/lib/editor/queryEditorNativeSelection";
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
import { isMacOS } from "@/lib/backend/platform";
import type { QueryEditorProps } from "./queryEditorTypes";
@@ -27,6 +27,8 @@ export function useQueryEditorPointer(options: QueryEditorPointerOptions) {
let editorNativeSelectionParkCleanup: (() => void) | null = null;
let editorNativeSelectionScrollParkCleanup: (() => void) | null = null;
let editorSelectionDragCleanup: (() => void) | null = null;
let editorSelectionDropCursorEl: HTMLDivElement | null = null;
@@ -149,6 +151,23 @@ export function useQueryEditorPointer(options: QueryEditorPointerOptions) {
};
}
/**
* Parks the browser selection for the length of a scroll burst.
*
* Scrolling a long selection asks the macOS 26/27 web view for the same
* per-run text-services operation a drag or an open context menu does, once
* per scroll event, so a select-all document stalls and drops frames the
* whole way down. The editor keeps its own selection (CodeMirror draws it),
* so nothing about what is highlighted, copied or selected changes; see
* queryEditorNativeSelection.ts.
*/
function registerEditorNativeSelectionScrollGuard(currentView: EditorViewType, guardOptions: QueryEditorNativeSelectionDragGuardOptions = {}) {
editorNativeSelectionScrollParkCleanup?.();
editorNativeSelectionScrollParkCleanup = keepNativeSelectionParkedWhileScrolling(currentView, {
finalizeClipboardText: guardOptions.finalizeClipboardText,
});
}
function selectedRangeAtPointer(currentView: EditorViewType, event: MouseEvent) {
if (props.readOnly || event.button !== 0) return null;
if (!currentView.contentDOM.contains(event.target as Node | null)) return null;
@@ -335,8 +354,9 @@ export function useQueryEditorPointer(options: QueryEditorPointerOptions) {
function dispose() {
editorScrollbarPointerCleanup?.();
editorNativeSelectionParkCleanup?.();
editorNativeSelectionScrollParkCleanup?.();
editorSelectionDragCleanup?.();
}
return { registerEditorScrollbarPointerGuard, registerEditorNativeSelectionDragGuard, startEditorSelectionDrag, dispose };
return { registerEditorScrollbarPointerGuard, registerEditorNativeSelectionDragGuard, registerEditorNativeSelectionScrollGuard, startEditorSelectionDrag, dispose };
}
@@ -0,0 +1,143 @@
// @vitest-environment happy-dom
import { describe, expect, it, vi } from "vitest";
import type { EditorView } from "@codemirror/view";
import { keepGuttersAttachedDuringSync } from "../codemirrorGutterSync";
interface FakeGutterHost {
dom: { classList: { contains: (token: string) => boolean } };
syncGutters?: (detach: boolean) => void;
}
interface FakeInstance {
update: (update: { view: EditorView }) => void;
destroy: () => void;
}
interface FakeView {
plugins: Array<{ value: unknown }>;
}
/** A host whose `syncGutters` lives on the prototype, like CodeMirror's. */
function fakeGutterHost(token = "cm-gutters") {
const calls: boolean[] = [];
class Host {
dom = { classList: { contains: (candidate: string) => candidate === token } };
syncGutters(detach: boolean) {
calls.push(detach);
}
}
return { host: new Host() as unknown as FakeGutterHost, calls };
}
/** Minimal stand-in for `ViewPlugin.fromClass`, keeping the created instance. */
function fakeViewPlugin() {
const instances: FakeInstance[] = [];
const ViewPlugin = {
fromClass: (cls: new (view: EditorView) => FakeInstance) => ({
create: (view: EditorView) => {
const instance = new cls(view);
instances.push(instance);
return instance;
},
}),
} as unknown as typeof import("@codemirror/view").ViewPlugin;
return { ViewPlugin, instances };
}
function fakeView(hosts: FakeGutterHost[]): FakeView {
return { plugins: hosts.map((value) => ({ value })) };
}
function createInstance(hosts: FakeGutterHost[]) {
const { ViewPlugin, instances } = fakeViewPlugin();
const spec = keepGuttersAttachedDuringSync(ViewPlugin) as unknown as { create: (view: EditorView) => FakeInstance };
const view = fakeView(hosts);
expect(instances).toHaveLength(0);
const instance = spec.create(view as unknown as EditorView);
expect(instances).toHaveLength(1);
return { instance, view };
}
describe("keepGuttersAttachedDuringSync", () => {
it("forces the gutter sync to update in place instead of detaching", () => {
const gutter = fakeGutterHost();
createInstance([gutter.host]);
expect(Object.prototype.hasOwnProperty.call(gutter.host, "syncGutters")).toBe(true);
gutter.host.syncGutters?.(true);
gutter.host.syncGutters?.(false);
expect(gutter.calls).toEqual([false, false]);
});
it("leaves a sync shadow owned by somebody else untouched", () => {
const gutter = fakeGutterHost();
const own = vi.fn<(detach: boolean) => void>();
gutter.host.syncGutters = own;
createInstance([gutter.host]);
gutter.host.syncGutters?.(true);
expect(own).toHaveBeenCalledWith(true);
expect(Object.getOwnPropertyDescriptor(gutter.host, "syncGutters")?.value).toBe(own);
expect(gutter.calls).toEqual([]);
});
it("finds a gutter plugin that is created after the guard", () => {
const { ViewPlugin, instances } = fakeViewPlugin();
const spec = keepGuttersAttachedDuringSync(ViewPlugin) as unknown as { create: (view: EditorView) => FakeInstance };
const view = fakeView([]);
const instance = spec.create(view as unknown as EditorView);
expect(instances).toHaveLength(1);
const gutter = fakeGutterHost();
view.plugins.push({ value: gutter.host });
instance.update({ view: view as unknown as EditorView });
expect(Object.prototype.hasOwnProperty.call(gutter.host, "syncGutters")).toBe(true);
gutter.host.syncGutters?.(true);
expect(gutter.calls).toEqual([false]);
});
it("moves the guard when the gutter plugin value is replaced", () => {
const first = fakeGutterHost();
const { instance, view } = createInstance([first.host]);
const second = fakeGutterHost();
view.plugins = [{ value: second.host }];
instance.update({ view: view as unknown as EditorView });
expect(Object.prototype.hasOwnProperty.call(first.host, "syncGutters")).toBe(false);
expect(Object.prototype.hasOwnProperty.call(second.host, "syncGutters")).toBe(true);
first.host.syncGutters?.(true);
second.host.syncGutters?.(true);
expect(first.calls).toEqual([true]);
expect(second.calls).toEqual([false]);
});
it("restores the prototype method when the guard is destroyed", () => {
const gutter = fakeGutterHost();
const { instance } = createInstance([gutter.host]);
instance.destroy();
expect(Object.prototype.hasOwnProperty.call(gutter.host, "syncGutters")).toBe(false);
gutter.host.syncGutters?.(true);
expect(gutter.calls).toEqual([true]);
});
it("ignores plugin values that do not own the gutter element", () => {
const other = fakeGutterHost("cm-something-else");
const { instance } = createInstance([other.host]);
expect(Object.prototype.hasOwnProperty.call(other.host, "syncGutters")).toBe(false);
other.host.syncGutters?.(true);
expect(other.calls).toEqual([true]);
instance.destroy();
});
it("does not attach when the gutter plugin is missing", () => {
const { instance } = createInstance([]);
instance.destroy();
});
});
@@ -0,0 +1,110 @@
import type { Extension } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
/**
* CodeMirror's gutter view re-syncs every gutter element whenever the viewport
* moves, and for a viewport change that covers more than 20% of the viewport it
* first detaches `.cm-gutters` from the scroller and re-inserts it afterwards,
* on the assumption that mutating a detached subtree is cheaper. On WebKit the
* opposite is true: re-inserting a `position: sticky` subtree whose inline
* `min-height` is the full content height (~41 000px for a 2 500 line script)
* forces a style recalculation and a layout of the whole scroller on the next
* frame. Scrolling a long script therefore spends ~5ms of the ~10ms of
* per-frame main-thread work in the re-insert, and the frames that pay it are
* exactly the ones a fast scroll produces.
*
* Measured on the shipped 2 500 line script, scrolling the same page three
* times in one run (gutter sync as CodeMirror ships it / sync forced to update
* in place / as CodeMirror ships it): per frame, `view.measure()` 9.26ms →
* 4.15ms → 8.23ms, of which computed-style resolution 4.27ms → 1.40ms → 4.14ms
* and `getBoundingClientRect` 1.86ms → 1.16ms → 1.73ms; frame gap mean
* 20.3ms → 15.0ms → 18.6ms. Hiding `.cm-gutters` entirely accounts for the
* same ~5ms, so the difference is the detach/re-insert and not the gutter
* content.
*
* The in-place path is the same code with the detach flag off, which is what
* CodeMirror already does for viewport changes below that threshold: the
* elements a sync has to update are always bounded by the size of the viewport,
* never by how far the viewport moved. So the shadow only forces the flag off;
* everything else about the sync is CodeMirror's.
*/
interface GutterSyncHost {
dom?: { classList?: { contains: (token: string) => boolean } } | null;
syncGutters?: (detach: boolean) => void;
}
const SYNC_GUTTERS = "syncGutters";
/**
* The gutter view is a CodeMirror plugin value, and `view.plugins` is the only
* way to reach it. Identify it by the element it owns rather than by position,
* because the plugin list order is not part of the public API.
*/
function gutterSyncHost(view: EditorView): GutterSyncHost | null {
const plugins = (view as unknown as { plugins?: readonly { value?: unknown }[] }).plugins;
if (!plugins) return null;
for (const plugin of plugins) {
const value = plugin?.value as GutterSyncHost | undefined;
if (!value || typeof value.syncGutters !== "function") continue;
if (value.dom?.classList?.contains("cm-gutters")) return value;
}
return null;
}
interface GutterSyncGuard {
host: GutterSyncHost;
guarded: (detach: boolean) => void;
original: (detach: boolean) => void;
}
function attachGutterSyncGuard(view: EditorView): GutterSyncGuard | null {
const host = gutterSyncHost(view);
if (!host || typeof host.syncGutters !== "function") return null;
// Never clobber a shadow somebody else owns; without ours, the prototype
// method is what CodeMirror calls, and that is what we restore.
if (Object.prototype.hasOwnProperty.call(host, SYNC_GUTTERS)) return null;
const original = host.syncGutters;
const guarded = (_detach: boolean) => original.call(host, false);
host[SYNC_GUTTERS] = guarded;
return { host, guarded, original };
}
function releaseGutterSyncGuard(guard: GutterSyncGuard): void {
if (guard.host[SYNC_GUTTERS] === guard.guarded) delete guard.host[SYNC_GUTTERS];
}
/**
* Keeps the gutter DOM attached to the scroller while CodeMirror syncs it.
*
* Nothing about the gutter's content, layout or behaviour changes — the
* detached sync CodeMirror performs is the same element updates, and a detached
* element cannot report its width to the gutter's `scrollMargins` provider while
* it is out of the document either.
*/
export function keepGuttersAttachedDuringSync(ViewPlugin: typeof import("@codemirror/view").ViewPlugin): Extension {
return ViewPlugin.fromClass(
class {
private guard: GutterSyncGuard | null = null;
constructor(view: EditorView) {
this.guard = attachGutterSyncGuard(view);
}
update(update: import("@codemirror/view").ViewUpdate) {
// The gutter plugin may be created after this one, and a reconfigure
// that swaps the gutter extensions replaces the plugin value, so the
// guard is re-attached until it is holding the live host.
const held = this.guard;
if (held && held.host === gutterSyncHost(update.view) && held.host[SYNC_GUTTERS] === held.guarded) return;
if (held) releaseGutterSyncGuard(held);
this.guard = attachGutterSyncGuard(update.view);
}
destroy() {
if (this.guard) releaseGutterSyncGuard(this.guard);
this.guard = null;
}
},
);
}
@@ -163,11 +163,59 @@ function markerClass(rects: TrimmedSelectionRect[], index: number): string {
return classes.join(" ");
}
/**
* A whole selected line's rectangles, plus the line block they were measured
* against. The block is what tells a later frame whether the measurement is
* still valid: a line's own top and height only move when its layout changes,
* and comparing the two of them is free next to re-running `coordsAtPos`.
*/
interface CachedLineRects {
top: number;
height: number;
rects: TrimmedSelectionRect[];
}
/**
* A line block is only allowed to move by less than half a pixel before its
* cached rectangles are re-measured. The heights CodeMirror reports while it is
* still refining a viewport are fractional and can wobble by a fraction of a
* pixel, and re-measuring for that would put the cost straight back.
*/
const CACHED_BLOCK_TOLERANCE = 0.5;
/**
* Upper bound on the per-line cache. A selection that spans more lines than
* this keeps the memory bounded and simply re-measures the overflow, which is
* what the layer did for every line before the cache.
*/
const MAX_CACHED_SELECTION_LINES = 20_000;
export function trimmedSelectionLayer() {
// Rectangles are produced in layer coordinates, which are measured from the
// scroll container's content origin, so they do not move while the viewport
// scrolls — only the layer's own offset does. A line that is wholly selected
// keeps the same rectangle for as long as it stays selected, so it is
// measured once instead of on every scroll frame. Without this a select-all
// re-measured each visible line (four `coordsAtPos` calls plus a visual-line
// binary search apiece) on every frame of the scroll.
const wholeLineRects = new Map<number, CachedLineRects>();
let geometrySignature = "";
// Line metrics change with a font zoom without any document or selection
// transaction, so they are part of the cache key rather than only an
// invalidation on `geometryChanged`.
const currentGeometrySignature = (view: EditorView) => `${view.scaleX}:${view.scaleY}:${view.defaultCharacterWidth}:${view.defaultLineHeight}`;
return layer({
above: false,
class: "cm-trimmedSelectionLayer",
markers(view) {
const signature = currentGeometrySignature(view);
if (signature !== geometrySignature) {
geometrySignature = signature;
wholeLineRects.clear();
}
const markers: InstanceType<typeof RectangleMarker>[] = [];
const base = layerBase(view);
@@ -184,7 +232,31 @@ export function trimmedSelectionLayer() {
const from = Math.max(pos, line.from);
const to = Math.min(endPos, line.to);
const includesLineBreak = endPos > line.to && range.to > line.to;
rects.push(...markerRectsForLineRange(view, from, to, line.from, line.to, includesLineBreak, base));
// Only a line the selection covers in full, line break included,
// has a rectangle that is independent of where the viewport sits:
// the trimming only has to reason about the two lines the selection
// starts and ends on.
const coversWholeLine = from === line.from && to === line.to && includesLineBreak;
let measured: TrimmedSelectionRect[] | undefined;
if (coversWholeLine) {
const block = view.lineBlockAt(line.from);
const cached = wholeLineRects.get(line.from);
if (cached && Math.abs(cached.top - block.top) < CACHED_BLOCK_TOLERANCE && Math.abs(cached.height - block.height) < CACHED_BLOCK_TOLERANCE) {
measured = cached.rects;
} else {
measured = markerRectsForLineRange(view, from, to, line.from, line.to, includesLineBreak, base);
// An empty measurement means the line was not laid out when it
// was taken; caching that would leave the line unpainted until
// something else invalidated it.
if (measured.length) {
if (wholeLineRects.size >= MAX_CACHED_SELECTION_LINES) wholeLineRects.clear();
wholeLineRects.set(line.from, { top: block.top, height: block.height, rects: measured });
}
}
} else {
measured = markerRectsForLineRange(view, from, to, line.from, line.to, includesLineBreak, base);
}
rects.push(...measured);
const next = line.to + 1;
if (next <= pos) break;
@@ -201,6 +273,15 @@ export function trimmedSelectionLayer() {
return markers;
},
update(update) {
// A scroll only moves the viewport, and the cached rectangles are
// measured from the content origin, so they survive it — including the
// `geometryChanged` an update carries while a scroll is measuring lines
// for the first time, which is most of the frames of a long scroll and
// used to throw every cached line away. Anything that can move a line's
// own rectangle — an edit, a different selection, a re-measure after a
// font or theme change — is caught either here or by the block and
// geometry checks in `markers` above.
if (update.docChanged || update.selectionSet) wholeLineRects.clear();
return update.docChanged || update.selectionSet || update.viewportChanged || update.geometryChanged;
},
});
@@ -403,6 +403,102 @@ export function parkEditorNativeSelection(currentView: EditorView, options: Edit
return createNativeSelectionPark(currentView, { shouldKeepParked: () => true, finalizeClipboardText: options.finalizeClipboardText ?? ((text: string) => text) });
}
/**
* How long a scroll may go without another event before the scroll park is
* released. Long enough to bridge the gaps between wheel notches and between
* momentum frames, short enough that the browser selection is back before a
* user who stopped scrolling would notice anything missing.
*/
export const NATIVE_SELECTION_SCROLL_PARK_IDLE_MS = 200;
export interface EditorNativeSelectionScrollParkOptions extends EditorNativeSelectionParkOptions {
/** Override {@link NATIVE_SELECTION_SCROLL_PARK_IDLE_MS}; read once. */
idleMs?: number;
}
/**
* Parks the browser selection while a long selection is being scrolled.
*
* Scrolling a selection long enough to be worth parking costs the same
* per-run text-services operation the drag park exists for, and it costs it on
* every scroll event rather than on every pointer move, which is what makes
* scrolling a select-all document stall for a second at a time. Nothing about
* the scroll needs the browser selection: CodeMirror paints the selection
* itself, the viewport moves without it, and it is handed back to CodeMirror
* the moment the scroll goes quiet.
*
* The park lives for the length of a scroll burst — from the first `wheel` or
* `scroll` event until {@link NATIVE_SELECTION_SCROLL_PARK_IDLE_MS} after the
* last one — and only while the editor's own selection is long enough for the
* park to be worth it. `scroll` is what covers a scrollbar drag and a keyboard
* scroll, neither of which produces a `wheel` event; the first non-modifier key
* ends the burst as well, so typing quickly after a scroll never lands inside a
* parked window.
*
* @returns a cleanup function that removes the listeners and releases the park.
*/
export function keepNativeSelectionParkedWhileScrolling(currentView: EditorView, options: EditorNativeSelectionScrollParkOptions = {}): () => void {
const idleMs = options.idleMs ?? NATIVE_SELECTION_SCROLL_PARK_IDLE_MS;
const doc = currentView.dom.ownerDocument;
let park: EditorNativeSelectionPark | null = null;
let idleTimer: ReturnType<typeof setTimeout> | null = null;
const release = () => {
if (idleTimer !== null) {
clearTimeout(idleTimer);
idleTimer = null;
}
park?.release();
park = null;
};
// A burst re-parks as soon as the wheel turns again, so the handle is created
// once per burst and reused: creating one per event would add a frame loop
// and a pair of clipboard listeners per notch.
const holdParked = () => {
if (!park && isLargeEditorSelection(currentView)) {
park = createNativeSelectionPark(currentView, {
shouldKeepParked: () => isLargeEditorSelection(currentView),
suppressWrites: true,
finalizeClipboardText: options.finalizeClipboardText ?? ((text: string) => text),
});
}
if (idleTimer !== null) clearTimeout(idleTimer);
idleTimer = setTimeout(() => {
idleTimer = null;
release();
}, idleMs);
};
const endBurstOnKey = (event: KeyboardEvent) => {
if (event.key === "Shift" || event.key === "Alt" || event.key === "Control" || event.key === "Meta") return;
release();
};
// A press anywhere ends the burst before anything else reads the selection:
// a click places a caret and a press on selected text starts the drag park,
// and either one wants the browser selection back under CodeMirror's control.
// Captured on the document so it releases ahead of the drag guard's own
// capture listener on `contentDOM`.
const endBurstOnPointerDown = () => release();
// Read-only listeners: parking must never change how a scroll behaves. The
// scrollbar drag that `scroll` covers also arrives here as a `wheel`-less
// pointer gesture, which is why the guard is not built on the pointer.
currentView.scrollDOM.addEventListener("wheel", holdParked, { passive: true });
currentView.scrollDOM.addEventListener("scroll", holdParked, { passive: true });
doc.addEventListener("keydown", endBurstOnKey, true);
doc.addEventListener("pointerdown", endBurstOnPointerDown, true);
return () => {
currentView.scrollDOM.removeEventListener("wheel", holdParked);
currentView.scrollDOM.removeEventListener("scroll", holdParked);
doc.removeEventListener("keydown", endBurstOnKey, true);
doc.removeEventListener("pointerdown", endBurstOnPointerDown, true);
release();
};
}
/**
* Parks the browser selection for the length of a pointer gesture.
*