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
server/share pages: improve the scrolling mechanism for highlighting a block
Adorian Doran6ef788996988
diff --git a/apps/client/src/services/block_reference.spec.ts b/apps/client/src/services/block_reference.spec.tsindex 5ffbca9f5b..6944de887b 100644--- a/apps/client/src/services/block_reference.spec.ts+++ b/apps/client/src/services/block_reference.spec.ts@@ -35,13 +35,13 @@ vi.mock("./content_renderer.js", () => ({getEmbedBoxSize: () => "medium"}));-const scrollIntoView = vi.fn();+const scrollBy = vi.fn();const getComponentByEl = vi.fn();beforeEach(() => {vi.clearAllMocks();vi.useFakeTimers();- Element.prototype.scrollIntoView = scrollIntoView;+ Element.prototype.scrollBy = scrollBy;glob.getComponentByEl = getComponentByEl;});@@ -56,7 +56,7 @@ describe("consumeBlockReference", () => {consumeBlockReference(container, viewScope);- expect(scrollIntoView.mock.contexts[0]).toBe(container.querySelector("p"));+ expect(scrollBy).toHaveBeenCalledOnce();expect(getFlashed(container)).toEqual([ "A" ]);expect(viewScope.block).toBeUndefined();expect(showError).not.toHaveBeenCalled();diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsxindex 20e81829e9..5715852f31 100644--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx@@ -265,8 +265,8 @@ describe("ReadOnlyText ?block= handling", () => {});async function mountWithBlock(block: string | undefined, isVisible = true) {- const scrollIntoView = vi.fn();- Element.prototype.scrollIntoView = scrollIntoView;+ const scrollBy = vi.fn();+ Element.prototype.scrollBy = scrollBy;const note = buildNote({title: "Blocks",type: "text",@@ -299,20 +299,25 @@ describe("ReadOnlyText ?block= handling", () => {const isBlockKept = noteContext.viewScope?.block === block;await act(async () => {});- return { parent, noteContext, container, scrollIntoView, isBlockKept };+ return { parent, noteContext, container, scrollBy, isBlockKept };+ }++ function isFlashed(container: HTMLElement, block: string) {+ const element = container.querySelector(`[data-trilium-block-id='${block}']`);+ return element?.classList.contains("block-reference-flash");}it("reveals the referenced block once the content renders", async () => {- const { noteContext, container, scrollIntoView, isBlockKept } = await mountWithBlock("b2");+ const { noteContext, container, scrollBy, isBlockKept } = await mountWithBlock("b2");expect(isBlockKept).toBe(true);expect(noteContext.viewScope?.block).toBeUndefined();- expect(scrollIntoView.mock.contexts)- .toEqual([ container.querySelector("[data-trilium-block-id='b2']") ]);+ expect(scrollBy).toHaveBeenCalledOnce();+ expect([ isFlashed(container, "b1"), isFlashed(container, "b2") ]).toEqual([ false, true ]);});it("reveals a block of the open note when a link to it is followed", async () => {- const { parent, noteContext, container, scrollIntoView } = await mountWithBlock("b2");+ const { parent, noteContext, container, scrollBy } = await mountWithBlock("b2");const otherContext = new NoteContext("other-ntx");otherContext.noteId = noteContext.noteId;@@ -326,8 +331,8 @@ describe("ReadOnlyText ?block= handling", () => {await parent.handleEvent("noteSwitched", { noteContext, notePath: "" });});expect(noteContext.viewScope?.block).toBeUndefined();- expect(scrollIntoView.mock.contexts.at(-1))- .toBe(container.querySelector("[data-trilium-block-id='b1']"));+ expect(scrollBy).toHaveBeenCalledTimes(2);+ expect(isFlashed(container, "b1")).toBe(true);});it("labels a link to a block of its note by the text of the block", async () => {@@ -345,7 +350,7 @@ describe("ReadOnlyText ?block= handling", () => {});it("leaves a link to a block of its note to the editor while hidden", async () => {- const { parent, noteContext, container, scrollIntoView } = await mountWithBlock(+ const { parent, noteContext, container, scrollBy } = await mountWithBlock(undefined,false);@@ -356,7 +361,7 @@ describe("ReadOnlyText ?block= handling", () => {await parent.handleEvent("noteSwitched", { noteContext, notePath: "" });});expect(noteContext.viewScope?.block).toBe("b1");- expect(scrollIntoView).not.toHaveBeenCalled();+ expect(scrollBy).not.toHaveBeenCalled();});});diff --git a/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.spec.ts b/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.spec.tsindex c5dc8be7e4..57c3c02c60 100644--- a/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.spec.ts+++ b/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.spec.ts@@ -3,66 +3,113 @@ import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } frimport { applyTabs } from "../tabs/tabs_read_only.js";import { getBlockRangeElements, showBlockReference } from "./block_reference_read_only.js";-let scrollIntoView: MockInstance<Element["scrollIntoView"]>;+const SPACER = "<div style=\"height: 1000px\"></div>";++let scrollBy: MockInstance<Element["scrollBy"]>;+let mounted: HTMLElement[] = [];beforeEach(() => {vi.useFakeTimers();- scrollIntoView = vi.spyOn(Element.prototype, "scrollIntoView").mockImplementation(() => {});+ // Scrolls at once instead of smoothly, so that the specs can measure where the blocks land.+ scrollBy = vi.spyOn(Element.prototype, "scrollBy")+ .mockImplementation(function (this: Element, ...args: unknown[]) {+ this.scrollTop += (args[0] as ScrollToOptions).top ?? 0;+ });});afterEach(() => {vi.useRealTimers();vi.restoreAllMocks();+ for (const element of mounted) {+ element.remove();+ }+ mounted = [];+ document.documentElement.scrollTop = 0;});describe("showBlockReference", () => {- it("opens the collapsed blocks around a block, centers it and flashes it for a moment", () => {+ it("opens the collapsed blocks around a block and flashes it for a moment", () => {const container = buildContainer("<details><summary>s1</summary><details><summary>s2</summary>"+ "<p data-trilium-block-id=\"a\">A</p></details></details>");- const block = container.querySelector("p");expect(showBlockReference(container, "a")).toBe(true);expect([ ...container.querySelectorAll("details") ].map((details) => details.open)).toEqual([ true, true ]);- expect(scrollIntoView).toHaveBeenCalledExactlyOnceWith({- behavior: "smooth", block: "center"- });- expect(scrollIntoView.mock.contexts[0]).toBe(block);+ expect(scrollBy).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ behavior: "smooth" }));expect(getFlashed(container)).toEqual([ "A" ]);vi.advanceTimersByTime(1500);expect(getFlashed(container)).toEqual([]);});- it("shows the tab that holds a block, and scrolls to the title of a linked tab", () => {- const container = buildContainer(- "<div class=\"trilium-tabs\">"+ it("centers blocks that fit, keeping at least 15% of the scroll container above them", () => {+ const scroller = mountScroller(+ SPACER + block("short", 100)+ + SPACER + block("almost", 350)+ + SPACER + block("tall", 600)+ + SPACER + block("from", 50) + "<div style=\"height: 100px\"></div>" + block("to", 50)+ + SPACER+ );++ showBlockReference(scroller, "short");+ expect(getOffset(scroller, "short")).toBeCloseTo(150);++ showBlockReference(scroller, "almost");+ expect(getOffset(scroller, "almost")).toBeCloseTo(60);++ showBlockReference(scroller, "tall");+ expect(getOffset(scroller, "tall")).toBeCloseTo(60);++ showBlockReference(scroller, "from:to");+ expect(getOffset(scroller, "from")).toBeCloseTo(100);+ });++ it("scrolls the document when no ancestor of the blocks scrolls", () => {+ const page = mount("<div style=\"overflow-x: auto\">"+ + SPACER + SPACER + block("a", 100) + SPACER + SPACER + "</div>");+ const viewportHeight = document.documentElement.clientHeight;+ document.documentElement.scrollTop = 300;++ showBlockReference(page, "a");++ expect(getBlock(page, "a").getBoundingClientRect().top)+ .toBeCloseTo(Math.max(viewportHeight * 0.15, (viewportHeight - 100) / 2));+ });++ it("shows the tab that holds a block, and centers a linked tab from its title down", () => {+ const scroller = mountScroller(+ SPACER + "<div class=\"trilium-tabs\">"+ "<section class=\"trilium-tab\"><p class=\"trilium-tab-title\">A</p>"+ "<div class=\"trilium-tab-panel\"></div></section>"- + "<section class=\"trilium-tab\" data-trilium-block-id=\"t\">"- + "<p class=\"trilium-tab-title\">B</p><div class=\"trilium-tab-panel\">"+ + "<section class=\"trilium-tab\" style=\"display: contents\" "+ + "data-trilium-block-id=\"t\"><p class=\"trilium-tab-title\">B</p>"+ + "<div class=\"trilium-tab-panel\" style=\"height: 200px\">"+ "<p data-trilium-block-id=\"a\">a</p></div></section>"+ "<section class=\"trilium-tab\" data-trilium-block-id=\"bare\"><p>c</p></section>"- + "</div>"+ + "</div>" + SPACER);- applyTabs(container, { placeholder: "" });+ applyTabs(scroller, { placeholder: "" });const activeTitle = () =>- container.querySelector(".trilium-tab--active > .trilium-tab-title");- const titleB = container.querySelectorAll(".trilium-tab-title")[1];+ scroller.querySelector(".trilium-tab--active > .trilium-tab-title");expect(activeTitle()?.textContent).toBe("A");- showBlockReference(container, "a");+ showBlockReference(scroller, "a");expect(activeTitle()?.textContent).toBe("B");- showBlockReference(container, "t");- expect(scrollIntoView.mock.contexts[1]).toBe(titleB);+ showBlockReference(scroller, "t");+ const title = getBlock(scroller, "t").querySelector(".trilium-tab-title");+ const panel = getBlock(scroller, "t").querySelector(".trilium-tab-panel");+ const titleTop = title?.getBoundingClientRect().top ?? NaN;+ const height = (panel?.getBoundingClientRect().bottom ?? NaN) - titleTop;+ expect(titleTop - scroller.getBoundingClientRect().top).toBeCloseTo((400 - height) / 2);- showBlockReference(container, "bare");- expect(scrollIntoView.mock.contexts[2])- .toBe(container.querySelector("[data-trilium-block-id=bare]"));+ showBlockReference(scroller, "bare");+ expect(getOffset(scroller, "bare"))+ .toBeCloseTo((400 - getBlock(scroller, "bare").offsetHeight) / 2);});it("flashes the outermost elements of a range, in document order", () => {@@ -82,10 +129,10 @@ describe("showBlockReference", () => {expect(showBlockReference(container, "gone")).toBe(false);expect(showBlockReference(container, "a:b:c")).toBe(false);- expect(scrollIntoView).not.toHaveBeenCalled();+ expect(scrollBy).not.toHaveBeenCalled();expect(showBlockReference(container, "gone:b")).toBe(false);- expect(scrollIntoView.mock.contexts[0]).toBe(container.querySelector("p"));+ expect(scrollBy).toHaveBeenCalledOnce();expect(getFlashed(container)).toEqual([ "B" ]);});});@@ -110,6 +157,37 @@ function buildContainer(html: string) {return container;}+function mount(html: string) {+ const container = buildContainer(html);+ document.body.append(container);+ mounted.push(container);+ return container;+}++/** Mounts `html` in a scroll container 400px high. */+function mountScroller(html: string) {+ const scroller = mount(html);+ scroller.style.height = "400px";+ scroller.style.overflowY = "auto";+ return scroller;+}++function block(id: string, height: number) {+ return `<div data-trilium-block-id="${id}" style="height: ${height}px"></div>`;+}++function getBlock(container: HTMLElement, id: string) {+ const element = container.querySelector<HTMLElement>(`[data-trilium-block-id="${id}"]`);+ expect(element).not.toBeNull();+ return element as HTMLElement;+}++/** The distance from the top of `scroller` to the block `id`. */+function getOffset(scroller: HTMLElement, id: string) {+ return getBlock(scroller, id).getBoundingClientRect().top+ - scroller.getBoundingClientRect().top;+}+function getFlashed(container: HTMLElement) {return [ ...container.querySelectorAll(".block-reference-flash") ].map((element) => element.textContent);diff --git a/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.ts b/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.tsindex 5bd8ca719b..cbf757b542 100644--- a/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.ts+++ b/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.ts@@ -7,11 +7,13 @@ import { revealTab } from "../tabs/tabs_read_only.js";const FLASH_CLASS = "block-reference-flash";/** The duration of the `block-reference-flash` animation in `block_reference.css`. */const FLASH_DURATION_MS = 1500;+/** The smallest gap above the shown blocks, as a share of the height of their scroll container. */+const MIN_TOP_GAP = 0.15;/*** Scrolls to the blocks that `value`, a `block` link parameter, points at in `container` and- * flashes them. Of a broken range, the block found is shown. Returns `false` when a block is- * missing.+ * flashes them. The blocks are centered, but start at least 15% below the top of their scroll+ * container. Of a broken range, the block found is shown. Returns `false` when a block is missing.** The module imports nothing from CKEditor, so pages that only display content can load it.*/@@ -19,9 +21,10 @@ export function showBlockReference(container: Element, value: string) {const { start, end } = resolveBlockReference<HTMLElement>(container, value);const first = start ?? end;if (first) {+ const last = start && end ? end : first;reveal(first);- getBlockBoxes(first).top.scrollIntoView({ behavior: "smooth", block: "center" });- flashBlocks(start && end ? getBlockRangeElements(start, end) : [ first ]);+ scrollToBlocks(first, last);+ flashBlocks(getBlockRangeElements(first, last));}return !!start && !!end;@@ -58,6 +61,30 @@ export function getBlockRangeElements(start: Element, end: Element) {return getElementsInRange(range, range.commonAncestorContainer);}+/** Smoothly scrolls to center the blocks from `first` to `last`, keeping `MIN_TOP_GAP` above. */+function scrollToBlocks(first: Element, last: Element) {+ const scroller = getScrollContainer(first);+ const top = getBlockBoxes(first).top.getBoundingClientRect().top;+ const height = getBlockBoxes(last).bottom.getBoundingClientRect().bottom - top;+ const viewportTop = scroller === first.ownerDocument.scrollingElement+ ? 0+ : scroller.getBoundingClientRect().top + scroller.clientTop;+ const viewportHeight = scroller.clientHeight;+ const gap = Math.max(viewportHeight * MIN_TOP_GAP, (viewportHeight - height) / 2);+ scroller.scrollBy({ top: top - viewportTop - gap, behavior: "smooth" });+}++/** The nearest ancestor of `element` that scrolls vertically, else the document's scroller. */+function getScrollContainer(element: Element) {+ for (let parent = element.parentElement; parent; parent = parent.parentElement) {+ const { overflowY } = getComputedStyle(parent);+ if ([ "auto", "scroll" ].includes(overflowY) && parent.scrollHeight > parent.clientHeight) {+ return parent;+ }+ }+ return element.ownerDocument.scrollingElement ?? element.ownerDocument.documentElement;+}+/** Opens the `<details>` and shows the tabs that enclose `element`. */function reveal(element: Element) {let details = element.closest("details");