Skip to content

Build your personal knowledge base with Trilium Notes

feat(text): persist collapsed list items as data-trilium-collapsed

Elian Doran78de8211d991
diff --git a/.gitignore b/.gitignore
index 2bbc2611e1..ddeccc7c9c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -37,6 +37,8 @@ Thumbs.db
vite.config.*.timestamp*
vitest.config.*.timestamp*
test-output
+__screenshots__
+.vitest-attachments
apps/*/data*
apps/*/out
diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
index 23f2ec1055..d575633392 100644
--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
+++ b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
@@ -1,4 +1,4 @@
-import { type Batch, CKTextEditor, ClassicEditor, EditorWatchdog, isListCollapseToggleBatch, PopupEditor, TemplateDefinition, type WatchdogConfig } from "@triliumnext/ckeditor5";
+import { CKTextEditor, ClassicEditor, EditorWatchdog, PopupEditor, TemplateDefinition, type WatchdogConfig } from "@triliumnext/ckeditor5";
import { DISPLAYABLE_LOCALE_IDS } from "@triliumnext/commons";
import { HTMLProps, RefObject, useEffect, useImperativeHandle, useRef, useState } from "preact/compat";
@@ -277,14 +277,8 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe
// React to on change listener.
useEffect(() => {
if (!editor) return;
- const handler = (_evt: unknown, batch: Batch) => {
- // Collapsing/expanding list items is editing-only view state that does not alter
- // the serialized content, so it must not mark the note as modified.
- if (isListCollapseToggleBatch(batch)) return;
- onChange();
- };
- editor.model.document.on("change:data", handler);
- return () => editor.model.document.off("change:data", handler);
+ editor.model.document.on("change:data", onChange);
+ return () => editor.model.document.off("change:data", onChange);
}, [ editor, onChange ]);
return (
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index d80e920e72..ca51d92d7b 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -7,11 +7,10 @@ import { BalloonEditor, DecoupledEditor, FindAndReplaceEditing, FindCommand } fr
import "./translation_overrides.js";
export { default as EditorWatchdog } from "./custom_watchdog";
export { loadPremiumPlugins } from "./plugins.js";
-export type { Batch, EditorConfig, MentionFeed, MentionFeedObjectItem, ModelNode, ModelPosition, ModelElement, ModelText, WatchdogConfig, WatchdogState } from "ckeditor5";
+export type { EditorConfig, MentionFeed, MentionFeedObjectItem, ModelNode, ModelPosition, ModelElement, ModelText, WatchdogConfig, WatchdogState } from "ckeditor5";
export type { TemplateDefinition } from "ckeditor5-premium-features";
export { default as buildExtraCommands } from "./extra_slash_commands.js";
export { default as getCkLocale } from "./i18n.js";
-export { isListCollapseToggleBatch } from "./plugins/collapsible_list_items.js";
export * from "./utils.js";
// Import with sideffects to ensure that type augmentations are present.
diff --git a/packages/ckeditor5/src/plugins/collapsible_list_items.ts b/packages/ckeditor5/src/plugins/collapsible_list_items.ts
index bce6bca63d..32f1c0aa89 100644
--- a/packages/ckeditor5/src/plugins/collapsible_list_items.ts
+++ b/packages/ckeditor5/src/plugins/collapsible_list_items.ts
@@ -1,18 +1,17 @@
import "../theme/collapsible_list_items.css";
-import { AttributeOperation, Command, ListEditing, MouseObserver, Plugin, type Batch, type Editor, type ModelElement, type ModelNode, type ModelWriter, type ViewDocumentMouseDownEvent, type ViewElement } from "ckeditor5";
+import { Command, ListEditing, MouseObserver, Plugin, type Editor, type ModelElement, type ModelNode, type ModelWriter, type ViewDocumentMouseDownEvent, type ViewElement } from "ckeditor5";
export const LIST_COLLAPSED_ATTRIBUTE = "listCollapsed";
-const COLLAPSED_CLASS = "tn-list-collapsed";
+const COLLAPSED_DATA_ATTRIBUTE = "data-trilium-collapsed";
/**
* Allows collapsing/expanding nested list items, similar to outliners such as Dynalist or Roam.
*
- * The collapsed state is kept as a `listCollapsed` model attribute that is rendered only on the
- * editing pipeline (as the `tn-list-collapsed` class on the `<li>`), so it is never written into
- * the saved note content and does not survive a reload. Toggling it must therefore not mark the
- * note as modified — collapse-only batches are filtered out via {@link isListCollapseToggleBatch}.
+ * The collapsed state is kept as a `listCollapsed` model attribute, persisted into the note
+ * content as `data-trilium-collapsed="true"` on the `<li>`. Hiding the nested items is done by
+ * CSS scoped to the editing view, so read-only and shared note rendering stay fully expanded.
*/
export default class CollapsibleListItems extends Plugin {
@@ -30,16 +29,23 @@ export default class CollapsibleListItems extends Plugin {
editor.plugins.get(ListEditing).registerDowncastStrategy({
scope: "item",
attributeName: LIST_COLLAPSED_ATTRIBUTE,
- setAttributeOnDowncast(writer, value, element, options) {
- // Editing pipeline only — the collapsed state is never saved into the content.
- if (value && !options?.dataPipeline) {
- writer.addClass(COLLAPSED_CLASS, element);
+ setAttributeOnDowncast(writer, value, element) {
+ if (value) {
+ writer.setAttribute(COLLAPSED_DATA_ATTRIBUTE, "true", element);
} else {
- writer.removeClass(COLLAPSED_CLASS, element);
+ writer.removeAttribute(COLLAPSED_DATA_ATTRIBUTE, element);
}
}
});
+ editor.conversion.for("upcast").attributeToAttribute({
+ view: {name: "li", key: COLLAPSED_DATA_ATTRIBUTE},
+ model: {
+ key: LIST_COLLAPSED_ATTRIBUTE,
+ value: (viewElement: ViewElement) => viewElement.getAttribute(COLLAPSED_DATA_ATTRIBUTE) === "true" ? true : null
+ }
+ });
+
this._enableToggleOnGutterClick();
this._enableAutoExpand();
}
@@ -109,23 +115,34 @@ export default class CollapsibleListItems extends Plugin {
});
model.document.registerPostFixer((writer) => {
+ const insertedNodes = new Set<ModelNode>();
const changedBlocks = new Set<ModelElement>();
for (const entry of model.document.differ.getChanges()) {
- let node: ModelNode | null = null;
if (entry.type === "insert") {
- node = entry.position.nodeAfter;
+ let node: ModelNode | null = entry.position.nodeAfter;
+ for (let i = 0; i < entry.length && node; i++, node = node.nextSibling) {
+ insertedNodes.add(node);
+ if (node.is("element") && node.hasAttribute("listItemId")) {
+ changedBlocks.add(node);
+ }
+ }
} else if (entry.type === "attribute" && (entry.attributeKey === "listIndent" || entry.attributeKey === "listItemId")) {
- node = entry.range.start.nodeAfter;
- }
- if (node && node.is("element") && node.hasAttribute("listItemId")) {
- changedBlocks.add(node);
+ const node = entry.range.start.nodeAfter;
+ if (node && node.is("element") && node.hasAttribute("listItemId")) {
+ changedBlocks.add(node);
+ }
}
}
let changed = false;
for (const block of changedBlocks) {
for (const ancestor of getCollapsedAncestors(block)) {
+ // An ancestor inserted in the same change set arrived together with its
+ // hidden children (data load, paste of a collapsed subtree) — keep it.
+ if (insertedNodes.has(ancestor)) {
+ continue;
+ }
expandItem(writer, ancestor);
changed = true;
}
@@ -166,21 +183,10 @@ export class ToggleListCollapseCommand extends Command {
}
-/**
- * Whether the batch consists solely of collapse/expand toggles. Such batches do not affect the
- * saved content (the attribute has no data downcast), so content-save listeners on `change:data`
- * should ignore them.
- */
-export function isListCollapseToggleBatch(batch: Batch): boolean {
- return batch.operations.length > 0
- && batch.operations.every((operation) => operation instanceof AttributeOperation && operation.key === LIST_COLLAPSED_ATTRIBUTE);
-}
-
function toggleCollapsed(editor: Editor, block: ModelElement): void {
const collapse = !block.getAttribute(LIST_COLLAPSED_ATTRIBUTE);
- // Not undoable: the state is view-only, an undo step would be invisible in the content.
- editor.model.enqueueChange({isUndoable: false}, (writer) => {
+ editor.model.change((writer) => {
for (const itemBlock of getItemBlocks(block)) {
if (collapse) {
writer.setAttribute(LIST_COLLAPSED_ATTRIBUTE, true, itemBlock);
diff --git a/packages/ckeditor5/src/theme/collapsible_list_items.css b/packages/ckeditor5/src/theme/collapsible_list_items.css
index db4e348d1b..50c3a706ad 100644
--- a/packages/ckeditor5/src/theme/collapsible_list_items.css
+++ b/packages/ckeditor5/src/theme/collapsible_list_items.css
@@ -1,9 +1,9 @@
/*
* Collapse/expand arrows for nested list items (CollapsibleListItems plugin).
*
- * The `tn-list-collapsed` class is applied on the editing view only — the collapsed state is
- * never persisted into the note content, which is why everything is scoped to
- * `.ck-editor__editable` and does not affect read-only or shared note rendering.
+ * The collapsed state is persisted as `data-trilium-collapsed` on the `<li>`, but the hiding is
+ * scoped to `.ck-editor__editable` so read-only and shared note rendering stay fully expanded
+ * (they have no way to toggle the state).
*/
.ck-content.ck-editor__editable li {
@@ -31,16 +31,16 @@
opacity: 0.4;
}
-.ck-content.ck-editor__editable li.tn-list-collapsed::before {
+.ck-content.ck-editor__editable li[data-trilium-collapsed="true"]::before {
transform: rotate(-45deg); /* chevron pointing at the text: collapsed */
opacity: 0.7;
}
-.ck-content.ck-editor__editable li.tn-list-collapsed:dir(rtl)::before {
+.ck-content.ck-editor__editable li[data-trilium-collapsed="true"]:dir(rtl)::before {
transform: rotate(135deg);
}
-.ck-content.ck-editor__editable li.tn-list-collapsed > ul,
-.ck-content.ck-editor__editable li.tn-list-collapsed > ol {
+.ck-content.ck-editor__editable li[data-trilium-collapsed="true"] > ul,
+.ck-content.ck-editor__editable li[data-trilium-collapsed="true"] > ol {
display: none;
}
diff --git a/packages/ckeditor5/tests/collapsible_list_items.spec.ts b/packages/ckeditor5/tests/collapsible_list_items.spec.ts
index c7b47dd35c..ef6d9fc5b1 100644
--- a/packages/ckeditor5/tests/collapsible_list_items.spec.ts
+++ b/packages/ckeditor5/tests/collapsible_list_items.spec.ts
@@ -1,7 +1,7 @@
-import { _setModelData as setModelData, ClassicEditor, List, Paragraph, Typing, Undo, type Batch, type ModelElement } from "ckeditor5";
+import { _setModelData as setModelData, ClassicEditor, List, Paragraph, Typing, Undo, type ModelElement } from "ckeditor5";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
-import CollapsibleListItems, { isListCollapseToggleBatch, LIST_COLLAPSED_ATTRIBUTE } from "../src/plugins/collapsible_list_items.js";
+import CollapsibleListItems, { LIST_COLLAPSED_ATTRIBUTE } from "../src/plugins/collapsible_list_items.js";
// Lists are flat in the model: sibling blocks related by listIndent/listItemId.
const LIST_FIXTURE =
@@ -32,7 +32,7 @@ describe("CollapsibleListItems", () => {
await editor.destroy();
});
- it("collapses and expands via the command without changing the saved data", () => {
+ it("collapses and expands via the command and persists the state into the data", () => {
const dataBefore = editor.getData();
const command = editor.commands.get("toggleListCollapse");
expect(command?.isEnabled).toBe(true);
@@ -43,7 +43,7 @@ describe("CollapsibleListItems", () => {
expect(command?.value).toBe(true);
const domRoot = editor.editing.view.getDomRoot();
- const collapsedItem = domRoot?.querySelector("li.tn-list-collapsed");
+ const collapsedItem = domRoot?.querySelector('li[data-trilium-collapsed="true"]');
expect(collapsedItem).not.toBeNull();
const nestedList = collapsedItem?.querySelector("ul");
expect(nestedList).not.toBeNull();
@@ -51,13 +51,49 @@ describe("CollapsibleListItems", () => {
expect(getComputedStyle(nestedList).display).toBe("none");
}
- // The collapsed state must never leak into the serialized content.
- expect(editor.getData()).toBe(dataBefore);
+ expect(editor.getData()).toContain('data-trilium-collapsed="true"');
editor.execute("toggleListCollapse");
expect(getBlock(editor, 0).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);
expect(command?.value).toBe(false);
- expect(domRoot?.querySelector("li.tn-list-collapsed")).toBeNull();
+ expect(domRoot?.querySelector("li[data-trilium-collapsed]")).toBeNull();
+ expect(editor.getData()).toBe(dataBefore);
+ });
+
+ it("round-trips the collapsed state through the data without expanding it on load", () => {
+ editor.setData(
+ '<ul><li data-trilium-collapsed="true">Parent<ul><li>Child</li></ul></li><li>Sibling</li></ul>');
+
+ // Loading a collapsed subtree must not trigger the "content placed under a
+ // collapsed parent" auto-expansion: the children arrive together with the parent.
+ expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
+
+ const domRoot = editor.editing.view.getDomRoot();
+ const nestedList = domRoot?.querySelector('li[data-trilium-collapsed="true"] ul');
+ expect(nestedList).not.toBeNull();
+ if (nestedList) {
+ expect(getComputedStyle(nestedList).display).toBe("none");
+ }
+
+ expect(editor.getData()).toContain('data-trilium-collapsed="true"');
+ });
+
+ it("normalizes away persisted state that has nothing to collapse", () => {
+ editor.setData('<ul><li data-trilium-collapsed="true">No children</li></ul>');
+
+ expect(getBlock(editor, 0).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);
+ expect(editor.getData()).not.toContain("data-trilium-collapsed");
+ });
+
+ it("collapse toggles are undoable", () => {
+ const dataBefore = editor.getData();
+
+ editor.execute("toggleListCollapse");
+ expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
+
+ editor.execute("undo");
+ expect(getBlock(editor, 0).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);
+ expect(editor.getData()).toBe(dataBefore);
});
it("is only enabled on list items that have nested items", () => {
@@ -85,24 +121,6 @@ describe("CollapsibleListItems", () => {
expect(getBlock(editor, 1).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);
});
- it("creates non-undoable batches that are recognizable for save suppression", () => {
- const batches: Batch[] = [];
- editor.model.document.on("change:data", (_evt, batch) => batches.push(batch as Batch));
-
- editor.execute("toggleListCollapse");
- expect(batches).toHaveLength(1);
- expect(batches.every(isListCollapseToggleBatch)).toBe(true);
-
- editor.execute("insertText", { text: "!" });
- const typingBatch = batches.at(-1);
- expect(typingBatch && isListCollapseToggleBatch(typingBatch)).toBe(false);
-
- // Undo reverts the typing but not the (non-undoable) collapse.
- editor.execute("undo");
- expect(getBlockText(editor, 0)).toBe("Parent");
- expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
- });
-
it("expands automatically when the selection moves into a hidden item", () => {
editor.execute("toggleListCollapse");
expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
@@ -110,6 +128,7 @@ describe("CollapsibleListItems", () => {
setSelectionIn(editor, 1);
expect(getBlock(editor, 0).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);
+ expect(editor.getData()).not.toContain("data-trilium-collapsed");
});
it("expands automatically when an item is indented under a collapsed parent", () => {
@@ -176,16 +195,6 @@ function getBlock(editor: ClassicEditor, index: number): ModelElement {
return child;
}
-function getBlockText(editor: ClassicEditor, index: number): string {
- let text = "";
- for (const node of getBlock(editor, index).getChildren()) {
- if (node.is("$text")) {
- text += node.data;
- }
- }
- return text;
-}
-
function setSelectionIn(editor: ClassicEditor, blockIndex: number): void {
editor.model.change((writer) => {
writer.setSelection(writer.createPositionAt(getBlock(editor, blockIndex), 0));