Skip to content

Build your personal knowledge base with Trilium Notes

fix(client): consume ?bookmark= only after read-only content renders

perfectra1n695138300953
diff --git a/apps/client/src/services/bookmark_jump.spec.ts b/apps/client/src/services/bookmark_jump.spec.ts
new file mode 100644
index 0000000000..caf9df732d
--- /dev/null
+++ b/apps/client/src/services/bookmark_jump.spec.ts
@@ -0,0 +1,77 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { consumeBookmark } from "./bookmark_jump.js";
+import type { ViewScope } from "./link.js";
+
+function buildContainer(html: string) {
+ const container = document.createElement("div");
+ container.innerHTML = html;
+ return container;
+}
+
+describe("consumeBookmark", () => {
+ const scrollIntoView = vi.fn();
+
+ beforeEach(() => {
+ scrollIntoView.mockClear();
+ Element.prototype.scrollIntoView = scrollIntoView;
+ });
+
+ it("expands collapsed <details> ancestors, scrolls to the target and consumes the bookmark", () => {
+ const container = buildContainer(
+ `<details><summary>outer</summary>` +
+ `<details><summary>inner</summary><p><a id="deep"></a>target</p></details>` +
+ `</details>`
+ );
+ const viewScope: ViewScope = { bookmark: "deep" };
+
+ consumeBookmark(container, viewScope);
+
+ for (const details of container.querySelectorAll("details")) {
+ expect(details.open).toBe(true);
+ }
+ expect(scrollIntoView).toHaveBeenCalledWith({ behavior: "smooth", block: "center" });
+ expect(viewScope.bookmark).toBeUndefined();
+ });
+
+ it("leaves the bookmark unconsumed when the content container is not rendered yet", () => {
+ const viewScope: ViewScope = { bookmark: "deep" };
+
+ consumeBookmark(null, viewScope);
+ consumeBookmark(undefined, viewScope);
+
+ expect(viewScope.bookmark).toBe("deep");
+ expect(scrollIntoView).not.toHaveBeenCalled();
+ });
+
+ it("finds ids that would break a CSS selector, and consumes dangling bookmarks without scrolling", () => {
+ const weirdId = `we"ird ]id`;
+ const container = buildContainer("<p>anchor here</p>");
+ const anchor = container.querySelector("p");
+ anchor?.setAttribute("id", weirdId);
+ const weirdScope: ViewScope = { bookmark: weirdId };
+
+ consumeBookmark(container, weirdScope);
+
+ expect(scrollIntoView).toHaveBeenCalledTimes(1);
+ expect(weirdScope.bookmark).toBeUndefined();
+
+ scrollIntoView.mockClear();
+ const danglingScope: ViewScope = { bookmark: "missing-anchor" };
+
+ consumeBookmark(buildContainer("<p>no anchor here</p>"), danglingScope);
+
+ expect(scrollIntoView).not.toHaveBeenCalled();
+ expect(danglingScope.bookmark).toBeUndefined();
+ });
+
+ it("no-ops without a bookmark or view scope", () => {
+ const viewScope: ViewScope = {};
+
+ consumeBookmark(buildContainer("<p><a id='deep'></a></p>"), viewScope);
+ consumeBookmark(buildContainer("<p><a id='deep'></a></p>"), undefined);
+
+ expect(scrollIntoView).not.toHaveBeenCalled();
+ expect(viewScope.bookmark).toBeUndefined();
+ });
+});
diff --git a/apps/client/src/services/bookmark_jump.ts b/apps/client/src/services/bookmark_jump.ts
new file mode 100644
index 0000000000..da6bc2a5c5
--- /dev/null
+++ b/apps/client/src/services/bookmark_jump.ts
@@ -0,0 +1,28 @@
+import { expandCollapsedAncestors } from "./collapsibles.js";
+import type { ViewScope } from "./link.js";
+
+/**
+ * Consumes `viewScope.bookmark` (the `?bookmark=` link parameter) against a rendered note
+ * content container: expands any closed collapsible ancestor of the target, scrolls to it,
+ * and clears the bookmark so it fires only once (mirrors `consumeSearchTerms`).
+ *
+ * When `container` is null/undefined the bookmark is left untouched — the content is not
+ * rendered yet, and a later call (after the content commit) must still find it. A bookmark
+ * whose anchor does not exist in the content is consumed without scrolling, so a dangling
+ * id does not re-fire on every content reload.
+ */
+export function consumeBookmark(container: ParentNode | null | undefined, viewScope: ViewScope | null | undefined) {
+ if (!viewScope?.bookmark || !container) {
+ return;
+ }
+
+ // Exact id comparison instead of an interpolated attribute selector — bookmark names are
+ // user text and may contain quotes/brackets that break CSS selector parsing.
+ const bookmark = viewScope.bookmark;
+ const el = [...container.querySelectorAll("[id]")].find((candidate) => candidate.id === bookmark);
+ if (el) {
+ expandCollapsedAncestors(el);
+ el.scrollIntoView({ behavior: "smooth", block: "center" });
+ }
+ viewScope.bookmark = undefined;
+}
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index f28e2b9bec..5f3694e8e5 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -6,7 +6,7 @@ import { deferred } from "@triliumnext/commons";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import appContext from "../../../components/app_context";
-import { expandCollapsedAncestors } from "../../../services/collapsibles";
+import { consumeBookmark } from "../../../services/bookmark_jump";
import dialog from "../../../services/dialog";
import { t } from "../../../services/i18n";
import link, { parseNavigationStateFromUrl } from "../../../services/link";
@@ -70,15 +70,8 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
// Scroll to bookmark anchor if navigated with ?bookmark=...
const viewScope = noteContext?.viewScope;
if (viewScope?.bookmark) {
- const bookmark = viewScope.bookmark;
requestAnimationFrame(() => {
- const el = watchdogRef.current?.editor?.editing.view.getDomRoot()
- ?.querySelector(`[id="${CSS.escape(bookmark)}"]`);
- if (el) {
- expandCollapsedAncestors(el);
- el.scrollIntoView({ behavior: "smooth", block: "center" });
- }
- viewScope.bookmark = undefined;
+ consumeBookmark(watchdogRef.current?.editor?.editing.view.getDomRoot(), viewScope);
});
}
},
diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx
new file mode 100644
index 0000000000..5415274b5d
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx
@@ -0,0 +1,87 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+// Imported by ReadOnlyText only for its content styles — irrelevant (and heavy) under happy-dom.
+vi.mock("@triliumnext/ckeditor5", () => ({}));
+vi.mock("../../../services/content_renderer_text", () => ({
+ applyInlineMermaid: vi.fn(async () => {}),
+ rewriteMermaidDiagramsInContainer: vi.fn(async () => {})
+}));
+vi.mock("../../../services/link_embed", () => ({ applyLinkEmbeds: vi.fn(async () => {}) }));
+vi.mock("../../../services/math", () => ({ renderMathInElement: vi.fn() }));
+vi.mock("../../../services/syntax_highlight", () => ({ formatCodeBlocks: vi.fn(async () => {}) }));
+vi.mock("../../../services/search_jump", () => ({ consumeSearchTerms: vi.fn() }));
+vi.mock("./read_only_helper", () => ({ applyReferenceLinks: vi.fn(async () => {}) }));
+vi.mock("./utils", () => ({
+ loadIncludedNote: vi.fn(async () => {}),
+ refreshIncludedNote: vi.fn(),
+ setupImageOpening: vi.fn()
+}));
+
+import type NoteContext from "../../../components/note_context";
+import type FNote from "../../../entities/fnote";
+import type { ViewScope } from "../../../services/link";
+import ReadOnlyText from "./ReadOnlyText";
+
+function makeNote(blobPromise: Promise<unknown>) {
+ return {
+ noteId: "note1",
+ getBlob: () => blobPromise,
+ getLabelValue: () => null
+ } as unknown as FNote;
+}
+
+describe("ReadOnlyText ?bookmark= handling", () => {
+ let container: HTMLDivElement;
+
+ beforeEach(() => {
+ Element.prototype.scrollIntoView = vi.fn();
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ });
+
+ afterEach(() => {
+ render(null, container);
+ container.remove();
+ });
+
+ it("keeps the bookmark until the content renders, then expands the collapsible and consumes it", async () => {
+ let resolveBlob!: (blob: unknown) => void;
+ const note = makeNote(new Promise((resolve) => { resolveBlob = resolve; }));
+ const viewScope: ViewScope = { bookmark: "deep-anchor" };
+ const noteContext = {
+ viewScope,
+ setContextData: vi.fn()
+ } as unknown as NoteContext;
+
+ await act(async () => {
+ render(
+ <ReadOnlyText
+ note={note}
+ noteContext={noteContext}
+ ntxId={null}
+ viewScope={viewScope}
+ parentComponent={undefined}
+ />,
+ container
+ );
+ });
+
+ // The mount effect runs while the blob is still loading (empty container) — it must not
+ // consume the bookmark yet, or the post-load pass has nothing left to reveal.
+ expect(viewScope.bookmark).toBe("deep-anchor");
+
+ await act(async () => {
+ resolveBlob({
+ content:
+ `<details class="trilium-collapsible"><summary>Hidden</summary>` +
+ `<p><a id="deep-anchor"></a>target</p></details>`
+ });
+ });
+
+ const details = container.querySelector("details");
+ expect(details?.open).toBe(true);
+ expect(viewScope.bookmark).toBeUndefined();
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
index 6f5c46db9a..ca648ab9b9 100644
--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
@@ -10,7 +10,7 @@ import { useEffect, useLayoutEffect, useMemo, useRef as usePreactRef } from "pre
import appContext from "../../../components/app_context";
import FNote from "../../../entities/fnote";
-import { expandCollapsedAncestors } from "../../../services/collapsibles";
+import { consumeBookmark } from "../../../services/bookmark_jump";
import { applyInlineMermaid, rewriteMermaidDiagramsInContainer } from "../../../services/content_renderer_text";
import { getLocaleById } from "../../../services/i18n";
import { applyLinkEmbeds } from "../../../services/link_embed";
@@ -29,17 +29,13 @@ export default function ReadOnlyText({ note, noteContext, ntxId }: TypeWidgetPro
const { isRtl } = useNoteLanguage(note);
const readOnlyContentRef = usePreactRef<HTMLDivElement>(null);
- // Scroll to bookmark anchor if navigated with ?bookmark=...
+ // Scroll to bookmark anchor if navigated with ?bookmark=... Gated on the blob: the mount
+ // run fires while the content is still loading (empty container), and consuming the
+ // bookmark there would leave nothing for the post-load run — this effect only re-fires
+ // on [blob].
useEffect(() => {
- const viewScope = noteContext?.viewScope;
- if (!viewScope?.bookmark || !readOnlyContentRef.current) return;
-
- const el = readOnlyContentRef.current.querySelector(`[id="${CSS.escape(viewScope.bookmark)}"]`);
- if (el) {
- expandCollapsedAncestors(el);
- el.scrollIntoView({ behavior: "smooth", block: "center" });
- }
- viewScope.bookmark = undefined;
+ if (!blob) return;
+ consumeBookmark(readOnlyContentRef.current, noteContext?.viewScope);
}, [blob]);
// Jump to the first search match (and pre-fill the find bar) when navigated from search results.