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
fix(client): expand collapsed blocks when revealing find matches and bookmarks
perfectra1ne3cba058ed5d
diff --git a/apps/client/src/services/collapsibles.spec.ts b/apps/client/src/services/collapsibles.spec.tsnew file mode 100644index 0000000000..f12b12569a--- /dev/null+++ b/apps/client/src/services/collapsibles.spec.ts@@ -0,0 +1,105 @@+import { describe, expect, it } from "vitest";++import { expandCollapsedAncestors } from "./collapsibles.js";++/** Builds a `<details>` element (optionally closed) with the given children appended. */+function makeDetails(open: boolean, ...children: Element[]): HTMLDetailsElement {+ const details = document.createElement("details");+ details.className = "trilium-collapsible";+ details.open = open;+ for (const child of children) {+ details.appendChild(child);+ }+ return details;+}++describe("expandCollapsedAncestors", () => {+ it("opens every closed <details> ancestor and returns true", () => {+ const leaf = document.createElement("span");+ const innerDetails = makeDetails(false, leaf);+ const outerDetails = makeDetails(false, innerDetails);+ document.body.appendChild(outerDetails);++ const result = expandCollapsedAncestors(leaf);++ expect(result).toBe(true);+ expect(innerDetails.open).toBe(true);+ expect(outerDetails.open).toBe(true);++ outerDetails.remove();+ });++ it("leaves already-open ancestors untouched and returns false", () => {+ const leaf = document.createElement("span");+ const innerDetails = makeDetails(true, leaf);+ const outerDetails = makeDetails(true, innerDetails);+ document.body.appendChild(outerDetails);++ const result = expandCollapsedAncestors(leaf);++ expect(result).toBe(false);+ expect(innerDetails.open).toBe(true);+ expect(outerDetails.open).toBe(true);++ outerDetails.remove();+ });++ it("returns false and does nothing for an element outside any <details>", () => {+ const el = document.createElement("span");+ document.body.appendChild(el);++ expect(expandCollapsedAncestors(el)).toBe(false);++ el.remove();+ });++ it("opens only the closed ancestors in a mixed open/closed chain", () => {+ const leaf = document.createElement("span");+ // Innermost is open, middle is closed, outermost is open.+ const innerDetails = makeDetails(true, leaf);+ const middleDetails = makeDetails(false, innerDetails);+ const outerDetails = makeDetails(true, middleDetails);+ document.body.appendChild(outerDetails);++ const result = expandCollapsedAncestors(leaf);++ expect(result).toBe(true);+ expect(innerDetails.open).toBe(true);+ expect(middleDetails.open).toBe(true);+ expect(outerDetails.open).toBe(true);++ outerDetails.remove();+ });++ it("expands the element itself when it is a closed <details>, plus closed ancestors", () => {+ // el.closest("details") matches el itself when el is a <details>.+ const innerDetails = makeDetails(false);+ const outerDetails = makeDetails(false, innerDetails);+ document.body.appendChild(outerDetails);++ const result = expandCollapsedAncestors(innerDetails);++ expect(result).toBe(true);+ expect(innerDetails.open).toBe(true);+ expect(outerDetails.open).toBe(true);++ outerDetails.remove();+ });++ it("handles a raw imported <details> nested inside another <details>", () => {+ const leaf = document.createElement("p");+ const rawDetails = document.createElement("details"); // no trilium-collapsible class+ rawDetails.open = false;+ rawDetails.appendChild(leaf);+ const outerCollapsible = makeDetails(false, rawDetails);+ document.body.appendChild(outerCollapsible);++ const result = expandCollapsedAncestors(leaf);++ expect(result).toBe(true);+ expect(rawDetails.open).toBe(true);+ expect(outerCollapsible.open).toBe(true);++ outerCollapsible.remove();+ });+});diff --git a/apps/client/src/services/collapsibles.ts b/apps/client/src/services/collapsibles.tsnew file mode 100644index 0000000000..381f092db6--- /dev/null+++ b/apps/client/src/services/collapsibles.ts@@ -0,0 +1,15 @@+/**+ * Opens every closed `<details>` ancestor of `el` (CKEditor collapsibles are native+ * `<details class="trilium-collapsible">`; raw imported `<details>` too). Returns true if+ * anything was expanded.+ */+export function expandCollapsedAncestors(el: Element): boolean {+ let expanded = false;+ for (let d = el.closest("details"); d; d = d.parentElement?.closest("details") ?? null) {+ if (!d.open) {+ d.open = true;+ expanded = true;+ }+ }+ return expanded;+}diff --git a/apps/client/src/widgets/find_in_html.ts b/apps/client/src/widgets/find_in_html.tsindex 0bf2bd376d..5c4d88be54 100644--- a/apps/client/src/widgets/find_in_html.ts+++ b/apps/client/src/widgets/find_in_html.ts@@ -2,6 +2,7 @@// uses for highlighting matches, use the same one on CodeMirror// for consistencyimport type Mark from "mark.js";+import { expandCollapsedAncestors } from "../services/collapsibles.js";import utils from "../services/utils.js";import type FindWidget from "./find.js";import type { FindResult } from "./find.js";@@ -85,6 +86,10 @@ export default class FindInHtml {if (this.$results?.length) {const $current = this.$results.eq(this.currentIndex);this.$results.removeClass(FIND_RESULT_SELECTED_CSS_CLASSNAME);+ // Reveal the match if it's hidden inside a closed <details> (e.g. a collapsed+ // CKEditor collapsible block) before scrolling to it, otherwise scrollIntoView is a+ // no-op for content that isn't actually visible (#10616).+ expandCollapsedAncestors($current[0]);$current[0].scrollIntoView({ block: 'center', inline: 'center'});$current.addClass(FIND_RESULT_SELECTED_CSS_CLASSNAME);}diff --git a/apps/client/src/widgets/find_in_text.ts b/apps/client/src/widgets/find_in_text.tsindex 049dd9f215..39c8b1ad00 100644--- a/apps/client/src/widgets/find_in_text.ts+++ b/apps/client/src/widgets/find_in_text.ts@@ -1,4 +1,5 @@-import type { FindAndReplaceState, FindCommandResult } from "@triliumnext/ckeditor5";+import type { CKTextEditor, FindAndReplaceState, FindCommandResult } from "@triliumnext/ckeditor5";+import { expandCollapsedAncestors } from "../services/collapsibles.js";import type { FindResult } from "./find.js";import type FindWidget from "./find.js";@@ -44,6 +45,7 @@ export default class FindInText {// totalFound = m ? m.length : 0;const options = { matchCase: matchCase, wholeWords: wholeWord };findResult = textEditor.execute("find", searchTerm, options);+ revealSelectedFindResult(textEditor);totalFound = findResult.results.length;const selection = model.document.selection;// If text is selected, highlight the corresponding result;@@ -99,6 +101,10 @@ export default class FindInText {} else {textEditor?.execute("findPrevious");}++ if (textEditor) {+ revealSelectedFindResult(textEditor);+ }}async findBoxClosed(totalFound: number, currentFound: number) {@@ -146,3 +152,26 @@ export default class FindInText {}}}++/**+ * Scrolls the currently-selected find match into view, expanding any closed `<details>`+ * ancestor (e.g. a collapsed CKEditor collapsible block) that hides it first.+ *+ * CKEditor's own debounced scroll (32ms, see `EditingView#scrollToTheSelection`) is a no-op for+ * a range that sits inside a closed `<details>`, since a collapsed subtree has no layout box to+ * scroll to. Deferred to the next animation frame so it runs after CKEditor has applied the+ * `.ck-find-result_selected` class and the DOM has settled; once we've expanded the ancestor+ * ourselves we re-scroll explicitly.+ *+ * Note: a later CKEditor reconversion (e.g. re-rendering the collapsible widget) may recreate+ * the `<details>` closed again. That's acceptable — it matches the collapsible plugin's+ * everything-loads-collapsed design; the user just has to find-next into it again.+ */+function revealSelectedFindResult(textEditor: CKTextEditor) {+ requestAnimationFrame(() => {+ const el = textEditor.editing.view.getDomRoot()?.querySelector(".ck-find-result_selected");+ if (el && expandCollapsedAncestors(el)) {+ el.scrollIntoView({ block: "center" });+ }+ });+}diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex 2e9e914ca1..f722ead23c 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -6,6 +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 dialog from "../../../services/dialog";import { t } from "../../../services/i18n";import link, { parseNavigationStateFromUrl } from "../../../services/link";@@ -63,10 +64,14 @@ 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(viewScope.bookmark!)}"]`);- el?.scrollIntoView({ behavior: "smooth", block: "center" });+ ?.querySelector(`[id="${CSS.escape(bookmark)}"]`);+ if (el) {+ expandCollapsedAncestors(el);+ el.scrollIntoView({ behavior: "smooth", block: "center" });+ }viewScope.bookmark = undefined;});}diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsxindex 7f040d2f82..d687b3a215 100644--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx@@ -10,6 +10,7 @@ import { useEffect, useLayoutEffect, useMemo, useRef as usePreactRef } from "preimport appContext from "../../../components/app_context";import FNote from "../../../entities/fnote";+import { expandCollapsedAncestors } from "../../../services/collapsibles";import { applyInlineMermaid, rewriteMermaidDiagramsInContainer } from "../../../services/content_renderer_text";import { getLocaleById } from "../../../services/i18n";import { applyLinkEmbeds } from "../../../services/link_embed";@@ -33,7 +34,10 @@ export default function ReadOnlyText({ note, noteContext, ntxId }: TypeWidgetProif (!viewScope?.bookmark || !readOnlyContentRef.current) return;const el = readOnlyContentRef.current.querySelector(`[id="${CSS.escape(viewScope.bookmark)}"]`);- el?.scrollIntoView({ behavior: "smooth", block: "center" });+ if (el) {+ expandCollapsedAncestors(el);+ el.scrollIntoView({ behavior: "smooth", block: "center" });+ }viewScope.bookmark = undefined;}, [blob]);