Skip to content

Build your personal knowledge base with Trilium Notes

fix(collapsible): don't let a delete fold a blank line into the block

Elian Doran9652334f403f
diff --git a/packages/ckeditor5/src/plugins/collapsible/collapsible_editing.ts b/packages/ckeditor5/src/plugins/collapsible/collapsible_editing.ts
index b4c7c16bfc..a6dd365ec9 100644
--- a/packages/ckeditor5/src/plugins/collapsible/collapsible_editing.ts
+++ b/packages/ckeditor5/src/plugins/collapsible/collapsible_editing.ts
@@ -141,6 +141,7 @@ export default class CollapsibleEditing extends Plugin {
this.registerConversion();
this.registerBodyPlaceholder();
this.registerKeyHandlers();
+ this.registerMergeGuard();
this.registerClickHandler();
this.registerDomListeners();
this.registerPostFixers();
@@ -539,6 +540,8 @@ export default class CollapsibleEditing extends Plugin {
(evt, data) => this.onUpArrow(evt, data));
this.listenTo<ViewDocumentDeleteEvent>(viewDocument, "delete",
(evt, data) => this.onDeleteAdjacentDetails(evt, data));
+ this.listenTo<ViewDocumentDeleteEvent>(viewDocument, "delete",
+ (evt, data) => this.onForwardDeleteBeforeDetails(evt, data));
this.listenTo<ViewDocumentDeleteEvent>(viewDocument, "delete",
(evt, data) => this.onBackspaceInEmptySummary(evt, data), { context: "summary" });
}
@@ -741,6 +744,79 @@ export default class CollapsibleEditing extends Plugin {
/* v8 ignore stop */
}
+ /**
+ * Forward Delete from an empty block sitting directly before a collapsible: drop the
+ * block and put the caret at the start of the title.
+ *
+ * That is the same outcome CKEditor's own merge was reaching for, minus the merge —
+ * which {@link CollapsibleEditing#registerMergeGuard} keeps away from a <details>,
+ * so without this handler the keystroke would do nothing at all. A plain remove plus
+ * a selection change converts correctly.
+ */
+ private onForwardDeleteBeforeDetails(evt: any, data: any) {
+ if (data.direction !== "forward") return;
+ const selection = this.editor.model.document.selection;
+ if (!selection.isCollapsed) return;
+ const block = selection.getFirstPosition()?.parent;
+ if (!block || !block.is("element") || !block.isEmpty) return;
+ const details = block.nextSibling;
+ if (!details?.is("element", "details")) return;
+ const summary = details.getChild(0);
+ /* v8 ignore next -- a <details> always holds a <summary> as its first child by the time this runs */
+ if (!summary?.is("element", "summary")) return;
+
+ data.preventDefault();
+ evt.stop();
+
+ this.editor.model.change(writer => {
+ writer.setSelection(summary, 0);
+ // An empty <summary> is a title, not a blank line the user wants gone:
+ // removing it would only make the summary-invariant post-fixer put a fresh
+ // one back, so there the caret move is the whole effect.
+ if (!block.is("element", "summary")) {
+ writer.remove(block);
+ }
+ });
+ }
+
+ /**
+ * Keep `deleteContent` from merging a block into a <details>.
+ *
+ * When a deletion leaves its start block empty, CKEditor merges *right*: the empty
+ * block is moved into the <details> that holds the end of the range, renamed to
+ * `summary`, and the old title merged into it. The resulting model is correct; the
+ * editing view is not. Reconverting a <details> re-slots its children's existing view
+ * elements instead of converting them again, so a child moved in during the same
+ * change block keeps the element name and the content it had before the move — the
+ * collapsible renders with no <summary> at all (a bare native "Details" marker) and
+ * the next caret move throws `mapping-model-offset-not-found`. This is reachable from
+ * every path that deletes across the boundary: Delete on a blank line above a
+ * collapsible, a selection running from there into the title or body, and typing or
+ * pasting over such a selection.
+ *
+ * `leaveUnmerged` skips `mergeBranches` only, so the selected content is still
+ * deleted — the emptied block simply stays put instead of being folded into the
+ * collapsible. Merges in the other direction are left alone: when content survives in
+ * the start block, or the range runs out of a collapsible rather than into one,
+ * CKEditor merges left and the element it moves is the one it then removes, so nothing
+ * stale is left behind to re-slot.
+ */
+ private registerMergeGuard() {
+ this.listenTo(this.editor.model, "deleteContent", (_evt, args: any[]) => {
+ const [selection, options] = args;
+ const range = selection.getFirstRange();
+ /* v8 ignore next -- deleteContent bails on a collapsed selection before this fires */
+ if (!range) return;
+ // Content survives in the start block → CKEditor merges left, which converts fine.
+ if (!range.start.isAtStart) return;
+ // Nothing is moved into a <details> unless the range ends inside one that does
+ // not already hold its start.
+ const details = range.end.findAncestor("details");
+ if (!details || range.start.getAncestors().includes(details)) return;
+ args[1] = { ...options, leaveUnmerged: true };
+ }, { priority: "high" });
+ }
+
/** Backspace at start of an empty summary unwraps the collapsible. */
private onBackspaceInEmptySummary(evt: any, data: any) {
const selection = this.editor.model.document.selection;
diff --git a/packages/ckeditor5/src/plugins/collapsible/delete_across_boundary.spec.ts b/packages/ckeditor5/src/plugins/collapsible/delete_across_boundary.spec.ts
new file mode 100644
index 0000000000..6cedf3f17b
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/collapsible/delete_across_boundary.spec.ts
@@ -0,0 +1,232 @@
+import { _getModelData as getModelData, _setModelData as setModelData, ClassicEditor, Essentials, Paragraph } from "ckeditor5";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createTestEditor } from "../../../test/editor-kit.js";
+import CollapsibleEditing from "./collapsible_editing.js";
+
+/**
+ * Deleting across a collapsible's boundary.
+ *
+ * CKEditor's own `deleteContent` folds a block that a deletion left empty *into* the
+ * <details> holding the other end of the range, renaming it to `summary` on the way. The
+ * model that comes out is fine, but the editing view keeps the moved element's old view
+ * element (reconverting a <details> re-slots its children rather than converting them
+ * again), so the collapsible renders with no title at all and the next caret move throws
+ * `mapping-model-offset-not-found`. Every test here asserts the *rendered* result, not
+ * just the model — the model was never the broken half.
+ */
+describe("collapsible: deleting across the boundary", () => {
+ let editor: ClassicEditor;
+ let root: HTMLElement;
+
+ beforeEach(async () => {
+ editor = await createTestEditor([Essentials, Paragraph, CollapsibleEditing]);
+ root = editor.editing.view.getDomRoot() as HTMLElement;
+ });
+
+ function fireDelete(direction: "backward" | "forward" = "forward"): void {
+ editor.editing.view.document.fire("delete", { direction, unit: "character", preventDefault: vi.fn() });
+ editor.editing.view.forceRender();
+ }
+
+ /** The editing view of the outermost collapsible, as rendered. */
+ function renderedCollapsible(): { title: string | null, body: string | null } {
+ const details = root.querySelector("details.trilium-collapsible");
+ return {
+ title: details?.querySelector(":scope > summary")?.textContent ?? null,
+ body: details?.querySelector(":scope > .trilium-collapsible-content")?.textContent ?? null
+ };
+ }
+
+ describe("Delete on a blank line above a collapsible", () => {
+ it("drops the blank line and moves the caret into the title", () => {
+ setModelData(
+ editor.model,
+ "<paragraph>[]</paragraph>" +
+ "<details open=\"true\"><summary>Title</summary><paragraph>body</paragraph></details>"
+ );
+
+ fireDelete();
+
+ expect(getModelData(editor.model)).toBe(
+ "<details open=\"true\"><summary>[]Title</summary><paragraph>body</paragraph></details>"
+ );
+ // The title still renders as a <summary> holding the model's text — the
+ // regression replaced it with the blank line's <p>, leaving the browser to
+ // draw its default "Details" marker.
+ expect(renderedCollapsible()).toEqual({ title: "Title", body: "body" });
+ // A second press used to throw mapping-model-offset-not-found.
+ expect(() => fireDelete()).not.toThrow();
+ });
+
+ it("works the same on a collapsed collapsible", () => {
+ setModelData(
+ editor.model,
+ "<paragraph>[]</paragraph>" +
+ "<details><summary>Title</summary><paragraph>body</paragraph></details>"
+ );
+
+ fireDelete();
+
+ expect(getModelData(editor.model)).toBe(
+ "<details><summary>[]Title</summary><paragraph>body</paragraph></details>"
+ );
+ expect(renderedCollapsible().title).toBe("Title");
+ });
+
+ it("moves into a nested collapsible from a blank body line", () => {
+ setModelData(
+ editor.model,
+ "<details open=\"true\"><summary>Outer</summary>" +
+ "<paragraph>[]</paragraph>" +
+ "<details open=\"true\"><summary>Inner</summary><paragraph>b</paragraph></details>" +
+ "</details>"
+ );
+
+ fireDelete();
+
+ expect(getModelData(editor.model)).toBe(
+ "<details open=\"true\"><summary>Outer</summary>" +
+ "<details open=\"true\"><summary>[]Inner</summary><paragraph>b</paragraph></details>" +
+ "</details>"
+ );
+ expect(root.querySelectorAll("summary")).toHaveLength(2);
+ });
+
+ it("only moves the caret when the blank block is the title itself", () => {
+ // An empty <summary> is a title, not a blank line: removing it would only make
+ // the summary-invariant post-fixer put a fresh one back.
+ setModelData(
+ editor.model,
+ "<details open=\"true\"><summary>[]</summary>" +
+ "<details open=\"true\"><summary>Inner</summary><paragraph>b</paragraph></details>" +
+ "</details>"
+ );
+
+ fireDelete();
+
+ expect(getModelData(editor.model)).toBe(
+ "<details open=\"true\"><summary></summary>" +
+ "<details open=\"true\"><summary>[]Inner</summary><paragraph>b</paragraph></details>" +
+ "</details>"
+ );
+ expect(root.querySelectorAll("summary")).toHaveLength(2);
+ });
+
+ it("leaves a block with content to CKEditor's own merge", () => {
+ setModelData(
+ editor.model,
+ "<paragraph>a[]</paragraph>" +
+ "<details open=\"true\"><summary>Title</summary><paragraph>body</paragraph></details>"
+ );
+
+ fireDelete();
+
+ // Merged left: the title text joins the paragraph and the collapsible keeps an
+ // empty title. Nothing was moved into the <details>, so the view is consistent.
+ expect(getModelData(editor.model)).toBe(
+ "<paragraph>a[]Title</paragraph>" +
+ "<details open=\"true\"><summary></summary><paragraph>body</paragraph></details>"
+ );
+ expect(renderedCollapsible()).toEqual({ title: "", body: "body" });
+ });
+ });
+
+ describe("selections running from above into a collapsible", () => {
+ it("deletes the selected content without folding the blank line into the title", () => {
+ setModelData(
+ editor.model,
+ "<paragraph>[</paragraph>" +
+ "<details open=\"true\"><summary>Ti]tle</summary><paragraph>body</paragraph></details>"
+ );
+
+ fireDelete();
+
+ expect(getModelData(editor.model)).toBe(
+ "<paragraph>[]</paragraph>" +
+ "<details open=\"true\"><summary>tle</summary><paragraph>body</paragraph></details>"
+ );
+ expect(renderedCollapsible()).toEqual({ title: "tle", body: "body" });
+ });
+
+ it("holds when the selection reaches into the body", () => {
+ setModelData(
+ editor.model,
+ "<paragraph>[</paragraph>" +
+ "<details open=\"true\"><summary>Title</summary><paragraph>bo]dy</paragraph></details>"
+ );
+
+ fireDelete();
+
+ expect(getModelData(editor.model)).toBe(
+ "<paragraph>[]</paragraph>" +
+ "<details open=\"true\"><summary></summary><paragraph>dy</paragraph></details>"
+ );
+ expect(renderedCollapsible()).toEqual({ title: "", body: "dy" });
+ });
+
+ it("holds when the selection is typed over", () => {
+ setModelData(
+ editor.model,
+ "<paragraph>[</paragraph>" +
+ "<details open=\"true\"><summary>Ti]tle</summary><paragraph>body</paragraph></details>"
+ );
+
+ editor.execute("insertText", { text: "Z" });
+ editor.editing.view.forceRender();
+
+ expect(getModelData(editor.model)).toBe(
+ "<paragraph>Z[]</paragraph>" +
+ "<details open=\"true\"><summary>tle</summary><paragraph>body</paragraph></details>"
+ );
+ expect(renderedCollapsible().title).toBe("tle");
+ });
+
+ it("still merges when content survives in the block above", () => {
+ setModelData(
+ editor.model,
+ "<paragraph>ab[c</paragraph>" +
+ "<details open=\"true\"><summary>Ti]tle</summary><paragraph>body</paragraph></details>"
+ );
+
+ fireDelete();
+
+ expect(getModelData(editor.model)).toBe(
+ "<paragraph>ab[]tle</paragraph>" +
+ "<details open=\"true\"><summary></summary><paragraph>body</paragraph></details>"
+ );
+ });
+
+ it("still merges a selection that stays inside one collapsible", () => {
+ // Both ends share the same <details>, so nothing is moved into it — the title
+ // is renamed into the body block it merges with, which reconverts correctly,
+ // and the summary-invariant post-fixer restores a blank title.
+ setModelData(
+ editor.model,
+ "<details open=\"true\"><summary>[Ti</summary><paragraph>bo]dy</paragraph></details>"
+ );
+
+ fireDelete();
+
+ expect(getModelData(editor.model)).toBe(
+ "<details open=\"true\"><summary></summary><paragraph>[]dy</paragraph></details>"
+ );
+ expect(renderedCollapsible()).toEqual({ title: "", body: "dy" });
+ });
+
+ it("still merges when the selection runs out of a collapsible instead of into one", () => {
+ setModelData(
+ editor.model,
+ "<details open=\"true\"><summary>T</summary><paragraph>[x</paragraph></details>" +
+ "<paragraph>y]z</paragraph>"
+ );
+
+ fireDelete();
+
+ expect(getModelData(editor.model)).toBe(
+ "<details open=\"true\"><summary>T</summary><paragraph>[]z</paragraph></details>"
+ );
+ expect(renderedCollapsible()).toEqual({ title: "T", body: "z" });
+ });
+ });
+});