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(text editor): handle Enter on collapsed list items (closes #11256)
Ampad3a5ddd04c6
diff --git a/packages/ckeditor5/src/plugins/collapsible_list_items.spec.ts b/packages/ckeditor5/src/plugins/collapsible_list_items.spec.tsindex 6c5d4a9b55..e0ba2b7168 100644--- a/packages/ckeditor5/src/plugins/collapsible_list_items.spec.ts+++ b/packages/ckeditor5/src/plugins/collapsible_list_items.spec.ts@@ -120,6 +120,23 @@ describe("CollapsibleListItems", () => {expect(editor.getData()).not.toContain("data-trilium-collapsed");});+ it("moves the selection to the parent when collapsing hides it (#11256)", () => {+ setSelectionIn(editor, 1);+ const parentItem = editor.editing.view.getDomRoot()?.querySelector("li");+ expect(parentItem).toBeTruthy();+ if (!parentItem) {+ return;+ }++ mouseDownAt(parentItem, -10);++ const parentBlock = getBlock(editor, 0);+ const position = editor.model.document.selection.getFirstPosition();+ expect(parentBlock.getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);+ expect(position?.parent).toBe(parentBlock);+ expect(position?.offset).toBe(parentBlock.maxOffset);+ });+it("expands automatically when an item is indented under a collapsed parent", () => {editor.execute("toggleListCollapse");setSelectionIn(editor, 3); // "Sibling", still visible at indent 0@@ -151,6 +168,105 @@ describe("CollapsibleListItems", () => {expect(getBlock(editor, 5).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);});+ it("leaves Enter behavior unchanged outside collapsed list items", () => {+ setModelData(editor.model, "<paragraph>paragraph[]</paragraph>");+ editor.execute("enter");+ expect(editor.model.document.getRoot()?.childCount).toBe(2);++ setModelData(editor.model,+ '<paragraph listIndent="0" listItemId="u-a" listType="bulleted">item[]</paragraph>' ++ '<paragraph listIndent="1" listItemId="u-b" listType="bulleted">child</paragraph>');+ editor.execute("enter");+ expect(getBlock(editor, 1).isEmpty).toBe(true);+ expect(getBlock(editor, 2).getAttribute("listItemId")).toBe("u-b");+ });++ it("moves a sibling past hidden children when Enter exits a collapsed multi-block item", () => {+ setModelData(editor.model,+ '<paragraph listIndent="0" listItemId="m-a" listType="bulleted">first</paragraph>' ++ '<paragraph listIndent="0" listItemId="m-a" listType="bulleted">second[]</paragraph>' ++ '<paragraph listIndent="1" listItemId="m-b" listType="bulleted">child</paragraph>');++ editor.execute("toggleListCollapse");+ pressEnter(editor);++ expect(getBlock(editor, 0).getAttribute("listItemId")).toBe("m-a");+ expect(getBlock(editor, 1).getAttribute("listItemId")).toBe("m-a");+ expect(getBlock(editor, 2).getAttribute("listItemId")).toBe("m-a");+ expect(getBlock(editor, 2).isEmpty).toBe(true);++ pressEnter(editor, true);+ expect(getBlock(editor, 2).getAttribute("listItemId")).toBe("m-a");++ pressEnter(editor);++ expect(getBlock(editor, 2).getAttribute("listItemId")).toBe("m-b");+ expect(getBlock(editor, 3).getAttribute("listItemId")).not.toBe("m-a");+ expect(getBlock(editor, 3).getAttribute("listIndent")).toBe(0);+ expect(getBlock(editor, 3).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);+ expect(editor.model.document.selection.getFirstPosition()?.parent)+ .toBe(getBlock(editor, 3));++ editor.execute("undo");+ expect(getBlock(editor, 2).getAttribute("listItemId")).toBe("m-a");+ expect(getBlock(editor, 2).isEmpty).toBe(true);+ expect(getBlock(editor, 3).getAttribute("listItemId")).toBe("m-b");+ });++ it("inserts after the hidden children when Enter splits a collapsed item (#11256)", () => {+ setModelData(editor.model,+ '<paragraph listIndent="0" listItemId="t-a" listType="todo">todo1[]</paragraph>' ++ '<paragraph listIndent="1" listItemId="t-b" listType="todo">a</paragraph>' ++ '<paragraph listIndent="1" listItemId="t-c" listType="todo">b</paragraph>');++ editor.execute("toggleListCollapse");+ editor.execute("enter");++ expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);+ expect(getBlock(editor, 1).getAttribute("listItemId")).toBe("t-b");+ expect(getBlock(editor, 2).getAttribute("listItemId")).toBe("t-c");+ expect(getBlock(editor, 3).getAttribute("listIndent")).toBe(0);+ expect(getBlock(editor, 3).isEmpty).toBe(true);+ expect(editor.model.document.selection.getFirstPosition()?.parent)+ .toBe(getBlock(editor, 3));++ editor.execute("undo");+ expect(editor.model.document.getRoot()?.childCount).toBe(3);+ expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);+ });++ it("inserts after the entire hidden subtree when Enter splits a collapsed item", () => {+ setModelData(editor.model,+ '<paragraph listIndent="0" listItemId="d-a" listType="bulleted">parent[]</paragraph>' ++ '<paragraph listIndent="1" listItemId="d-b" listType="bulleted">mid</paragraph>' ++ '<paragraph listIndent="2" listItemId="d-c" listType="bulleted">leaf</paragraph>');++ editor.execute("toggleListCollapse");+ editor.execute("enter");++ expect(getBlock(editor, 0).getAttribute("listItemId")).toBe("d-a");+ expect(getBlock(editor, 1).getAttribute("listItemId")).toBe("d-b");+ expect(getBlock(editor, 2).getAttribute("listItemId")).toBe("d-c");+ expect(getBlock(editor, 3).getAttribute("listIndent")).toBe(0);+ expect(getBlock(editor, 3).isEmpty).toBe(true);+ });++ it("does not crash when Enter follows a collapsed item with no remaining children", () => {+ setModelData(editor.model,+ '<paragraph listIndent="0" listItemId="s-a" listType="bulleted">parent[]</paragraph>' ++ '<paragraph listIndent="1" listItemId="s-b" listType="bulleted">kid</paragraph>');++ editor.execute("toggleListCollapse");+ for (let i = 0; i < 4; i++) {+ editor.execute("forwardDelete");+ }++ expect(editor.model.document.getRoot()?.childCount).toBe(1);+ expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);+ expect(() => editor.execute("enter")).not.toThrow();+ expect(editor.model.document.getRoot()?.childCount).toBe(2);+ });+it("toggles when clicking the arrow in the gutter and ignores other clicks", () => {const domRoot = editor.editing.view.getDomRoot();const items = domRoot ? Array.from(domRoot.querySelectorAll("li")) : [];@@ -565,6 +681,10 @@ function pressCtrlEnter(editor: ClassicEditor): void {});}+function pressEnter(editor: ClassicEditor, isSoft = false): void {+ editor.editing.view.document.fire("enter", { preventDefault: () => {}, isSoft });+}+/*** On-screen centre of the arrow drawn next to a list item, read back from the stylesheet rather* than restated here: the arrow is a pseudo-element (so it has no rect of its own), but itsdiff --git a/packages/ckeditor5/src/plugins/collapsible_list_items.ts b/packages/ckeditor5/src/plugins/collapsible_list_items.tsindex a8b935e9d2..876b001587 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, FindAndReplaceEditing, ListEditing, MouseObserver, Plugin, type Editor, type FindResultType, 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 EnterCommand, type FindResultType, type ListSplitCommand, type ModelElement, type ModelNode, type ModelWriter, type ViewDocumentDomEventData, type ViewDocumentEnterEvent, type ViewDocumentMouseDownEvent, type ViewDocumentMouseOutEvent, type ViewElement } from "ckeditor5";export const LIST_COLLAPSED_ATTRIBUTE = "listCollapsed";@@ -70,6 +70,7 @@ export default class CollapsibleListItems extends Plugin {this._enableToggleOnGutterClick();this._enableArrowHoverFeedback();this._enableToggleOnKeystroke();+ this._enableEnterAfterCollapsedItem();this._enableAutoExpand();this._enableFindReveal();}@@ -179,6 +180,74 @@ export default class CollapsibleListItems extends Plugin {});}+ /** Moves new list siblings after hidden descendants for both CKEditor Enter command paths. */+ private _enableEnterAfterCollapsedItem() {+ const editor = this.editor;+ const enterCommand = editor.commands.get("enter") as EnterCommand;+ const splitCommand = editor.commands.get("splitListItemBefore") as ListSplitCommand;+ let pendingEnterSplit: ModelElement | null = null;++ // ListEditing handles an empty final block with splitListItemBefore and stops the event,+ // so EnterCommand never runs on that path.+ this.listenTo<ViewDocumentEnterEvent>(+ editor.editing.view.document, "enter", (_evt, data) => {+ if (data.isSoft) {+ pendingEnterSplit = null;+ return;+ }+ const selectedBlock = getSelectedListBlock(editor);+ pendingEnterSplit = selectedBlock?.isEmpty+ && selectedBlock.getAttribute(LIST_COLLAPSED_ATTRIBUTE) === true+ && hasNestedItems(selectedBlock)+ ? selectedBlock+ : null;++ if (pendingEnterSplit) {+ // The split command runs synchronously; clear state if another listener+ // handles Enter.+ void Promise.resolve().then(() => {+ pendingEnterSplit = null;+ });+ }+ }, { context: "li", priority: "high" }+ );++ this.listenTo(splitCommand, "afterExecute", () => {+ if (!pendingEnterSplit || pendingEnterSplit !== getSelectedListBlock(editor)) {+ return;+ }+ pendingEnterSplit = null;+ editor.model.change((writer) => this._moveItemAfterCollapsedDescendants(writer));+ });++ this.listenTo(enterCommand, "afterExecute", (_evt, data: { writer: ModelWriter }) => {+ this._moveItemAfterCollapsedDescendants(data.writer);+ });+ }++ /**+ * Moves the item Enter creates in a collapsed list item after that item's hidden descendants.+ */+ private _moveItemAfterCollapsedDescendants(writer: ModelWriter) {+ const block = getSelectedListBlock(this.editor);+ if (!block || !block.isEmpty) {+ return;+ }++ const previousBlock = block.previousSibling;+ if (!isListBlock(previousBlock)+ || previousBlock.getAttribute(LIST_COLLAPSED_ATTRIBUTE) !== true+ || previousBlock.getAttribute("listItemId") === block.getAttribute("listItemId")) {+ return;+ }++ const lastNestedBlock = getNestedBlocks(block).at(-1);+ if (!lastNestedBlock) {+ return;+ }+ writer.move(writer.createRangeOn(block), writer.createPositionAfter(lastNestedBlock));+ }+/*** Toggles the collapsed state when the arrow rendered in the gutter next to a list item is* clicked.@@ -397,15 +466,26 @@ function getArrowBlockAtPointer(editor: Editor, data: ViewDocumentDomEventData<Mfunction toggleCollapsed(editor: Editor, block: ModelElement): void {const collapse = !block.getAttribute(LIST_COLLAPSED_ATTRIBUTE);+ const itemBlocks = getItemBlocks(block);+ const selectionBlock = editor.model.document.selection.getFirstPosition()?.parent;+ const hidesSelection = collapse+ && !!selectionBlock+ && selectionBlock.is("element")+ && getNestedBlocks(block).includes(selectionBlock);editor.model.change((writer) => {- for (const itemBlock of getItemBlocks(block)) {+ for (const itemBlock of itemBlocks) {if (collapse) {writer.setAttribute(LIST_COLLAPSED_ATTRIBUTE, true, itemBlock);} else {writer.removeAttribute(LIST_COLLAPSED_ATTRIBUTE, itemBlock);}}++ if (hidesSelection) {+ const lastItemBlock = itemBlocks[itemBlocks.length - 1];+ writer.setSelection(writer.createPositionAt(lastItemBlock, "end"));+ }});}@@ -470,6 +550,22 @@ function hasNestedItems(block: ModelElement): boolean {return false;}+/** Returns the list blocks hidden by collapsing `block`, including all descendant levels. */+function getNestedBlocks(block: ModelElement): ModelElement[] {+ const blocks: ModelElement[] = [];+ const indent = getIndent(block);+ const lastItemBlock = getItemBlocks(block).at(-1);++ for (+ let sibling = lastItemBlock?.nextSibling;+ isListBlock(sibling) && getIndent(sibling) > indent;+ sibling = sibling.nextSibling+ ) {+ blocks.push(sibling);+ }+ return blocks;+}+/** All consecutive blocks belonging to the same (possibly multi-block) list item. */function getItemBlocks(block: ModelElement): ModelElement[] {const itemId = block.getAttribute("listItemId");@@ -505,7 +601,7 @@ function getCollapsedAncestors(block: ModelElement): ModelElement[] {return ancestors;}-function isListBlock(node: ModelNode | null): node is ModelElement {+function isListBlock(node: ModelNode | null | undefined): node is ModelElement {return !!node && node.is("element") && node.hasAttribute("listItemId");}