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
feat(text): insert paragraph buttons to code blocks (closes #10128)
Elian Doran4902a57c391b
diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.tsindex 2515eb6d67..3084b9ff1f 100644--- a/packages/ckeditor5/src/plugins.ts+++ b/packages/ckeditor5/src/plugins.ts@@ -33,6 +33,7 @@ import ImageActions from "./plugins/image_actions.js";// import "@triliumnext/ckeditor5-math/index.css";import CodeBlockToolbar from "./plugins/code_block_toolbar.js";import CodeBlockLanguageDropdown from "./plugins/code_block_language_dropdown.js";+import CodeBlockInsertParagraph from "./plugins/code_block_insert_paragraph.js";import MoveBlockUpDownPlugin from "./plugins/move_block_updown.js";import ScrollOnUndoRedoPlugin from "./plugins/scroll_on_undo_redo.js"import InlineCodeNoSpellcheck from "./plugins/inline_code_no_spellcheck.js";@@ -64,6 +65,7 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [SyntaxHighlighting,CodeBlockLanguageDropdown,CodeBlockToolbar,+ CodeBlockInsertParagraph,MoveBlockUpDownPlugin,ScrollOnUndoRedoPlugin,InlineCodeNoSpellcheck,diff --git a/packages/ckeditor5/src/plugins/code_block_insert_paragraph.ts b/packages/ckeditor5/src/plugins/code_block_insert_paragraph.tsnew file mode 100644index 0000000000..0647684cb4--- /dev/null+++ b/packages/ckeditor5/src/plugins/code_block_insert_paragraph.ts@@ -0,0 +1,124 @@+import { CodeBlock, MouseObserver, Plugin, type DowncastConversionApi, type DowncastInsertEvent, type ViewDowncastWriter, type ViewElement } from "ckeditor5";+import "../theme/code_block_insert_paragraph.css";++/*+ * Adds "insert paragraph before/after" hover buttons to code blocks, mirroring the+ * type-around affordance that CKEditor's WidgetTypeAround plugin provides for block+ * widgets (tables, images, horizontal lines, ...).+ *+ * 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.+ */++const POSITIONS = ["before", "after"] as const;+type InsertPosition = typeof POSITIONS[number];++const WRAPPER_CLASS = "ck-code-block__type-around";+const BUTTON_CLASS = "ck-code-block__type-around__button";++export default class CodeBlockInsertParagraph extends Plugin {++ static get requires() {+ return [CodeBlock] as const;+ }++ static get pluginName() {+ return "CodeBlockInsertParagraph" as const;+ }++ init() {+ // The click handler listens to view-document `mousedown`, which is only fired when a+ // MouseObserver is registered. The Widget plugin normally adds it, but register it here+ // too so this plugin works even without other widget-based features loaded.+ this.editor.editing.view.addObserver(MouseObserver);++ this._enableUIInjection();+ this._enableInsertingParagraphsOnButtonClick();+ }++ /**+ * Injects the type-around UI element into every code block created in the editing view.+ * Runs at low priority so the default CodeBlock converter has already built <pre><code>.+ * Re-fires on reconversion (e.g. language change), so the buttons survive rebuilds.+ */+ private _enableUIInjection() {+ const editor = this.editor;+ const t = editor.locale.t;+ const titles: Record<InsertPosition, string> = {+ before: t("Insert paragraph before code block"),+ after: t("Insert paragraph after code block")+ };++ editor.editing.downcastDispatcher.on<DowncastInsertEvent>("insert", (evt, data, conversionApi: DowncastConversionApi) => {+ if (!data.item.is("element", "codeBlock")) {+ return;+ }++ const viewCode = conversionApi.mapper.toViewElement(data.item);+ const pre = viewCode?.parent;+ if (!pre || !pre.is("element", "pre")) {+ return;+ }++ injectButtons(conversionApi.writer, pre, titles);+ }, { priority: "low" });+ }++ /**+ * Intercepts mousedown on the injected buttons and inserts a paragraph next to the+ * related code block. A single delegated listener (rather than per-button handlers)+ * avoids having to clean up listeners as code blocks come and go.+ */+ private _enableInsertingParagraphsOnButtonClick() {+ const editor = this.editor;+ const view = editor.editing.view;++ this.listenTo(view.document, "mousedown", (evt, domEventData) => {+ const domTarget = domEventData.domTarget;+ const button = domTarget instanceof Element ? domTarget.closest(`.${BUTTON_CLASS}`) : null;+ if (!button) {+ return;+ }++ const position: InsertPosition = button.classList.contains(`${BUTTON_CLASS}_before`) ? "before" : "after";+ const domCode = button.closest("pre")?.querySelector("code");+ const viewCode = domCode ? view.domConverter.mapDomToView(domCode) : undefined;+ const codeBlock = viewCode?.is("element") ? editor.editing.mapper.toModelElement(viewCode) : null;+ if (!codeBlock) {+ return;+ }++ editor.execute("insertParagraph", {+ position: editor.model.createPositionAt(codeBlock, position)+ });+ view.focus();+ view.scrollToTheSelection();++ domEventData.preventDefault();+ evt.stop();+ });+ }++}++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>) {+ const wrapper = writer.createUIElement("div", { class: `ck ck-reset_all ${WRAPPER_CLASS}` }, function (domDocument) {+ const domElement = this.toDomElement(domDocument);+ for (const position of POSITIONS) {+ const button = domDocument.createElement("div");+ button.className = `ck ${BUTTON_CLASS} ${BUTTON_CLASS}_${position}`;+ button.title = titles[position];+ button.setAttribute("aria-hidden", "true");+ button.innerHTML = RETURN_ARROW_ICON;+ domElement.appendChild(button);+ }+ return domElement;+ });++ writer.insert(writer.createPositionAt(pre, "end"), wrapper);+}diff --git a/packages/ckeditor5/src/theme/code_block_insert_paragraph.css b/packages/ckeditor5/src/theme/code_block_insert_paragraph.cssnew file mode 100644index 0000000000..c8993f4272--- /dev/null+++ b/packages/ckeditor5/src/theme/code_block_insert_paragraph.css@@ -0,0 +1,136 @@+/*+ * "Insert paragraph before/after" hover buttons for code blocks.+ *+ * Code blocks are not widgets, so they don't receive CKEditor's WidgetTypeAround affordance.+ * This plugin injects an equivalent UI element into the editable <pre>; the rules below mirror+ * the widget type-around arrows (tables/images/horizontal lines) as closely as possible by+ * reusing the same CSS custom properties and @keyframes defined by ckeditor5-widget, so the+ * look, colours and transitions stay in sync with the editor theme.+ *+ * Source of truth: @ckeditor/ckeditor5-widget/dist/index.css (.ck-widget__type-around__*).+ */++/* The wrapper overlays the <pre> padding box (already `position: relative`) without taking flow space. */+.ck.ck-editor__editable .ck-code-block__type-around {+ position: absolute;+ inset: 0;+ pointer-events: none;+}++.ck.ck-editor__editable .ck-code-block__type-around__button {+ width: var(--ck-widget-type-around-button-size);+ height: var(--ck-widget-type-around-button-size);+ background: var(--ck-color-widget-type-around-button-hover);+ transition:+ opacity var(--ck-widget-handler-animation-duration) var(--ck-widget-handler-animation-curve),+ background var(--ck-widget-handler-animation-duration) var(--ck-widget-handler-animation-curve);+ opacity: 0;+ pointer-events: none;+ cursor: pointer;+ z-index: var(--ck-z-default);+ border-radius: 100px;+ display: block;+ position: absolute;+ overflow: hidden;+}++@media (prefers-reduced-motion: reduce) {+ .ck.ck-editor__editable .ck-code-block__type-around__button {+ transition: none;+ }+}++.ck.ck-editor__editable .ck-code-block__type-around__button svg {+ width: 10px;+ height: 8px;+ margin-top: 1px;+ transition: transform .5s;+ position: absolute;+ top: 50%;+ left: 50%;+ transform: translate(-50%, -50%);+ z-index: calc(var(--ck-z-default) + 2);+}++@media (prefers-reduced-motion: reduce) {+ .ck.ck-editor__editable .ck-code-block__type-around__button svg {+ transition: none;+ }+}++.ck.ck-editor__editable .ck-code-block__type-around__button svg * {+ stroke-dasharray: 10;+ stroke-dashoffset: 0;+ fill: none;+ stroke: var(--ck-color-widget-type-around-button-icon);+ stroke-width: 1.5px;+ stroke-linecap: round;+ stroke-linejoin: round;+}++.ck.ck-editor__editable .ck-code-block__type-around__button svg line {+ stroke-dasharray: 7;+}++/* Positioning: "before" straddles the top-left edge, "after" the bottom-right — same as widgets. */+.ck.ck-editor__editable .ck-code-block__type-around__button_before {+ top: calc(-.5 * var(--ck-widget-outline-thickness));+ left: min(10%, 30px);+ transform: translateY(-50%);+}++.ck.ck-editor__editable .ck-code-block__type-around__button_after {+ bottom: calc(-.5 * var(--ck-widget-outline-thickness));+ right: min(10%, 30px);+ transform: translateY(50%);+}++/* 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 {+ opacity: 1;+ pointer-events: auto;+}++/* Active colour + sonar pulse + arrow dash when hovering the button itself (keyframes from ckeditor5-widget). */+.ck.ck-editor__editable .ck-code-block__type-around__button:hover {+ background: var(--ck-color-widget-type-around-button-active);+ animation: 1s infinite ck-widget-type-around-button-sonar;+}++.ck.ck-editor__editable .ck-code-block__type-around__button:hover svg polyline {+ animation: 2s linear ck-widget-type-around-arrow-dash;+}++.ck.ck-editor__editable .ck-code-block__type-around__button:hover svg line {+ animation: 2s linear ck-widget-type-around-arrow-tip-dash;+}++@media (prefers-reduced-motion: reduce) {+ .ck.ck-editor__editable .ck-code-block__type-around__button:hover {+ animation: none;+ }++ .ck.ck-editor__editable .ck-code-block__type-around__button:hover svg polyline,+ .ck.ck-editor__editable .ck-code-block__type-around__button:hover svg line {+ animation: none;+ }+}++/* Glossy highlight overlay on hover, matching the widget. */+.ck.ck-editor__editable .ck-code-block__type-around__button:hover::after {+ content: "";+ width: calc(var(--ck-widget-type-around-button-size) - 2px);+ height: calc(var(--ck-widget-type-around-button-size) - 2px);+ z-index: calc(var(--ck-z-default) + 1);+ background: linear-gradient(135deg, #fff0 0%, #ffffff4d 100%);+ border-radius: 100px;+ display: block;+ position: absolute;+ top: 1px;+ left: 1px;+}++/* In read-only mode the paragraph can't be inserted, so don't offer the affordance. */+.ck.ck-editor__editable.ck-read-only .ck-code-block__type-around {+ display: none;+}