Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
Merge branch 'main' of https://github.com/TriliumNext/Trilium into feat/general-improvements-7
Adorian Doranddf3eb1de5e4
diff --cc packages/ckeditor5/src/plugins/block_drag_handle.spec.tsindex f2c0ed33b9,429ec63d45..321c7983bf--- a/packages/ckeditor5/src/plugins/block_drag_handle.spec.ts+++ b/packages/ckeditor5/src/plugins/block_drag_handle.spec.ts@@@ -69,74 -64,68 +69,129 @@@ 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);- editorElement?.style.setProperty("margin", "80px 200px");- document.dispatchEvent(new Event("scroll"));+ // 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);+ });++ 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("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("follows scrolls and resizes only while the editor has focus", async () => {+ const { editor } = await createEditor("<paragraph>on[]e</paragraph>");+ getEditable(editor).blur();+ await expect.poll(() => editor.ui.focusTracker.isFocused).toBe(false);+ const requestAnimationFrame = vi.spyOn(window, "requestAnimationFrame");+ onTestFinished(() => requestAnimationFrame.mockRestore());++ document.dispatchEvent(new Event("scroll"));+ window.dispatchEvent(new Event("resize"));+ expect(requestAnimationFrame).not.toHaveBeenCalled();++ editor.editing.view.focus();+ await expect.poll(() => editor.ui.focusTracker.isFocused).toBe(true);+ document.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>"@@@ -566,10 -555,86 +621,87 @@@ async function createEditorreturn { 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;+ }+/*** 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;diff --cc packages/ckeditor5/src/plugins/block_drag_handle.tsindex 5926c0c810,485faaf98c..7f9318fc23--- a/packages/ckeditor5/src/plugins/block_drag_handle.ts+++ b/packages/ckeditor5/src/plugins/block_drag_handle.ts@@@ -20,12 -17,6 +20,12 @@@ const TARGET_CLASS = "block-drag-handleexport 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;++ /** Whether the handle scrolls along with its block, as of the last placement. */++ private isScrollingWithBlock = false;+ private resizeObserver?: ResizeObserver;private isDragging = false;private isHovered = false;private isUpdateScheduled = false;@@@ -98,22 -87,29 +96,42 @@@override destroy() {this.domEmitter.stopListening();+ this.layoutEmitter.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.+ * Moves the handle with its block on resizes and scrolls while the editor has focus. Without+ * focus there is no handle to move.*/- private isMovedApartBy(scrolled: EventTarget | null) {- const { domEditable, containingBlock } = this;- return scrolled instanceof Node && !!domEditable && !!containingBlock- && scrolled.contains(domEditable) && !scrolled.contains(containingBlock);+ private followLayoutChanges(isFocused: boolean) {+ if (!isFocused) {+ this.layoutEmitter.stopListening();+ return;+ }++ this.layoutEmitter.listenTo(window, "resize", () => this.scheduleUpdate());+ this.layoutEmitter.listenTo(document, "scroll", (_evt, domEvent: Event) => {- if (this.canMoveEditable(domEvent.target as Node)) {++ if (this.mustFollowScrollOf(domEvent.target)) {+ this.scheduleUpdate();+ }+ }, { useCapture: true, usePassive: true });+ }+++ /**++ * Whether the placed handle has to follow a scroll of `scrolled`: a scroll inside the editable++ * moves the blocks away from the handle, and a scroll of an element that holds the editable++ * moves a handle that does not scroll with its block.++ */++ private mustFollowScrollOf(scrolled: EventTarget | null) {++ const domEditable = this.domEditable;++ return scrolled instanceof Node && !!domEditable && (domEditable.contains(scrolled)++ || (!this.isScrollingWithBlock && scrolled.contains(domEditable)));+ }+private scheduleUpdate() {if (this.isUpdateScheduled) {return;@@@ -126,7 -122,16 +144,10 @@@});}- /** 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) {@@@ -146,51 -152,6 +168,48 @@@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.++ * and places the handle again whenever the size of the editable changes while the editor has++ * focus, 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 = new ResizeObserver(() => {++ if (this.editor.ui.focusTracker.isFocused) {++ this.scheduleUpdate();++ }++ });+ this.resizeObserver.observe(domEditable);+ return container;+ }+- /** Whether the handle scrolls along with `domBlock`, within its closest scrolling ancestor. */- private scrollsWith(domBlock: HTMLElement) {++ /**++ * Whether the handle in `container` scrolls along with `domBlock`, within the closest scrolling++ * ancestor of the block.++ */++ private scrollsWith(container: HTMLElement, domBlock: HTMLElement) {+ const scrollable = findClosestScrollableAncestor(domBlock);- return !!scrollable && !!this.containingBlock && scrollable.contains(this.containingBlock);++ const containingBlock = container.offsetParent;++ return !!scrollable && !!containingBlock && scrollable.contains(containingBlock);+ }+/** Tints the blocks that a drag moves while the pointer is over the visible handle. */private updateTargets() {const view = this.editor.editing.view;@@@ -250,33 -211,53 +269,62 @@@}/**- * 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.++ * Finds where the handle goes in its container: 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 and the handle does not scroll with the block.*/- private placeButton(+ private findPosition(buttonView: BlockButtonView,buttonElement: HTMLElement,- container: HTMLElement,target: BlockTarget) {const { domBlock, domEditable } = target;++ const container = this.mount(buttonElement, domEditable);+ 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 containerRect = new Rect(container);const left = this.editor.locale.uiLanguageDirection === "ltr"? editableRect.left - buttonRect.width: editableRect.right;const top = new Rect(domBlock).top + paddingTop + (lineHeight - buttonRect.height) / 2;-- buttonRect.moveTo(left, top);++ const position = { top: top - containerRect.top, left: left - containerRect.left };- buttonView.top = top - containerRect.top;- buttonView.left = left - containerRect.left;- this.containingBlock = container.offsetParent;- const buttonCenter = buttonRect.top + buttonRect.height / 2;++ // 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.++ this.isScrollingWithBlock = this.scrollsWith(container, domBlock);++ if (this.isScrollingWithBlock) {++ return position;++ }+++ const visibleRect = editableRect.getVisible();++ const buttonCenter = top + buttonRect.height / 2;+ if (!visibleRect || buttonCenter < visibleRect.top || buttonCenter > visibleRect.bottom) {+ return null;+ }+- return buttonRect.toAbsoluteRect();++ return position;+ }++ /**+ * 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;}