Skip to content

Build your personal knowledge base with Trilium Notes

perf(client): find the scroll anchor from the last one instead of the first block (closes #11630)

Scott Campbellcd864ce37dd1
diff --git a/apps/client/src/widgets/containers/scroll_anchor.spec.ts b/apps/client/src/widgets/containers/scroll_anchor.spec.ts
index cccb2f8a50..7abe539550 100644
--- a/apps/client/src/widgets/containers/scroll_anchor.spec.ts
+++ b/apps/client/src/widgets/containers/scroll_anchor.spec.ts
@@ -48,6 +48,48 @@ describe("findScrollAnchor", () => {
expect(findScrollAnchor(container))
.toEqual({ element: byId(container, "next"), offset: 30 });
});
+
+ describe("with the previous anchor", () => {
+ it("walks forward from it without reading the blocks above it", () => {
+ const { container, rects } = buildParagraphs([ -500, -400, -300, -200, -100, 20 ]);
+ const previous = byId(container, "p3");
+
+ expect(findScrollAnchor(container, previous))
+ .toEqual({ element: byId(container, "p5"), offset: -80 });
+ expect(rects[0]).not.toHaveBeenCalled();
+ expect(rects[2]).not.toHaveBeenCalled();
+ });
+
+ it("walks back from it when the content moved down", () => {
+ const { container, rects } = buildParagraphs([ -200, -100, 20, 120, 220, 320 ]);
+ const previous = byId(container, "p4");
+
+ expect(findScrollAnchor(container, previous))
+ .toEqual({ element: byId(container, "p2"), offset: -80 });
+ expect(rects[0]).not.toHaveBeenCalled();
+ expect(rects[5]).not.toHaveBeenCalled();
+ });
+
+ it("searches all blocks when it left the container", () => {
+ const { container, rects } = buildParagraphs([ -200, -100, 20, 120, 220, 320 ]);
+ const previous = byId(container, "p4");
+ previous.remove();
+
+ expect(findScrollAnchor(container, previous))
+ .toEqual({ element: byId(container, "p2"), offset: -80 });
+ expect(rects[0]).toHaveBeenCalled();
+ });
+
+ it("searches all blocks when it is hidden", () => {
+ const { container, rects } = buildParagraphs([ -200, -100, 20, 120, 220, 320 ]);
+ const previous = byId(container, "p4");
+ placeAt(previous, 0, 0, 0);
+
+ expect(findScrollAnchor(container, previous))
+ .toEqual({ element: byId(container, "p2"), offset: -80 });
+ expect(rects[0]).toHaveBeenCalled();
+ });
+ });
});
describe("restoreScrollAnchor", () => {
@@ -95,6 +137,18 @@ function buildContainer(html: string) {
return container;
}
+/**
+ * Builds a container with a `content` block holding paragraphs `p0`, `p1`… 100px tall at `tops`,
+ * and returns the mocks of their boxes.
+ */
+function buildParagraphs(tops: number[]) {
+ const paragraphs = tops.map((_, index) => `<p id="p${index}"></p>`).join("");
+ const container = buildContainer(`<div id="content">${paragraphs}</div>`);
+ placeAt(byId(container, "content"), tops[0], 1000);
+ const rects = tops.map((top, index) => placeAt(byId(container, `p${index}`), top, 100));
+ return { container, rects };
+}
+
function byId(container: HTMLElement, id: string) {
const element = container.querySelector(`#${id}`);
if (!element) {
@@ -105,5 +159,6 @@ function byId(container: HTMLElement, id: string) {
/** Mocks the box of `element`, since happy-dom does no layout. */
function placeAt(element: Element, top: number, height: number, width = 100) {
- vi.spyOn(element, "getBoundingClientRect").mockReturnValue(new DOMRect(0, top, width, height));
+ return vi.spyOn(element, "getBoundingClientRect")
+ .mockReturnValue(new DOMRect(0, top, width, height));
}
diff --git a/apps/client/src/widgets/containers/scroll_anchor.ts b/apps/client/src/widgets/containers/scroll_anchor.ts
index 85794db10f..4816ec86fb 100644
--- a/apps/client/src/widgets/containers/scroll_anchor.ts
+++ b/apps/client/src/widgets/containers/scroll_anchor.ts
@@ -5,30 +5,24 @@ export interface ScrollAnchor {
}
/**
- * Finds the innermost block at the top edge of `container`: the first child that reaches past the
- * edge, descending into it while the edge cuts through it.
+ * Finds the innermost block at the top edge of `container`. With `previous`, the anchor found last
+ * time, each level searches from it instead of from the first child.
*/
-export function findScrollAnchor(container: HTMLElement): ScrollAnchor | null {
+export function findScrollAnchor(
+ container: HTMLElement,
+ previous?: Element | null
+): ScrollAnchor | null {
const top = container.getBoundingClientRect().top;
let anchor: ScrollAnchor | null = null;
let parent: Element = container;
- descend: for (;;) {
- for (const child of parent.children) {
- const rect = child.getBoundingClientRect();
- if (rect.bottom <= top || (rect.width === 0 && rect.height === 0)) continue;
+ for (;;) {
+ const found = findFirstChildPastEdge(parent, top, getChildContaining(parent, previous));
+ if (!found) break;
- const style = getComputedStyle(child);
- const isInline = style.display.startsWith("inline");
- if (isInline || UNANCHORED_POSITIONS.includes(style.position)) continue;
-
- anchor = { element: child, offset: rect.top - top };
- if (rect.top >= top) break descend;
-
- parent = child;
- continue descend;
- }
- break;
+ anchor = { element: found.element, offset: found.rect.top - top };
+ if (found.rect.top >= top) break;
+ parent = found.element;
}
return anchor;
@@ -46,5 +40,60 @@ export function restoreScrollAnchor(container: HTMLElement, { element, offset }:
container.scrollTo({ top: container.scrollTop + drift, behavior: "instant" });
}
+interface PlacedElement {
+ element: Element;
+ rect: DOMRect;
+}
+
+/**
+ * Finds the first block among the children of `parent` that reaches past `top`. A usable `start`
+ * limits the search to the siblings between it and the edge; otherwise all children are scanned.
+ */
+function findFirstChildPastEdge(
+ parent: Element,
+ top: number,
+ start: Element | null
+): PlacedElement | null {
+ const startRect = start && getAnchorableRect(start);
+ if (!start || !startRect) return scanForward(parent.firstElementChild, top);
+ if (startRect.bottom <= top) return scanForward(start.nextElementSibling, top);
+
+ let first: PlacedElement = { element: start, rect: startRect };
+ let sibling = start.previousElementSibling;
+ while (sibling) {
+ const rect = getAnchorableRect(sibling);
+ if (rect && rect.bottom <= top) break;
+ if (rect) first = { element: sibling, rect };
+ sibling = sibling.previousElementSibling;
+ }
+ return first;
+}
+
+function scanForward(from: Element | null, top: number): PlacedElement | null {
+ for (let element = from; element; element = element.nextElementSibling) {
+ const rect = element.getBoundingClientRect();
+ if (rect.bottom > top && getAnchorableRect(element, rect)) return { element, rect };
+ }
+ return null;
+}
+
+/** Returns the box of `element` when it can anchor the scroll position: a visible in-flow block. */
+function getAnchorableRect(element: Element, rect = element.getBoundingClientRect()) {
+ if (rect.width === 0 && rect.height === 0) return null;
+
+ const style = getComputedStyle(element);
+ const isInline = style.display.startsWith("inline");
+ if (isInline || UNANCHORED_POSITIONS.includes(style.position)) return null;
+ return rect;
+}
+
+/** Returns the child of `parent` that is or holds `element`, if any. */
+function getChildContaining(parent: Element, element: Element | null | undefined): Element | null {
+ for (let current = element; current; current = current.parentElement) {
+ if (current.parentElement === parent) return current;
+ }
+ return null;
+}
+
/** Positions whose boxes do not move with the content around them. */
const UNANCHORED_POSITIONS = [ "absolute", "fixed", "sticky" ];
diff --git a/apps/client/src/widgets/containers/scrolling_container.spec.ts b/apps/client/src/widgets/containers/scrolling_container.spec.ts
index 83709cb0fb..20b49a0746 100644
--- a/apps/client/src/widgets/containers/scrolling_container.spec.ts
+++ b/apps/client/src/widgets/containers/scrolling_container.spec.ts
@@ -63,6 +63,21 @@ describe("ScrollingContainer", () => {
expect(scrollTo).not.toHaveBeenCalled();
});
+ it("searches from the last anchor on the next scroll", () => {
+ const { container } = render();
+ const first = document.createElement("p");
+ const second = document.createElement("p");
+ container.prepend(first, second);
+ const firstRect = vi.spyOn(first, "getBoundingClientRect")
+ .mockReturnValue(new DOMRect(0, -150, 500, 50));
+ vi.spyOn(second, "getBoundingClientRect").mockReturnValue(new DOMRect(0, -100, 500, 50));
+
+ paragraphTop = -20;
+ scrollAndWaitForFrame(container, 1020);
+
+ expect(firstRect).not.toHaveBeenCalled();
+ });
+
it("stops observing on cleanup", () => {
const { scrollingContainer, container, observer } = render();
const cancelAnimationFrame = vi.fn();
diff --git a/apps/client/src/widgets/containers/scrolling_container.ts b/apps/client/src/widgets/containers/scrolling_container.ts
index 196d8e7c28..ae5c8c4d94 100644
--- a/apps/client/src/widgets/containers/scrolling_container.ts
+++ b/apps/client/src/widgets/containers/scrolling_container.ts
@@ -31,7 +31,9 @@ export default class ScrollingContainer extends Container<BasicWidget> {
const recordAnchor = () => {
// A hidden container reads `scrollTop` as 0, so the recorded anchor stays.
if (!container.getClientRects().length) return;
- this.scrollAnchor = container.scrollTop > 0 ? findScrollAnchor(container) : null;
+ this.scrollAnchor = container.scrollTop > 0
+ ? findScrollAnchor(container, this.scrollAnchor?.element)
+ : null;
};
container.addEventListener("scroll", () => {