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
client/text editor/collapsible blocks: persist the expanded/collapsed state
Adorian Dorana8b94db31324
diff --git a/packages/ckeditor5-collapsible/src/block-drag-handle.ts b/packages/ckeditor5-collapsible/src/block-drag-handle.tsindex 6e9fb35994..ebe1d90993 100644--- a/packages/ckeditor5-collapsible/src/block-drag-handle.ts+++ b/packages/ckeditor5-collapsible/src/block-drag-handle.ts@@ -13,12 +13,6 @@ export interface BlockDragHandleOptions {refineTarget?: (model: any) => any;/** Invoked when the user clicks the handle without dragging past the threshold. */onClick?: (model: any) => void;- /**- * Invoked just before the move runs (inside the same model.change batch- * would be ideal, but the call happens immediately before — close enough- * for capturing pre-move DOM state of the dragged element).- */- beforeMove?: (model: any) => void;}interface DragState {@@ -118,7 +112,6 @@ export default class BlockDragHandle {for (let node: any = target.model; node; node = node.parent) {if (node === state.model) return;}- this.opts.beforeMove?.(state.model);this.opts.editor.model.change(writer => {const pos = target.before? writer.createPositionBefore(target.model)diff --git a/packages/ckeditor5-collapsible/src/collapsible-command.ts b/packages/ckeditor5-collapsible/src/collapsible-command.tsindex 92c7d4994a..df4a153bb5 100644--- a/packages/ckeditor5-collapsible/src/collapsible-command.ts+++ b/packages/ckeditor5-collapsible/src/collapsible-command.ts@@ -1,5 +1,7 @@import { Command } from "ckeditor5";+import { OPEN_ATTRIBUTE } from "./constants.js";+/*** Inserts a new collapsible block (<details><summary>…</summary>…</details>) at the* current selection. The summary becomes the editable title; the body holds whatever@@ -29,7 +31,11 @@ export default class CollapsibleCommand extends Command {// Clone the selected content up front (does not modify the document).const fragment = !selection.isCollapsed ? model.getSelectedContent(selection) : null;- const details = writer.createElement("details");+ // A collapsible the user just inserted starts expanded — they are about+ // to type a title and then its content. The attribute is set at creation+ // (rather than after insertion) so it belongs to this command's batch:+ // undoing the insert removes it, and redoing replays it.+ const details = writer.createElement("details", { [OPEN_ATTRIBUTE]: true });const summary = writer.createElement("summary");writer.append(summary, details);diff --git a/packages/ckeditor5-collapsible/src/collapsible-editing.ts b/packages/ckeditor5-collapsible/src/collapsible-editing.tsindex fa28d73d4e..0595ff21b4 100644--- a/packages/ckeditor5-collapsible/src/collapsible-editing.ts+++ b/packages/ckeditor5-collapsible/src/collapsible-editing.ts@@ -3,6 +3,7 @@ import { formatShortcut, joinShortcut } from "@triliumnext/commons";import { ContentHintManager, type HintHandle } from "@triliumnext/ckeditor5-utils";import BlockDragHandle from "./block-drag-handle.js";import CollapsibleCommand from "./collapsible-command.js";+import { OPEN_ATTRIBUTE } from "./constants.js";type TranslateFn = (key: string, params?: Record<string, unknown>) => string;@@ -57,13 +58,18 @@ interface SummaryHintState {/*** Schema, conversion and key handling for collapsible blocks.*- * Model: <details><summary>title</summary>…blocks…</details>- * Data view: <details class="trilium-collapsible"><summary>…</summary>…</details>+ * Model: <details open><summary>title</summary>…blocks…</details>+ * Data view: <details class="trilium-collapsible" open><summary>…</summary>…</details>* Editing view: same, plus a custom arrow UIElement in the summary for toggling.- * The DOM `open` attribute is the source of truth for collapsed state- * and is intentionally not persisted in the model — everything loads- * collapsed; freshly-inserted blocks (including those re-created by- * redo) are opened by the differ-driven listener below.+ *+ * The expanded state lives in the model as the {@link OPEN_ATTRIBUTE} attribute and+ * is therefore persisted into the note's saved HTML: a block the user left open+ * reopens on the next visit. A **missing** attribute means collapsed, so notes+ * written before the state was persisted keep loading fully collapsed.+ *+ * Toggling is a model change like any other, with one deliberate exception: it runs+ * in a non-undoable batch (see {@link CollapsibleEditing#setDetailsOpen}), so+ * Ctrl+Z after reading a note doesn't re-collapse what the reader just expanded.*/export default class CollapsibleEditing extends Plugin {@@ -77,26 +83,7 @@ export default class CollapsibleEditing extends Plugin {private keydownListeners: Array<{ root: HTMLElement, handler: (e: KeyboardEvent) => void }> = [];private toggleListeners: Array<{ root: HTMLElement, handler: (e: Event) => void }> = [];- private autoOpenTimer?: ReturnType<typeof setTimeout>;private dragHandle!: BlockDragHandle;- /**- * Pre-move open state for details that are about to be re-inserted via- * drag. Consulted by the auto-open differ listener so a collapsed block- * stays collapsed after being moved (instead of being unconditionally- * opened like a freshly-inserted one).- */- private readonly preserveOpenOnNextInsert = new Map<any, boolean>();- /**- * Open/collapsed state per <details> model element. The editing view wraps- * the body in a content container via `elementToStructure`, which reconverts- * the whole <details> whenever its body blocks change — that rebuilds the- * <details> DOM element, which defaults to closed and would silently collapse- * a block the user has open while they edit its body. The downcast `view()`- * reads this back so the rebuilt <details> keeps its `open` attribute. Only- * <details> toggled/opened at least once appear here; untouched ones stay- * closed (the loaded-document default). Weak so deleted collapsibles drop out.- */- private readonly detailsOpenState = new WeakMap<any, boolean>();/*** Shared manager for summary hints (screen-corner popup on each <summary>).* Each summary owns ONE handle in {@link summaryHints}; visibility is@@ -142,11 +129,6 @@ export default class CollapsibleEditing extends Plugin {onClick: (model) => {this.editor.model.change(w => w.setSelection(model, "on"));this.editor.editing.view.focus();- },- beforeMove: (model) => {- if (model?.is?.("element", "details")) {- this.preserveOpenOnNextInsert.set(model, this.isDetailsOpen(model));- }}});this.registerSchema();@@ -155,7 +137,6 @@ export default class CollapsibleEditing extends Plugin {this.registerKeyHandlers();this.registerClickHandler();this.registerDomListeners();- this.registerAutoOpenNewDetails();this.registerPostFixers();// Global user preference: skip all content-hint wiring when off. The// rest of `init()` (schema, key handlers, drag, post-fixers) stays@@ -176,10 +157,6 @@ export default class CollapsibleEditing extends Plugin {root.removeEventListener("toggle", handler, true);}this.toggleListeners = [];- if (this.autoOpenTimer !== undefined) {- clearTimeout(this.autoOpenTimer);- this.autoOpenTimer = undefined;- }for (const state of this.summaryHints.values()) {this.detachSummaryHoverListeners(state, state.dom);state.handle.dispose();@@ -194,7 +171,6 @@ export default class CollapsibleEditing extends Plugin {this.handleHintManager?.destroy();this.handleHintManager = undefined;this.dragHandle?.cancel();- this.preserveOpenOnNextInsert.clear();super.destroy();}@@ -204,7 +180,12 @@ export default class CollapsibleEditing extends Plugin {private registerSchema() {const schema = this.editor.model.schema;- schema.register("details", { inheritAllFrom: "$container" });+ schema.register("details", {+ inheritAllFrom: "$container",+ // Without this the attribute would be stripped by `insertContent`+ // (schema-driven filtering) when a collapsible is pasted or inserted.+ allowAttributes: [OPEN_ATTRIBUTE]+ });schema.register("summary", {allowIn: "details",allowContentOf: "$block",@@ -223,6 +204,32 @@ export default class CollapsibleEditing extends Plugin {// <details>conversion.for("upcast").elementToElement({ view: "details", model: "details" });conversion.for("dataDowncast").elementToElement({ model: "details", view: detailsView });++ // `open` — the persisted expanded state. Upcast maps the native boolean+ // attribute (whose value is the empty string) to a model `true`; a missing+ // attribute yields no model attribute at all, i.e. collapsed.+ conversion.for("upcast").attributeToAttribute({+ view: { name: "details", key: OPEN_ATTRIBUTE },+ model: { key: OPEN_ATTRIBUTE, value: () => true }+ });+ // Both downcasts use the same explicit converter rather than the+ // `attributeToAttribute` helper: the helper derives the view value from the+ // model value (giving `open="true"`), whereas a native boolean attribute+ // wants `open=""`. Removal has to clear the view attribute outright.+ const openDowncast = (dispatcher: any) => {+ dispatcher.on(`attribute:${OPEN_ATTRIBUTE}:details`, (evt: any, data: any, conversionApi: any) => {+ if (!conversionApi.consumable.consume(data.item, evt.name)) return;+ const viewElement = conversionApi.mapper.toViewElement(data.item);+ if (!viewElement) return;+ if (data.attributeNewValue) {+ conversionApi.writer.setAttribute(OPEN_ATTRIBUTE, "", viewElement);+ } else {+ conversionApi.writer.removeAttribute(OPEN_ATTRIBUTE, viewElement);+ }+ });+ };+ conversion.for("dataDowncast").add(openDowncast);+ conversion.for("editingDowncast").add(openDowncast);// The editing view wraps the body blocks in a <div class="trilium-collapsible-content">.// Chromium caps a native mouse drag-selection to a single block whenever the blocks are// direct children of a <details> in a contenteditable (its ::details-content slot acts as@@ -237,11 +244,11 @@ export default class CollapsibleEditing extends Plugin {view: (modelElement: any, { writer }: any) => {// Reconversion (triggered whenever the body blocks change) rebuilds this// <details>, which would otherwise default to closed and collapse a block- // the user is editing. Re-apply the tracked open state as the `open`- // attribute so the renderer itself restores it — a post-render fix-up can't,- // because the view's "render" event fires *before* the DOM is reconciled.+ // the user is editing. Seed `open` from the model here so the renderer+ // itself restores it — a post-render fix-up can't, because the view's+ // "render" event fires *before* the DOM is reconciled.const attributes: Record<string, string> = { class: "trilium-collapsible" };- if (this.detailsOpenState.get(modelElement)) attributes.open = "";+ if (modelElement.getAttribute(OPEN_ATTRIBUTE)) attributes.open = "";const details = writer.createContainerElement("details", attributes);writer.insert(writer.createPositionAt(details, 0),@@ -294,12 +301,7 @@ export default class CollapsibleEditing extends Plugin {"aria-label": t("text-editor.collapsible-select-label")}, function(this: any, domDocument: any) {const span: HTMLElement = this.toDomElement(domDocument);- const resolveDetails = () => {- const detailsDom = span.closest("details");- if (!detailsDom) return null;- const view = editor.editing.view.domConverter.mapDomToView(detailsDom);- return view ? editor.editing.mapper.toModelElement(view as any) : null;- };+ const resolveDetails = () => plugin.detailsFromDom(span);const selectBlock = () => {const model = resolveDetails();if (!model) return;@@ -344,9 +346,12 @@ export default class CollapsibleEditing extends Plugin {"aria-expanded": "false"}, function(this: any, domDocument: any) {const span: HTMLElement = this.toDomElement(domDocument);+ // Toggle through the model, never by writing `detailsDom.open`: `open` is+ // now part of the editing view, so a direct DOM write would desynchronise+ // the view tree from the DOM and be clobbered by the next render.const toggle = () => {- const details = span.closest("details");- if (details) details.open = !details.open;+ const model = plugin.detailsFromDom(span);+ if (model) plugin.toggleDetails(model);};// mousedown preventDefault keeps the browser from placing a caret// inside the non-editable UI element.@@ -390,23 +395,46 @@ export default class CollapsibleEditing extends Plugin {return dom instanceof Element ? (dom as unknown as T) : null;}- /** True if the <details> is currently expanded (or no DOM mapping yet). */+ /** True if the <details> is currently expanded. A missing attribute means collapsed. */private isDetailsOpen(model: any): boolean {- // Prefer the tracked state: mid-reconversion the rebuilt DOM is momentarily- // closed even for a block the user has open, and `detailsOpenState` is the- // authoritative memory of that (see its declaration). Fall back to the DOM- // for <details> that have never been toggled (never entered the map).- const tracked = this.detailsOpenState.get(model);- if (tracked !== undefined) return tracked;- const dom = this.getDom<HTMLDetailsElement>(model);- return !dom || dom.open;+ return !!model.getAttribute?.(OPEN_ATTRIBUTE);}- /** Remember the open state (so reconversion can restore it) and reflect it to the DOM. */+ /**+ * Write the expanded state to the model, which the downcast reflects to the DOM.+ *+ * `enqueueChange`, not `change`: a toggle can originate from a DOM event that+ * fires while a model change block is still open (the downcast setting `open`+ * makes the browser emit `toggle`), and `model.change` nested in a block joins+ * that block's batch — silently making the toggle part of the user's undo step.+ * `enqueueChange` always creates its own batch, and `isUndoable: false` keeps it+ * off the undo stack: Ctrl+Z after reading must not re-collapse the block.+ */private setDetailsOpen(model: any, open: boolean) {- this.detailsOpenState.set(model, open);- const dom = this.getDom<HTMLDetailsElement>(model);- if (dom) dom.open = open;+ // Cheap guard against the downcast → DOM `toggle` → write-back loop. The+ // writer would swallow the no-op anyway, but bailing here also avoids+ // queueing an empty change block on every render-driven toggle.+ if (this.isDetailsOpen(model) === open) return;+ this.editor.model.enqueueChange({ isUndoable: false }, (writer: any) => {+ if (open) {+ writer.setAttribute(OPEN_ATTRIBUTE, true, model);+ } else {+ writer.removeAttribute(OPEN_ATTRIBUTE, model);+ }+ });+ }++ /** Flip the expanded state of a <details>. */+ private toggleDetails(model: any) {+ this.setDetailsOpen(model, !this.isDetailsOpen(model));+ }++ /** Resolve the <details> model element enclosing a DOM node, if any. */+ private detailsFromDom(node: Element): any | null {+ const detailsDom = node.closest("details");+ if (!detailsDom) return null;+ const view = this.editor.editing.view.domConverter.mapDomToView(detailsDom);+ return view ? this.editor.editing.mapper.toModelElement(view as any) : null;}/** Is the caret on the first ("top") or last ("bottom") visual line of `dom`? */@@ -518,22 +546,13 @@ export default class CollapsibleEditing extends Plugin {const details = summary.parent;if (!details || !details.is("element", "details")) return;- // If the title is currently collapsed and we'll need to expand it (middle-- // of-title split), do it now — before model.change runs and the hidden-body- // post-fixer gets a chance to snap the caret out of the new body paragraph.- const willSplit = !selection.isCollapsed- ? false // selection will be deleted first, then the new collapsed position determines branch- : !selection.getLastPosition()!.isAtStart && !selection.getLastPosition()!.isAtEnd;- if (willSplit && !this.isDetailsOpen(details)) {- this.setDetailsOpen(details, true);- }-model.change(writer => {// Drop any non-collapsed selection so we operate on a single position.if (!selection.isCollapsed) {model.deleteContent(selection);}- const position = selection.getLastPosition()!;+ const position = selection.getLastPosition();+ if (!position) return;if (position.isAtStart) {this.insertParagraphAt(writer, writer.createPositionBefore(details));@@ -558,11 +577,13 @@ export default class CollapsibleEditing extends Plugin {return;}- // Middle of title: split. If we entered this branch via the selection-- // delete path (rather than `willSplit` above), expand now too.- if (!this.isDetailsOpen(details)) {- this.setDetailsOpen(details, true);- }+ // Middle of title: split, which needs the body visible. Expand inside+ // this same change block so the hidden-body post-fixer (which runs once+ // the block completes) sees the block already open and leaves the caret+ // in the new body paragraph. Using the block's own writer rather than+ // `setDetailsOpen` is deliberate here: the expansion is part of the+ // user's edit, so undoing the split should restore the collapsed state.+ writer.setAttribute(OPEN_ATTRIBUTE, true, details);const rightRange = writer.createRange(writer.createPositionAt(summary, position.offset),writer.createPositionAt(summary, "end")@@ -777,9 +798,7 @@ export default class CollapsibleEditing extends Plugin {const summary = selection.getFirstPosition()?.findAncestor("summary");const details = summary?.parent;if (!details?.is("element", "details")) return;- const dom = this.getDom<HTMLDetailsElement>(details);- if (!dom) return;- dom.open = !dom.open;+ this.toggleDetails(details);event.preventDefault();event.stopPropagation();return;@@ -803,8 +822,16 @@ export default class CollapsibleEditing extends Plugin {}}+ /**+ * The DOM `toggle` event, which fires both for our own downcast-driven changes+ * and for toggles the browser performs on its own (Chromium expands a closed+ * <details> to reveal a find-in-page match).+ *+ * Moving the caret out of a body that just collapsed is *not* handled here —+ * {@link CollapsibleEditing#hiddenBodyPostFixer} reads the same model attribute+ * and does it for every path that can close a block, including this one.+ */private onDetailsToggle(event: Event) {- const editor = this.editor;const detailsDom = event.target as HTMLDetailsElement;if (detailsDom.tagName?.toLowerCase() !== "details") return;if (!detailsDom.classList.contains("trilium-collapsible")) return;@@ -813,114 +840,10 @@ export default class CollapsibleEditing extends Plugin {const arrow = detailsDom.querySelector(":scope > summary > .trilium-collapsible-arrow");arrow?.setAttribute("aria-expanded", String(detailsDom.open));- const detailsView = editor.editing.view.domConverter.mapDomToView(detailsDom);- const detailsModel = detailsView ? editor.editing.mapper.toModelElement(detailsView as any) : null;- // Record the new state so a later reconversion restores it (the arrow's- // click handler flips `detailsDom.open` directly, bypassing setDetailsOpen).- if (detailsModel) this.detailsOpenState.set(detailsModel, detailsDom.open);-- if (detailsDom.open) return;- if (!detailsModel) return;-- const summary = detailsModel.getChild(0);- if (!summary?.is("element", "summary")) return;-- const position = editor.model.document.selection.getFirstPosition();- if (!position) return;-- // Already in the toggled block's own summary — caret is still visible.- if (position.findAncestor("summary") === summary) return;-- // The caret only needs to move if it's inside the toggled details- // (could be many levels deep — e.g. a nested collapsible's body or its- // summary; both get hidden when the outer one collapses).- let isInside = false;- for (let node: any = position.parent; node; node = node.parent) {- if (node === detailsModel) { isInside = true; break; }- }- if (!isInside) return;-- editor.model.change(writer => writer.setSelection(summary, "end"));- }-- // ------------------------------------------------------------------ // Auto-open freshly-inserted collapsibles- // ------------------------------------------------------------------- /**- * The editing downcast emits <details> closed by default so loaded documents- * stay collapsed. We do want freshly-inserted collapsibles to open, though —- * via the toolbar, via paste, and importantly via *redo* (which re-applies- * the insert and would otherwise leave the redone block closed because the- * one-shot `setTimeout` from `CollapsibleCommand.execute` has already run).- *- * Watching the differ for new <details> insertions after the editor is- * `ready` covers all three paths uniformly and survives undo/redo.- */- private registerAutoOpenNewDetails() {- const editor = this.editor;- let ready = false;- // Trilium loads note content via `editor.setData(...)` after the editor- // is ready, so the change:data that follows is a wholesale data load —- // not user-initiated insertions. Bracket the entire setData call with- // `loading=true/false` (highest fires before the data is written,- // lowest after everything setData triggered synchronously) so every- // change:data that fires inside is covered — not just the first one.- // The CKEditor public API doesn't guarantee setData emits exactly one- // change:data, so a single-shot flag would leak follow-ups.- let loading = false;- // Accumulate across `change:data` events: if two events fire in the- // same tick (separate model transactions), each restarting the timer- // would otherwise drop the previous batch on the floor.- const pendingOpen = new Set<any>();-- this.listenTo(editor, "ready", () => { ready = true; });- this.listenTo(editor.data, "set", () => { loading = true; }, { priority: "highest" });- this.listenTo(editor.data, "set", () => { loading = false; }, { priority: "lowest" });-- this.listenTo(editor.model.document, "change:data", () => {- if (loading) return;- if (!ready) return;- for (const entry of editor.model.document.differ.getChanges()) {- if (entry.type !== "insert") continue;- // A single insert entry can cover multiple top-level nodes (e.g. a- // multi-block paste). Walk via nextSibling up to entry.length so- // every inserted <details> gets queued for auto-open, not just the- // first one at the entry's position.- let node = (entry as any).position?.nodeAfter;- for (let i = 0; i < (entry as any).length && node; i++) {- if (node.is?.("element", "details")) pendingOpen.add(node);- node = node.nextSibling;- }- }- if (pendingOpen.size === 0) return;-- // Defer to the next tick so the editing view has rendered the new- // DOM elements. Replace any in-flight timer so destroy can cancel.- // The accumulated `pendingOpen` survives the restart.- if (this.autoOpenTimer !== undefined) clearTimeout(this.autoOpenTimer);- this.autoOpenTimer = setTimeout(() => {- this.autoOpenTimer = undefined;- if ((editor as any).state === "destroyed") {- pendingOpen.clear();- this.preserveOpenOnNextInsert.clear();- return;- }- for (const node of pendingOpen) {- if (!this.getDom<HTMLDetailsElement>(node)) continue;- // A move (drag-and-drop) records as remove + insert; restore the- // pre-move open state so a collapsed block stays collapsed.- // Fresh inserts have no entry here and default to open.- if (this.preserveOpenOnNextInsert.has(node)) {- this.setDetailsOpen(node, this.preserveOpenOnNextInsert.get(node) ?? true);- this.preserveOpenOnNextInsert.delete(node);- } else {- this.setDetailsOpen(node, true);- }- }- pendingOpen.clear();- }, 0);- });+ // Adopt a state the model doesn't know about yet. Toggles that originated+ // from the model land here too and are absorbed by setDetailsOpen's guard.+ const detailsModel = this.detailsFromDom(detailsDom);+ if (detailsModel) this.setDetailsOpen(detailsModel, detailsDom.open);}// -----------------------------------------------------------------@@ -1350,8 +1273,7 @@ export default class CollapsibleEditing extends Plugin {let outermostClosed: any = null;for (let node: any = position.parent; node; node = node.parent) {if (!node.is?.("element", "details")) continue;- const dom = this.getDom<HTMLDetailsElement>(node);- if (dom && !dom.open) outermostClosed = node;+ if (!this.isDetailsOpen(node)) outermostClosed = node;}if (!outermostClosed) return false;diff --git a/packages/ckeditor5-collapsible/src/constants.ts b/packages/ckeditor5-collapsible/src/constants.tsnew file mode 100644index 0000000000..4f677dedbe--- /dev/null+++ b/packages/ckeditor5-collapsible/src/constants.ts@@ -0,0 +1,13 @@+/**+ * Model attribute holding a collapsible's expanded state, downcast to the native+ * `open` attribute on `<details>` in both the data and the editing view.+ *+ * A **missing** attribute means collapsed. That keeps every note authored before+ * the state was persisted loading exactly as it did then (fully collapsed), and+ * keeps the saved HTML free of `open="false"` noise — the attribute is only ever+ * present or absent, matching the native boolean-attribute semantics.+ *+ * Lives in its own module so `collapsible-command.ts` can use it without+ * importing `collapsible-editing.ts`, which imports the command back.+ */+export const OPEN_ATTRIBUTE = "open";diff --git a/packages/ckeditor5-collapsible/tests/command.ts b/packages/ckeditor5-collapsible/tests/command.tsindex 7627c23601..8a4addd6da 100644--- a/packages/ckeditor5-collapsible/tests/command.ts+++ b/packages/ckeditor5-collapsible/tests/command.ts@@ -26,9 +26,11 @@ describe("CollapsibleCommand", () => {it("inserts an empty collapsible at a collapsed caret and parks the caret in the new summary", () => {setModelData(model, "<paragraph>[]</paragraph>");editor.execute("collapsible");- // Caret in the new summary; the empty body paragraph follows it.+ // Caret in the new summary; the empty body paragraph follows it. The+ // block is created expanded so the user can see the body they're about+ // to fill in — `open` is part of the command's own batch.expect(getModelData(model)).toContain(- "<details><summary>[]</summary><paragraph></paragraph></details>"+ "<details open=\"true\"><summary>[]</summary><paragraph></paragraph></details>");});@@ -36,7 +38,7 @@ describe("CollapsibleCommand", () => {setModelData(model, "<paragraph>Hello [selected] world</paragraph>");editor.execute("collapsible");expect(getModelData(model, { withoutSelection: true })).toContain(- "<details><summary></summary><paragraph>selected</paragraph></details>"+ "<details open=\"true\"><summary></summary><paragraph>selected</paragraph></details>");});@@ -49,7 +51,7 @@ describe("CollapsibleCommand", () => {expect(data).toContain("<paragraph>Block one</paragraph>");expect(data).toContain("<paragraph>Block two</paragraph>");// Both selected paragraphs end up inside the new <details>.- expect(data).toMatch(/<details><summary><\/summary><paragraph>Block one<\/paragraph><paragraph>Block two<\/paragraph><\/details>/);+ expect(data).toMatch(/<details open="true"><summary><\/summary><paragraph>Block one<\/paragraph><paragraph>Block two<\/paragraph><\/details>/);});it("unwraps a nested <details> in the selection so we don't gain an extra level of nesting", () => {@@ -62,7 +64,7 @@ describe("CollapsibleCommand", () => {editor.execute("collapsible");const data = getModelData(model, { withoutSelection: true });// Exactly ONE <details> in the output — the inner one was unwrapped.- expect((data.match(/<details>/g) ?? []).length).toBe(1);+ expect((data.match(/<details[ >]/g) ?? []).length).toBe(1);// The inner body is preserved as the new collapsible's body.expect(data).toContain("<paragraph>Inner body</paragraph>");// The inner summary's text isn't pulled into the new summary (thediff --git a/packages/ckeditor5-collapsible/tests/conversion.ts b/packages/ckeditor5-collapsible/tests/conversion.tsindex d2abba09e6..0b007e249a 100644--- a/packages/ckeditor5-collapsible/tests/conversion.ts+++ b/packages/ckeditor5-collapsible/tests/conversion.ts@@ -74,8 +74,9 @@ describe("CollapsibleEditing conversion", () => {const root = editor.editing.view.getDomRoot();const selector = "details.trilium-collapsible";const detailsBefore = root?.querySelector<HTMLDetailsElement>(selector);- // Simulate the user opening the block: flip `open` and fire the native- // `toggle` the plugin listens for (the arrow's click handler does the same).+ // Simulate a toggle the plugin didn't originate (the browser expanding a+ // block to reveal a find-in-page match): flip `open` and fire the native+ // `toggle` event, which the plugin adopts into the model.if (detailsBefore) {detailsBefore.open = true;detailsBefore.dispatchEvent(new Event("toggle"));diff --git a/packages/ckeditor5-collapsible/tests/enter-in-summary.ts b/packages/ckeditor5-collapsible/tests/enter-in-summary.tsindex 34e1bee4e9..5910f3b025 100644--- a/packages/ckeditor5-collapsible/tests/enter-in-summary.ts+++ b/packages/ckeditor5-collapsible/tests/enter-in-summary.ts@@ -29,20 +29,41 @@ describe("onEnterInSummary", () => {});it("at the end of a title (expanded) parks the caret in the existing empty body paragraph instead of stacking a second one", () => {+ // The expanded/collapsed branch is decided by the `open` model attribute,+ // so the state is set up in the model rather than on the DOM element.setModelData(model,- "<details><summary>Title[]</summary><paragraph></paragraph></details>"+ "<details open=\"true\"><summary>Title[]</summary><paragraph></paragraph></details>");- // Auto-open won't have fired in this synchronous slice, so the details- // dom.open is still false. The expanded vs collapsed branch decision is- // made via dom.open — force it true to exercise the expanded branch.- const detailsDom = editor.editing.view.getDomRoot()!.querySelector("details") as HTMLDetailsElement;- detailsDom.open = true;fireEnter();// Caret moved into the existing empty paragraph; no second one was inserted.expect(getModelData(model)).toBe(- "<details><summary>Title</summary><paragraph>[]</paragraph></details>"+ "<details open=\"true\"><summary>Title</summary><paragraph>[]</paragraph></details>"+ );+ });++ it("expands a collapsed block when splitting its title, as part of the same undo step", () => {+ setModelData(model,+ "<details><summary>Ti[]tle</summary><paragraph>body</paragraph></details>"+ );++ fireEnter();++ // The right half of the title became the first body block, and the block+ // expanded so the caret lands somewhere the user can actually see.+ expect(getModelData(model)).toBe(+ "<details open=\"true\"><summary>Ti</summary>" ++ "<paragraph>[]tle</paragraph><paragraph>body</paragraph>" ++ "</details>"+ );++ editor.execute("undo");++ // The expansion belongs to the user's edit — unlike a plain toggle — so+ // undoing the split restores the collapsed state along with the title.+ expect(getModelData(model, { withoutSelection: true })).toBe(+ "<details><summary>Title</summary><paragraph>body</paragraph></details>");});@@ -51,7 +72,7 @@ describe("onEnterInSummary", () => {"<details><summary>Title[]</summary><paragraph>body</paragraph></details>" +"<paragraph></paragraph>");- // dom.open stays false in happy-dom, exercising the collapsed branch.+ // No `open` attribute — the collapsed branch.fireEnter();diff --git a/packages/ckeditor5-collapsible/tests/open-state.ts b/packages/ckeditor5-collapsible/tests/open-state.tsnew file mode 100644index 0000000000..5c03d6092d--- /dev/null+++ b/packages/ckeditor5-collapsible/tests/open-state.ts@@ -0,0 +1,239 @@+import { ClassicEditor, Essentials, Paragraph, _setModelData as setModelData, _getModelData as getModelData } from "ckeditor5";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import CollapsibleEditing from "../src/collapsible-editing.js";++/**+ * The expanded state is persisted as the `open` model attribute, which round-trips+ * into the note's saved HTML. A *missing* attribute means collapsed, so content+ * written before the state was persisted keeps loading fully collapsed.+ */+describe("collapsible open state", () => {+ let domElement: HTMLDivElement;+ let editor: ClassicEditor;+ let model: ClassicEditor["model"];++ beforeEach(async () => {+ domElement = document.createElement("div");+ document.body.appendChild(domElement);+ editor = await ClassicEditor.create(domElement, {+ licenseKey: "GPL",+ plugins: [Essentials, Paragraph, CollapsibleEditing]+ });+ model = editor.model;+ });++ afterEach(() => {+ domElement.remove();+ return editor.destroy();+ });++ const domRoot = () => editor.editing.view.getDomRoot() as HTMLElement;+ const detailsDom = (index = 0) =>+ domRoot().querySelectorAll<HTMLDetailsElement>("details.trilium-collapsible")[index];+ const clickArrow = (index = 0) =>+ domRoot()+ .querySelectorAll<HTMLElement>(".trilium-collapsible-arrow")[index]+ .dispatchEvent(new MouseEvent("click", { bubbles: true }));++ describe("persistence", () => {+ it("round-trips the state a user leaves behind: collapsed content loads collapsed, expanding writes `open` into the saved HTML, and reloading that HTML comes back expanded", () => {+ // Existing content — authored before the state was persisted.+ editor.setData("<details class=\"trilium-collapsible\"><summary>T</summary><p>body</p></details>");+ expect(detailsDom().open).toBe(false);+ expect(editor.getData()).not.toContain("open");++ clickArrow();++ expect(detailsDom().open).toBe(true);+ expect(editor.getData()).toBe(+ "<details class=\"trilium-collapsible\" open=\"\"><summary>T</summary><p>body</p></details>"+ );++ // Reload exactly what would have been saved.+ editor.setData(editor.getData());+ expect(detailsDom().open).toBe(true);+ });++ it("upcasts the native boolean attribute to a model `true`, and its absence to no attribute at all", () => {+ editor.setData("<details open><summary>A</summary><p>a</p></details><details><summary>B</summary><p>b</p></details>");+ expect(getModelData(model, { withoutSelection: true })).toBe(+ "<details open=\"true\"><summary>A</summary><paragraph>a</paragraph></details>" ++ "<details><summary>B</summary><paragraph>b</paragraph></details>"+ );+ });++ it("collapsing removes the attribute rather than writing open=\"false\", keeping the saved HTML clean", () => {+ editor.setData("<details class=\"trilium-collapsible\" open><summary>T</summary><p>body</p></details>");+ expect(detailsDom().open).toBe(true);++ clickArrow();++ expect(getModelData(model, { withoutSelection: true })).toBe(+ "<details><summary>T</summary><paragraph>body</paragraph></details>"+ );+ expect(editor.getData()).not.toContain("open");+ });++ it("tracks nested collapsibles independently", () => {+ editor.setData(+ "<details><summary>Outer</summary>" ++ "<details><summary>Inner</summary><p>x</p></details>" ++ "</details>"+ );+ // Index 1 is the nested one; expanding it must not expand its parent.+ clickArrow(1);++ expect(getModelData(model, { withoutSelection: true })).toBe(+ "<details><summary>Outer</summary>" ++ "<details open=\"true\"><summary>Inner</summary><paragraph>x</paragraph></details>" ++ "</details>"+ );+ });++ it("survives the reconversion that a body-block change triggers", () => {+ // elementToStructure rebuilds the whole <details> when its children+ // change; the fresh DOM element defaults to closed unless the downcast+ // re-applies the state.+ editor.setData("<details class=\"trilium-collapsible\" open><summary>T</summary><p>First</p></details>");+ expect(detailsDom().open).toBe(true);++ model.change((writer) => {+ const details = model.document.getRoot()?.getChild(0);+ if (details?.is("element", "details")) {+ writer.insertElement("paragraph", details, "end");+ }+ });++ expect(detailsDom().open).toBe(true);+ });++ it("keeps the attribute through insertContent, which filters against the schema", () => {+ // `allowAttributes` on the schema is what stops `open` being stripped+ // here — pasting an expanded collapsible must stay expanded.+ setModelData(model, "<paragraph>[]</paragraph>");+ model.change((writer) => {+ const details = writer.createElement("details", { open: true });+ const summary = writer.createElement("summary");+ writer.append(summary, details);+ writer.append(writer.createElement("paragraph"), details);+ model.insertContent(details);+ });++ expect(getModelData(model, { withoutSelection: true })).toContain("<details open=\"true\">");+ });++ it("carries the state along when the block is moved (a drag records as remove + insert)", () => {+ setModelData(model,+ "<paragraph>before</paragraph>" ++ "<details open=\"true\"><summary>T</summary><paragraph>body</paragraph></details>"+ );+ model.change((writer) => {+ const root = model.document.getRoot();+ const details = root?.getChild(1);+ if (root && details) {+ writer.move(writer.createRangeOn(details), writer.createPositionAt(root, 0));+ }+ });++ expect(getModelData(model, { withoutSelection: true })).toBe(+ "<details open=\"true\"><summary>T</summary><paragraph>body</paragraph></details>" ++ "<paragraph>before</paragraph>"+ );+ });+ });++ describe("toggling", () => {+ it("toggles via the arrow and via Ctrl+Enter in the summary", () => {+ setModelData(model, "<details><summary>T[]</summary><paragraph>body</paragraph></details>");++ clickArrow();+ expect(detailsDom().open).toBe(true);++ domRoot().dispatchEvent(new KeyboardEvent("keydown", {+ key: "Enter", ctrlKey: true, bubbles: true, cancelable: true+ }));+ expect(detailsDom().open).toBe(false);+ });++ it("adopts a toggle the browser performed on its own (e.g. find-in-page expanding a closed block)", () => {+ setModelData(model, "<details><summary>T</summary><paragraph>body</paragraph></details>");++ const dom = detailsDom();+ dom.open = true;+ dom.dispatchEvent(new Event("toggle"));++ expect(getModelData(model, { withoutSelection: true })).toContain("<details open=\"true\">");+ });++ it("keeps the arrow's aria-expanded in sync", () => {+ setModelData(model, "<details><summary>T</summary><paragraph>body</paragraph></details>");+ const arrow = domRoot().querySelector(".trilium-collapsible-arrow");+ expect(arrow?.getAttribute("aria-expanded")).toBe("false");++ clickArrow();++ expect(arrow?.getAttribute("aria-expanded")).toBe("true");+ });+ });++ describe("undo", () => {+ it("does not put a toggle on the undo stack — Ctrl+Z after reading must not re-collapse the block", () => {+ setModelData(model, "<details open=\"true\"><summary>Title</summary><paragraph>body</paragraph></details>");++ // A real, undoable edit for the undo stack to hold.+ model.change((writer) => {+ const details = model.document.getRoot()?.getChild(0);+ const summary = details?.is("element", "details") ? details.getChild(0) : null;+ if (summary?.is("element", "summary")) {+ writer.insertText("!", summary, "end");+ }+ });+ expect(getModelData(model, { withoutSelection: true })).toContain("<summary>Title!</summary>");++ // Collapse: a model change, but not an undoable one.+ clickArrow();+ expect(detailsDom().open).toBe(false);++ editor.execute("undo");++ // The text edit was undone, so the toggle never occupied a stack slot…+ expect(getModelData(model, { withoutSelection: true })).toContain("<summary>Title</summary>");+ // …and the collapse itself survived the undo.+ expect(getModelData(model, { withoutSelection: true })).not.toContain("open=");+ });++ it("restores the state with the block when an insert is undone and redone", () => {+ setModelData(model, "<paragraph>[]</paragraph>");+ editor.execute("collapsible");+ expect(getModelData(model, { withoutSelection: true })).toContain("<details open=\"true\">");++ editor.execute("undo");+ expect(getModelData(model, { withoutSelection: true })).not.toContain("<details");++ editor.execute("redo");+ // The attribute rides along in the insert operation — no separate+ // re-open pass is needed for the redone block.+ expect(getModelData(model, { withoutSelection: true })).toContain("<details open=\"true\">");+ });+ });++ describe("hiddenBodyPostFixer", () => {+ it("never leaves the caret inside a collapsed body", () => {+ // Placing the caret in the body of a closed block must bounce it to the+ // summary — the body is display:none, so a caret there is invisible.+ setModelData(model, "<details><summary>T</summary><paragraph>bo[]dy</paragraph></details>");++ expect(getModelData(model)).toBe(+ "<details><summary>T[]</summary><paragraph>body</paragraph></details>"+ );+ });++ it("leaves the caret alone when the block is open", () => {+ setModelData(model, "<details open=\"true\"><summary>T</summary><paragraph>bo[]dy</paragraph></details>");++ expect(getModelData(model)).toBe(+ "<details open=\"true\"><summary>T</summary><paragraph>bo[]dy</paragraph></details>"+ );+ });+ });+});diff --git a/packages/ckeditor5-collapsible/tests/post-fixer-gap.ts b/packages/ckeditor5-collapsible/tests/post-fixer-gap.tsindex 1cf7bcb9bc..62e7f8657c 100644--- a/packages/ckeditor5-collapsible/tests/post-fixer-gap.ts+++ b/packages/ckeditor5-collapsible/tests/post-fixer-gap.ts@@ -40,19 +40,14 @@ describe("gapPostFixer + onEnterInBody", () => {});it("dives into a nested <details>'s last block when the gap before the caret is a nested <details>", () => {+ // Both details are open so hiddenBodyPostFixer doesn't rescue the caret+ // away from the nested body — we're isolating gapPostFixer here.setModelData(model,- "<details>" ++ "<details open=\"true\">" +"<summary>Outer</summary>" +- "<details><summary>Inner</summary><paragraph>nested</paragraph></details>" ++ "<details open=\"true\"><summary>Inner</summary><paragraph>nested</paragraph></details>" +"</details>");- // Open both details manually so hiddenBodyPostFixer doesn't rescue- // the caret away from the nested body — we're isolating gapPostFixer.- // (Auto-open only walks top-level siblings of the insert entry, so- // nested details from a single setModelData stay closed in tests.)- for (const d of editor.editing.view.getDomRoot()!.querySelectorAll("details")) {- (d as HTMLDetailsElement).open = true;- }model.change(writer => {const outer = model.document.getRoot()!.getChild(0)!;// Position at outer's end: between inner-details and end-of-outer.@@ -60,8 +55,8 @@ describe("gapPostFixer + onEnterInBody", () => {});// Caret should land at the end of the nested details' last block.expect(getModelData(model)).toBe(- "<details><summary>Outer</summary>" +- "<details><summary>Inner</summary><paragraph>nested[]</paragraph></details>" ++ "<details open=\"true\"><summary>Outer</summary>" ++ "<details open=\"true\"><summary>Inner</summary><paragraph>nested[]</paragraph></details>" +"</details>");});@@ -69,8 +64,11 @@ describe("gapPostFixer + onEnterInBody", () => {describe("onEnterInBody", () => {it("escapes the collapsible when Enter is pressed in an empty trailing body paragraph", () => {+ // Open: a caret can only ever be in a body that is actually visible —+ // hiddenBodyPostFixer bounces it to the summary otherwise, so a+ // collapsed block could never reach onEnterInBody in the first place.setModelData(model,- "<details>" ++ "<details open=\"true\">" +"<summary>X</summary>" +"<paragraph>existing</paragraph>" +"<paragraph>[]</paragraph>" +@@ -85,7 +83,7 @@ describe("gapPostFixer + onEnterInBody", () => {// The empty trailing paragraph is gone; the caret has moved to a new// paragraph outside the details.expect(getModelData(model)).toBe(- "<details><summary>X</summary><paragraph>existing</paragraph></details>" ++ "<details open=\"true\"><summary>X</summary><paragraph>existing</paragraph></details>" +"<paragraph>[]</paragraph>");});