Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/collapsible lists: temporarily expand to reveal search results

Adorian Dorane67f048e43ba
diff --git a/packages/ckeditor5/src/plugins/collapsible_list_items.spec.ts b/packages/ckeditor5/src/plugins/collapsible_list_items.spec.ts
index 6309e0080b..6c5d4a9b55 100644
--- a/packages/ckeditor5/src/plugins/collapsible_list_items.spec.ts
+++ b/packages/ckeditor5/src/plugins/collapsible_list_items.spec.ts
@@ -1,4 +1,4 @@
-import { _setModelData as setModelData, ClassicEditor, keyCodes, List, Paragraph, TodoList, Typing, Undo, type ModelElement } from "ckeditor5";
+import { _setModelData as setModelData, ClassicEditor, FindAndReplace, FindAndReplaceEditing, keyCodes, List, Paragraph, TodoList, Typing, Undo, type ModelElement } from "ckeditor5";
import { beforeEach, describe, expect, it } from "vitest";
import { createTestEditor, getEditorElement } from "../../test/editor-kit.js";
@@ -454,6 +454,83 @@ describe("CollapsibleListItems", () => {
editor.execute("toggleListCollapse");
expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
});
+
+ describe("find-in-note reveal", () => {
+ // A fresh editor *with* the find plugin (the default one above deliberately has none, so
+ // the "no find plugin" early-return stays exercised). The parent is collapsed, hiding
+ // "Child" and "Other child".
+ async function createCollapsedFindEditor(): Promise<ClassicEditor> {
+ const findEditor = await createTestEditor([CollapsibleListItems, List, TodoList, Paragraph, Typing, Undo, FindAndReplace]);
+ setModelData(findEditor.model, LIST_FIXTURE);
+ findEditor.execute("toggleListCollapse");
+ return findEditor;
+ }
+
+ function collapsedItem(findEditor: ClassicEditor): { li: HTMLElement; nested: HTMLElement } {
+ const li = findEditor.editing.view.getDomRoot()?.querySelector<HTMLElement>('li[data-trilium-collapsed="true"]');
+ const nested = li?.querySelector<HTMLElement>("ul");
+ if (!li || !nested) {
+ throw new Error("Expected a collapsed list item with a hidden nested list.");
+ }
+ return { li, nested };
+ }
+
+ it("reveals a collapsed item to show a match inside it and follows the highlight, without persisting", async () => {
+ const findEditor = await createCollapsedFindEditor();
+ const { li, nested } = collapsedItem(findEditor);
+ expect(getComputedStyle(nested).display).toBe("none");
+
+ findEditor.execute("find", "child"); // first match: "Child", hidden under the collapsed parent
+
+ expect(li.classList.contains("trilium-list-temporarily-expanded")).toBe(true);
+ expect(getComputedStyle(nested).display).not.toBe("none");
+
+ // Advancing to the sibling match keeps the same ancestor revealed (no churn, no error).
+ findEditor.execute("findNext"); // "Other child", still under the same collapsed parent
+ expect(li.classList.contains("trilium-list-temporarily-expanded")).toBe(true);
+
+ // The persisted collapsed state is never touched — search must not rewrite the layout.
+ expect(getBlock(findEditor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
+ expect(findEditor.getData()).toContain('data-trilium-collapsed="true"');
+ });
+
+ it("re-collapses once the search is cleared", async () => {
+ const findEditor = await createCollapsedFindEditor();
+ const { li, nested } = collapsedItem(findEditor);
+
+ findEditor.execute("find", "child");
+ expect(getComputedStyle(nested).display).not.toBe("none");
+
+ findEditor.plugins.get(FindAndReplaceEditing).state?.clear(findEditor.model);
+
+ expect(li.classList.contains("trilium-list-temporarily-expanded")).toBe(false);
+ expect(getComputedStyle(nested).display).toBe("none");
+ });
+
+ it("does not permanently expand when the search closes with the highlight inside the item", async () => {
+ const findEditor = await createCollapsedFindEditor();
+ const { nested } = collapsedItem(findEditor);
+
+ findEditor.execute("find", "Other child");
+ expect(getComputedStyle(nested).display).not.toBe("none");
+
+ // Reproduce find_in_text.findBoxClosed: clear the highlight, then drop the caret on the
+ // match. Both are synchronous, so the "find is closing" window is still open here.
+ const state = findEditor.plugins.get(FindAndReplaceEditing).state;
+ const range = state?.highlightedResult?.marker?.getRange();
+ expect(range).toBeTruthy();
+ state?.clear(findEditor.model);
+ if (range) {
+ findEditor.model.change((writer) => writer.setSelection(range));
+ }
+
+ // The item stays collapsed (saved layout intact) instead of expanding...
+ expect(getBlock(findEditor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
+ expect(getComputedStyle(nested).display).toBe("none");
+ // ...and the caret sits on the collapsed item's own line, not stranded in the hidden child.
+ expect(findEditor.model.document.selection.getFirstPosition()?.parent).toBe(getBlock(findEditor, 0));
+ });
+ });
});
function getBlock(editor: ClassicEditor, index: number): ModelElement {
diff --git a/packages/ckeditor5/src/plugins/collapsible_list_items.ts b/packages/ckeditor5/src/plugins/collapsible_list_items.ts
index a3762d6aac..a8b935e9d2 100644
--- a/packages/ckeditor5/src/plugins/collapsible_list_items.ts
+++ b/packages/ckeditor5/src/plugins/collapsible_list_items.ts
@@ -1,6 +1,6 @@
import "../theme/collapsible_list_items.css";
-import { Command, DomEventObserver, ListEditing, MouseObserver, Plugin, type Editor, type ModelElement, type ModelNode, type ModelWriter, type ViewDocumentDomEventData, type ViewDocumentMouseDownEvent, type ViewDocumentMouseOutEvent, type ViewElement } from "ckeditor5";
+import { Command, DomEventObserver, FindAndReplaceEditing, ListEditing, MouseObserver, Plugin, type Editor, type FindResultType, type ModelElement, type ModelNode, type ModelWriter, type ViewDocumentDomEventData, type ViewDocumentMouseDownEvent, type ViewDocumentMouseOutEvent, type ViewElement } from "ckeditor5";
export const LIST_COLLAPSED_ATTRIBUTE = "listCollapsed";
@@ -9,6 +9,13 @@ const COLLAPSED_DATA_ATTRIBUTE = "data-trilium-collapsed";
/** Marks the item whose arrow the pointer is on, so the stylesheet can give it a filled circle. */
const ARROW_HOVERED_CLASS = "trilium-list-arrow-hovered";
+/**
+ * View-only class placed on a collapsed `<li>` whose hidden children are temporarily shown to
+ * reveal a find-in-note match inside them. It only exists in the editing view (the hiding CSS
+ * opts out when it is present), so the persisted `data-trilium-collapsed` state is never touched.
+ */
+const TEMPORARILY_EXPANDED_CLASS = "trilium-list-temporarily-expanded";
+
/**
* Allows collapsing/expanding nested list items, similar to outliners such as Dynalist or Roam.
*
@@ -19,6 +26,15 @@ const ARROW_HOVERED_CLASS = "trilium-list-arrow-hovered";
export default class CollapsibleListItems extends Plugin {
private _hoveredArrowItem: ViewElement | null = null;
+ /** Collapsed list items currently force-expanded (view-only) to reveal a find highlight. */
+ private readonly _findRevealed = new Set<ModelElement>();
+ /**
+ * True only for the microtask in which find is closing. Closing drops the caret onto the match
+ * (see find_in_text.findBoxClosed); without this, that caret landing inside a re-collapsed item
+ * would make {@link _enableAutoExpand} permanently expand it. While set, the caret is moved to
+ * the collapsed item's line instead — the way the collapsible <details> reveal leaves it.
+ */
+ private _findClosing = false;
static get requires() {
return [ListEditing] as const;
@@ -55,6 +71,94 @@ export default class CollapsibleListItems extends Plugin {
this._enableArrowHoverFeedback();
this._enableToggleOnKeystroke();
this._enableAutoExpand();
+ this._enableFindReveal();
+ }
+
+ /**
+ * Temporarily reveals a collapsed item's hidden children while a find-in-note highlight sits
+ * inside them, re-collapsing once the highlight moves away — the same treatment collapsible
+ * `<details>` blocks get. Unlike {@link _enableAutoExpand} (which permanently drops the
+ * collapsed state when the caret enters a hidden block), this is view-only and never touches
+ * the persisted attribute: search must not rewrite the user's collapsed layout. No-op when
+ * the editor has no find plugin.
+ */
+ private _enableFindReveal() {
+ const editor = this.editor;
+ if (!editor.plugins.has(FindAndReplaceEditing)) {
+ return;
+ }
+ // Wire up on "ready", not here: FindAndReplaceEditing may load after this plugin and only
+ // creates its state in its own init(), so the state isn't available yet at this point.
+ this.listenTo(editor, "ready", () => {
+ const state = editor.plugins.get(FindAndReplaceEditing).state;
+ /* v8 ignore next 3 -- by "ready" FindAndReplaceEditing has initialized and always has a state; the guard only satisfies the optional type. */
+ if (!state) {
+ return;
+ }
+ this.listenTo(state, "change:highlightedResult", (_evt, _name, highlighted) => {
+ this._syncFindReveal(highlighted as FindResultType | null);
+ });
+ });
+ }
+
+ /**
+ * Reconcile {@link _findRevealed} with the collapsed items hiding the current highlight:
+ * reveal ancestors newly hiding it, re-collapse ones that no longer do. A `null` highlight
+ * (search cleared) collapses everything.
+ */
+ private _syncFindReveal(highlighted: FindResultType | null) {
+ const wanted = new Set<ModelElement>();
+ // Split from `highlighted` so a cleared highlight (null) leaves `marker` undefined, keeping
+ // the marker-absent path reachable rather than short-circuited away on the first `?.`.
+ const marker = highlighted?.marker;
+ const block = marker?.getStart().parent;
+ // getCollapsedAncestors tolerates any block (a non-list block has no collapsed ancestors),
+ // so no list-specific guard is needed beyond narrowing the position parent to an element.
+ if (block?.is("element")) {
+ for (const ancestor of getCollapsedAncestors(block)) {
+ wanted.add(ancestor);
+ }
+ }
+
+ // A cleared highlight means find is closing (or moving off): flag the current microtask so
+ // the caret it is about to drop on the match doesn't permanently expand the item that
+ // {@link _enableAutoExpand} would otherwise open. Reset after the tick, so it only affects
+ // that synchronous caret landing and never a later real navigation.
+ if (!highlighted) {
+ this._findClosing = true;
+ void Promise.resolve().then(() => {
+ this._findClosing = false;
+ });
+ }
+
+ for (const revealed of this._findRevealed) {
+ if (!wanted.has(revealed)) {
+ this._applyFindReveal(revealed, false);
+ this._findRevealed.delete(revealed);
+ }
+ }
+ for (const target of wanted) {
+ if (!this._findRevealed.has(target)) {
+ this._findRevealed.add(target);
+ this._applyFindReveal(target, true);
+ }
+ }
+ }
+
+ /** Add or remove the view-only "temporarily expanded" class on the collapsed item's `<li>`. */
+ private _applyFindReveal(block: ModelElement, reveal: boolean) {
+ const viewItem = this.editor.editing.mapper.toViewElement(block)?.findAncestor("li");
+ /* v8 ignore next 3 -- defensive: a rendered collapsed ancestor always maps to its <li>. */
+ if (!viewItem) {
+ return;
+ }
+ this.editor.editing.view.change((writer) => {
+ if (reveal) {
+ writer.addClass(TEMPORARILY_EXPANDED_CLASS, viewItem);
+ } else {
+ writer.removeClass(TEMPORARILY_EXPANDED_CLASS, viewItem);
+ }
+ });
}
/**
@@ -164,6 +268,17 @@ export default class CollapsibleListItems extends Plugin {
return;
}
+ if (this._findClosing) {
+ // Find is closing and dropped the caret on the match inside a re-collapsed item.
+ // Keep the saved layout collapsed: move the caret to the outermost collapsed
+ // ancestor's line instead of expanding (mirrors the <details> reveal on close).
+ const outermost = collapsedAncestors[collapsedAncestors.length - 1];
+ model.enqueueChange({isUndoable: false}, (writer) => {
+ writer.setSelection(writer.createPositionAt(outermost, 0));
+ });
+ return;
+ }
+
model.enqueueChange({isUndoable: false}, (writer) => {
for (const ancestor of collapsedAncestors) {
expandItem(writer, ancestor);
diff --git a/packages/ckeditor5/src/theme/collapsible_list_items.css b/packages/ckeditor5/src/theme/collapsible_list_items.css
index 94d7390517..fa70437833 100644
--- a/packages/ckeditor5/src/theme/collapsible_list_items.css
+++ b/packages/ckeditor5/src/theme/collapsible_list_items.css
@@ -81,7 +81,14 @@
background-color: var(--text-editor-collapsible-list-arrow-hover-background, rgba(128, 128, 128, 0.25));
}
-.ck-content.ck-editor__editable li[data-trilium-collapsed="true"] > ul,
-.ck-content.ck-editor__editable li[data-trilium-collapsed="true"] > ol {
+.ck-content.ck-editor__editable li[data-trilium-collapsed="true"]:not(.trilium-list-temporarily-expanded) > ul,
+.ck-content.ck-editor__editable li[data-trilium-collapsed="true"]:not(.trilium-list-temporarily-expanded) > ol {
display: none;
}
+
+/* A find match temporarily reveals a collapsed item's children (view-only, the persisted state
+ * stays collapsed). Point the arrow the expanded way so the visible nested list isn't contradicted
+ * by a "collapsed" arrow. Placed last so it wins over the collapsed rules on equal specificity. */
+.ck-content.ck-editor__editable li[data-trilium-collapsed="true"].trilium-list-temporarily-expanded::before {
+ --_arrow-rotation: 90deg;
+}