Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/block drag handle: optimize performance

Adorian Doran6ec56ef4ec5b
diff --git a/apps/client/src/stylesheets/theme-next/notes/text.css b/apps/client/src/stylesheets/theme-next/notes/text.css
index 0b88dd3caf..09b21276ed 100644
--- a/apps/client/src/stylesheets/theme-next/notes/text.css
+++ b/apps/client/src/stylesheets/theme-next/notes/text.css
@@ -63,6 +63,11 @@
z-index: 1600;
}
+/* Inside the note, under the sticky formatting toolbar of the popup editor (998). */
+:root .block-drag-handle-container .ck.ck-block-toolbar-button {
+ z-index: auto;
+}
+
:root .ck.block-drag-handle:not(:hover) {
color: var(--main-border-color);
}
diff --git a/packages/ckeditor5/src/plugins/block_drag_handle.spec.ts b/packages/ckeditor5/src/plugins/block_drag_handle.spec.ts
index 4c23e8fc64..f2c0ed33b9 100644
--- a/packages/ckeditor5/src/plugins/block_drag_handle.spec.ts
+++ b/packages/ckeditor5/src/plugins/block_drag_handle.spec.ts
@@ -31,7 +31,10 @@ describe("BlockDragHandle", () => {
expect(getComputedStyle(button).cursor).toBe("grab");
expect(isBesideBlock(editor, button, 1)).toBe(true);
+ // A press focuses the handle, which keeps it shown for the drag that follows.
button.focus();
+ await nextFrames();
+ expect(buttonView?.isVisible).toBe(true);
button.click();
expect(document.activeElement).toBe(getEditable(editor));
@@ -55,8 +58,10 @@ describe("BlockDragHandle", () => {
await expect.poll(() => buttonView?.isVisible).toBe(false);
});
- it("follows its block when the window resizes or the page scrolls", async () => {
- const { editor, button } = await createEditor("<paragraph>on[]e</paragraph>");
+ it("follows its block when the window resizes or the content above it grows", async () => {
+ const { editor, button } = await createEditor(
+ "<paragraph>one</paragraph><paragraph>tw[]o</paragraph>"
+ );
const editorElement = editor.ui.view.element;
// Without a line height in pixels, the first line is measured from the font size.
getEditable(editor).style.lineHeight = "normal";
@@ -64,11 +69,72 @@ describe("BlockDragHandle", () => {
editorElement?.style.setProperty("margin", "40px 150px");
window.dispatchEvent(new Event("resize"));
window.dispatchEvent(new Event("resize"));
- await expect.poll(() => isBesideBlock(editor, button, 0)).toBe(true);
+ await expect.poll(() => isBesideBlock(editor, button, 1)).toBe(true);
+
+ // Content such as an embed can grow without a render of the editing view.
+ getBlock(editor, 0).style.setProperty("height", "200px");
+ await expect.poll(() => isBesideBlock(editor, button, 1)).toBe(true);
+ });
+
+ it("scrolls with its block, without being measured or moved again", async () => {
+ const { editor, button } = await createEditor(
+ `<paragraph>fi[]rst</paragraph>${"<paragraph>more</paragraph>".repeat(20)}`
+ );
+ const { scrollable } = placeInScrollingContainer(editor);
+ scrollable.style.setProperty("position", "relative");
+ scrollable.style.setProperty("height", "100px");
+ // As in a note, the editable does not scroll by itself.
+ const view = editor.editing.view;
+ view.change((writer) => {
+ const root = view.document.getRoot();
+ if (root) {
+ writer.setStyle("overflow", "visible", root);
+ }
+ });
+ // Moving the editor takes the focus away from it.
+ view.focus();
+ await expect.poll(() => editor.ui.focusTracker.isFocused).toBe(true);
+ editor.ui.update();
+ await nextFrames();
+ expect(isBesideBlock(editor, button, 0)).toBe(true);
+
+ const style = button.getAttribute("style");
+ let visibilityChanges = 0;
+ editor.plugins.get(BlockDragHandle).buttonView?.on("change:isVisible", () => {
+ visibilityChanges++;
+ });
+ for (const scrollTop of [ 20, 400, 0 ]) {
+ scrollable.scrollTop = scrollTop;
+ expect(isBesideBlock(editor, button, 0)).toBe(true);
+ await nextFrames();
+ // A render while the block is out of view keeps the handle for when it comes back.
+ editor.ui.update();
+ expect(button.getAttribute("style")).toBe(style);
+ }
+ expect(visibilityChanges).toBe(0);
+ });
- editorElement?.style.setProperty("margin", "80px 200px");
- document.dispatchEvent(new Event("scroll"));
+ it("follows its block and hides with it when the editable scrolls on its own", async () => {
+ const { editor, button } = await createEditor(
+ `<paragraph>fi[]rst</paragraph>${"<paragraph>more</paragraph>".repeat(20)}`
+ );
+ const buttonView = editor.plugins.get(BlockDragHandle).buttonView;
+ const view = editor.editing.view;
+ view.change((writer) => {
+ const root = view.document.getRoot();
+ if (root) {
+ writer.setStyle({ "overflow-y": "auto", height: "100px" }, root);
+ }
+ });
+ const editable = getEditable(editor);
+
+ editable.scrollTop = 10;
await expect.poll(() => isBesideBlock(editor, button, 0)).toBe(true);
+ editable.scrollTop = 400;
+ await expect.poll(() => buttonView?.isVisible).toBe(false);
+ editable.scrollTop = 0;
+ await expect.poll(() => buttonView?.isVisible).toBe(true);
+ expect(isBesideBlock(editor, button, 0)).toBe(true);
});
it("drags the selected block to where it is dropped", async () => {
@@ -502,7 +568,8 @@ async function createEditor(
/**
* Moves the editor into a scrolling container, between an element above it and one below it, as
- * a note's title and the space after its content surround it. Returns the two elements' rectangles.
+ * a note's title and the space after its content surround it. Returns the container and the two
+ * elements' rectangles.
*/
function placeInScrollingContainer(editor: ClassicEditor) {
const editorElement = editor.ui.view.element;
@@ -521,7 +588,18 @@ function placeInScrollingContainer(editor: ClassicEditor) {
scrollable.scrollIntoView();
onTestFinished(() => scrollable.remove());
- return { above: above.getBoundingClientRect(), below: below.getBoundingClientRect() };
+ return {
+ scrollable,
+ above: above.getBoundingClientRect(),
+ below: below.getBoundingClientRect()
+ };
+}
+
+/** Waits until the browser has drawn two frames, so that a scroll and its listeners have run. */
+function nextFrames() {
+ return new Promise((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(resolve));
+ });
}
/** Whether `button` is left of the editable, level with the first line of the block at `index`. */
diff --git a/packages/ckeditor5/src/plugins/block_drag_handle.ts b/packages/ckeditor5/src/plugins/block_drag_handle.ts
index 3e30089f3b..5926c0c810 100644
--- a/packages/ckeditor5/src/plugins/block_drag_handle.ts
+++ b/packages/ckeditor5/src/plugins/block_drag_handle.ts
@@ -1,5 +1,5 @@
import {
- BlockButtonView, ClipboardObserver, DomEmitterMixin, DragDrop, env,
+ BlockButtonView, ClipboardObserver, createElement, DomEmitterMixin, DragDrop, env,
findClosestScrollableAncestor, IconDragIndicator, type Model, type ModelElement,
ModelLiveRange, type ModelRange, type ModelSchema, Plugin, Rect, type ViewElement
} from "ckeditor5";
@@ -13,10 +13,19 @@ const TARGET_CLASS = "block-drag-handle-target";
* The drag handle of `BlockToolbar` without the toolbar, for the fixed-toolbar editor: a grip
* beside the block at the selection that drags the selected blocks to another place in the note.
* The drag follows `DragDropBlockToolbar`, which only works with `BlockToolbar` itself.
+ *
+ * The handle sits in a container right after the editable, inside whatever scrolls the blocks,
+ * so a scroll moves it along with them and needs no work here.
*/
export default class BlockDragHandle extends Plugin {
buttonView?: BlockButtonView;
+ private container?: HTMLElement;
+ /** The editable that `container` follows, observed for changes of its size. */
+ private domEditable?: HTMLElement;
+ /** The element that `container` is positioned against, as of the last placement. */
+ private containingBlock: Element | null = null;
+ private resizeObserver?: ResizeObserver;
private isDragging = false;
private isHovered = false;
private isUpdateScheduled = false;
@@ -62,7 +71,7 @@ export default class BlockDragHandle extends Plugin {
}
});
buttonView.on("execute", () => editor.editing.view.focus());
- editor.ui.view.body.add(buttonView);
+ buttonView.render();
this.buttonView = buttonView;
this.listenTo(editor.ui, "update", () => this.update());
@@ -70,10 +79,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.isMovedApartBy(domEvent.target)) {
+ this.scheduleUpdate();
+ }
+ }, { useCapture: true, usePassive: true });
this.domEmitter.listenTo(document, "dragover", (_evt, domEvent: DragEvent) => {
this.forwardDrag(domEvent);
@@ -88,10 +98,22 @@ export default class BlockDragHandle extends Plugin {
override destroy() {
this.domEmitter.stopListening();
+ this.resizeObserver?.disconnect();
+ this.container?.remove();
this.buttonView?.destroy();
super.destroy();
}
+ /**
+ * Whether a scroll of `scrolled` moves the blocks but not the placed handle: it holds the
+ * editable, but not the element that the handle is positioned against.
+ */
+ private isMovedApartBy(scrolled: EventTarget | null) {
+ const { domEditable, containingBlock } = this;
+ return scrolled instanceof Node && !!domEditable && !!containingBlock
+ && scrolled.contains(domEditable) && !scrolled.contains(containingBlock);
+ }
+
private scheduleUpdate() {
if (this.isUpdateScheduled) {
return;
@@ -118,19 +140,57 @@ export default class BlockDragHandle extends Plugin {
return;
}
+ const container = this.mount(buttonView.element, target.domEditable);
// The button must be visible before it can be measured.
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;
+ const buttonRect = this.placeButton(buttonView, buttonView.element, container, target);
+
+ // A handle that scrolls with its block is clipped with it. Any other one hides when its
+ // block scrolls out of the visible part of the editable.
+ if (!this.scrollsWith(target.domBlock)) {
+ const visibleRect = new Rect(target.domEditable).getVisible();
+ const buttonCenter = buttonRect.top + buttonRect.height / 2;
+ buttonView.isVisible = !!visibleRect
+ && buttonCenter >= visibleRect.top
+ && buttonCenter <= visibleRect.bottom;
+ }
this.updateTargets();
}
+ /**
+ * Puts the handle's container right after `domEditable`, inside whatever scrolls the blocks,
+ * and places the handle again whenever the size of the editable changes, as when an embed
+ * renders. Returns the container.
+ */
+ private mount(buttonElement: HTMLElement, domEditable: HTMLElement) {
+ if (!this.container) {
+ // The classes of the body collection, which the styles of the editor's UI expect.
+ this.container = createElement(document, "div", {
+ class: "ck ck-reset_all ck-rounded-corners block-drag-handle-container",
+ dir: this.editor.locale.uiLanguageDirection
+ }, [ buttonElement ]);
+ // A press focuses the handle, and the editor must stay focused for the drag to start.
+ this.editor.ui.focusTracker.add(this.container);
+ }
+ const container = this.container;
+ if (container.previousElementSibling === domEditable) {
+ return container;
+ }
+
+ domEditable.after(container);
+ this.domEditable = domEditable;
+ this.resizeObserver?.disconnect();
+ this.resizeObserver = new ResizeObserver(() => this.scheduleUpdate());
+ this.resizeObserver.observe(domEditable);
+ return container;
+ }
+
+ /** Whether the handle scrolls along with `domBlock`, within its closest scrolling ancestor. */
+ private scrollsWith(domBlock: HTMLElement) {
+ const scrollable = findClosestScrollableAncestor(domBlock);
+ return !!scrollable && !!this.containingBlock && scrollable.contains(this.containingBlock);
+ }
+
/** Tints the blocks that a drag moves while the pointer is over the visible handle. */
private updateTargets() {
const view = this.editor.editing.view;
@@ -196,6 +256,7 @@ export default class BlockDragHandle extends Plugin {
private placeButton(
buttonView: BlockButtonView,
buttonElement: HTMLElement,
+ container: HTMLElement,
target: BlockTarget
) {
const { domBlock, domEditable } = target;
@@ -204,6 +265,7 @@ export default class BlockDragHandle extends Plugin {
const lineHeight = parseInt(styles.lineHeight, 10) || parseInt(styles.fontSize, 10) * 1.2;
const editableRect = new Rect(domEditable);
const buttonRect = new Rect(buttonElement);
+ const containerRect = new Rect(container);
const left = this.editor.locale.uiLanguageDirection === "ltr"
? editableRect.left - buttonRect.width
@@ -211,9 +273,9 @@ 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;
+ buttonView.top = top - containerRect.top;
+ buttonView.left = left - containerRect.left;
+ this.containingBlock = container.offsetParent;
return buttonRect;
}
diff --git a/packages/ckeditor5/src/theme/block_drag_handle.css b/packages/ckeditor5/src/theme/block_drag_handle.css
index bf8750aea7..d44901af1d 100644
--- a/packages/ckeditor5/src/theme/block_drag_handle.css
+++ b/packages/ckeditor5/src/theme/block_drag_handle.css
@@ -3,6 +3,12 @@
color-mix(in srgb, var(--main-text-color, var(--ck-color-text)) 6%, transparent);
}
+.ck.ck-reset_all.block-drag-handle-container {
+ position: absolute;
+ top: 0;
+ left: 0;
+}
+
.ck.ck-button.block-drag-handle {
cursor: grab;