Skip to content

Build your personal knowledge base with Trilium Notes

perf(text): stop the block drag handle forcing layout on scroll

Elian Doran1313345cf5eb
diff --git a/packages/ckeditor5/src/plugins/block_drag_handle.spec.ts b/packages/ckeditor5/src/plugins/block_drag_handle.spec.ts
index eeff42bd32..35f8fbfd82 100644
--- a/packages/ckeditor5/src/plugins/block_drag_handle.spec.ts
+++ b/packages/ckeditor5/src/plugins/block_drag_handle.spec.ts
@@ -3,7 +3,7 @@ import {
DragDrop, env, Essentials, Paragraph, Table, TableCaption
} from "ckeditor5";
import editorStylesheetUrl from "ckeditor5/ckeditor5.css?url";
-import { beforeAll, describe, expect, it, onTestFinished } from "vitest";
+import { beforeAll, describe, expect, it, onTestFinished, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
import Admonition from "./admonition/admonition.js";
@@ -64,6 +64,44 @@ describe("BlockDragHandle", () => {
await expect.poll(() => isBesideBlock(editor, button, 0)).toBe(true);
});
+ it("follows its block through a scroll, measuring before it changes the handle", async () => {
+ const { editor, button, scroller } = await createScrolledEditor(3);
+ const buttonView = editor.plugins.get(BlockDragHandle).buttonView;
+ const forcedLayouts = watchForcedLayouts(button);
+
+ await scrollTo(scroller, 20);
+ expect(isBesideBlock(editor, button, 3)).toBe(true);
+ expect(buttonView?.isVisible).toBe(true);
+
+ // Out of the visible part of the editable, and back.
+ const bottom = scroller.scrollHeight - scroller.clientHeight;
+ await scrollTo(scroller, bottom);
+ expect(buttonView?.isVisible).toBe(false);
+ await scrollTo(scroller, bottom - 50);
+ expect(buttonView?.isVisible).toBe(false);
+ await scrollTo(scroller, 0);
+ expect(buttonView?.isVisible).toBe(true);
+ expect(isBesideBlock(editor, button, 3)).toBe(true);
+
+ expect(forcedLayouts).toEqual([]);
+ });
+
+ it("ignores the scrolls of elements that cannot move the editable", async () => {
+ const { editor } = await createEditor("<paragraph>on[]e</paragraph>");
+ const other = document.createElement("div");
+ document.body.append(other);
+ onTestFinished(() => other.remove());
+ const requestAnimationFrame = vi.spyOn(window, "requestAnimationFrame");
+ onTestFinished(() => requestAnimationFrame.mockRestore());
+
+ other.dispatchEvent(new Event("scroll"));
+ expect(requestAnimationFrame).not.toHaveBeenCalled();
+
+ // A scrolled element inside the editable moves the blocks it holds.
+ getBlock(editor, 0).dispatchEvent(new Event("scroll"));
+ expect(requestAnimationFrame).toHaveBeenCalledOnce();
+ });
+
it("drags the selected block to where it is dropped", async () => {
const { editor, button } = await createEditor(
"<paragraph>fi[]rst</paragraph><paragraph>second</paragraph>"
@@ -302,6 +340,83 @@ async function createEditor(
return { editor, button };
}
+/**
+ * Creates an editor of 40 paragraphs in a scrolled box, as the note pane holds it, with the
+ * selection in the paragraph at `index`.
+ */
+async function createScrolledEditor(index: number) {
+ const paragraphs = Array.from({ length: 40 }, (_, paragraphIndex) => (
+ paragraphIndex === index ? "<paragraph>bl[]ock</paragraph>" : "<paragraph>text</paragraph>"
+ ));
+ const { editor, button } = await createEditor(paragraphs.join(""));
+ const scroller = document.createElement("div");
+ scroller.style.setProperty("height", "200px");
+ scroller.style.setProperty("overflow", "auto");
+ document.body.prepend(scroller);
+ onTestFinished(() => scroller.remove());
+
+ const editorElement = editor.ui.view.element;
+ if (editorElement) {
+ scroller.append(editorElement);
+ }
+ editor.editing.view.focus();
+ await expect.poll(() => editor.ui.focusTracker.isFocused).toBe(true);
+ editor.ui.update();
+
+ return { editor, button, scroller };
+}
+
+/** Scrolls `scroller` to `top` and waits for the frame in which the handle follows. */
+async function scrollTo(scroller: HTMLElement, top: number) {
+ if (Math.round(scroller.scrollTop) === top) {
+ throw new Error(`The box is already scrolled to ${top}.`);
+ }
+
+ const scrolled = new Promise((resolve) => {
+ scroller.addEventListener("scroll", resolve, { once: true });
+ });
+ scroller.scrollTop = top;
+ await scrolled;
+ await new Promise(requestAnimationFrame);
+}
+
+/**
+ * Lists the layout reads of `BlockDragHandle` that follow a change to `button`: each makes the
+ * browser compute style and layout again within the frame.
+ */
+function watchForcedLayouts(button: HTMLElement) {
+ const forcedLayouts: string[] = [];
+ const observer = new MutationObserver(() => undefined);
+ observer.observe(button, { attributes: true });
+ const readers = [
+ { owner: Element.prototype, name: "getBoundingClientRect" },
+ { owner: Element.prototype, name: "getClientRects" },
+ { owner: window, name: "getComputedStyle" }
+ ] as const;
+ for (const { owner, name } of readers) {
+ const read = owner[name] as (...args: unknown[]) => unknown;
+ Object.defineProperty(owner, name, {
+ configurable: true,
+ writable: true,
+ value(this: unknown, ...args: unknown[]) {
+ if (new Error().stack?.includes("/block_drag_handle.ts")) {
+ const changes = observer.takeRecords().map((record) => record.attributeName);
+ if (changes.length) {
+ forcedLayouts.push(`${name} after a change to ${changes.join(", ")}`);
+ }
+ }
+ return read.apply(this, args);
+ }
+ });
+ onTestFinished(() => {
+ Object.defineProperty(owner, name, { configurable: true, writable: true, value: read });
+ });
+ }
+ onTestFinished(() => observer.disconnect());
+
+ return forcedLayouts;
+}
+
/** Whether `button` is left of the editable, level with the first line of the block at `index`. */
function isBesideBlock(editor: ClassicEditor, button: HTMLElement, index: number) {
const buttonRect = button.getBoundingClientRect();
diff --git a/packages/ckeditor5/src/plugins/block_drag_handle.ts b/packages/ckeditor5/src/plugins/block_drag_handle.ts
index ee19bc313e..ebbc8ae344 100644
--- a/packages/ckeditor5/src/plugins/block_drag_handle.ts
+++ b/packages/ckeditor5/src/plugins/block_drag_handle.ts
@@ -13,6 +13,7 @@ export default class BlockDragHandle extends Plugin {
buttonView?: BlockButtonView;
private isDragging = false;
private isUpdateScheduled = false;
+ private buttonSize?: { width: number; height: number };
private readonly domEmitter = new (DomEmitterMixin())();
static get pluginName() {
@@ -54,10 +55,11 @@ export default class BlockDragHandle extends Plugin {
this.listenTo(editor.ui.focusTracker, "change:isFocused", () => this.update());
this.domEmitter.listenTo(window, "resize", () => this.scheduleUpdate());
- this.domEmitter.listenTo(document, "scroll", () => this.scheduleUpdate(), {
- useCapture: true,
- usePassive: true
- });
+ this.domEmitter.listenTo(document, "scroll", (_evt, domEvent: Event) => {
+ if (this.canMoveEditable(domEvent.target as Node)) {
+ this.scheduleUpdate();
+ }
+ }, { useCapture: true, usePassive: true });
this.domEmitter.listenTo(document, "dragover", (_evt, domEvent: DragEvent) => {
this.forwardDrag(domEvent);
@@ -89,7 +91,16 @@ export default class BlockDragHandle extends Plugin {
});
}
- /** Shows the handle beside the first selected block, or hides it. */
+ /** Whether a scroll of `scrolled` can move the editable, or a block inside it. */
+ private canMoveEditable(scrolled: Node) {
+ const domEditable = this.editor.ui.getEditableElement();
+ return !!domEditable && (scrolled.contains(domEditable) || domEditable.contains(scrolled));
+ }
+
+ /**
+ * Shows the handle beside the first selected block, or hides it. Measures everything before
+ * changing the button, so that a scroll costs no layout of its own.
+ */
private update() {
const buttonView = this.buttonView;
if (!buttonView?.element || this.isDragging) {
@@ -97,21 +108,15 @@ export default class BlockDragHandle extends Plugin {
}
const target = this.getTarget();
- if (!target) {
+ const position = target && this.findPosition(buttonView, buttonView.element, target);
+ if (!position) {
buttonView.isVisible = false;
return;
}
- // The button must be visible before it can be measured.
+ buttonView.top = position.top;
+ buttonView.left = position.left;
buttonView.isVisible = true;
- const buttonRect = this.placeButton(buttonView, buttonView.element, target);
-
- // Hide the handle when its block scrolls out of the visible part of the editable.
- const visibleRect = new Rect(target.domEditable).getVisible();
- const buttonCenter = buttonRect.top + buttonRect.height / 2;
- buttonView.isVisible = !!visibleRect
- && buttonCenter >= visibleRect.top
- && buttonCenter <= visibleRect.bottom;
}
private getTarget(): BlockTarget | null {
@@ -135,20 +140,22 @@ export default class BlockDragHandle extends Plugin {
}
/**
- * Places the handle outside the editable, level with the first line of the block.
- * Same geometry as `BlockToolbar`. Returns the handle's rectangle in the viewport.
+ * Finds where the handle goes: outside the editable, level with the first line of the block,
+ * as `BlockToolbar` places it. Returns nothing when that is out of the visible part of the
+ * editable.
*/
- private placeButton(
+ private findPosition(
buttonView: BlockButtonView,
buttonElement: HTMLElement,
target: BlockTarget
) {
const { domBlock, domEditable } = target;
+ const buttonRect = this.measureButton(buttonView, buttonElement);
const styles = window.getComputedStyle(domBlock);
const paddingTop = parseInt(styles.paddingTop, 10);
const lineHeight = parseInt(styles.lineHeight, 10) || parseInt(styles.fontSize, 10) * 1.2;
const editableRect = new Rect(domEditable);
- const buttonRect = new Rect(buttonElement);
+ const visibleRect = editableRect.getVisible();
const left = this.editor.locale.uiLanguageDirection === "ltr"
? editableRect.left - buttonRect.width
@@ -156,10 +163,30 @@ export default class BlockDragHandle extends Plugin {
const top = new Rect(domBlock).top + paddingTop + (lineHeight - buttonRect.height) / 2;
buttonRect.moveTo(left, top);
- const absoluteRect = buttonRect.toAbsoluteRect();
- buttonView.top = absoluteRect.top;
- buttonView.left = absoluteRect.left;
+ const buttonCenter = buttonRect.top + buttonRect.height / 2;
+ if (!visibleRect || buttonCenter < visibleRect.top || buttonCenter > visibleRect.bottom) {
+ return null;
+ }
+
+ return buttonRect.toAbsoluteRect();
+ }
+
+ /**
+ * Measures the handle. A hidden handle has no box, so it gets the size it had when last shown
+ * instead of being shown to be measured, which would cost a layout on every scroll. Only the
+ * first measurement shows it.
+ */
+ private measureButton(buttonView: BlockButtonView, buttonElement: HTMLElement) {
+ if (!buttonView.isVisible && !this.buttonSize) {
+ buttonView.isVisible = true;
+ }
+ const buttonRect = new Rect(buttonElement);
+ if (buttonView.isVisible) {
+ this.buttonSize = { width: buttonRect.width, height: buttonRect.height };
+ } else {
+ Object.assign(buttonRect, this.buttonSize);
+ }
return buttonRect;
}