Skip to content

Build your personal knowledge base with Trilium Notes

fix(client): keep a tab's scroll position when its width changed while hidden (closes #11630)

Scott Campbell1b804f51de63
diff --git a/apps/client/src/widgets/containers/scroll_anchor.spec.ts b/apps/client/src/widgets/containers/scroll_anchor.spec.ts
new file mode 100644
index 0000000000..cccb2f8a50
--- /dev/null
+++ b/apps/client/src/widgets/containers/scroll_anchor.spec.ts
@@ -0,0 +1,109 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { findScrollAnchor, restoreScrollAnchor } from "./scroll_anchor";
+
+describe("findScrollAnchor", () => {
+ afterEach(() => {
+ document.body.innerHTML = "";
+ vi.restoreAllMocks();
+ });
+
+ it("takes the first block that reaches past the top edge", () => {
+ const container = buildContainer(`<p id="a"></p><p id="b"></p><p id="c"></p>`);
+ placeAt(byId(container, "a"), 20, 50);
+ placeAt(byId(container, "b"), 70, 50);
+ placeAt(byId(container, "c"), 120, 50);
+ expect(findScrollAnchor(container)).toEqual({ element: byId(container, "b"), offset: -30 });
+
+ expect(findScrollAnchor(buildContainer(""))).toBeNull();
+ });
+
+ it("descends into a block that the top edge cuts through", () => {
+ const container = buildContainer(
+ `<div id="content"><p id="a"></p><figure id="b"></figure></div>`);
+ placeAt(byId(container, "content"), -400, 1000);
+ placeAt(byId(container, "a"), -400, 50);
+ placeAt(byId(container, "b"), 110, 200);
+
+ expect(findScrollAnchor(container)).toEqual({ element: byId(container, "b"), offset: 10 });
+ });
+
+ it("skips inline, positioned and hidden boxes", () => {
+ const container = buildContainer(`
+ <p id="text"><strong id="inline" style="display: inline"></strong></p>
+ <div id="sticky" style="position: sticky"></div>
+ <div id="hidden"></div>
+ <p id="next"></p>`);
+ placeAt(byId(container, "text"), 80, 50);
+ placeAt(byId(container, "inline"), 110, 20);
+ placeAt(byId(container, "sticky"), 100, 40);
+ placeAt(byId(container, "hidden"), 0, 0, 0);
+ placeAt(byId(container, "next"), 130, 50);
+
+ // The paragraph stays the anchor, since its only child is inline.
+ expect(findScrollAnchor(container))
+ .toEqual({ element: byId(container, "text"), offset: -20 });
+
+ placeAt(byId(container, "text"), 20, 50);
+ expect(findScrollAnchor(container))
+ .toEqual({ element: byId(container, "next"), offset: 30 });
+ });
+});
+
+describe("restoreScrollAnchor", () => {
+ afterEach(() => {
+ document.body.innerHTML = "";
+ vi.restoreAllMocks();
+ });
+
+ it("scrolls by the distance the anchor moved, and only when it moved", () => {
+ const container = buildContainer(`<p id="a"></p>`);
+ const element = byId(container, "a");
+ const scrollTo = vi.fn();
+ container.scrollTo = scrollTo;
+ container.scrollTop = 500;
+
+ placeAt(element, 80.5, 50);
+ restoreScrollAnchor(container, { element, offset: -20 });
+ expect(scrollTo).not.toHaveBeenCalled();
+
+ placeAt(element, 160, 50);
+ restoreScrollAnchor(container, { element, offset: -20 });
+ expect(scrollTo).toHaveBeenCalledExactlyOnceWith({ top: 580, behavior: "instant" });
+ });
+
+ it("leaves the position alone once the anchor left the container", () => {
+ const container = buildContainer(`<p id="a"></p>`);
+ const element = byId(container, "a");
+ const scrollTo = vi.fn();
+ container.scrollTo = scrollTo;
+ placeAt(element, 400, 50);
+ element.remove();
+
+ restoreScrollAnchor(container, { element, offset: 0 });
+
+ expect(scrollTo).not.toHaveBeenCalled();
+ });
+});
+
+/** Builds a container whose visible area starts at y=100. */
+function buildContainer(html: string) {
+ const container = document.createElement("div");
+ container.innerHTML = html;
+ document.body.appendChild(container);
+ placeAt(container, 100, 400);
+ return container;
+}
+
+function byId(container: HTMLElement, id: string) {
+ const element = container.querySelector(`#${id}`);
+ if (!element) {
+ throw new Error(`No element with the ID ${id}.`);
+ }
+ return element;
+}
+
+/** 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));
+}
diff --git a/apps/client/src/widgets/containers/scroll_anchor.ts b/apps/client/src/widgets/containers/scroll_anchor.ts
new file mode 100644
index 0000000000..85794db10f
--- /dev/null
+++ b/apps/client/src/widgets/containers/scroll_anchor.ts
@@ -0,0 +1,50 @@
+/** The element at the top of a scrolled container, and how far its top is from the container's. */
+export interface ScrollAnchor {
+ element: Element;
+ offset: number;
+}
+
+/**
+ * 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.
+ */
+export function findScrollAnchor(container: HTMLElement): 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;
+
+ 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;
+ }
+
+ return anchor;
+}
+
+/** Scrolls `container` so that the anchor's element is back at its recorded offset. */
+export function restoreScrollAnchor(container: HTMLElement, { element, offset }: ScrollAnchor) {
+ if (!container.contains(element)) return;
+
+ const top = container.getBoundingClientRect().top;
+ const drift = element.getBoundingClientRect().top - top - offset;
+ if (Math.abs(drift) < 1) return;
+
+ // `behavior: "instant"` overrides the container's `scroll-behavior: smooth`.
+ container.scrollTo({ top: container.scrollTop + drift, behavior: "instant" });
+}
+
+/** 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
new file mode 100644
index 0000000000..83709cb0fb
--- /dev/null
+++ b/apps/client/src/widgets/containers/scrolling_container.spec.ts
@@ -0,0 +1,125 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import ScrollingContainer from "./scrolling_container";
+
+describe("ScrollingContainer", () => {
+ let paragraphTop: number;
+ let isDisplayed: boolean;
+ let frames: FrameRequestCallback[];
+
+ beforeEach(() => {
+ FakeResizeObserver.instances = [];
+ vi.stubGlobal("ResizeObserver", FakeResizeObserver);
+ frames = [];
+ vi.stubGlobal("requestAnimationFrame",
+ (callback: FrameRequestCallback) => frames.push(callback));
+ paragraphTop = 0;
+ isDisplayed = true;
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ document.body.innerHTML = "";
+ });
+
+ it("puts the block at the top back in place once shown again at another width", () => {
+ const { scrollTo, observer } = render();
+
+ isDisplayed = false;
+ observer.resize(0, 0);
+ isDisplayed = true;
+ paragraphTop = -120;
+ observer.resize(300, 400);
+
+ expect(scrollTo).toHaveBeenCalledExactlyOnceWith({ top: 880, behavior: "instant" });
+ });
+
+ it("keeps the anchor through a scroll event that arrives while hidden", () => {
+ const { container, scrollTo, observer } = render();
+
+ // A hidden element reads `scrollTop` as 0; the browser restores it once shown.
+ isDisplayed = false;
+ observer.resize(0, 0);
+ scrollAndWaitForFrame(container, 0);
+ isDisplayed = true;
+ container.scrollTop = 1000;
+ paragraphTop = 40;
+ observer.resize(300, 400);
+
+ expect(scrollTo).toHaveBeenCalledExactlyOnceWith({ top: 1040, behavior: "instant" });
+ });
+
+ it("leaves the position alone on a resize while shown, and when scrolled to the top", () => {
+ const { container, scrollTo, observer } = render();
+
+ paragraphTop = -120;
+ observer.resize(300, 400);
+
+ scrollAndWaitForFrame(container, 0);
+ observer.resize(0, 0);
+ observer.resize(500, 400);
+
+ expect(scrollTo).not.toHaveBeenCalled();
+ });
+
+ it("stops observing on cleanup", () => {
+ const { scrollingContainer, container, observer } = render();
+ const cancelAnimationFrame = vi.fn();
+ vi.stubGlobal("cancelAnimationFrame", cancelAnimationFrame);
+
+ container.dispatchEvent(new Event("scroll"));
+ scrollingContainer.cleanup();
+
+ expect(observer.disconnected).toBe(true);
+ expect(cancelAnimationFrame).toHaveBeenCalledWith(frames.length);
+ });
+
+ /** Renders a container scrolled so that a paragraph sits right at its top edge. */
+ function render() {
+ const scrollingContainer = new ScrollingContainer();
+ const container = scrollingContainer.render()[0];
+ const paragraph = document.createElement("p");
+ container.appendChild(paragraph);
+ document.body.appendChild(container);
+
+ vi.spyOn(container, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 0, 500, 400));
+ vi.spyOn(container, "getClientRects").mockImplementation(
+ () => (isDisplayed ? [ new DOMRect() ] : []) as unknown as DOMRectList);
+ vi.spyOn(paragraph, "getBoundingClientRect").mockImplementation(
+ () => new DOMRect(0, paragraphTop, 500, 50));
+ const scrollTo = vi.fn();
+ container.scrollTo = scrollTo;
+ scrollAndWaitForFrame(container, 1000);
+
+ const observer = FakeResizeObserver.instances[0];
+ return { scrollingContainer, container, scrollTo, observer };
+ }
+
+ function scrollAndWaitForFrame(container: HTMLElement, top: number) {
+ container.scrollTop = top;
+ container.dispatchEvent(new Event("scroll"));
+ for (const callback of frames.splice(0)) callback(0);
+ }
+});
+
+/** Reports a size of the observed container on demand, as the browser does after a layout. */
+class FakeResizeObserver {
+ static instances: FakeResizeObserver[] = [];
+ disconnected = false;
+
+ constructor(private callback: ResizeObserverCallback) {
+ FakeResizeObserver.instances.push(this);
+ }
+
+ observe() {}
+
+ disconnect() {
+ this.disconnected = true;
+ }
+
+ resize(width: number, height: number) {
+ const entry = { contentRect: new DOMRect(0, 0, width, height) } as ResizeObserverEntry;
+ this.callback([ entry ], this as unknown as ResizeObserver);
+ }
+}
diff --git a/apps/client/src/widgets/containers/scrolling_container.ts b/apps/client/src/widgets/containers/scrolling_container.ts
index 736bda8e03..196d8e7c28 100644
--- a/apps/client/src/widgets/containers/scrolling_container.ts
+++ b/apps/client/src/widgets/containers/scrolling_container.ts
@@ -2,11 +2,15 @@ import type { CommandListenerData, EventData, EventNames } from "../../component
import type NoteContext from "../../components/note_context.js";
import type BasicWidget from "../basic_widget.js";
import Container from "./container.js";
+import { findScrollAnchor, restoreScrollAnchor, type ScrollAnchor } from "./scroll_anchor.js";
import "./scrolling_container.css";
export default class ScrollingContainer extends Container<BasicWidget> {
private noteContext?: NoteContext;
+ private scrollAnchor: ScrollAnchor | null = null;
+ private pendingAnchorFrame: number | null = null;
+ private resizeObserver?: ResizeObserver;
constructor() {
super();
@@ -14,6 +18,54 @@ export default class ScrollingContainer extends Container<BasicWidget> {
this.class("scrolling-container");
}
+ doRender() {
+ super.doRender();
+ this.keepScrollAnchorWhileHidden(this.$widget[0]);
+ }
+
+ /**
+ * Puts the block at the top of the view back in place when the container is shown again: the
+ * browser restores only `scrollTop`, which is stale if the width changed while it was hidden.
+ */
+ private keepScrollAnchorWhileHidden(container: HTMLElement) {
+ 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;
+ };
+
+ container.addEventListener("scroll", () => {
+ if (this.pendingAnchorFrame !== null) return;
+ this.pendingAnchorFrame = requestAnimationFrame(() => {
+ this.pendingAnchorFrame = null;
+ recordAnchor();
+ });
+ }, { passive: true });
+
+ let wasHidden = false;
+ this.resizeObserver = new ResizeObserver(([ entry ]) => {
+ const isHidden = entry.contentRect.width === 0 && entry.contentRect.height === 0;
+ if (isHidden) {
+ wasHidden = true;
+ return;
+ }
+
+ if (wasHidden && this.scrollAnchor) {
+ restoreScrollAnchor(container, this.scrollAnchor);
+ }
+ wasHidden = false;
+ recordAnchor();
+ });
+ this.resizeObserver.observe(container);
+ }
+
+ cleanup() {
+ this.resizeObserver?.disconnect();
+ if (this.pendingAnchorFrame !== null) {
+ cancelAnimationFrame(this.pendingAnchorFrame);
+ }
+ }
+
setNoteContextEvent({ noteContext }: EventData<"setNoteContext">) {
this.noteContext = noteContext;
}