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): inject code-block insert-paragraph UI into the mapped <code>
Elian Doran76c2ae8d717c
diff --git a/packages/ckeditor5/src/plugins/code_block_insert_paragraph.spec.ts b/packages/ckeditor5/src/plugins/code_block_insert_paragraph.spec.tsnew file mode 100644index 0000000000..82d922f0dd--- /dev/null+++ b/packages/ckeditor5/src/plugins/code_block_insert_paragraph.spec.ts@@ -0,0 +1,141 @@+import { ClassicEditor, CodeBlock, Essentials, GeneralHtmlSupport, List, Paragraph, _getModelData as getModelData, _setModelData as setModelData } from "ckeditor5";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { createTestEditor } from "../../test/editor-kit.js";+import CodeBlockInsertParagraph from "./code_block_insert_paragraph.js";++const WRAPPER = ".ck-code-block__type-around";+const BUTTON = ".ck-code-block__type-around__button";++describe("CodeBlockInsertParagraph", () => {+ let editor: ClassicEditor;++ beforeEach(async () => {+ editor = await createTestEditor([Essentials, Paragraph, CodeBlock, CodeBlockInsertParagraph]);+ });++ /** Render a model fragment to the editing DOM and return the contenteditable root. */+ function render(content = "<codeBlock language=\"plaintext\">foo[]</codeBlock>"): Element {+ setModelData(editor.model, content);+ editor.editing.view.forceRender();+ const root = editor.editing.view.getDomRoot();+ if (!root) {+ throw new Error("Editing view has no DOM root.");+ }+ return root;+ }++ /** Fire a `mousedown` on the editing view document (the channel the plugin listens to). */+ function fireMouseDown(domTarget: unknown): ReturnType<typeof vi.fn> {+ const preventDefault = vi.fn();+ const viewDocument = editor.editing.view.document as unknown as { fire(event: string, data: unknown): void };+ viewDocument.fire("mousedown", { domTarget, preventDefault });+ return preventDefault;+ }++ describe("metadata", () => {+ it("loads the plugin", () => {+ expect(editor.plugins.get(CodeBlockInsertParagraph)).toBeInstanceOf(CodeBlockInsertParagraph);+ });++ it("exposes the plugin name and requires CodeBlock", () => {+ expect(CodeBlockInsertParagraph.pluginName).toBe("CodeBlockInsertParagraph");+ expect(CodeBlockInsertParagraph.requires).toContain(CodeBlock);+ });+ });++ describe("UI injection", () => {+ it("injects two type-around buttons into the code block's mapped <code>", () => {+ const root = render();++ expect(root.querySelectorAll(WRAPPER).length).toBe(1);+ expect(root.querySelectorAll(BUTTON).length).toBe(2);+ // The wrapper lives inside the <code> (the element the model is bound to), not the+ // parent <pre> — injecting into a non-mapped container breaks downcast removal.+ const wrapper = root.querySelector(WRAPPER);+ expect(wrapper?.parentElement?.tagName).toBe("CODE");+ expect(wrapper?.closest("pre")).not.toBeNull();+ });++ it("labels the buttons with localized before/after titles", () => {+ const root = render();++ expect(root.querySelector(`${BUTTON}_before`)?.getAttribute("title")).toBe("Insert paragraph before code block");+ expect(root.querySelector(`${BUTTON}_after`)?.getAttribute("title")).toBe("Insert paragraph after code block");+ });++ it("does not inject the UI into non-code-block elements", () => {+ const root = render("<paragraph>foo[]</paragraph><codeBlock language=\"plaintext\">bar</codeBlock>");++ // Only the single code block is decorated; the paragraph is left untouched.+ expect(root.querySelectorAll(WRAPPER).length).toBe(1);+ });+ });++ describe("inserting paragraphs on click", () => {+ it("inserts a paragraph after the code block when the after-button is pressed", () => {+ const root = render();++ const preventDefault = fireMouseDown(root.querySelector(`${BUTTON}_after`));++ expect(getModelData(editor.model)).toBe("<codeBlock language=\"plaintext\">foo</codeBlock><paragraph>[]</paragraph>");+ expect(preventDefault).toHaveBeenCalled();+ });++ it("inserts a paragraph before the code block when the before-button is pressed", () => {+ const root = render();++ fireMouseDown(root.querySelector(`${BUTTON}_before`));++ expect(getModelData(editor.model)).toBe("<paragraph>[]</paragraph><codeBlock language=\"plaintext\">foo</codeBlock>");+ });++ it("ignores a mousedown that is not on a type-around button", () => {+ const root = render();+ const before = getModelData(editor.model);++ fireMouseDown(root); // the editable root, which has no button ancestor++ expect(getModelData(editor.model)).toBe(before);+ });++ it("ignores a button that is detached from any code block", () => {+ render();+ const before = getModelData(editor.model);++ const orphan = document.createElement("div");+ orphan.className = "ck-code-block__type-around__button ck-code-block__type-around__button_after";+ fireMouseDown(orphan);++ expect(getModelData(editor.model)).toBe(before);+ });+ });++ describe("conversion lifecycle", () => {+ // Replacing the editor content (e.g. switching notes, which calls editor.setData)+ // must remove the decorated code block without tripping the view writer.+ it("survives content replacement that removes a decorated code block", () => {+ editor.setData("<pre><code class=\"language-plaintext\">foo</code></pre>");+ expect(() => editor.setData("<p>bar</p>")).not.toThrow();+ });+ });+});++describe("CodeBlockInsertParagraph — nested code blocks", () => {+ let editor: ClassicEditor;++ beforeEach(async () => {+ editor = await createTestEditor(+ [Essentials, Paragraph, CodeBlock, List, GeneralHtmlSupport, CodeBlockInsertParagraph],+ { htmlSupport: { allow: [{ name: /.*/, attributes: true, classes: true, styles: true }] } }+ );+ });++ // Regression: a decorated code block inside a list item used to throw+ // `view-writer-invalid-range-container` on removal, because the UI element was injected+ // into the non-mapped <pre>. See the plugin's module comment.+ it("survives removing a code block nested in a list item", () => {+ editor.setData("<ul><li><pre><code class=\"language-plaintext\">foo</code></pre></li></ul>");+ expect(() => editor.setData("<p>bar</p>")).not.toThrow();+ });+});diff --git a/packages/ckeditor5/src/plugins/code_block_insert_paragraph.ts b/packages/ckeditor5/src/plugins/code_block_insert_paragraph.tsindex 0647684cb4..500207d7a2 100644--- a/packages/ckeditor5/src/plugins/code_block_insert_paragraph.ts+++ b/packages/ckeditor5/src/plugins/code_block_insert_paragraph.ts@@ -8,9 +8,16 @@ import "../theme/code_block_insert_paragraph.css";** Code blocks are NOT widgets — they downcast to a plain editable <pre><code> — so* WidgetTypeAround skips them and exposes no public API to opt them in. This plugin- * re-implements the slice we need: it injects a non-editable UI element into the <pre>- * (a sibling of the bound <code>, so model<->view position mapping is untouched) and- * inserts a paragraph next to the block on click.+ * re-implements the slice we need: a non-editable UI element injected into the editing+ * view, plus a click handler that inserts a paragraph next to the block.+ *+ * The UI element is injected into the <code> element (the one the model `codeBlock` is+ * bound to), exactly like WidgetTypeAround injects into its mapped widget element — NOT+ * into the parent <pre>. Injecting into a non-mapped container breaks downcast removal+ * (e.g. a code block inside a list item throws `view-writer-invalid-range-container` when+ * the content is replaced), because the stray child shifts the trimmed remove range out+ * of its container. The buttons stay positioned against the <pre> via CSS (it is the+ * nearest positioned ancestor), so the placement is unaffected.*/const POSITIONS = ["before", "after"] as const;@@ -58,12 +65,12 @@ export default class CodeBlockInsertParagraph extends Plugin {}const viewCode = conversionApi.mapper.toViewElement(data.item);- const pre = viewCode?.parent;- if (!pre || !pre.is("element", "pre")) {+ /* v8 ignore next 3 -- defensive: at low priority the code block has already been converted, so it always maps to a view element */+ if (!viewCode) {return;}- injectButtons(conversionApi.writer, pre, titles);+ injectButtons(conversionApi.writer, viewCode, titles);}, { priority: "low" });}@@ -78,7 +85,12 @@ export default class CodeBlockInsertParagraph extends Plugin {this.listenTo(view.document, "mousedown", (evt, domEventData) => {const domTarget = domEventData.domTarget;- const button = domTarget instanceof Element ? domTarget.closest(`.${BUTTON_CLASS}`) : null;+ /* v8 ignore next 3 -- defensive: a real mousedown always targets an Element (CKEditor's own widget code assumes the same) */+ if (!(domTarget instanceof Element)) {+ return;+ }++ const button = domTarget.closest(`.${BUTTON_CLASS}`);if (!button) {return;}@@ -106,7 +118,7 @@ export default class CodeBlockInsertParagraph extends Plugin {const RETURN_ARROW_ICON = '<svg viewBox="0 0 10 8" xmlns="http://www.w3.org/2000/svg"><path d="M9.055.263v3.972h-6.77M1 4.216l2-2.038m-2 2 2 2.038"/></svg>';-function injectButtons(writer: ViewDowncastWriter, pre: ViewElement, titles: Record<InsertPosition, string>) {+function injectButtons(writer: ViewDowncastWriter, codeElement: ViewElement, titles: Record<InsertPosition, string>) {const wrapper = writer.createUIElement("div", { class: `ck ck-reset_all ${WRAPPER_CLASS}` }, function (domDocument) {const domElement = this.toDomElement(domDocument);for (const position of POSITIONS) {@@ -120,5 +132,5 @@ function injectButtons(writer: ViewDowncastWriter, pre: ViewElement, titles: Recreturn domElement;});- writer.insert(writer.createPositionAt(pre, "end"), wrapper);+ writer.insert(writer.createPositionAt(codeElement, "end"), wrapper);}diff --git a/packages/ckeditor5/src/theme/code_block_insert_paragraph.css b/packages/ckeditor5/src/theme/code_block_insert_paragraph.cssindex c8993f4272..cb60dd7eec 100644--- a/packages/ckeditor5/src/theme/code_block_insert_paragraph.css+++ b/packages/ckeditor5/src/theme/code_block_insert_paragraph.css@@ -86,7 +86,7 @@}/* Reveal the buttons while hovering the code block. */-.ck.ck-editor__editable pre:hover > .ck-code-block__type-around > .ck-code-block__type-around__button {+.ck.ck-editor__editable pre:hover .ck-code-block__type-around__button {opacity: 1;pointer-events: auto;}