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(collapsible): keep Backspace from wiping a collapsed block's body (closes #11050)
Elian Doran8f344545a34e
diff --git a/packages/ckeditor5/src/plugins/collapsible/collapsible_editing.ts b/packages/ckeditor5/src/plugins/collapsible/collapsible_editing.tsindex a6dd365ec9..50716cd380 100644--- a/packages/ckeditor5/src/plugins/collapsible/collapsible_editing.ts+++ b/packages/ckeditor5/src/plugins/collapsible/collapsible_editing.ts@@ -538,6 +538,8 @@ export default class CollapsibleEditing extends Plugin {(evt, data) => this.onEnterInBody(evt, data));this.listenTo<ViewDocumentArrowKeyEvent>(viewDocument, "arrowKey",(evt, data) => this.onUpArrow(evt, data));+ this.listenTo<ViewDocumentDeleteEvent>(viewDocument, "delete",+ (evt, data) => this.onDeleteThroughHiddenBody(evt, data), { priority: "high" });this.listenTo<ViewDocumentDeleteEvent>(viewDocument, "delete",(evt, data) => this.onDeleteAdjacentDetails(evt, data));this.listenTo<ViewDocumentDeleteEvent>(viewDocument, "delete",@@ -704,6 +706,46 @@ export default class CollapsibleEditing extends Plugin {evt.stop();}+ /**+ * Drop a browser-supplied delete range that reaches through a collapsed body.+ *+ * Chrome derives the target range of `deleteContentBackward` from the rendered+ * layout, where a closed <details> shows nothing but its title. Backspace at the+ * start of the line below one therefore arrives as a range running from the end of+ * the <summary> to the caret, and CKEditor's `Delete` removes every hidden block in+ * between — the collapsible stays closed, so the loss is invisible. Clearing the+ * range falls back to the model-driven `modifySelection` path, which walks the model+ * rather than the layout: it merges into the last body block, and+ * {@link CollapsibleEditing#hiddenBodyPostFixer} then parks the caret in the summary.+ *+ * Only a collapsed model selection is corrected. A range the user selected by hand+ * can legitimately span a collapsed block (dragging from before it to after it), and+ * deleting that is what they asked for.+ */+ private onDeleteThroughHiddenBody(_evt: any, data: any) {+ if (data.unit !== "selection") return;+ if (!this.editor.model.document.selection.isCollapsed) return;++ const mapper = this.editor.editing.mapper;+ for (const viewRange of data.selectionToRemove.getRanges()) {+ if (!this.crossesCollapsedBoundary(mapper.toModelRange(viewRange))) continue;+ data.unit = "codePoint";+ data.selectionToRemove = undefined;+ return;+ }+ }++ /** True when a collapsed <details> holds one end of the range but not the other. */+ private crossesCollapsedBoundary(range: any): boolean {+ const startAncestors = range.start.getAncestors();+ const endAncestors = range.end.getAncestors();+ for (const node of [...startAncestors, ...endAncestors]) {+ if (!node.is("element", "details") || this.isDetailsOpen(node)) continue;+ if (startAncestors.includes(node) !== endAncestors.includes(node)) return true;+ }+ return false;+ }+/*** Two-step delete next to a <details> (matches CKEditor's widget/object pattern):* 1st press: select the whole <details> so the user sees what's about to go.diff --git a/packages/ckeditor5/src/plugins/collapsible/delete_across_boundary.spec.ts b/packages/ckeditor5/src/plugins/collapsible/delete_across_boundary.spec.tsindex 6cedf3f17b..43510450c6 100644--- a/packages/ckeditor5/src/plugins/collapsible/delete_across_boundary.spec.ts+++ b/packages/ckeditor5/src/plugins/collapsible/delete_across_boundary.spec.ts@@ -1,5 +1,6 @@import { _getModelData as getModelData, _setModelData as setModelData, ClassicEditor, Essentials, Paragraph } from "ckeditor5";import { beforeEach, describe, expect, it, vi } from "vitest";+import { userEvent } from "vitest/browser";import { createTestEditor } from "../../../test/editor-kit.js";import CollapsibleEditing from "./collapsible_editing.js";@@ -29,6 +30,32 @@ describe("collapsible: deleting across the boundary", () => {editor.editing.view.forceRender();}+ /**+ * A delete carrying a browser-computed range, the way `DeleteObserver` reports one for+ * `deleteContentBackward`. `selectionToRemove` is built from a model range so a spec can+ * state the span it means; the observer derives the same thing from the DOM.+ */+ function fireDeleteSelection(range: any, direction: "backward" | "forward" = "backward"): void {+ const view = editor.editing.view;+ view.document.fire("delete", {+ direction,+ unit: "selection",+ selectionToRemove: view.createSelection(editor.editing.mapper.toViewRange(range)),+ preventDefault: vi.fn()+ });+ view.forceRender();+ }++ /** Model range between two positions, each given as a path from the root. */+ function modelRange(start: number[], end: number[]): any {+ const model = editor.model;+ const root = model.document.getRoot() as any;+ return model.createRange(+ model.createPositionFromPath(root, start),+ model.createPositionFromPath(root, end)+ );+ }+/** The editing view of the outermost collapsible, as rendered. */function renderedCollapsible(): { title: string | null, body: string | null } {const details = root.querySelector("details.trilium-collapsible");@@ -229,4 +256,123 @@ describe("collapsible: deleting across the boundary", () => {expect(renderedCollapsible()).toEqual({ title: "T", body: "z" });});});++ /**+ * Backspace at the start of the line below a *collapsed* collapsible (issue #11050).+ *+ * Chrome derives the target range of `deleteContentBackward` from the rendered layout,+ * where a closed collapsible shows nothing but its title, so it reports a range running+ * from the end of the <summary> through every hidden block to the caret. Acting on it+ * wipes the body while the block stays closed, and the user sees nothing happen. The+ * first four need a real key press: a synthetic `delete` event carries no browser range.+ */+ describe("Backspace below a collapsed collapsible", () => {+ const BODY = "<paragraph>one</paragraph><paragraph>two</paragraph>";+ const CLOSED = `<details><summary>Title</summary>${BODY}</details>`;+ const OPEN = `<details open="true"><summary>Title</summary>${BODY}</details>`;++ it("removes the blank line and leaves the hidden body untouched", async () => {+ setModelData(editor.model, `${CLOSED}<paragraph>[]</paragraph>`);+ editor.editing.view.focus();++ await userEvent.keyboard("{Backspace}");++ expect(getModelData(editor.model)).toBe(+ `<details><summary>Title[]</summary>${BODY}</details>`+ );+ expect(renderedCollapsible()).toEqual({ title: "Title", body: "onetwo" });+ });++ it("merges a line that has content instead of dropping the body", async () => {+ setModelData(editor.model, `${CLOSED}<paragraph>[]after</paragraph>`);+ editor.editing.view.focus();++ await userEvent.keyboard("{Backspace}");++ expect(getModelData(editor.model)).toBe(+ "<details><summary>Title[]</summary>" ++ "<paragraph>one</paragraph><paragraph>twoafter</paragraph>" ++ "</details>"+ );+ });++ it("protects a collapsed collapsible nested in an open one", async () => {+ setModelData(editor.model,+ "<details open=\"true\"><summary>Outer</summary>" ++ `<details><summary>Inner</summary>${BODY}</details>` ++ "<paragraph>[]</paragraph>" ++ "</details>");+ editor.editing.view.focus();++ await userEvent.keyboard("{Backspace}");++ expect(getModelData(editor.model)).toBe(+ "<details open=\"true\"><summary>Outer</summary>" ++ `<details><summary>Inner[]</summary>${BODY}</details>` ++ "</details>"+ );+ });++ it("leaves an open collapsible to CKEditor's own merge", async () => {+ setModelData(editor.model, `${OPEN}<paragraph>[]</paragraph>`);+ editor.editing.view.focus();++ await userEvent.keyboard("{Backspace}");++ expect(getModelData(editor.model)).toBe(+ "<details open=\"true\"><summary>Title</summary>" ++ "<paragraph>one</paragraph><paragraph>two[]</paragraph>" ++ "</details>"+ );+ });++ it("keeps a range the user selected across a collapsed collapsible", () => {+ // A hand-made selection can legitimately span a closed block — dragging from+ // above it to below it — and deleting that is what was asked for. Only a+ // collapsed caret gets the browser's range second-guessed.+ setModelData(editor.model,+ `<paragraph>a[bove</paragraph>${CLOSED}<paragraph>be]low</paragraph>`);++ fireDeleteSelection(editor.model.document.selection.getFirstRange());++ expect(getModelData(editor.model)).toBe("<paragraph>a[]low</paragraph>");+ });++ it("leaves a browser range that stays clear of a collapsed body alone", () => {+ setModelData(editor.model, `${CLOSED}<paragraph>abc[]</paragraph>`);++ fireDeleteSelection(modelRange([1, 0], [1, 2]));++ expect(getModelData(editor.model)).toBe(`${CLOSED}<paragraph>[]c</paragraph>`);+ });++ it("leaves a browser range confined to one collapsed collapsible alone", () => {+ // Both ends sit inside the same closed block, so nothing is hidden from the+ // range and the browser's reading of it stands. Reachable while find-in-note+ // holds a match's block open without touching its model attribute.+ setModelData(editor.model, `${CLOSED}<paragraph>[]</paragraph>`);++ fireDeleteSelection(modelRange([0, 1, 0], [0, 1, 3]));++ expect(getModelData(editor.model)).toBe(+ "<details><summary>Title[]</summary>" ++ "<paragraph></paragraph><paragraph>two</paragraph>" ++ "</details><paragraph></paragraph>"+ );+ });++ it("leaves a browser range crossing an open collapsible alone", () => {+ setModelData(editor.model, `${OPEN}<paragraph>[]after</paragraph>`);++ // End of the last body block → start of the line below: what the browser reports+ // when the body is on screen, and what CKEditor should act on unchanged.+ fireDeleteSelection(modelRange([0, 2, 3], [1, 0]));++ expect(getModelData(editor.model)).toBe(+ "<details open=\"true\"><summary>Title</summary>" ++ "<paragraph>one</paragraph><paragraph>two[]after</paragraph>" ++ "</details>"+ );+ });+ });});