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 a paste inside the title (closes #11084)
Elian Dorand1d5c474d5d0
diff --git a/packages/ckeditor5/src/plugins/collapsible/collapsible_editing.ts b/packages/ckeditor5/src/plugins/collapsible/collapsible_editing.tsindex 14dbad6e79..c34268f034 100644--- a/packages/ckeditor5/src/plugins/collapsible/collapsible_editing.ts+++ b/packages/ckeditor5/src/plugins/collapsible/collapsible_editing.ts@@ -143,6 +143,7 @@ export default class CollapsibleEditing extends Plugin {this.registerKeyHandlers();this.registerMergeGuard();this.registerHiddenMergeReveal();+ this.registerSummaryInsertGuard();this.registerClickHandler();this.registerDomListeners();this.registerPostFixers();@@ -934,6 +935,87 @@ export default class CollapsibleEditing extends Plugin {});}+ // -----------------------------------------------------------------+ // Insertion into a title+ // -----------------------------------------------------------------++ /**+ * Keep content pasted into a title inside the title.+ *+ * A <summary> takes inline content only, so `insertContent` looks further up for+ * somewhere a pasted block fits and finds the <details>: it splits the summary and+ * drops the pasted blocks — along with whatever followed the caret in the title — into+ * the body, which is hidden while the block is collapsed. Flattening the content to its+ * inline nodes keeps the paste where the caret is.+ *+ * A caption gets this from `isLimit`, which a <summary> cannot have: it would also make+ * the title a hard boundary for deletions, which+ * {@link CollapsibleEditing#registerMergeGuard} and+ * {@link CollapsibleEditing#onBackspaceInEmptySummary} deliberately let cross.+ */+ private registerSummaryInsertGuard() {+ const model = this.editor.model;+ this.listenTo(model, "insertContent", (_evt, args: any[]) => {+ const [content, selectable] = args;+ const selection = selectable ?? model.document.selection;+ const summary = selection.getFirstPosition()?.findAncestor("summary");+ if (!summary) return;+ // A selection running out of the title is left to CKEditor: part of what it+ // replaces belongs to the body, so part of the insertion can too.+ if (selection.getLastPosition()?.findAncestor("summary") !== summary) return;+ args[0] = this.flattenToInlineContent(content);+ }, { priority: "high" });+ }++ /**+ * Copy of `content` holding only its inline nodes, as a document fragment.+ *+ * Each source block becomes one run and the runs are joined with a space, so two pasted+ * paragraphs read as two words rather than one. Block objects (a table, a block image)+ * hold nothing a title can show and are dropped, matching what `insertContent` does with+ * an object it cannot place.+ */+ private flattenToInlineContent(content: any): any {+ const schema = this.editor.model.schema;+ const runs: any[][] = [];+ let run: any[] = [];+ const closeRun = () => {+ if (run.length) {+ runs.push(run);+ run = [];+ }+ };+ const walk = (nodes: Iterable<any>) => {+ for (const node of nodes) {+ if (schema.isInline(node)) {+ run.push(node);+ } else if (!schema.isObject(node)) {+ closeRun();+ walk(node.getChildren());+ closeRun();+ }+ }+ };+ walk(content.is("documentFragment") ? content.getChildren() : [content]);+ closeRun();++ // The nodes are moved out of `content` into a fragment of their own. Both are+ // detached from the document, so the moves produce no document operations and stay+ // out of the undo step the insertion itself creates.+ return this.editor.model.change(writer => {+ const fragment = writer.createDocumentFragment();+ for (const [index, nodes] of runs.entries()) {+ if (index > 0) {+ writer.appendText(" ", fragment);+ }+ for (const node of nodes) {+ writer.append(node, fragment);+ }+ }+ return fragment;+ });+ }+// -----------------------------------------------------------------// Click handler// -----------------------------------------------------------------diff --git a/packages/ckeditor5/src/plugins/collapsible/paste_in_summary.spec.ts b/packages/ckeditor5/src/plugins/collapsible/paste_in_summary.spec.tsnew file mode 100644index 0000000000..30b69136a3--- /dev/null+++ b/packages/ckeditor5/src/plugins/collapsible/paste_in_summary.spec.ts@@ -0,0 +1,154 @@+import {+ BlockQuote, Bold, ClassicEditor, Essentials, Heading, List, Paragraph, Table, Undo,+ _getModelData as getModelData, _setModelData as setModelData+} from "ckeditor5";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import CollapsibleEditing from "./collapsible_editing.js";++describe("inserting content into a title", () => {+ 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, Undo, Paragraph, Bold, Heading, List, BlockQuote, Table,+ CollapsibleEditing+ ]+ });+ model = editor.model;+ });++ afterEach(() => {+ domElement.remove();+ return editor.destroy();+ });++ /** Paste `html`, the way ClipboardPipeline hands dropped or pasted content to the model. */+ const paste = (html: string) => {+ model.insertContent(editor.data.toModel(editor.data.htmlProcessor.toView(html)));+ };++ const withCaretInTitle = () => setModelData(model,+ "<details open=\"true\"><summary>Ti[]tle</summary><paragraph>body</paragraph></details>"+ );++ it("keeps a single pasted block in the title, with its inline formatting", () => {+ withCaretInTitle();++ paste("<p>pas<strong>ted</strong></p>");++ expect(getModelData(model)).toBe(+ "<details open=\"true\">" ++ "<summary>Tipas<$text bold=\"true\">ted[]</$text>tle</summary>" ++ "<paragraph>body</paragraph>" ++ "</details>"+ );+ });++ it("flattens several pasted blocks into the title, one space per block boundary", () => {+ withCaretInTitle();++ // Without the guard the second paragraph — and the rest of the title with it —+ // would be split out of the <summary> and into the body.+ paste("<p>one</p><p>two</p><ul><li>three</li></ul><blockquote><p>four</p></blockquote>");++ expect(getModelData(model)).toBe(+ "<details open=\"true\">" ++ "<summary>Tione two three four[]tle</summary>" ++ "<paragraph>body</paragraph>" ++ "</details>"+ );+ });++ it("drops a pasted block object, which a title cannot show", () => {+ withCaretInTitle();++ paste("<p>before</p><table><tr><td>cell</td></tr></table>");++ expect(getModelData(model)).toBe(+ "<details open=\"true\">" ++ "<summary>Tibefore[]tle</summary>" ++ "<paragraph>body</paragraph>" ++ "</details>"+ );+ });++ it("takes the whole paste back on one undo", () => {+ withCaretInTitle();++ paste("<p>one</p><p>two</p>");+ editor.execute("undo");++ expect(getModelData(model)).toBe(+ "<details open=\"true\"><summary>Ti[]tle</summary><paragraph>body</paragraph></details>"+ );+ });++ it("replaces a selection that stays inside the title", () => {+ setModelData(model,+ "<details open=\"true\"><summary>Ti[tl]e</summary><paragraph>body</paragraph></details>"+ );++ paste("<p>one</p><p>two</p>");++ expect(getModelData(model)).toBe(+ "<details open=\"true\">" ++ "<summary>Tione two[]e</summary>" ++ "<paragraph>body</paragraph>" ++ "</details>"+ );+ });++ it("applies to any insertion into a title, not only a paste", () => {+ withCaretInTitle();++ // A single element inserted at an explicit position — the shape features other+ // than the clipboard use.+ model.change(writer => {+ const paragraph = writer.createElement("paragraph");+ writer.insertText("added", paragraph, 0);+ const summary = model.document.getRoot()?.getChild(0)?.getChild(0);+ model.insertContent(paragraph, writer.createPositionAt(summary, "end"));+ });++ expect(getModelData(model)).toBe(+ "<details open=\"true\">" ++ "<summary>Ti[]tleadded</summary>" ++ "<paragraph>body</paragraph>" ++ "</details>"+ );+ });++ it("leaves an insertion in the body alone", () => {+ setModelData(model,+ "<details open=\"true\"><summary>Title</summary><paragraph>bo[]dy</paragraph></details>"+ );++ paste("<p>one</p><p>two</p>");++ expect(getModelData(model)).toBe(+ "<details open=\"true\"><summary>Title</summary>" ++ "<paragraph>boone</paragraph><paragraph>two[]dy</paragraph>" ++ "</details>"+ );+ });++ it("leaves a selection running out of the title to CKEditor", () => {+ setModelData(model,+ "<details open=\"true\"><summary>Ti[tle</summary><paragraph>bo]dy</paragraph></details>"+ );++ paste("<p>one</p>");++ // CKEditor's own `deleteContent` merged the surviving "dy" into the title first,+ // then the single pasted block merged in at the caret.+ expect(getModelData(model)).toBe(+ "<details open=\"true\"><summary>Tione[]dy</summary><paragraph></paragraph></details>"+ );+ });+});