Skip to content

Build your personal knowledge base with Trilium Notes

refactor(text): remove the old Mermaid editing plugin

Elian Doran2a4cb4f1a72c
diff --git a/apps/client/src/fonts/text-editor-icons.woff2 b/apps/client/src/fonts/text-editor-icons.woff2
index 81b23b1766..dba6d060e5 100644
Binary files a/apps/client/src/fonts/text-editor-icons.woff2 and b/apps/client/src/fonts/text-editor-icons.woff2 differ
diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.css
index 2f1e0fbba3..13aaaa89f8 100644
--- a/apps/client/src/stylesheets/style.css
+++ b/apps/client/src/stylesheets/style.css
@@ -289,7 +289,7 @@ samp {
* content and not what anyone is asking for. Inheritance is what makes `.cm-editor` enough to cover
* CodeMirror's internals.
*/
-body.monospace-ligatures-disabled :is(code, kbd, pre, samp, .cm-editor, .ck-mermaid__editing-view) {
+body.monospace-ligatures-disabled :is(code, kbd, pre, samp, .cm-editor) {
font-variant-ligatures: none;
}
@@ -826,10 +826,6 @@ div[data-notify="container"] {
color: var(--muted-text-color);
}
-.ck-editor__editable .ck-mermaid__editing-view {
- font-family: var(--monospace-font-family);
-}
-
svg.ck-icon.note-icon {
color: var(--main-text-color);
font-size: 20px;
diff --git a/apps/client/src/stylesheets/theme-next/notes/text.css b/apps/client/src/stylesheets/theme-next/notes/text.css
index f090b15798..60a4e08784 100644
--- a/apps/client/src/stylesheets/theme-next/notes/text.css
+++ b/apps/client/src/stylesheets/theme-next/notes/text.css
@@ -706,8 +706,7 @@ button.ck.ck-button:is(.ck-button-action, .ck-button-save, .ck-button-cancel).ck
*/
.attachment-content-wrapper pre,
-:root .ck-content pre,
-.ck-mermaid__editing-view {
+:root .ck-content pre {
border: 0;
border-radius: 6px;
box-shadow: var(--code-block-box-shadow);
@@ -773,8 +772,7 @@ html .note-detail-editable-text > :not(figure, .include-note, hr):first-child {
}
.attachment-content-wrapper pre code,
-:root .ck-content pre code,
-.ck-mermaid__editing-view {
+:root .ck-content pre code {
display: block;
padding: var(--padding-size, 1em);
overflow: auto;
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index f1a60326dd..347b5eb4e9 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -4425,7 +4425,6 @@
"insert-date-time": "Insert date/time",
"insert-date-time-0": "Insert date/time: %0",
"insert-footnote-0": "Insert footnote %0",
- "insert-mermaid-source-code": "Insert Mermaid source code",
"insert-paragraph-after-code-block": "Insert paragraph after code block",
"insert-paragraph-before-code-block": "Insert paragraph before code block",
"insert-text-snippet": "Insert text snippet",
@@ -4445,8 +4444,6 @@
"medium": "Medium",
"mermaid-diagram": "Mermaid diagram",
"mermaid-diagram-0": "Mermaid diagram: %0",
- "mermaid-toolbar": "Mermaid toolbar",
- "mermaid-widget": "Mermaid widget",
"missing-definition": "(missing definition)",
"new-footnote": "New footnote",
"no-anchors-available": "No anchors available.",
diff --git a/packages/ckeditor5/src/icons/mermaid-info.svg b/packages/ckeditor5/src/icons/mermaid-info.svg
deleted file mode 100644
index c9614b2aa8..0000000000
--- a/packages/ckeditor5/src/icons/mermaid-info.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M8 1.219C4.254 1.219 1.219 4.28 1.219 8A6.78 6.78 0 0 0 8 14.781c3.719 0 6.781-3.035 6.781-6.781 0-3.719-3.062-6.781-6.781-6.781Zm0 12.25A5.45 5.45 0 0 1 2.531 8 5.467 5.467 0 0 1 8 2.531c3.008 0 5.469 2.461 5.469 5.469A5.467 5.467 0 0 1 8 13.469Zm0-9.242c-.656 0-1.148.52-1.148 1.148 0 .656.492 1.148 1.148 1.148.629 0 1.148-.492 1.148-1.148 0-.629-.52-1.148-1.148-1.148Zm1.531 6.945v-.656a.353.353 0 0 0-.328-.329h-.328V7.454a.353.353 0 0 0-.328-.328h-1.75a.332.332 0 0 0-.328.328v.656c0 .192.136.329.328.329h.328v1.75h-.328a.333.333 0 0 0-.328.328v.656c0 .191.136.328.328.328h2.406a.332.332 0 0 0 .328-.328Z"/></svg>
diff --git a/packages/ckeditor5/src/icons/mermaid-preview-mode.svg b/packages/ckeditor5/src/icons/mermaid-preview-mode.svg
deleted file mode 100644
index cdccfcaf1c..0000000000
--- a/packages/ckeditor5/src/icons/mermaid-preview-mode.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M13.8 11.609V13.4a.4.4 0 0 1-.4.4H2.6a.4.4 0 0 1-.4-.4v-1.791H1V13.4A1.6 1.6 0 0 0 2.6 15h10.8a1.6 1.6 0 0 0 1.6-1.6v-1.791h-1.2ZM13.8 4.997H15V2.6A1.6 1.6 0 0 0 13.4 1H2.6A1.6 1.6 0 0 0 1 2.6v2.397h1.2V2.6c0-.22.18-.4.4-.4h10.8c.22 0 .4.18.4.4v2.397Z"/><path d="M8 11.095c-1.92 0-3.837-.919-5.749-2.757L2 8.095l.251-.242c3.815-3.677 7.683-3.677 11.498 0l.251.242-.251.243C11.84 10.176 9.925 11.095 8 11.096Zm-5.02-3c3.375 3.1 6.665 3.1 10.04 0-3.375-3.1-6.665-3.095-10.04 0Z"/><path fill-rule="evenodd" clip-rule="evenodd" d="M13.514 8.095c-3.676 3.543-7.352 3.543-11.028 0 3.676-3.542 7.352-3.542 11.028 0Zm-3.586 0A1.926 1.926 0 0 1 8 10.02a1.926 1.926 0 0 1-1.928-1.924c0-1.062.863-1.924 1.928-1.924s1.928.862 1.928 1.924Z"/><path d="M8 8.861a.767.767 0 1 0 .002-1.533A.767.767 0 0 0 8 8.86Z"/></svg>
diff --git a/packages/ckeditor5/src/icons/mermaid-source-mode.svg b/packages/ckeditor5/src/icons/mermaid-source-mode.svg
deleted file mode 100644
index be4647c111..0000000000
--- a/packages/ckeditor5/src/icons/mermaid-source-mode.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M11.609 2.2H13.4c.22 0 .4.18.4.4v10.8a.4.4 0 0 1-.4.4h-1.791V15H13.4a1.6 1.6 0 0 0 1.6-1.6V2.6A1.6 1.6 0 0 0 13.4 1h-1.791v1.2ZM4.997 2.2V1H2.6A1.6 1.6 0 0 0 1 2.6v10.8A1.6 1.6 0 0 0 2.6 15h2.397v-1.2H2.6a.4.4 0 0 1-.4-.4V2.6c0-.22.18-.4.4-.4h2.397Z"/><path d="M3.511 4.778a.75.75 0 0 1 .75-.75h3.697a.75.75 0 1 1 0 1.5H4.26a.75.75 0 0 1-.75-.75ZM6.595 7.629a.75.75 0 0 1 .75-.75h3.588a.75.75 0 0 1 0 1.5H7.345a.75.75 0 0 1-.75-.75ZM6.595 10.48a.75.75 0 0 1 .75-.75h1.143a.75.75 0 1 1 0 1.5H7.345a.75.75 0 0 1-.75-.75ZM3.511 7.629a.75.75 0 0 1 .75-.75h.983a.75.75 0 1 1 0 1.5h-.983a.75.75 0 0 1-.75-.75ZM3.511 10.48a.75.75 0 0 1 .75-.75h.983a.75.75 0 1 1 0 1.5h-.983a.75.75 0 0 1-.75-.75Z"/></svg>
diff --git a/packages/ckeditor5/src/icons/mermaid-split-mode.svg b/packages/ckeditor5/src/icons/mermaid-split-mode.svg
deleted file mode 100644
index ef07ec1854..0000000000
--- a/packages/ckeditor5/src/icons/mermaid-split-mode.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M13.8 3.076H8.588V13.8H13.4a.4.4 0 0 0 .4-.4V3.076Zm-6.412 0H2.2V13.4c0 .22.18.4.4.4h4.788V3.076ZM2.6 1A1.6 1.6 0 0 0 1 2.6v10.8A1.6 1.6 0 0 0 2.6 15h10.8a1.6 1.6 0 0 0 1.6-1.6V2.6A1.6 1.6 0 0 0 13.4 1H2.6Z"/></svg>
diff --git a/packages/ckeditor5/src/plugins/mermaid/README.md b/packages/ckeditor5/src/plugins/mermaid/README.md
index c5dc3e08e3..4417a07e72 100644
--- a/packages/ckeditor5/src/plugins/mermaid/README.md
+++ b/packages/ckeditor5/src/plugins/mermaid/README.md
@@ -1,57 +1,23 @@
# Mermaid diagrams
-A `<mermaid>` block widget holding diagram source, shown as a source textarea, a rendered preview,
-or both side by side. Load the `Mermaid` glue plugin; it pulls in `MermaidEditing`,
-`MermaidToolbar` and `MermaidUI`.
+The `mermaid` split button and the Mermaid slash commands, which insert a diagram, blank or from a
+template in `mermaid.samples`. Load the `Mermaid` glue plugin; it pulls in `MermaidUI`.
| File | Role |
|---|---|
-| `mermaid.ts` | Glue plugin; also declares the `ckeditor5` module augmentation and the global mermaid types |
-| `mermaid_editing.ts` | Schema, conversion, and the renderer (`renderMermaid`) |
-| `mermaid_ui.ts` | The insert split button with its template dropdown, the mode buttons, the info button |
-| `mermaid_toolbar.ts` | Registers the balloon toolbar shown when a diagram is selected |
-| `insert_mermaid_command.ts` | `insertMermaid` — inserts a blank or pre-filled diagram |
-| `mermaid_{preview,source_view,split_view}_command.ts` | Switch the widget's `displayMode` |
-| `utils.ts` | `debounce` for the source textarea, `checkIsOn` for button state |
+| `mermaid.ts` | Glue plugin; also declares the `ckeditor5` module augmentation |
+| `mermaid_ui.ts` | The insert split button with its template dropdown, and `insertMermaidDiagram()` |
-## The display mode is part of the content
+## A diagram is an inline embed
-A diagram round-trips as `<pre spellcheck="false"><code class="language-mermaid">…</code></pre>`, with
-the picked mode persisted on the `<code>` as `data-trilium-display-mode` — the same treatment
-collapsed list items get with `data-trilium-collapsed`. The default (`split`) is left out, so a
-diagram nobody switched keeps producing exactly the content it did before; a missing or unknown
-value upcasts back to `split`.
-
-## The mermaid library is not a dependency
-
-The plugin never imports mermaid. The host passes it in through editor config:
-
-```js
-mermaid: {
- lazyLoad: () => import( 'mermaid' ).then( m => m.default ),
- config: { /* mermaid initialize() config */ },
- samples: [ /* diagram templates for the insert dropdown */ ]
-}
-```
-
-`renderMermaid` calls `lazyLoad` once, memoises the promise, and calls `initialize()` on the
-resolved instance. Renders are generation-stamped so a slow render that has been superseded cannot
-overwrite a newer one, and a failed render shows the error message in place. It is public because
-the widget is not the only diagram on screen: the AI assistant renders the `language-mermaid` blocks
-of a finished response through it, so its review shows what committing will produce.
+This package has no Mermaid editing or rendering of its own. A diagram is a `contentEmbed` that
+keeps its source in the note (`content_embed/inline_source.ts`): it is saved as
+`<pre><code class="language-mermaid">…</code></pre>`, with the box size, flags and size of the
+embed on the `<pre>`, and the host renders and edits it through `loadInlineEmbed()`. The host must
+list `mermaid` in `contentEmbed.inlineLanguages`, or a diagram loads as a plain code block.
## Provenance
-Derived from CKSource's `@ckeditor/ckeditor5-mermaid`, copyright CKSource Holding sp. z o.o., used
-under the GPL-2.0-or-later arm of its license — see `LICENSE.md` next to this file, which combines
-with this repository's AGPL-3.0-only.
-
-Upstream describes itself as experimental and unsupported, and Trilium's copy has diverged
-substantially: the split-button insert with diagram templates, the render generation guard, the
-protection against double initialisation and stale renders, the lazy-load hook, and the flicker-free
-re-render mechanism are all Trilium's.
-
-It lived at `packages/ckeditor5-mermaid` until it was folded into this package — it had no consumers
-outside `@triliumnext/ckeditor5`, declared no dependencies of its own, was never published, and
-carried a `ckeditor5-package-generator` scaffold (sample pages, its own ESLint/Stylelint/vitest
-configs) that nothing invoked.
+The insert button derives from CKSource's `@ckeditor/ckeditor5-mermaid`, copyright CKSource
+Holding sp. z o.o., used under the GPL-2.0-or-later arm of its license — see `LICENSE.md` next to
+this file, which combines with this repository's AGPL-3.0-only.
diff --git a/packages/ckeditor5/src/plugins/mermaid/insert_mermaid_command.spec.ts b/packages/ckeditor5/src/plugins/mermaid/insert_mermaid_command.spec.ts
deleted file mode 100644
index b98712da3b..0000000000
--- a/packages/ckeditor5/src/plugins/mermaid/insert_mermaid_command.spec.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-import { ClassicEditor, Paragraph, _setModelData as setModelData, _getModelData as getModelData } from 'ckeditor5';
-import { afterEach, beforeEach, describe, it } from 'vitest';
-import { expect } from 'vitest';
-import MermaidEditing from './mermaid_editing.js';
-import InsertMermaidCommand from './insert_mermaid_command.js';
-
-/* global document */
-
-describe( 'InsertMermaidCommand', () => {
- let domElement, editor, model, command;
-
- beforeEach( async () => {
- domElement = document.createElement( 'div' );
- document.body.appendChild( domElement );
-
- editor = await ClassicEditor.create( domElement, {
- licenseKey: "GPL",
- plugins: [
- MermaidEditing,
- Paragraph
- ]
- } );
-
- model = editor.model;
-
- command = new InsertMermaidCommand( editor );
- } );
-
- afterEach( () => {
- domElement.remove();
- return editor.destroy();
- } );
-
- describe( '#isEnabled', () => {
- describe( 'should be false', () => {
- it( 'when selection is inside mermaid', () => {
- setModelData( model,
- '<paragraph>foo</paragraph>' +
- '<mermaid source="flowchart TB\nA --> B\nB --> C">[]</mermaid>'
- );
-
- expect( command.isEnabled ).to.be.false;
- } );
-
- it( 'when mermaid is selected', () => {
- setModelData( model,
- '<paragraph>foo</paragraph>' +
- '[<mermaid source="flowchart TB\nA --> B\nB --> C"></mermaid>]'
- );
-
- expect( command.isEnabled ).to.be.false;
- } );
- } );
-
- describe( 'should be true', () => {
- it( 'when text is selected', () => {
- setModelData( model,
- '<paragraph>[foo]</paragraph>' +
- '<mermaid source="flowchart TB\nA --> B\nB --> C"></mermaid>'
- );
-
- expect( command.isEnabled ).to.be.true;
- } );
-
- it( 'when mermaid is part of the selection', () => {
- setModelData( model,
- '<paragraph>[foo</paragraph>' +
- '<mermaid source="flowchart TB\nA --> B\nB --> C"></mermaid>' +
- '<paragraph>b]az</paragraph>'
- );
-
- expect( command.isEnabled ).to.be.true;
- } );
- } );
- } );
-
- describe( 'execute()', () => {
- it( 'should add mermaid with the provided source', () => {
- setModelData( model,
- '<paragraph>[foo]</paragraph>'
- );
-
- command.execute( { source: 'graph LR; X --> Y' } );
-
- expect( getModelData( model, { withoutSelection: true } ) ).to.equal(
- '<mermaid displayMode="split" source="graph LR; X --> Y"></mermaid>'
- );
- } );
-
- it( 'should add sample mermaid', () => {
- setModelData( model,
- '<paragraph>[foo]</paragraph>'
- );
-
- command.execute();
-
- expect( getModelData( model, { withoutSelection: true } ) ).to.equal(
- '<mermaid displayMode="split" source="flowchart TB\nA --> B\nB --> C"></mermaid>'
- );
- } );
- } );
-} );
diff --git a/packages/ckeditor5/src/plugins/mermaid/insert_mermaid_command.ts b/packages/ckeditor5/src/plugins/mermaid/insert_mermaid_command.ts
deleted file mode 100644
index 7e5c7ea176..0000000000
--- a/packages/ckeditor5/src/plugins/mermaid/insert_mermaid_command.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { Command } from "ckeditor5";
-
-/** The name under which {@link InsertMermaidCommand} is registered in the editor. */
-export const INSERT_MERMAID_COMMAND = "insertMermaidCommand";
-
-const MOCK_MERMAID_MARKUP = `flowchart TB
-A --> B
-B --> C`;
-
-/**
- * The insert mermaid command.
- *
- * Allows to insert mermaid.
- */
-export default class InsertMermaidCommand extends Command {
-
- override refresh() {
- const documentSelection = this.editor.model.document.selection;
- const selectedElement = documentSelection.getSelectedElement();
-
- if ( selectedElement && selectedElement.name === 'mermaid' ) {
- this.isEnabled = false;
- } else {
- this.isEnabled = true;
- }
- }
-
- override execute( options: { source?: string; displayMode?: string } = {} ) {
- const editor = this.editor;
- const model = editor.model;
- let mermaidItem;
-
- model.change( writer => {
- mermaidItem = writer.createElement( 'mermaid', {
- displayMode: options.displayMode ?? 'split',
- source: options.source ?? MOCK_MERMAID_MARKUP
- } );
-
- model.insertContent( mermaidItem );
- } );
-
- return mermaidItem;
- }
-}
diff --git a/packages/ckeditor5/src/plugins/mermaid/mermaid.spec.ts b/packages/ckeditor5/src/plugins/mermaid/mermaid.spec.ts
deleted file mode 100644
index 45d0ebac4a..0000000000
--- a/packages/ckeditor5/src/plugins/mermaid/mermaid.spec.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import { ClassicEditor, Essentials, Paragraph, Heading, _setModelData as setModelData } from 'ckeditor5';
-
-import Mermaid from './mermaid.js';
-import { afterEach, beforeEach, describe, it } from 'vitest';
-import { expect } from 'vitest';
-
-/* global document */
-
-describe( 'Mermaid', () => {
- it( 'should be named', () => {
- expect( Mermaid.pluginName ).to.equal( 'Mermaid' );
- } );
-
- describe( 'init()', () => {
- let domElement, editor;
-
- beforeEach( async () => {
- domElement = document.createElement( 'div' );
- document.body.appendChild( domElement );
-
- editor = await ClassicEditor.create( domElement, {
- licenseKey: "GPL",
- plugins: [
- Paragraph,
- Heading,
- Essentials,
- Mermaid
- ],
- toolbar: [
- 'mermaid'
- ]
- } );
-
- setModelData( editor.model, '<paragraph>[]</paragraph>' );
- } );
-
- afterEach( () => {
- domElement.remove();
- return editor.destroy();
- } );
-
- it( 'should add an icon to the toolbar', () => {
- expect( editor.ui.componentFactory.has( 'Mermaid' ) ).to.equal( true );
- } );
- } );
-} );
diff --git a/packages/ckeditor5/src/plugins/mermaid/mermaid_converter_guards.spec.ts b/packages/ckeditor5/src/plugins/mermaid/mermaid_converter_guards.spec.ts
deleted file mode 100644
index 9225d99c26..0000000000
--- a/packages/ckeditor5/src/plugins/mermaid/mermaid_converter_guards.spec.ts
+++ /dev/null
@@ -1,127 +0,0 @@
-import { ClassicEditor, CodeBlockEditing, Essentials, Paragraph, _getModelData as getModelData, _setModelData as setModelData } from 'ckeditor5';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import MermaidEditing from './mermaid_editing.js';
-
-/* global document */
-
-/**
- * The converters all begin by asking whether someone else has already claimed the item. Those
- * guards only fire when another converter of higher priority consumed it first, so each test
- * here registers exactly such a competitor.
- */
-describe( 'MermaidEditing converter guards', () => {
- let domElement: HTMLDivElement, editor: ClassicEditor;
-
- beforeEach( () => {
- domElement = document.createElement( 'div' );
- document.body.appendChild( domElement );
- } );
-
- afterEach( async () => {
- domElement.remove();
- await editor?.destroy();
- } );
-
- async function createEditor( extraPlugins: unknown[] = [] ) {
- return ClassicEditor.create( domElement, {
- licenseKey: 'GPL',
- plugins: [ Paragraph, Essentials, CodeBlockEditing, MermaidEditing, ...extraPlugins ] as never
- } ) as Promise<ClassicEditor>;
- }
-
- it( 'skips the data downcast when another converter already consumed the item', async () => {
- editor = await createEditor();
-
- editor.data.downcastDispatcher.on( 'insert:mermaid', ( evt, data, conversionApi ) => {
- conversionApi.consumable.consume( data.item, 'insert' );
- }, { priority: 'highest' } );
-
- setModelData( editor.model, '[<mermaid displayMode="split" source="graph TD;"></mermaid>]' );
-
- // Ours bailed out, so nothing of its <pre><code> structure reached the data.
- expect( editor.getData() ).to.not.contain( 'language-mermaid' );
- } );
-
- it( 'skips the editing downcast when another converter already consumed the item', async () => {
- editor = await createEditor();
-
- editor.editing.downcastDispatcher.on( 'insert:mermaid', ( evt, data, conversionApi ) => {
- // Claim the item *and* stand in for it, otherwise the attribute converters that run
- // afterwards have no view element to attach to.
- conversionApi.consumable.consume( data.item, 'insert' );
- conversionApi.consumable.consume( data.item, 'attribute:displayMode' );
- conversionApi.consumable.consume( data.item, 'attribute:source' );
-
- const stub = conversionApi.writer.createContainerElement( 'div', { class: 'stub' } );
- conversionApi.mapper.bindElements( data.item as never, stub );
- conversionApi.writer.insert(
- conversionApi.mapper.toViewPosition( editor.model.createPositionBefore( data.item as never ) ),
- stub
- );
- }, { priority: 'highest' } );
-
- setModelData( editor.model, '[<mermaid displayMode="split" source="graph TD;"></mermaid>]' );
-
- expect( editor.editing.view.getDomRoot()?.querySelector( '.ck-mermaid__wrapper' ) ).to.equal( null );
- } );
-
- it( 'skips the upcast when another converter already claimed the code element', async () => {
- editor = await createEditor();
-
- editor.data.upcastDispatcher.on( 'element:code', ( evt, data, conversionApi ) => {
- conversionApi.consumable.consume( data.viewItem, { name: true } );
- }, { priority: 'highest' } );
-
- editor.setData(
- '<pre spellcheck="false"><code class="language-mermaid">flowchart TB</code></pre>'
- );
-
- expect( getModelData( editor.model, { withoutSelection: true } ) ).to.not.contain( '<mermaid' );
- } );
-
- describe( 'the source attribute downcast', () => {
- /** Invoke the converter directly — these guards depend on mapper/DOM lookups failing. */
- function callSourceDowncast( mapperResult: unknown, viewToDomResult: unknown ) {
- const plugin = editor.plugins.get( MermaidEditing ) as unknown as {
- _sourceAttributeDowncast( evt: unknown, data: unknown, conversionApi: unknown ): void;
- };
- const item = editor.model.document.getRoot()?.getChild( 0 );
-
- // Only the preview lookup is stubbed: the textarea branch runs first and dereferences
- // its DOM element unguarded.
- const realViewToDom = editor.editing.view.domConverter.viewToDom.bind( editor.editing.view.domConverter );
- vi.spyOn( editor.editing.view.domConverter, 'viewToDom' ).mockImplementation( ( view: never ) => {
- const element = view as unknown as { hasClass( name: string ): boolean };
- if ( element.hasClass?.( 'ck-mermaid__preview' ) ) {
- return viewToDomResult as ReturnType<typeof realViewToDom>;
- }
- return realViewToDom( view );
- } );
-
- plugin._sourceAttributeDowncast(
- {},
- { item, attributeNewValue: 'graph TD;' },
- { mapper: { toViewElement: () => mapperResult } }
- );
- }
-
- beforeEach( async () => {
- editor = await createEditor();
- setModelData( editor.model, '[<mermaid displayMode="split" source="a"></mermaid>]' );
- } );
-
- it( 'does nothing when the item has no view element', () => {
- expect( () => callSourceDowncast( undefined, null ) ).to.not.throw();
- } );
-
- it( 'does nothing when the preview wrapper has no DOM element', () => {
- const viewElement = editor.editing.mapper.toViewElement(
- editor.model.document.getRoot()?.getChild( 0 ) as never
- );
-
- // The preview child is found in the view, but has no DOM counterpart.
- expect( () => callSourceDowncast( viewElement, null ) ).to.not.throw();
- } );
- } );
-} );
diff --git a/packages/ckeditor5/src/plugins/mermaid/mermaid_editing.spec.ts b/packages/ckeditor5/src/plugins/mermaid/mermaid_editing.spec.ts
deleted file mode 100644
index 03b28f9810..0000000000
--- a/packages/ckeditor5/src/plugins/mermaid/mermaid_editing.spec.ts
+++ /dev/null
@@ -1,385 +0,0 @@
-import { ClassicEditor, Essentials, Paragraph, Heading, CodeBlockEditing, ViewElement, _setModelData as setModelData, _getModelData as getModelData, _getViewData as getViewData } from 'ckeditor5';
-import MermaidEditing from './mermaid_editing.js';
-import { afterEach, beforeEach, describe, it, expect, vi, type MockInstance } from 'vitest';
-
-/* global document */
-
-describe( 'MermaidEditing', () => {
- it( 'should be named', () => {
- expect( MermaidEditing.pluginName ).to.equal( 'MermaidEditing' );
- } );
-
- describe( 'conversion', () => {
- let domElement: HTMLDivElement, editor: ClassicEditor, model: ClassicEditor['model'];
-
- beforeEach( async () => {
- domElement = document.createElement( 'div' );
- document.body.appendChild( domElement );
-
- editor = await ClassicEditor.create( domElement, {
- licenseKey: "GPL",
- plugins: [
- Paragraph,
- Heading,
- Essentials,
- CodeBlockEditing,
- MermaidEditing
- ]
- } );
-
- model = editor.model;
- } );
-
- afterEach( () => {
- domElement.remove();
- return editor.destroy();
- } );
-
- it( 'makes a selected mermaid one of the selected blocks', () => {
- expect( model.schema.isBlock( 'mermaid' ) ).to.equal( true );
-
- setModelData( model, '[<mermaid displayMode="split" source="flowchart TB"></mermaid>]' );
- const blocks = Array.from( model.document.selection.getSelectedBlocks() );
- expect( blocks.map( block => block.name ) ).to.deep.equal( [ 'mermaid' ] );
- } );
-
- describe( 'conversion', () => {
- describe( 'upcast', () => {
- it( 'works correctly', () => {
- editor.setData(
- '<pre spellcheck="false">' +
- '<code class="language-mermaid">flowchart TB\nA --> B\nB --> C</code>' +
- '</pre>'
- );
-
- expect( getModelData( model, { withoutSelection: true } ) ).to.equal(
- '<mermaid displayMode="split" source="flowchart TB\nA --> B\nB --> C">' +
- '</mermaid>'
- );
- } );
-
- it( 'ignores a language-mermaid code element that is not inside a pre', () => {
- editor.setData( '<code class="language-mermaid">flowchart TB</code>' );
-
- // Left to the code-block/paragraph converters — no mermaid widget.
- expect( getModelData( model, { withoutSelection: true } ) ).to.not.contain( '<mermaid' );
- } );
-
- it( 'ignores a code element without the language-mermaid class', () => {
- editor.setData( '<pre spellcheck="false"><code class="language-plaintext">plain</code></pre>' );
-
- expect( getModelData( model, { withoutSelection: true } ) ).to.not.contain( '<mermaid' );
- } );
-
- it( 'ignores a mermaid block nested inside another code element', () => {
- editor.setData(
- '<pre spellcheck="false"><code class="language-plaintext">' +
- '<pre spellcheck="false"><code class="language-mermaid">flowchart TB</code></pre>' +
- '</code></pre>'
- );
-
- expect( getModelData( model, { withoutSelection: true } ) ).to.not.contain( '<mermaid' );
- } );
-
- it( 'works correctly when empty', () => {
- editor.setData(
- '<pre spellcheck="false">' +
- '<code class="language-mermaid"></code>' +
- '</pre>'
- );
-
- expect( getModelData( model, { withoutSelection: true } ) ).to.equal(
- '<mermaid displayMode="split" source=""></mermaid>'
- );
- } );
-
- it( 'restores the persisted display mode', () => {
- for ( const mode of [ 'source', 'preview' ] ) {
- editor.setData(
- '<pre spellcheck="false">' +
- `<code class="language-mermaid" data-trilium-display-mode="${ mode }">flowchart TB</code>` +
- '</pre>'
- );
-
- expect( getModelData( model, { withoutSelection: true } ) ).to.equal(
- `<mermaid displayMode="${ mode }" source="flowchart TB"></mermaid>`
- );
- }
- } );
-
- it( 'falls back to the split mode for a missing or unknown display mode', () => {
- // A diagram saved before the mode was persisted, and one carrying a mode this
- // version has no widget state for (hand-edited or imported content).
- for ( const attribute of [ '', ' data-trilium-display-mode="nonsense"' ] ) {
- editor.setData(
- '<pre spellcheck="false">' +
- `<code class="language-mermaid"${ attribute }>flowchart TB</code>` +
- '</pre>'
- );
-
- expect( getModelData( model, { withoutSelection: true } ) ).to.equal(
- '<mermaid displayMode="split" source="flowchart TB"></mermaid>'
- );
- }
- } );
- } );
-
- describe( 'data downcast', () => {
- it( 'works correctly', () => {
- // Using editor.setData() instead of setModelData helper because of #11365.
- editor.setData(
- '<pre spellcheck="false">' +
- '<code class="language-mermaid">flowchart TB\nA --> B\nB --> C</code>' +
- '</pre>'
- );
-
- expect( editor.getData() ).to.equal(
- '<pre spellcheck="false">' +
- '<code class="language-mermaid">flowchart TB\nA --&gt; B\nB --&gt; C</code>' +
- '</pre>'
- );
- } );
-
- it( 'works correctly when empty ', () => {
- // Using editor.setData() instead of setModelData helper because of #11365.
- editor.setData(
- '<pre spellcheck="false">' +
- '<code class="language-mermaid"></code>' +
- '</pre>'
- );
-
- expect( editor.getData() ).to.equal(
- '<pre spellcheck="false">' +
- '<code class="language-mermaid"></code>' +
- '</pre>'
- );
- } );
-
- it( 'persists a non-default display mode, and only that', () => {
- // The default (split) stays out of the data so untouched diagrams keep
- // producing the very same content.
- setModelData( editor.model, '<mermaid displayMode="split" source="flowchart TB"></mermaid>' );
-
- expect( editor.getData() ).to.equal(
- '<pre spellcheck="false"><code class="language-mermaid">flowchart TB</code></pre>'
- );
-
- for ( const mode of [ 'source', 'preview' ] ) {
- setModelData( editor.model, `<mermaid displayMode="${ mode }" source="flowchart TB"></mermaid>` );
-
- expect( editor.getData() ).to.equal(
- '<pre spellcheck="false">' +
- `<code class="language-mermaid" data-trilium-display-mode="${ mode }">flowchart TB</code>` +
- '</pre>'
- );
- }
- } );
-
- it( 'round-trips the mode a display-mode command switched to', () => {
- editor.setData(
- '<pre spellcheck="false">' +
- '<code class="language-mermaid">flowchart TB</code>' +
- '</pre>'
- );
-
- editor.execute( 'mermaidPreviewCommand' );
-
- expect( editor.getData() ).to.equal(
- '<pre spellcheck="false">' +
- '<code class="language-mermaid" data-trilium-display-mode="preview">flowchart TB</code>' +
- '</pre>'
- );
-
- editor.setData( editor.getData() );
-
- expect( getModelData( model, { withoutSelection: true } ) ).to.equal(
- '<mermaid displayMode="preview" source="flowchart TB"></mermaid>'
- );
- } );
- } );
-
- describe( 'editing downcast', () => {
- it( 'works correctly without displayMode attribute', () => {
- // Using editor.setData() instead of setModelData helper because of #11365.
- editor.setData(
- '<pre spellcheck="false">' +
- '<code class="language-mermaid">flowchart TB\nA --> B\nB --> C</code>' +
- '</pre>'
- );
-
- expect( getViewData( editor.editing.view, { withoutSelection: true } ) ).to.equal(
- '<div class="ck-mermaid__split-mode ck-mermaid__wrapper ck-widget ck-widget_selected' +
- ' ck-widget_with-selection-handle" contenteditable="false">' +
- '<div class="ck ck-widget__selection-handle"></div>' +
- // New lines replaced with space, same issue in getViewData as in #11365.
- '<textarea class="ck-mermaid__editing-view" data-cke-ignore-events="true"' +
- ' placeholder="Insert Mermaid source code"></textarea>' +
- '<div class="ck-mermaid__preview"></div>' +
- '<div class="ck ck-reset_all ck-widget__type-around"></div>' +
- '</div>'
- );
- } );
-
- it( 'works correctly with displayMode attribute', () => {
- setModelData( editor.model,
- '<mermaid source="foo" displayMode="preview"></mermaid>'
- );
-
- expect( getViewData( editor.editing.view, { withoutSelection: true } ) ).to.equal(
- '<div class="ck-mermaid__preview-mode ck-mermaid__wrapper ck-widget ck-widget_selected ' +
- 'ck-widget_with-selection-handle" contenteditable="false">' +
- '<div class="ck ck-widget__selection-handle"></div>' +
- '<textarea class="ck-mermaid__editing-view" data-cke-ignore-events="true"' +
- ' placeholder="Insert Mermaid source code"></textarea>' +
- '<div class="ck-mermaid__preview"></div>' +
- '<div class="ck ck-reset_all ck-widget__type-around"></div>' +
- '</div>'
- );
- } );
-
- it( 'works correctly with empty source', () => {
- setModelData( editor.model,
- '<mermaid source="" displayMode="preview"></mermaid>'
- );
-
- expect( getViewData( editor.editing.view, { withoutSelection: true } ) ).to.equal(
- '<div class="ck-mermaid__preview-mode ck-mermaid__wrapper ck-widget ck-widget_selected ' +
- 'ck-widget_with-selection-handle" contenteditable="false">' +
- '<div class="ck ck-widget__selection-handle"></div>' +
- '<textarea class="ck-mermaid__editing-view" data-cke-ignore-events="true"' +
- ' placeholder="Insert Mermaid source code"></textarea>' +
- '<div class="ck-mermaid__preview"></div>' +
- '<div class="ck ck-reset_all ck-widget__type-around"></div>' +
- '</div>'
- );
- } );
-
- describe( 'textarea value', () => {
- let domTextarea: HTMLTextAreaElement;
-
- beforeEach( () => {
- // Using editor.setData() instead of setModelData helper because of #11365.
- editor.setData(
- '<pre spellcheck="false">' +
- '<code class="language-mermaid">flowchart TB\nA --> B\nB --> C</code>' +
- '</pre>'
- );
-
- const textareaView = editor.editing.view.document.getRoot()!.getChild( 0 )! as ViewElement;
- domTextarea = editor.editing.view.domConverter.viewToDom( textareaView.getChild( 1 )! ) as HTMLTextAreaElement;
- } );
-
- it( 'is properly set during the initial conversion', () => {
- expect( domTextarea.value ).to.equal( 'flowchart TB\nA --> B\nB --> C' );
- } );
-
- it( 'is properly updated after model\'s attribute change', () => {
- const { model } = editor;
-
- const mermaidModel = model.document.getRoot()!.getChild( 0 )!;
-
- model.change( writer => {
- writer.setAttribute( 'source', 'abc', mermaidModel );
- } );
-
- expect( domTextarea.value ).to.equal( 'abc' );
- } );
-
- it( 'doesn\'t loop if model attribute changes to the same value', () => {
- const { model } = editor;
-
- const mermaidModel = model.document.getRoot()!.getChild( 0 )!;
-
- model.change( writer => {
- writer.setAttribute( 'source', 'flowchart TB\nA --> B\nB --> C', mermaidModel );
- } );
-
- expect( domTextarea.value ).to.equal( 'flowchart TB\nA --> B\nB --> C' );
- } );
- } );
-
- describe( 'preview div', () => {
- let domPreviewContainer: HTMLElement;
- let renderMermaidStub: MockInstance;
-
- beforeEach( () => {
- renderMermaidStub = vi.spyOn( editor.plugins.get( 'MermaidEditing' ) as unknown as MermaidEditing, 'renderMermaid' );
-
- // Using editor.setData() instead of setModelData helper because of #11365.
- editor.setData(
- '<pre spellcheck="false">' +
- '<code class="language-mermaid">flowchart TB\nA --> B\nB --> C</code>' +
- '</pre>'
- );
-
- const wrapperView = editor.editing.view.document.getRoot()!.getChild( 0 )! as ViewElement;
- const previewContainerView = wrapperView.getChild( 2 )!;
- domPreviewContainer = editor.editing.view.domConverter.viewToDom( previewContainerView ) as HTMLElement;
- } );
-
- afterEach( () => {
- vi.clearAllMocks();
- } );
-
- it( 'calls render with source during the initial conversion', () => {
- expect( renderMermaidStub ).toBeCalledWith( domPreviewContainer, 'flowchart TB\nA --> B\nB --> C' );
- } );
-
- it( 'calls render with updated source after a model\'s attribute change', () => {
- const { model } = editor;
-
- renderMermaidStub.mockClear();
-
- const mermaidModel = model.document.getRoot()!.getChild( 0 )!;
-
- model.change( writer => {
- writer.setAttribute( 'source', 'abc', mermaidModel );
- } );
-
- expect( renderMermaidStub ).toBeCalledWith( domPreviewContainer, 'abc' );
- } );
- } );
- } );
-
- it( 'adds a editing pipeline converter that has a precedence over code block', () => {
- setModelData( editor.model, '<mermaid source="foo"></mermaid>' );
-
- const firstViewChild = editor.editing.view.document.getRoot()!.getChild( 0 ) as ViewElement;
-
- expect( firstViewChild.name ).to.equal( 'div' );
- expect( firstViewChild.hasClass( 'ck-mermaid__wrapper' ), 'has ck-mermaid__wrapper class' ).to.be.true;
- } );
-
- it( 'does not convert code blocks other than mermaid language', () => {
- setModelData( editor.model, '<codeBlock language="javascript">foo</codeBlock>' );
-
- const firstViewChild = editor.editing.view.document.getRoot()!.getChild( 0 ) as ViewElement;
-
- expect( firstViewChild.name ).not.to.equal( 'div' );
- expect( firstViewChild.hasClass( 'ck-mermaid__wrapper' ), 'has ck-mermaid__wrapper class' ).to.be.false;
- } );
-
- it( 'adds a preview element', () => {
- setModelData( editor.model, '<mermaid source="foo"></mermaid>' );
-
- const widget = editor.editing.view.document.getRoot()!.getChild( 0 ) as ViewElement;
- const widgetChildren = [ ...widget.getChildren() ] as ViewElement[];
- const previewView = widgetChildren.filter( item => item.name === 'div' && item.hasClass( 'ck-mermaid__preview' ) );
-
- expect( previewView.length ).to.equal( 1 );
- } );
-
- it( 'adds an editing element', () => {
- setModelData( editor.model, '<mermaid source="foo"></mermaid>' );
-
- const widget = editor.editing.view.document.getRoot()!.getChild( 0 ) as ViewElement;
- const widgetChildren = [ ...widget.getChildren() ] as ViewElement[];
- const previewView = widgetChildren.filter(
- item => item.name === 'textarea' && item.hasClass( 'ck-mermaid__editing-view' )
- );
-
- expect( previewView.length ).to.equal( 1 );
- } );
- } );
- } );
-} );
diff --git a/packages/ckeditor5/src/plugins/mermaid/mermaid_editing.ts b/packages/ckeditor5/src/plugins/mermaid/mermaid_editing.ts
deleted file mode 100644
index f8b06720f9..0000000000
--- a/packages/ckeditor5/src/plugins/mermaid/mermaid_editing.ts
+++ /dev/null
@@ -1,369 +0,0 @@
-/**
- * @module mermaid/mermaid_editing
- */
-
-import MermaidPreviewCommand from './mermaid_preview_command.js';
-import MermaidSourceViewCommand from './mermaid_source_view_command.js';
-import MermaidSplitViewCommand from './mermaid_split_view_command.js';
-import InsertMermaidCommand, { INSERT_MERMAID_COMMAND } from './insert_mermaid_command.js';
-import { DowncastAttributeEvent, DowncastConversionApi, EditorConfig, ModelElement, EventInfo, ModelItem, ModelNode, Plugin, toWidget, uid, UpcastConversionApi, UpcastConversionData, ViewElement, ViewText, ViewUIElement } from 'ckeditor5';
-
-import { debounce } from './utils.js';
-
-// Time in milliseconds.
-const DEBOUNCE_TIME = 300;
-
-/* global window */
-
-type DowncastConversionData = DowncastAttributeEvent["args"][0];
-
-/** The modes the widget can be shown in, i.e. the values of its `displayMode` model attribute. */
-const DISPLAY_MODES = [ 'source', 'split', 'preview' ] as const;
-
-type MermaidDisplayMode = typeof DISPLAY_MODES[ number ];
-
-const DEFAULT_DISPLAY_MODE: MermaidDisplayMode = 'split';
-
-/**
- * Carries the mode the user picked into the note content, the way collapsed list items persist
- * `data-trilium-collapsed`. It is written on the `<code>` element the widget already round-trips
- * through, and only for a non-default mode — so a diagram left in split view keeps producing
- * byte-identical content, and every consumer that keys off `code.language-mermaid` (the share
- * view, markdown export, the importers) is unaffected.
- */
-const DISPLAY_MODE_DATA_ATTRIBUTE = 'data-trilium-display-mode';
-
-export default class MermaidEditing extends Plugin {
-
- private _config!: EditorConfig["mermaid"];
- private _mermaidPromise?: Promise<MermaidInstance>;
- /**
- * Per-preview-element render generation. A single shared counter would discard
- * in-flight results for other widgets when several diagrams render at once
- * (e.g. after importing a note with multiple Mermaid blocks), leaving blank
- * previews that look like the diagram "disappeared" in preview mode.
- */
- private _renderGenerations = new WeakMap<HTMLElement, number>();
- /**
- * Serialize mermaid.render() calls. Concurrent renders share temporary DOM
- * measurement nodes inside the mermaid library and can leave blank/broken SVGs.
- */
- private _renderQueue: Promise<void> = Promise.resolve();
-
- /**
- * @inheritDoc
- */
- static get pluginName() {
- return 'MermaidEditing' as const;
- }
-
- /**
- * @inheritDoc
- */
- init() {
- this._registerCommands();
- this._defineConverters();
- this._config = this.editor.config.get("mermaid");
- }
-
- /**
- * @inheritDoc
- */
- afterInit() {
- this.editor.model.schema.register( 'mermaid', {
- allowAttributes: [ 'displayMode', 'source' ],
- allowWhere: '$block',
- isObject: true,
- isBlock: true
- } );
- }
-
- /**
- * @inheritDoc
- */
- _registerCommands() {
- const editor = this.editor;
-
- editor.commands.add( 'mermaidPreviewCommand', new MermaidPreviewCommand( editor ) );
- editor.commands.add( 'mermaidSplitViewCommand', new MermaidSplitViewCommand( editor ) );
- editor.commands.add( 'mermaidSourceViewCommand', new MermaidSourceViewCommand( editor ) );
- editor.commands.add( INSERT_MERMAID_COMMAND, new InsertMermaidCommand( editor ) );
- }
-
- /**
- * Adds converters.
- *
- * @private
- */
- _defineConverters() {
- const editor = this.editor;
-
- editor.data.downcastDispatcher.on( 'insert:mermaid', this._mermaidDataDowncast.bind( this ) );
- editor.editing.downcastDispatcher.on( 'insert:mermaid', this._mermaidDowncast.bind( this ) );
- editor.editing.downcastDispatcher.on( 'attribute:source:mermaid', this._sourceAttributeDowncast.bind( this ) );
-
- editor.data.upcastDispatcher.on( 'element:code', this._mermaidUpcast.bind( this ), { priority: 'high' } );
-
- editor.conversion.for( 'editingDowncast' ).attributeToAttribute( {
- model: {
- name: 'mermaid',
- key: 'displayMode'
- },
- view: modelAttributeValue => ( {
- key: 'class',
- value: 'ck-mermaid__' + modelAttributeValue + '-mode'
- } )
- } );
- }
-
- _mermaidDataDowncast( evt: EventInfo, data: DowncastConversionData, conversionApi: DowncastConversionApi ) {
- const model = this.editor.model;
- const { writer, mapper } = conversionApi;
-
- if ( !conversionApi.consumable.consume( data.item, 'insert' ) ) {
- return;
- }
-
- const targetViewPosition = mapper.toViewPosition( model.createPositionBefore( data.item as ModelItem ) );
- const displayMode = readDisplayMode( data.item.getAttribute( 'displayMode' ) );
- // For downcast we're using only language-mermaid class. We don't set class to `mermaid language-mermaid` as
- // multiple markdown converters that we have seen are using only `language-mermaid` class and not `mermaid` alone.
- const codeAttributes: Record<string, string> = {
- class: 'language-mermaid'
- };
-
- if ( displayMode !== DEFAULT_DISPLAY_MODE ) {
- codeAttributes[ DISPLAY_MODE_DATA_ATTRIBUTE ] = displayMode;
- }
-
- const code = writer.createContainerElement( 'code', codeAttributes ) as any;
- const pre = writer.createContainerElement( 'pre', {
- spellcheck: 'false'
- } ) as any;
- const sourceTextNode = writer.createText( data.item.getAttribute( 'source' ) as string);
-
- writer.insert( model.createPositionAt( code, 'end' ) as any, sourceTextNode );
- writer.insert( model.createPositionAt( pre, 'end' ) as any, code );
- writer.insert( targetViewPosition, pre );
- mapper.bindElements( data.item as ModelElement, code as ViewElement );
- }
-
- _mermaidDowncast( evt: EventInfo, data: DowncastConversionData, conversionApi: DowncastConversionApi ) {
- const { writer, mapper, consumable } = conversionApi;
- const { editor } = this;
- const { model, t } = editor;
- const that = this;
-
- if ( !consumable.consume( data.item, 'insert' ) ) {
- return;
- }
-
- const targetViewPosition = mapper.toViewPosition( model.createPositionBefore( data.item as ModelItem ) );
-
- const wrapperAttributes = {
- class: [ 'ck-mermaid__wrapper' ]
- };
- const textareaAttributes = {
- class: [ 'ck-mermaid__editing-view' ],
- placeholder: t( 'Insert Mermaid source code' ),
- 'data-cke-ignore-events': true
- };
-
- const wrapper = writer.createContainerElement( 'div', wrapperAttributes );
- const editingContainer = writer.createUIElement( 'textarea', textareaAttributes, createEditingTextarea );
- const previewContainer = writer.createUIElement( 'div', { class: [ 'ck-mermaid__preview' ] }, createMermaidPreview );
-
- //@ts-expect-error
- writer.insert( writer.createPositionAt( wrapper, 'start' ), previewContainer );
- //@ts-expect-error
- writer.insert( writer.createPositionAt( wrapper, 'start' ), editingContainer );
-
- writer.insert( targetViewPosition, wrapper );
-
- mapper.bindElements( data.item as ModelElement, wrapper );
-
- return toWidget( wrapper, writer, {
- label: t( 'Mermaid widget' ),
- hasSelectionHandle: true
- } );
-
- function createEditingTextarea(this: ViewUIElement, domDocument: Document ) {
- const domElement = this.toDomElement( domDocument ) as HTMLElement as HTMLInputElement;
-
- domElement.value = data.item.getAttribute( 'source' ) as string;
-
- const debouncedListener = debounce( event => {
- editor.model.change( writer => {
- writer.setAttribute( 'source', event.target.value, data.item as ModelNode );
- } );
- }, DEBOUNCE_TIME );
-
- domElement.addEventListener( 'input', debouncedListener );
-
- /* Workaround for internal #1544 */
- domElement.addEventListener( 'focus', () => {
- const model = editor.model;
- const selectedElement = model.document.selection.getSelectedElement();
-
- // Move the selection onto the mermaid widget if it's currently not selected.
- if ( selectedElement !== data.item ) {
- model.change( writer => writer.setSelection( data.item as ModelNode, 'on' ) );
- }
- }, true );
-
- return domElement;
- }
-
- function createMermaidPreview(this: ViewUIElement, domDocument: Document ) {
- const mermaidSource = data.item.getAttribute( 'source' ) as string;
- const domElement = this.toDomElement( domDocument );
-
- that.renderMermaid( domElement, mermaidSource );
-
- return domElement;
- }
- }
-
- _sourceAttributeDowncast( evt: EventInfo, data: DowncastConversionData, conversionApi: DowncastConversionApi ) {
- // @todo: test whether the attribute was consumed.
- const newSource = ( data.attributeNewValue as string ) ?? '';
- const domConverter = this.editor.editing.view.domConverter;
-
- const mermaidView = conversionApi.mapper.toViewElement( data.item as ModelElement );
- if ( !mermaidView ) {
- return;
- }
-
- for ( const _child of mermaidView.getChildren() ) {
- const child = _child as ViewElement;
- if ( child.name === 'textarea' && child.hasClass( 'ck-mermaid__editing-view' ) ) {
- // Text & HTMLElement & ModelNode & DocumentFragment
- const domEditingTextarea = domConverter.viewToDom( child ) as HTMLElement as HTMLInputElement;
-
- if ( domEditingTextarea.value != newSource ) {
- domEditingTextarea.value = newSource;
- }
- } else if ( child.name === 'div' && child.hasClass( 'ck-mermaid__preview' ) ) {
- // @todo: we could optimize this and not refresh mermaid if widget is in source mode.
- const domPreviewWrapper = domConverter.viewToDom( child );
-
- if ( domPreviewWrapper ) {
- this.renderMermaid( domPreviewWrapper, newSource );
- }
- }
- }
- }
-
- _mermaidUpcast( evt: EventInfo, data: UpcastConversionData, conversionApi: UpcastConversionApi ) {
- const viewCodeElement = data.viewItem as ViewElement;
- const hasPreElementParent = !viewCodeElement.parent || !viewCodeElement.parent.is( 'element', 'pre' );
- const hasCodeAncestors = data.modelCursor.findAncestor( 'code' );
- const { consumable, writer } = conversionApi;
-
- if ( !viewCodeElement.hasClass( 'language-mermaid' ) || hasPreElementParent || hasCodeAncestors ) {
- return;
- }
-
- if ( !consumable.test( viewCodeElement, { name: true } ) ) {
- return;
- }
- const mermaidSource = Array.from( viewCodeElement.getChildren() )
- .filter( item => item.is( '$text' ) )
- .map( item => (item as ViewText).data )
- .join( '' );
-
- const mermaidElement = writer.createElement( 'mermaid', {
- source: mermaidSource,
- displayMode: readDisplayMode( viewCodeElement.getAttribute( DISPLAY_MODE_DATA_ATTRIBUTE ) )
- } );
-
- // Let's try to insert mermaid element.
- if ( !conversionApi.safeInsert( mermaidElement, data.modelCursor ) ) {
- return;
- }
-
- consumable.consume( viewCodeElement, { name: true } );
-
- conversionApi.updateConversionResult( mermaidElement, data );
- }
-
- /**
- * Renders Mermaid (a parsed `source`) in a given `domElement`.
- *
- * Public because the widget's preview pane is no longer the only surface showing a diagram:
- * the AI assistant renders the `language-mermaid` blocks of a finished response the same way,
- * so that what it previews is what committing it will produce. Everything the widget needs of
- * the renderer — the one lazy load, the shared queue, the per-element generation — is what an
- * outside caller needs too, so it takes this rather than a copy of it.
- */
- async renderMermaid( domElement: HTMLElement, source: string ) {
- if ( !source?.trim() ) {
- // Bump generation so an in-flight render for the previous source cannot
- // write its SVG back into a cleared preview.
- const generation = ( this._renderGenerations.get( domElement ) ?? 0 ) + 1;
- this._renderGenerations.set( domElement, generation );
- domElement.innerHTML = '';
- return;
- }
-
- if ( !this._mermaidPromise && typeof this._config?.lazyLoad === 'function' ) {
- this._mermaidPromise = Promise.resolve( this._config.lazyLoad() ).then( instance => {
- instance.initialize( this._config?.config ?? {} );
- return instance;
- } );
- }
-
- const mermaid = await this._mermaidPromise;
-
- if ( !mermaid ) {
- return;
- }
-
- const generation = ( this._renderGenerations.get( domElement ) ?? 0 ) + 1;
- this._renderGenerations.set( domElement, generation );
- const id = `ck-mermaid-${ uid() }`;
-
- const run = async () => {
- // A newer edit for this same preview landed while we waited in the queue.
- if ( generation !== this._renderGenerations.get( domElement ) ) {
- return;
- }
-
- try {
- const { svg } = await mermaid.render( id, source );
-
- // Mermaid leaves a temporary probe node with `id`. Remove it *before*
- // inserting the SVG — the returned SVG reuses the same id, so a later
- // getElementById(id).remove() would delete the rendered diagram.
- document.getElementById( id )?.remove();
-
- if ( generation === this._renderGenerations.get( domElement ) ) {
- domElement.innerHTML = svg;
- }
- } catch ( err: unknown ) {
- document.getElementById( id )?.remove();
- if ( generation === this._renderGenerations.get( domElement ) ) {
- domElement.innerText = err instanceof Error ? err.message : String( err );
- }
- }
- };
-
- // Chain onto the queue so only one mermaid.render runs at a time, while still
- // letting each caller's promise settle when *its* turn finishes. `run` swallows its
- // own failures, so the chain never rejects; passing it as the rejection handler too
- // means a future throw would still let the next render through instead of wedging
- // the queue permanently.
- const queued = this._renderQueue.then( run, run );
- this._renderQueue = queued;
- await queued;
- }
-}
-
-/**
- * Narrows a persisted (or model-held) display mode to a known one, falling back to the default.
- * Content can carry anything: an older note has no attribute at all, and a hand-edited or
- * imported one can carry a value the widget has no mode for.
- */
-function readDisplayMode( value: unknown ): MermaidDisplayMode {
- return DISPLAY_MODES.includes( value as MermaidDisplayMode ) ? value as MermaidDisplayMode : DEFAULT_DISPLAY_MODE;
-}
diff --git a/packages/ckeditor5/src/plugins/mermaid/mermaid_preview_command.spec.ts b/packages/ckeditor5/src/plugins/mermaid/mermaid_preview_command.spec.ts
deleted file mode 100644
index 9ce7b053fb..0000000000
--- a/packages/ckeditor5/src/plugins/mermaid/mermaid_preview_command.spec.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-import { ClassicEditor, Paragraph, _setModelData as setModelData, _getModelData as getModelData } from 'ckeditor5';
-
-import MermaidPreviewCommand from './mermaid_preview_command.js';
-import MermaidEditing from './mermaid_editing.js';
-import { afterEach, beforeEach, describe, it } from 'vitest';
-import { expect } from 'vitest';
-
-/* global document */
-
-describe( 'MermaidPreviewCommand', () => {
- let domElement, editor, model, command;
-
- beforeEach( async () => {
- domElement = document.createElement( 'div' );
- document.body.appendChild( domElement );
-
- editor = await ClassicEditor.create( domElement, {
- licenseKey: "GPL",
- plugins: [
- MermaidEditing,
- Paragraph
- ]
- } );
-
- model = editor.model;
-
- command = new MermaidPreviewCommand( editor );
- } );
-
- afterEach( () => {
- domElement.remove();
- return editor.destroy();
- } );
-
- describe( '#value', () => {
- it( 'should be true when mermaid element has displayMode attribute equal to "preview"', () => {
- setModelData( model, '<mermaid displayMode="preview" source="foo"></mermaid>' );
-
- expect( command.value ).to.equal( true );
- } );
-
- it( 'should be false when mermaid element has displayMode attribute equal to "split"', () => {
- setModelData( model, '<mermaid displayMode="split" source="foo"></mermaid>' );
-
- expect( command.value ).to.equal( false );
- } );
-
- it( 'should be false when mermaid element has displayMode attribute equal to "source"', () => {
- setModelData( model, '<mermaid displayMode="source" source="foo"></mermaid>' );
-
- expect( command.value ).to.equal( false );
- } );
- } );
-
- describe( '#isEnabled', () => {
- describe( 'should be false', () => {
- it( 'when text is selected', () => {
- setModelData( model,
- '<paragraph>[foo]</paragraph>' +
- '<mermaid source="flowchart TB\nA --> B\nB --> C"></mermaid>'
- );
-
- expect( command.isEnabled ).to.be.false;
- } );
-
- it( 'when mermaid is part of the selection', () => {
- setModelData( model,
- '<paragraph>[foo</paragraph>' +
- '<mermaid source="flowchart TB\nA --> B\nB --> C"></mermaid>' +
- '<paragraph>b]az</paragraph>'
- );
-
- expect( command.isEnabled ).to.be.false;
- } );
- } );
-
- describe( 'should be true', () => {
- it( 'when selection is inside mermaid', () => {
- setModelData( model,
- '<paragraph>foo</paragraph>' +
- '<mermaid source="flowchart TB\nA --> B\nB --> C">[]</mermaid>'
- );
-
- expect( command.isEnabled ).to.be.true;
- } );
-
- it( 'when mermaid is selected', () => {
- setModelData( model,
- '<paragraph>foo</paragraph>' +
- '[<mermaid source="flowchart TB\nA --> B\nB --> C"></mermaid>]'
- );
-
- expect( command.isEnabled ).to.be.true;
- } );
- } );
- } );
-
- describe( 'execute()', () => {
- it( 'should change displayMode to "preview" for mermaid', () => {
- setModelData( model,
- '[<mermaid displayMode="source" source="foo"></mermaid>]'
- );
-
- command.execute();
-
- expect( getModelData( model ) ).to.equal(
- '[<mermaid displayMode="preview" source="foo"></mermaid>]'
- );
- } );
- } );
-
- describe( "#execute() edge cases", () => {
- it( "resolves the mermaid from the caret when nothing is selected", () => {
- setModelData( model, '<mermaid displayMode="split" source="foo">[]</mermaid>' );
-
- command.execute();
-
- expect( getModelData( model, { withoutSelection: true } ) )
- .to.equal( `<mermaid displayMode="preview" source="foo"></mermaid>` );
- } );
-
- it( "leaves a mermaid already in preview mode untouched", () => {
- setModelData( model, `[<mermaid displayMode="preview" source="foo"></mermaid>]` );
- const before = getModelData( model, { withoutSelection: true } );
-
- command.execute();
-
- expect( getModelData( model, { withoutSelection: true } ) ).to.equal( before );
- } );
-
- it( "does nothing when no mermaid is selected", () => {
- setModelData( model, "<paragraph>foo[]</paragraph>" );
- const before = getModelData( model, { withoutSelection: true } );
-
- // CKEditor blocks execute() on a disabled command, and this command disables itself
- // when nothing is selected — so force it through to exercise the guard itself.
- command.isEnabled = true;
- command.execute();
-
- expect( getModelData( model, { withoutSelection: true } ) ).to.equal( before );
- } );
- } );
-} );
diff --git a/packages/ckeditor5/src/plugins/mermaid/mermaid_preview_command.ts b/packages/ckeditor5/src/plugins/mermaid/mermaid_preview_command.ts
deleted file mode 100644
index 04c49cc9b1..0000000000
--- a/packages/ckeditor5/src/plugins/mermaid/mermaid_preview_command.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { checkIsOn } from './utils.js';
-import { Command, ModelElement } from 'ckeditor5';
-
-/**
- * The mermaid preview command.
- *
- * Allows to switch to a preview mode.
- */
-export default class MermaidPreviewCommand extends Command {
-
- override refresh() {
- const editor = this.editor;
- const documentSelection = editor.model.document.selection;
- const selectedElement = documentSelection.getSelectedElement();
- const isSelectedElementMermaid = selectedElement && selectedElement.name === 'mermaid';
-
- if ( isSelectedElementMermaid || documentSelection.getLastPosition()?.findAncestor( 'mermaid' ) ) {
- this.isEnabled = !!selectedElement;
- } else {
- this.isEnabled = false;
- }
-
- this.value = checkIsOn( editor, 'preview' );
- }
-
- override execute() {
- const editor = this.editor;
- const model = editor.model;
- const documentSelection = this.editor.model.document.selection;
- // `mermaid` is an object element, so the selection is always *on* it — never inside.
- const mermaidItem = documentSelection.getSelectedElement() as ModelElement | null;
-
- if (mermaidItem) {
- model.change( writer => {
- if ( mermaidItem.getAttribute( 'displayMode' ) !== 'preview' ) {
- writer.setAttribute( 'displayMode', 'preview', mermaidItem );
- }
- } );
- }
- }
-}
diff --git a/packages/ckeditor5/src/plugins/mermaid/mermaid_rendering.spec.ts b/packages/ckeditor5/src/plugins/mermaid/mermaid_rendering.spec.ts
deleted file mode 100644
index 105e3f7c22..0000000000
--- a/packages/ckeditor5/src/plugins/mermaid/mermaid_rendering.spec.ts
+++ /dev/null
@@ -1,379 +0,0 @@
-import { ClassicEditor, CodeBlockEditing, Essentials, Paragraph, _getModelData as getModelData, _setModelData as setModelData } from 'ckeditor5';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import MermaidEditing from './mermaid_editing.js';
-
-/* global document */
-
-/**
- * The diagram renderer: how `renderMermaid` lazy-loads the mermaid instance, what it does with
- * the SVG it gets back, and how it behaves when a render fails or is superseded by a newer one.
- */
-describe( 'MermaidEditing rendering', () => {
- let domElement: HTMLDivElement, editor: ClassicEditor;
-
- /** A stand-in for the mermaid library, with a render we can resolve or reject at will. */
- function createFakeMermaid( render: MermaidInstance['render'] ) {
- return { initialize: vi.fn(), render: vi.fn( render ) };
- }
-
- async function createEditor( mermaidConfig?: Record<string, unknown> ) {
- domElement = document.createElement( 'div' );
- document.body.appendChild( domElement );
-
- return ClassicEditor.create( domElement, {
- licenseKey: 'GPL',
- plugins: [ Paragraph, Essentials, CodeBlockEditing, MermaidEditing ],
- ...( mermaidConfig ? { mermaid: mermaidConfig } : {} )
- } ) as Promise<ClassicEditor>;
- }
-
- /** The rendered preview pane of the first mermaid widget in the editing view. */
- function previewDom(): HTMLElement {
- const preview = editor.editing.view.getDomRoot()?.querySelector( '.ck-mermaid__preview' );
- if ( !( preview instanceof HTMLElement ) ) {
- throw new Error( 'Expected a rendered mermaid preview.' );
- }
- return preview;
- }
-
- /** Let the render promise chain settle. */
- const flush = () => new Promise( resolve => setTimeout( resolve, 0 ) );
-
- /** Poll until `predicate` holds — the render chain takes several microtask turns. */
- async function waitFor( predicate: () => boolean ) {
- for ( let i = 0; i < 50 && !predicate(); i++ ) {
- await flush();
- }
- if ( !predicate() ) {
- throw new Error( 'Timed out waiting for the render to start.' );
- }
- }
-
- /** The `source` attribute of the first mermaid element in the model. */
- function sourceAttribute(): unknown {
- const item = editor.model.document.getRoot()?.getChild( 0 );
- return item?.is( 'element' ) ? item.getAttribute( 'source' ) : undefined;
- }
-
- afterEach( async () => {
- domElement?.remove();
- await editor?.destroy();
- } );
-
- it( 'lazy-loads mermaid once, initialises it, and injects the SVG', async () => {
- const instance = createFakeMermaid( async () => ( { svg: '<svg id="rendered"></svg>' } ) );
- const lazyLoad = vi.fn( async () => instance );
- editor = await createEditor( { lazyLoad, config: { theme: 'dark' } } );
-
- setModelData( editor.model, '[<mermaid displayMode="split" source="graph TD;"></mermaid>]' );
- editor.model.change( writer => {
- const item = editor.model.document.getRoot()?.getChild( 0 );
- if ( item?.is( 'element' ) ) {
- writer.setAttribute( 'source', 'graph TD; A-->B;', item );
- }
- } );
- await flush();
-
- expect( lazyLoad ).toHaveBeenCalledTimes( 1 );
- expect( instance.initialize ).toHaveBeenCalledWith( { theme: 'dark' } );
- expect( previewDom().innerHTML ).to.equal( '<svg id="rendered"></svg>' );
- } );
-
- it( 'falls back to an empty config object when none is supplied', async () => {
- const instance = createFakeMermaid( async () => ( { svg: '<svg></svg>' } ) );
- editor = await createEditor( { lazyLoad: async () => instance } );
-
- setModelData( editor.model, '[<mermaid displayMode="split" source="a"></mermaid>]' );
- editor.model.change( writer => {
- const item = editor.model.document.getRoot()?.getChild( 0 );
- if ( item?.is( 'element' ) ) {
- writer.setAttribute( 'source', 'b', item );
- }
- } );
- await flush();
-
- expect( instance.initialize ).toHaveBeenCalledWith( {} );
- } );
-
- it( 'shows the error message when a render throws, and cleans up the orphan node', async () => {
- const instance = createFakeMermaid( async ( id: string ) => {
- // mermaid leaves a probe element behind in the document when it fails.
- const orphan = document.createElement( 'div' );
- orphan.id = id;
- document.body.appendChild( orphan );
- throw new Error( 'Parse error on line 1' );
- } );
- editor = await createEditor( { lazyLoad: async () => instance } );
-
- setModelData( editor.model, '[<mermaid displayMode="split" source="a"></mermaid>]' );
- editor.model.change( writer => {
- const item = editor.model.document.getRoot()?.getChild( 0 );
- if ( item?.is( 'element' ) ) {
- writer.setAttribute( 'source', 'not a diagram', item );
- }
- } );
- await flush();
-
- expect( previewDom().innerText ).to.equal( 'Parse error on line 1' );
- expect( document.querySelectorAll( '[id^="ck-mermaid-"]' ) ).to.have.length( 0 );
- } );
-
- it( 'ignores a render that a newer one has superseded', async () => {
- const pending: Array<( value: { svg: string } ) => void> = [];
- const instance = createFakeMermaid( () => new Promise( resolve => {
- pending.push( resolve );
- } ) );
- editor = await createEditor( { lazyLoad: async () => instance } );
-
- // Drive the renderer directly: going through attribute changes would re-render the
- // widget and hand each render a different preview node, which is not what is under
- // test here — the generation guard is.
- const plugin = editor.plugins.get( MermaidEditing ) as unknown as {
- renderMermaid( domElement: HTMLElement, source: string ): Promise<void>;
- };
- const target = document.createElement( 'div' );
-
- const stale = plugin.renderMermaid( target, 'first' );
- await waitFor( () => pending.length >= 1 );
- // Queue the newer render while the first is still in flight. Renders are serialized,
- // so the second mermaid.render() only starts after the first settles — but the
- // generation bump must still discard the stale SVG.
- const latest = plugin.renderMermaid( target, 'second' );
-
- pending[ 0 ]?.( { svg: '<svg id="first"></svg>' } );
- await stale;
- await waitFor( () => pending.length >= 2 );
- pending[ 1 ]?.( { svg: '<svg id="second"></svg>' } );
- await latest;
-
- expect( target.innerHTML ).to.equal( '<svg id="second"></svg>' );
- } );
-
- it( 'keeps concurrent renders on different preview elements independent', async () => {
- const pending = new Map<string, ( value: { svg: string } ) => void>();
- const instance = createFakeMermaid( ( _id: string, source: string ) => new Promise( resolve => {
- pending.set( source, resolve );
- } ) );
- editor = await createEditor( { lazyLoad: async () => instance } );
-
- const plugin = editor.plugins.get( MermaidEditing ) as unknown as {
- renderMermaid( domElement: HTMLElement, source: string ): Promise<void>;
- };
- const first = document.createElement( 'div' );
- const second = document.createElement( 'div' );
-
- const firstRender = plugin.renderMermaid( first, 'diagram-a' );
- const secondRender = plugin.renderMermaid( second, 'diagram-b' );
-
- // Serialized queue: only the first render is in flight initially.
- await waitFor( () => pending.has( 'diagram-a' ) );
- expect( pending.has( 'diagram-b' ) ).to.equal( false );
-
- pending.get( 'diagram-a' )?.( { svg: '<svg id="a"></svg>' } );
- await firstRender;
- await waitFor( () => pending.has( 'diagram-b' ) );
- pending.get( 'diagram-b' )?.( { svg: '<svg id="b"></svg>' } );
- await secondRender;
-
- expect( first.innerHTML ).to.equal( '<svg id="a"></svg>' );
- expect( second.innerHTML ).to.equal( '<svg id="b"></svg>' );
- } );
-
- it( 'clears the preview when the source becomes empty', async () => {
- const instance = createFakeMermaid( async () => ( { svg: '<svg id="rendered"></svg>' } ) );
- editor = await createEditor( { lazyLoad: async () => instance } );
-
- const plugin = editor.plugins.get( MermaidEditing ) as unknown as {
- renderMermaid( domElement: HTMLElement, source: string ): Promise<void>;
- };
- const target = document.createElement( 'div' );
- target.innerHTML = '<svg id="stale"></svg>';
-
- await plugin.renderMermaid( target, ' ' );
-
- expect( target.innerHTML ).to.equal( '' );
- expect( instance.render ).not.toHaveBeenCalled();
- } );
-
- it( 'does not restore a stale SVG after the source is cleared mid-render', async () => {
- const pending: Array<( value: { svg: string } ) => void> = [];
- const instance = createFakeMermaid( () => new Promise( resolve => {
- pending.push( resolve );
- } ) );
- editor = await createEditor( { lazyLoad: async () => instance } );
-
- const plugin = editor.plugins.get( MermaidEditing ) as unknown as {
- renderMermaid( domElement: HTMLElement, source: string ): Promise<void>;
- };
- const target = document.createElement( 'div' );
-
- const first = plugin.renderMermaid( target, 'graph TD; A-->B;' );
- await waitFor( () => pending.length >= 1 );
-
- await plugin.renderMermaid( target, ' ' );
- expect( target.innerHTML ).to.equal( '' );
-
- pending[ 0 ]?.( { svg: '<svg id="stale"></svg>' } );
- await first;
-
- expect( target.innerHTML ).to.equal( '' );
- } );
-
- it( 'removes the temporary mermaid probe node after a successful render', async () => {
- const instance = createFakeMermaid( async ( id: string ) => {
- const probe = document.createElement( 'div' );
- probe.id = id;
- document.body.appendChild( probe );
- // Real mermaid SVGs reuse the render id; ensure we don't delete that
- // after inserting it into the preview.
- return { svg: `<svg id="${ id }"></svg>` };
- } );
- editor = await createEditor( { lazyLoad: async () => instance } );
-
- const plugin = editor.plugins.get( MermaidEditing ) as unknown as {
- renderMermaid( domElement: HTMLElement, source: string ): Promise<void>;
- };
- const target = document.createElement( 'div' );
-
- await plugin.renderMermaid( target, 'graph TD; A-->B;' );
-
- expect( target.querySelector( 'svg' ) ).to.not.equal( null );
- expect( target.contains( target.querySelector( 'svg' )! ) ).to.equal( true );
- // Probe on document.body is gone; only the preview SVG remains.
- expect( document.body.querySelector( '[id^="ck-mermaid-"]' ) ).to.equal( null );
- } );
-
- it( 'does nothing when the host configured no lazyLoad', async () => {
- editor = await createEditor( {} );
-
- setModelData( editor.model, '[<mermaid displayMode="split" source="a"></mermaid>]' );
- editor.model.change( writer => {
- const item = editor.model.document.getRoot()?.getChild( 0 );
- if ( item?.is( 'element' ) ) {
- writer.setAttribute( 'source', 'b', item );
- }
- } );
- await flush();
-
- expect( previewDom().innerHTML ).to.equal( '' );
- } );
-
- it( 'clears the preview when the source attribute is removed outright', async () => {
- const instance = createFakeMermaid( async () => ( { svg: '<svg id="rendered"></svg>' } ) );
- editor = await createEditor( { lazyLoad: async () => instance } );
-
- setModelData( editor.model, '[<mermaid displayMode="split" source="a"></mermaid>]' );
- editor.model.change( writer => {
- const item = editor.model.document.getRoot()?.getChild( 0 );
- if ( item?.is( 'element' ) ) {
- writer.setAttribute( 'source', 'b', item );
- }
- } );
- await waitFor( () => previewDom().innerHTML !== '' );
-
- // Removal hands the downcast a null value rather than an empty string.
- editor.model.change( writer => {
- const item = editor.model.document.getRoot()?.getChild( 0 );
- if ( item?.is( 'element' ) ) {
- writer.removeAttribute( 'source', item );
- }
- } );
- await waitFor( () => previewDom().innerHTML === '' );
-
- expect( previewDom().innerHTML ).to.equal( '' );
- } );
-
- it( 'stringifies a non-Error thrown by the renderer', async () => {
- const instance = createFakeMermaid( async () => {
- throw 'boom';
- } );
- editor = await createEditor( { lazyLoad: async () => instance } );
-
- setModelData( editor.model, '[<mermaid displayMode="split" source="a"></mermaid>]' );
- editor.model.change( writer => {
- const item = editor.model.document.getRoot()?.getChild( 0 );
- if ( item?.is( 'element' ) ) {
- writer.setAttribute( 'source', 'not a diagram', item );
- }
- } );
- await waitFor( () => previewDom().innerText === 'boom' );
-
- expect( previewDom().innerText ).to.equal( 'boom' );
- } );
-
- it( 'does not surface an error from a render a newer one has superseded', async () => {
- const pending: Array<( reason: unknown ) => void> = [];
- const instance = createFakeMermaid( () => new Promise( ( _resolve, reject ) => {
- pending.push( reject );
- } ) );
- editor = await createEditor( { lazyLoad: async () => instance } );
-
- const plugin = editor.plugins.get( MermaidEditing ) as unknown as {
- renderMermaid( domElement: HTMLElement, source: string ): Promise<void>;
- };
- const target = document.createElement( 'div' );
-
- const stale = plugin.renderMermaid( target, 'first' );
- await waitFor( () => pending.length >= 1 );
- // Clearing bumps this element's generation synchronously, so the in-flight render is
- // already stale by the time it rejects.
- await plugin.renderMermaid( target, '' );
-
- pending[ 0 ]?.( new Error( 'Parse error on line 1' ) );
- await stale;
-
- expect( target.innerHTML ).to.equal( '' );
- } );
-
- describe( 'the source textarea', () => {
- beforeEach( async () => {
- editor = await createEditor( { lazyLoad: async () => createFakeMermaid( async () => ( { svg: '' } ) ) } );
- } );
-
- function textarea(): HTMLTextAreaElement {
- const el = editor.editing.view.getDomRoot()?.querySelector( '.ck-mermaid__editing-view' );
- if ( !( el instanceof HTMLTextAreaElement ) ) {
- throw new Error( 'Expected a rendered mermaid textarea.' );
- }
- return el;
- }
-
- it( 'writes typed text back to the model, debounced', async () => {
- vi.useFakeTimers();
- try {
- setModelData( editor.model, '[<mermaid displayMode="split" source="a"></mermaid>]' );
-
- const el = textarea();
- el.value = 'graph TD; A-->B;';
- el.dispatchEvent( new Event( 'input' ) );
-
- // Nothing yet — the listener is debounced.
- expect( sourceAttribute() ).to.equal( 'a' );
-
- vi.advanceTimersByTime( 300 );
-
- expect( sourceAttribute() ).to.equal( 'graph TD; A-->B;' );
- } finally {
- vi.useRealTimers();
- }
- } );
-
- it( 'selects the widget when the textarea takes focus', () => {
- setModelData( editor.model, '<paragraph>[]foo</paragraph><mermaid displayMode="split" source="a"></mermaid>' );
-
- textarea().dispatchEvent( new FocusEvent( 'focus' ) );
-
- expect( editor.model.document.selection.getSelectedElement()?.name ).to.equal( 'mermaid' );
- } );
-
- it( 'leaves the selection alone when the widget is already selected', () => {
- setModelData( editor.model, '[<mermaid displayMode="split" source="a"></mermaid>]' );
- const before = getModelData( editor.model );
-
- textarea().dispatchEvent( new FocusEvent( 'focus' ) );
-
- expect( getModelData( editor.model ) ).to.equal( before );
- } );
- } );
-} );
diff --git a/packages/ckeditor5/src/plugins/mermaid/mermaid_source_view_command.spec.ts b/packages/ckeditor5/src/plugins/mermaid/mermaid_source_view_command.spec.ts
deleted file mode 100644
index 649b151b87..0000000000
--- a/packages/ckeditor5/src/plugins/mermaid/mermaid_source_view_command.spec.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-import { ClassicEditor, Paragraph, _setModelData as setModelData, _getModelData as getModelData } from 'ckeditor5';
-
-import MermaidSourceViewCommand from './mermaid_source_view_command.js';
-import MermaidEditing from './mermaid_editing.js';
-import { afterEach, beforeEach, describe, it } from 'vitest';
-import { expect } from 'vitest';
-
-/* global document */
-
-describe( 'MermaidSourceViewCommand', () => {
- let domElement, editor, model, command;
-
- beforeEach( async () => {
- domElement = document.createElement( 'div' );
- document.body.appendChild( domElement );
-
- editor = await ClassicEditor.create( domElement, {
- licenseKey: "GPL",
- plugins: [
- MermaidEditing,
- Paragraph
- ]
- } );
-
- model = editor.model;
-
- command = new MermaidSourceViewCommand( editor );
- } );
-
- afterEach( () => {
- domElement.remove();
- return editor.destroy();
- } );
-
- describe( '#value', () => {
- it( 'should be true when mermaid element has displayMode attribute equal to "preview"', () => {
- setModelData( model, '<mermaid displayMode="preview" source="foo"></mermaid>' );
-
- expect( command.value ).to.equal( false );
- } );
-
- it( 'should be false when mermaid element has displayMode attribute equal to "split"', () => {
- setModelData( model, '<mermaid displayMode="split" source="foo"></mermaid>' );
-
- expect( command.value ).to.equal( false );
- } );
-
- it( 'should be false when mermaid element has displayMode attribute equal to "source"', () => {
- setModelData( model, '<mermaid displayMode="source" source="foo"></mermaid>' );
-
- expect( command.value ).to.equal( true );
- } );
- } );
-
- describe( '#isEnabled', () => {
- describe( 'should be false', () => {
- it( 'when text is selected', () => {
- setModelData( model,
- '<paragraph>[foo]</paragraph>' +
- '<mermaid source="flowchart TB\nA --> B\nB --> C"></mermaid>'
- );
-
- expect( command.isEnabled ).to.be.false;
- } );
-
- it( 'when mermaid is part of the selection', () => {
- setModelData( model,
- '<paragraph>[foo</paragraph>' +
- '<mermaid source="flowchart TB\nA --> B\nB --> C"></mermaid>' +
- '<paragraph>b]az</paragraph>'
- );
-
- expect( command.isEnabled ).to.be.false;
- } );
- } );
-
- describe( 'should be true', () => {
- it( 'when selection is inside mermaid', () => {
- setModelData( model,
- '<paragraph>foo</paragraph>' +
- '<mermaid source="flowchart TB\nA --> B\nB --> C">[]</mermaid>'
- );
-
- expect( command.isEnabled ).to.be.true;
- } );
-
- it( 'when mermaid is selected', () => {
- setModelData( model,
- '<paragraph>foo</paragraph>' +
- '[<mermaid source="flowchart TB\nA --> B\nB --> C"></mermaid>]'
- );
-
- expect( command.isEnabled ).to.be.true;
- } );
- } );
- } );
-
- describe( 'execute()', () => {
- it( 'should add text', () => {
- setModelData( model,
- '[<mermaid displayMode="preview" source="foo"></mermaid>]'
- );
-
- command.execute();
-
- expect( getModelData( model ) ).to.equal(
- '[<mermaid displayMode="source" source="foo"></mermaid>]'
- );
- } );
- } );
-
- describe( "#execute() edge cases", () => {
- it( "resolves the mermaid from the caret when nothing is selected", () => {
- setModelData( model, '<mermaid displayMode="split" source="foo">[]</mermaid>' );
-
- command.execute();
-
- expect( getModelData( model, { withoutSelection: true } ) )
- .to.equal( `<mermaid displayMode="source" source="foo"></mermaid>` );
- } );
-
- it( "leaves a mermaid already in source mode untouched", () => {
- setModelData( model, `[<mermaid displayMode="source" source="foo"></mermaid>]` );
- const before = getModelData( model, { withoutSelection: true } );
-
- command.execute();
-
- expect( getModelData( model, { withoutSelection: true } ) ).to.equal( before );
- } );
-
- it( "does nothing when no mermaid is selected", () => {
- setModelData( model, "<paragraph>foo[]</paragraph>" );
- const before = getModelData( model, { withoutSelection: true } );
-
- // CKEditor blocks execute() on a disabled command, and this command disables itself
- // when nothing is selected — so force it through to exercise the guard itself.
- command.isEnabled = true;
- command.execute();
-
- expect( getModelData( model, { withoutSelection: true } ) ).to.equal( before );
- } );
- } );
-} );
diff --git a/packages/ckeditor5/src/plugins/mermaid/mermaid_source_view_command.ts b/packages/ckeditor5/src/plugins/mermaid/mermaid_source_view_command.ts
deleted file mode 100644
index 296b11d148..0000000000
--- a/packages/ckeditor5/src/plugins/mermaid/mermaid_source_view_command.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { checkIsOn } from './utils.js';
-import { Command, ModelElement } from 'ckeditor5';
-
-/**
- * The mermaid source view command.
- *
- * Allows to switch to a source view mode.
- *
- * @extends module:core/command~Command
- */
-export default class MermaidSourceViewCommand extends Command {
-
- override refresh() {
- const editor = this.editor;
- const documentSelection = editor.model.document.selection;
- const selectedElement = documentSelection.getSelectedElement();
- const isSelectedElementMermaid = selectedElement && selectedElement.name === 'mermaid';
-
- if ( isSelectedElementMermaid || documentSelection.getLastPosition()?.findAncestor( 'mermaid' ) ) {
- this.isEnabled = !!selectedElement;
- } else {
- this.isEnabled = false;
- }
-
- this.value = checkIsOn( editor, 'source' );
- }
-
- override execute() {
- const editor = this.editor;
- const model = editor.model;
- const documentSelection = this.editor.model.document.selection;
- // `mermaid` is an object element, so the selection is always *on* it — never inside.
- const mermaidItem = documentSelection.getSelectedElement() as ModelElement | null;
-
- if ( mermaidItem ) {
- model.change( writer => {
- if ( mermaidItem.getAttribute( 'displayMode' ) !== 'source' ) {
- writer.setAttribute( 'displayMode', 'source', mermaidItem );
- }
- } );
- }
- }
-}
diff --git a/packages/ckeditor5/src/plugins/mermaid/mermaid_split_view_command.spec.ts b/packages/ckeditor5/src/plugins/mermaid/mermaid_split_view_command.spec.ts
deleted file mode 100644
index 822c23e92d..0000000000
--- a/packages/ckeditor5/src/plugins/mermaid/mermaid_split_view_command.spec.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-import { ClassicEditor, Paragraph, _setModelData as setModelData, _getModelData as getModelData } from 'ckeditor5';
-
-import MermaidSplitViewCommand from './mermaid_split_view_command.js';
-import MermaidEditing from './mermaid_editing.js';
-import { afterEach, beforeEach, describe, it } from 'vitest';
-import { expect } from 'vitest';
-
-/* global document */
-
-describe( 'MermaidSplitViewCommand', () => {
- let domElement, editor, model, command;
-
- beforeEach( async () => {
- domElement = document.createElement( 'div' );
- document.body.appendChild( domElement );
-
- editor = await ClassicEditor.create( domElement, {
- licenseKey: "GPL",
- plugins: [
- MermaidEditing,
- Paragraph
- ]
- } );
-
- model = editor.model;
-
- command = new MermaidSplitViewCommand( editor );
- } );
-
- afterEach( () => {
- domElement.remove();
- return editor.destroy();
- } );
-
- describe( '#value', () => {
- it( 'should be true when mermaid element has displayMode attribute equal to "preview"', () => {
- setModelData( model, '<mermaid displayMode="preview" source="foo"></mermaid>' );
-
- expect( command.value ).to.equal( false );
- } );
-
- it( 'should be false when mermaid element has displayMode attribute equal to "split"', () => {
- setModelData( model, '<mermaid displayMode="split" source="foo"></mermaid>' );
-
- expect( command.value ).to.equal( true );
- } );
-
- it( 'should be false when mermaid element has source attribute equal to "source"', () => {
- setModelData( model, '<mermaid displayMode="source" source="foo"></mermaid>' );
-
- expect( command.value ).to.equal( false );
- } );
- } );
-
- describe( '#isEnabled', () => {
- describe( 'should be false', () => {
- it( 'when text is selected', () => {
- setModelData( model,
- '<paragraph>[foo]</paragraph>' +
- '<mermaid source="flowchart TB\nA --> B\nB --> C"></mermaid>'
- );
-
- expect( command.isEnabled ).to.be.false;
- } );
-
- it( 'when mermaid is part of the selection', () => {
- setModelData( model,
- '<paragraph>[foo</paragraph>' +
- '<mermaid source="flowchart TB\nA --> B\nB --> C"></mermaid>' +
- '<paragraph>b]az</paragraph>'
- );
-
- expect( command.isEnabled ).to.be.false;
- } );
- } );
-
- describe( 'should be true', () => {
- it( 'when selection is inside mermaid', () => {
- setModelData( model,
- '<paragraph>foo</paragraph>' +
- '<mermaid source="flowchart TB\nA --> B\nB --> C">[]</mermaid>'
- );
-
- expect( command.isEnabled ).to.be.true;
- } );
-
- it( 'when mermaid is selected', () => {
- setModelData( model,
- '<paragraph>foo</paragraph>' +
- '[<mermaid source="flowchart TB\nA --> B\nB --> C"></mermaid>]'
- );
-
- expect( command.isEnabled ).to.be.true;
- } );
- } );
- } );
-
- describe( 'execute()', () => {
- it( 'should change displayMode to "source" for mermaid', () => {
- setModelData( model,
- '[<mermaid displayMode="source" source="foo"></mermaid>]'
- );
-
- command.execute();
-
- expect( getModelData( model ) ).to.equal(
- '[<mermaid displayMode="split" source="foo"></mermaid>]'
- );
- } );
- } );
-
- describe( "#execute() edge cases", () => {
- it( "resolves the mermaid from the caret when nothing is selected", () => {
- setModelData( model, '<mermaid displayMode="preview" source="foo">[]</mermaid>' );
-
- command.execute();
-
- expect( getModelData( model, { withoutSelection: true } ) )
- .to.equal( `<mermaid displayMode="split" source="foo"></mermaid>` );
- } );
-
- it( "leaves a mermaid already in split mode untouched", () => {
- setModelData( model, `[<mermaid displayMode="split" source="foo"></mermaid>]` );
- const before = getModelData( model, { withoutSelection: true } );
-
- command.execute();
-
- expect( getModelData( model, { withoutSelection: true } ) ).to.equal( before );
- } );
-
- it( "does nothing when no mermaid is selected", () => {
- setModelData( model, "<paragraph>foo[]</paragraph>" );
- const before = getModelData( model, { withoutSelection: true } );
-
- // CKEditor blocks execute() on a disabled command, and this command disables itself
- // when nothing is selected — so force it through to exercise the guard itself.
- command.isEnabled = true;
- command.execute();
-
- expect( getModelData( model, { withoutSelection: true } ) ).to.equal( before );
- } );
- } );
-} );
diff --git a/packages/ckeditor5/src/plugins/mermaid/mermaid_split_view_command.ts b/packages/ckeditor5/src/plugins/mermaid/mermaid_split_view_command.ts
deleted file mode 100644
index adeb6c722c..0000000000
--- a/packages/ckeditor5/src/plugins/mermaid/mermaid_split_view_command.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-/**
- * @module mermaid/mermaidsplitviewcommand
- */
-
-import { checkIsOn } from './utils.js';
-import { Command, ModelElement } from 'ckeditor5';
-
-/**
- * The mermaid split view command.
- *
- * Allows to switch to a split view mode.
- */
-export default class MermaidSplitViewCommand extends Command {
-
- override refresh() {
- const editor = this.editor;
- const documentSelection = editor.model.document.selection;
- const selectedElement = documentSelection.getSelectedElement();
- const isSelectedElementMermaid = selectedElement && selectedElement.name === 'mermaid';
-
- if ( isSelectedElementMermaid || documentSelection.getLastPosition()?.findAncestor( 'mermaid' ) ) {
- this.isEnabled = !!selectedElement;
- } else {
- this.isEnabled = false;
- }
-
- this.value = checkIsOn( editor, 'split' );
- }
-
- override execute() {
- const editor = this.editor;
- const model = editor.model;
- const documentSelection = this.editor.model.document.selection;
- // `mermaid` is an object element, so the selection is always *on* it — never inside.
- const mermaidItem = documentSelection.getSelectedElement() as ModelElement | null;
-
- if ( mermaidItem ) {
- model.change( writer => {
- if ( mermaidItem.getAttribute( 'displayMode' ) !== 'split' ) {
- writer.setAttribute( 'displayMode', 'split', mermaidItem );
- }
- } );
- }
- }
-}
diff --git a/packages/ckeditor5/src/plugins/mermaid/mermaid_toolbar.spec.ts b/packages/ckeditor5/src/plugins/mermaid/mermaid_toolbar.spec.ts
deleted file mode 100644
index 4a7360a838..0000000000
--- a/packages/ckeditor5/src/plugins/mermaid/mermaid_toolbar.spec.ts
+++ /dev/null
@@ -1,153 +0,0 @@
-import { ClassicEditor as ClassicTestEditor, Essentials, Paragraph, WidgetToolbarRepository, _setModelData as setData } from 'ckeditor5';
-
-import Mermaid from './mermaid.js';
-import { afterEach, beforeEach, describe, it } from 'vitest';
-import { expect } from 'vitest';
-
-/* global document */
-
-describe( 'MermaidToolbar', () => {
- let editor, domElement, widgetToolbarRepository, balloon, toolbar, model;
-
- beforeEach( () => {
- domElement = document.createElement( 'div' );
- document.body.appendChild( domElement );
-
- return ClassicTestEditor.create( domElement, {
- licenseKey: "GPL",
- plugins: [ Essentials, Paragraph, Mermaid ],
- mermaid: {
- toolbar: [ 'fake_button' ]
- }
- } ).then( newEditor => {
- editor = newEditor;
- model = newEditor.model;
- widgetToolbarRepository = editor.plugins.get( WidgetToolbarRepository );
- toolbar = widgetToolbarRepository._toolbarDefinitions.get( 'mermaidToolbar' ).view;
- balloon = editor.plugins.get( 'ContextualBalloon' );
- } );
- } );
-
- afterEach( () => {
- domElement.remove();
- return editor.destroy();
- } );
-
- describe( 'toolbar', () => {
- it( 'should be initialized with expected buttons', () => {
- editor.ui.focusTracker.isFocused = true;
-
- setData( model, '<mermaid displayMode="split" source="">[]</mermaid>' );
-
- expect( toolbar.items ).to.have.length( 5 );
- expect( toolbar.items.get( 0 ).label ).to.equal( 'Source view' );
- expect( toolbar.items.get( 1 ).label ).to.equal( 'Split view' );
- expect( toolbar.items.get( 2 ).label ).to.equal( 'Preview' );
- expect( toolbar.items.get( 4 ).label ).to.equal( 'Read more about Mermaid diagram syntax' );
- } );
- } );
-
- describe( 'integration with the editor focus', () => {
- it( 'should show the toolbar when the editor gains focus and the mermaid widget is selected', () => {
- setData( model,
- '[<mermaid source="flowchart TB\nA --> B\nB --> C"></mermaid>]'
- );
-
- expect( balloon.visibleView ).to.be.null;
- // @todo: remove me
- // expect( balloon.visibleView === null, 'balloon.visibleView === null' ).to.be.true;
-
- editor.ui.focusTracker.isFocused = true;
- expect( balloon.visibleView ).to.equal( toolbar );
- // @todo: remove me
- // expect( balloon.visibleView === toolbar, 'balloon.visibleView === toolbar' ).to.be.true;
- } );
-
- it( 'should hide the toolbar when the editor loses focus and the mermaid widget is selected', () => {
- setData( model,
- '[<mermaid source="flowchart TB\nA --> B\nB --> C"></mermaid>]'
- );
-
- editor.ui.focusTracker.isFocused = true;
- expect( balloon.visibleView ).to.equal( toolbar );
-
- editor.ui.focusTracker.isFocused = false;
- expect( balloon.visibleView ).to.be.null;
- } );
- } );
-
- describe( 'integration with the editor selection', () => {
- beforeEach( () => {
- editor.ui.focusTracker.isFocused = true;
- } );
-
- it( 'should show the toolbar on ui#update when the mermaid widget is selected', () => {
- setData( model,
- '<paragraph>[foo]</paragraph>' +
- '<mermaid source="flowchart TB\nA --> B\nB --> C"></mermaid>'
- );
-
- expect( balloon.visibleView ).to.be.null;
-
- editor.ui.fire( 'update' );
-
- expect( balloon.visibleView ).to.be.null;
-
- model.change( writer => {
- // Set selection to the [<mermaid source="flowchart TB\nA --> B\nB --> C"></mermaid>]
- writer.setSelection( model.document.getRoot().getChild( 1 ), 'on' );
- } );
-
- expect( balloon.visibleView ).to.equal( toolbar );
-
- // Make sure successive change does not throw, e.g. attempting
- // to insert the toolbar twice.
- editor.ui.fire( 'update' );
-
- expect( balloon.visibleView ).to.equal( toolbar );
- } );
-
- it( 'should hide the toolbar on ui#update if the mermaid widget is de–selected', () => {
- setData( model,
- '<paragraph>foo</paragraph>' +
- '[<mermaid source="flowchart TB\nA --> B\nB --> C"></mermaid>]'
- );
- expect( balloon.visibleView ).to.equal( toolbar );
-
- model.change( writer => {
- // Select the <paragraph>[foo]</paragraph>
- writer.setSelection( model.document.getRoot().getChild( 0 ), 'in' );
- } );
-
- expect( balloon.visibleView ).to.be.null;
-
- // Make sure successive change does not throw, e.g. attempting
- // to remove the toolbar twice.
- editor.ui.fire( 'update' );
-
- expect( balloon.visibleView ).to.be.null;
- } );
-
- it( 'should not hide the toolbar on ui#update when the selection is being moved from one mermaid widget to another', () => {
- setData( model,
- '[<mermaid source="flowchart TB\nA --> B\nB --> C"></mermaid>]' +
- '<mermaid source="flowchart TB\nA --> B\nB --> C"></mermaid>'
- );
-
- expect( balloon.visibleView ).to.equal( toolbar );
-
- model.change( writer => {
- // Set selection to the second <mermaid></mermaid>
- writer.setSelection( model.document.selection.getSelectedElement().nextSibling, 'on' );
- } );
-
- expect( balloon.visibleView ).to.equal( toolbar );
-
- // Make sure successive change does not throw, e.g. attempting
- // to insert the toolbar twice.
- editor.ui.fire( 'update' );
-
- expect( balloon.visibleView ).to.equal( toolbar );
- } );
- } );
-} );
diff --git a/packages/ckeditor5/src/plugins/mermaid/mermaid_toolbar.ts b/packages/ckeditor5/src/plugins/mermaid/mermaid_toolbar.ts
deleted file mode 100644
index 70017f492a..0000000000
--- a/packages/ckeditor5/src/plugins/mermaid/mermaid_toolbar.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * @module mermaid/mermaid_toolbar
- */
-
-import { Plugin, ViewDocumentSelection, ViewElement, WidgetToolbarRepository } from "ckeditor5";
-
-
-export default class MermaidToolbar extends Plugin {
-
- static get requires() {
- return [ WidgetToolbarRepository ];
- }
-
- static get pluginName() {
- return 'MermaidToolbar' as const;
- }
-
- afterInit() {
- const editor = this.editor;
- const t = editor.t;
-
- const widgetToolbarRepository = editor.plugins.get( WidgetToolbarRepository );
- const mermaidToolbarItems = [ 'mermaidSourceView', 'mermaidSplitView', 'mermaidPreview', '|', 'mermaidInfo' ];
-
- widgetToolbarRepository.register( 'mermaidToolbar', {
- ariaLabel: t( 'Mermaid toolbar' ),
- items: mermaidToolbarItems,
- getRelatedElement: selection => getSelectedElement( selection )
- } );
- }
-}
-
-function getSelectedElement( selection: ViewDocumentSelection ) {
- const viewElement = selection.getSelectedElement() as unknown as ViewElement;
-
- if ( viewElement && viewElement.hasClass( 'ck-mermaid__wrapper' ) ) {
- return viewElement;
- }
-
- return null;
-}
diff --git a/packages/ckeditor5/src/plugins/mermaid/mermaid_ui.spec.ts b/packages/ckeditor5/src/plugins/mermaid/mermaid_ui.spec.ts
deleted file mode 100644
index f996adadcc..0000000000
--- a/packages/ckeditor5/src/plugins/mermaid/mermaid_ui.spec.ts
+++ /dev/null
@@ -1,257 +0,0 @@
-import { ClassicEditor, Paragraph, _getModelData as getModelData, _setModelData as setModelData } from 'ckeditor5';
-
-import './mermaid.js';
-import Mermaid from './mermaid.js';
-import MermaidUI from './mermaid_ui.js';
-import { afterEach, beforeEach, describe, it, vi } from 'vitest';
-import { expect } from 'vitest';
-
-/* global document */
-
-describe( 'MermaidUI', () => {
- it( 'should be named', () => {
- expect( MermaidUI.pluginName ).to.equal( 'MermaidUI' );
- } );
-
- describe( 'init()', () => {
- let domElement, editor;
-
- beforeEach( async () => {
- domElement = document.createElement( 'div' );
- document.body.appendChild( domElement );
-
- editor = await ClassicEditor.create( domElement, {
- licenseKey: "GPL",
- plugins: [
- Mermaid
- ]
- } );
- } );
-
- afterEach( () => {
- domElement.remove();
- return editor.destroy();
- } );
-
- it( 'should register the UI item', () => {
- expect( editor.ui.componentFactory.has( 'mermaid' ) ).to.equal( true );
- } );
-
- it( 'has the base properties', () => {
- const dropdown = editor.ui.componentFactory.create( 'mermaid' );
-
- expect( dropdown.buttonView ).to.have.property( 'label', 'Mermaid diagram' );
- expect( dropdown.buttonView ).to.have.property( 'icon' );
- expect( dropdown.buttonView ).to.have.property( 'tooltip', true );
- } );
-
- describe( 'UI components', () => {
- for ( const buttonName of [
- 'mermaidPreview',
- 'mermaidSourceView',
- 'mermaidSplitView',
- 'mermaidInfo'
- ] ) {
- it( `should register the ${ buttonName } button`, () => {
- expect( editor.ui.componentFactory.has( buttonName ) ).to.equal( true );
- } );
-
- it( `should add the base properties for ${ buttonName } button`, () => {
- const button = editor.ui.componentFactory.create( buttonName );
-
- expect( button ).to.have.property( 'label' );
- expect( button ).to.have.property( 'icon' );
- expect( button ).to.have.property( 'tooltip', true );
- } );
- }
- } );
-
- it( 'should set focus inside textarea of a newly created mermaid', () => {
- const dropdown = editor.ui.componentFactory.create( 'mermaid' );
-
- dropdown.buttonView.fire( 'execute' );
-
- expect( document.activeElement.tagName ).to.equal( 'TEXTAREA' );
- } );
-
- it( 'should insert exactly one diagram on the main action (no double insert)', () => {
- const dropdown = editor.ui.componentFactory.create( 'mermaid' );
-
- dropdown.buttonView.fire( 'execute' );
-
- const data = getModelData( editor.model, { withoutSelection: true } );
- expect( ( data.match( /<mermaid/g ) || [] ).length ).to.equal( 1 );
- } );
-
- it( 'should not crash if the button is fired inside model.change()', () => {
- const dropdown = editor.ui.componentFactory.create( 'mermaid' );
-
- setModelData( editor.model, '[]' );
-
- editor.model.change( () => {
- dropdown.buttonView.fire( 'execute' );
- } );
- // As the conversion is to be executed after the model.change(), we don't have access to the fully prepared view and
- // despite that, we should still successfully add mermaid widget to the editor, not requiring the selection change
- // to the inside of the nonexisting textarea element.
- } );
- } );
-
- describe( 'diagram templates', () => {
- let domElement, editor;
-
- const SAMPLES = [
- { name: 'Flowchart', content: 'graph LR; A --> B' },
- { name: 'Pie', content: 'pie title Pets' }
- ];
-
- beforeEach( async () => {
- domElement = document.createElement( 'div' );
- document.body.appendChild( domElement );
-
- editor = await ClassicEditor.create( domElement, {
- licenseKey: "GPL",
- plugins: [
- Mermaid,
- Paragraph
- ],
- mermaid: {
- config: {},
- samples: SAMPLES
- }
- } );
- } );
-
- afterEach( () => {
- domElement.remove();
- return editor.destroy();
- } );
-
- it( 'lists the configured templates in the dropdown', () => {
- const dropdown = editor.ui.componentFactory.create( 'mermaid' );
- dropdown.render();
- document.body.appendChild( dropdown.element );
- dropdown.isOpen = true;
-
- const labels = [ ...dropdown.listView.items ].map( item => item.children.first.label );
- expect( labels ).to.deep.equal( [ 'Flowchart', 'Pie' ] );
-
- dropdown.element.remove();
- } );
-
- it( 'inserts a diagram pre-filled with the picked template source', () => {
- setModelData( editor.model, '<paragraph>[foo]</paragraph>' );
-
- const dropdown = editor.ui.componentFactory.create( 'mermaid' );
- dropdown.render();
- document.body.appendChild( dropdown.element );
- dropdown.isOpen = true;
-
- dropdown.listView.items.first.children.first.fire( 'execute' );
-
- expect( getModelData( editor.model, { withoutSelection: true } ) ).to.equal(
- '<mermaid displayMode="split" source="graph LR; A --> B"></mermaid>'
- );
-
- dropdown.element.remove();
- } );
- } );
-} );
-
-
-describe( 'MermaidUI without its commands', () => {
- let domElement: HTMLDivElement;
-
- beforeEach( () => {
- domElement = document.createElement( 'div' );
- document.body.appendChild( domElement );
- } );
-
- afterEach( () => {
- domElement.remove();
- } );
-
- it( 'refuses to initialise without the insert command', async () => {
- // MermaidUI alone: MermaidEditing never registered insertMermaid, and the
- // insert button is built during init(), so the whole editor fails to start.
- await expect( ClassicEditor.create( domElement, {
- licenseKey: 'GPL',
- plugins: [ Paragraph, MermaidUI ]
- } ) ).rejects.toThrow( 'Missing command.' );
- } );
-
- it( 'refuses to build a toolbar button whose command is missing', async () => {
- const editor = await ClassicEditor.create( domElement, {
- licenseKey: 'GPL',
- plugins: [ Paragraph, Mermaid ]
- } );
- const ui = editor.plugins.get( MermaidUI ) as unknown as {
- _createToolbarButton( editor: ClassicEditor, name: string, label: string, icon: string ): void;
- };
-
- // Toolbar buttons resolve their command lazily, inside the factory callback.
- ui._createToolbarButton( editor, 'mermaidNoSuch', 'No such', '<svg></svg>' );
-
- expect( () => editor.ui.componentFactory.create( 'mermaidNoSuch' ) ).to.throw( 'Missing command.' );
-
- await editor.destroy();
- } );
-} );
-
-describe( 'MermaidUI buttons', () => {
- let domElement: HTMLDivElement, editor: ClassicEditor;
-
- beforeEach( async () => {
- domElement = document.createElement( 'div' );
- document.body.appendChild( domElement );
-
- editor = await ClassicEditor.create( domElement, {
- licenseKey: 'GPL',
- plugins: [ Paragraph, Mermaid ]
- } );
- } );
-
- afterEach( () => {
- domElement.remove();
- return editor.destroy();
- } );
-
- it( 'opens the help through the configured callback, and does nothing without one', () => {
- const open = vi.spyOn( window, 'open' ).mockReturnValue( null );
- const button = editor.ui.componentFactory.create( 'mermaidInfo' );
-
- button.fire( 'execute' );
- expect( open ).not.toHaveBeenCalled();
- open.mockRestore();
-
- const openHelp = vi.fn();
- editor.config.set( 'mermaid.openHelp', openHelp );
- button.fire( 'execute' );
- expect( openHelp ).toHaveBeenCalledOnce();
- } );
-
- it( 'runs the matching command and returns focus when a toolbar button executes', () => {
- setModelData( editor.model, '[<mermaid displayMode="split" source="foo"></mermaid>]' );
-
- const execute = vi.spyOn( editor, 'execute' );
- const focus = vi.spyOn( editor.editing.view, 'focus' );
- const scroll = vi.spyOn( editor.editing.view, 'scrollToTheSelection' );
-
- editor.ui.componentFactory.create( 'mermaidPreview' ).fire( 'execute' );
-
- expect( execute ).toHaveBeenCalledWith( 'mermaidPreviewCommand' );
- expect( scroll ).toHaveBeenCalled();
- expect( focus ).toHaveBeenCalled();
- } );
-
- it( 'tracks its command through isOn and isEnabled', () => {
- setModelData( editor.model, '[<mermaid displayMode="preview" source="foo"></mermaid>]' );
-
- const button = editor.ui.componentFactory.create( 'mermaidPreview' ) as unknown as {
- isOn: boolean; isEnabled: boolean;
- };
-
- expect( button.isOn ).to.equal( true );
- expect( button.isEnabled ).to.equal( true );
- } );
-} );
diff --git a/packages/ckeditor5/src/plugins/mermaid/utils.spec.ts b/packages/ckeditor5/src/plugins/mermaid/utils.spec.ts
deleted file mode 100644
index 527e8837ea..0000000000
--- a/packages/ckeditor5/src/plugins/mermaid/utils.spec.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import { ClassicEditor, Paragraph, _setModelData as setModelData } from 'ckeditor5';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import MermaidEditing from './mermaid_editing.js';
-import { checkIsOn, debounce } from './utils.js';
-
-/* global document */
-
-describe( 'utils', () => {
- describe( 'debounce()', () => {
- beforeEach( () => {
- vi.useFakeTimers();
- } );
-
- afterEach( () => {
- vi.useRealTimers();
- } );
-
- it( 'defers the call until the wait elapses', () => {
- const spy = vi.fn();
- const debounced = debounce( spy, 50 );
-
- debounced( 'a' );
-
- expect( spy ).not.toHaveBeenCalled();
-
- vi.advanceTimersByTime( 50 );
-
- expect( spy ).toHaveBeenCalledTimes( 1 );
- expect( spy ).toHaveBeenCalledWith( 'a' );
- } );
-
- it( 'collapses a burst of calls into the last one', () => {
- const spy = vi.fn();
- const debounced = debounce( spy, 50 );
-
- debounced( 'first' );
- vi.advanceTimersByTime( 20 );
- // Lands inside the window, so the pending timeout is cleared and restarted.
- debounced( 'second' );
- vi.advanceTimersByTime( 20 );
- debounced( 'third' );
- vi.advanceTimersByTime( 50 );
-
- expect( spy ).toHaveBeenCalledTimes( 1 );
- expect( spy ).toHaveBeenCalledWith( 'third' );
- } );
-
- it( 'preserves the caller as `this`', () => {
- const calls: unknown[] = [];
- const debounced = debounce( function( this: unknown ) {
- calls.push( this );
- }, 10 );
- const host = { run: debounced };
-
- host.run();
- vi.advanceTimersByTime( 10 );
-
- expect( calls ).to.deep.equal( [ host ] );
- } );
- } );
-
- describe( 'checkIsOn()', () => {
- let domElement: HTMLDivElement, editor: ClassicEditor;
-
- beforeEach( async () => {
- domElement = document.createElement( 'div' );
- document.body.appendChild( domElement );
-
- editor = await ClassicEditor.create( domElement, {
- licenseKey: 'GPL',
- plugins: [ Paragraph, MermaidEditing ]
- } );
- } );
-
- afterEach( () => {
- domElement.remove();
- return editor.destroy();
- } );
-
- it( 'is true for the selected mermaid whose displayMode matches', () => {
- setModelData( editor.model, '[<mermaid displayMode="preview" source="foo"></mermaid>]' );
-
- expect( checkIsOn( editor, 'preview' ) ).to.equal( true );
- } );
-
- it( 'is false for the selected mermaid whose displayMode differs', () => {
- setModelData( editor.model, '[<mermaid displayMode="split" source="foo"></mermaid>]' );
-
- expect( checkIsOn( editor, 'preview' ) ).to.equal( false );
- } );
-
- it( 'is false when the selection is not on a mermaid at all', () => {
- setModelData( editor.model, '<paragraph>foo[]</paragraph>' );
-
- expect( checkIsOn( editor, 'preview' ) ).to.equal( false );
- } );
- } );
-} );
diff --git a/packages/ckeditor5/src/plugins/mermaid/utils.ts b/packages/ckeditor5/src/plugins/mermaid/utils.ts
deleted file mode 100644
index 894c863875..0000000000
--- a/packages/ckeditor5/src/plugins/mermaid/utils.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * @license Copyright (c) 2003-2022, CKSource Holding sp. z o.o. All rights reserved.
- * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
- */
-
-import { Editor } from "ckeditor5";
-
-export function debounce<T extends (...args: any[]) => void>( fn: T, waitMs: number ): T {
- let timeout: ReturnType<typeof setTimeout> | null = null;
- return function( this: unknown, ...args: Parameters<T> ) {
- if ( timeout ) {
- clearTimeout( timeout );
- }
- timeout = setTimeout( () => fn.apply( this, args ), waitMs );
- } as T;
-}
-
-/**
- * Helper function for setting the `isOn` state of buttons.
- *
- * @private
- * @param commandName Short name of the command.
- */
-export function checkIsOn( editor: Editor, commandName: string ) {
- const selection = editor.model.document.selection;
- const mermaidItem = selection.getSelectedElement() || selection.getLastPosition()?.parent;
-
- if ( mermaidItem && mermaidItem.is( 'element', 'mermaid' ) && mermaidItem.getAttribute( 'displayMode' ) === commandName ) {
- return true;
- }
-
- return false;
-}
diff --git a/packages/ckeditor5/src/theme/mermaid.css b/packages/ckeditor5/src/theme/mermaid.css
deleted file mode 100644
index c1bfa02797..0000000000
--- a/packages/ckeditor5/src/theme/mermaid.css
+++ /dev/null
@@ -1,71 +0,0 @@
-/* Mermaid wrapper */
-.ck-mermaid__wrapper {
- display: flex;
- justify-content: center;
-}
-
-/* Editing
- Assigned to textarea
- */
-.ck-mermaid__wrapper .ck-mermaid__editing-view {
- padding: 16px; /* just like pre element */
- background-color: hsla(0, 0%, 78%, 0.3); /* just like pre element */
- min-height: 200px;
- border: 0;
- resize: vertical;
- font-size: 12px; /* just like pre element */
- outline: 0; /* just like pre element */
-}
-
-/* Preview */
-.ck-mermaid__preview {
- display: flex;
- justify-content: center;
- align-items: flex-start;
- overflow-x: auto;
- min-width: 0;
-}
-
-/* Keep the SVG's intrinsic size so wide flowcharts stay readable; the
- preview pane scrolls horizontally instead of squashing into a thin strip. */
-.ck-mermaid__preview svg {
- flex-shrink: 0;
- max-width: none;
-}
-
-/* Preview error state */
-[id^="dmermaid-"] {
- display: flex;
- align-items: center;
- height: 100%;
- justify-content: center;
-}
-
-[id^="dmermaid-"] svg {
- display: block;
- width: 60%;
- height: auto;
-}
-
-/* Source mode */
-.ck-mermaid__source-mode .ck-mermaid__editing-view {
- width: 100%;
-}
-
-.ck-mermaid__source-mode .ck-mermaid__preview {
- display: none;
-}
-
-/* Split mode */
-.ck-mermaid__split-mode .ck-mermaid__editing-view {
- width: 50%;
-}
-
-.ck-mermaid__split-mode .ck-mermaid__preview {
- width: 50%;
-}
-
-/* Preview mode */
-.ck-mermaid__preview-mode .ck-mermaid__editing-view {
- display: none;
-}
\ No newline at end of file
diff --git a/packages/trilium-core/src/services/icon_pack_text_editor.json b/packages/trilium-core/src/services/icon_pack_text_editor.json
index 99f31d8cfe..51ebd17c5b 100644
--- a/packages/trilium-core/src/services/icon_pack_text_editor.json
+++ b/packages/trilium-core/src/services/icon_pack_text_editor.json
@@ -1374,80 +1374,56 @@
"trilium-math"
]
},
- "cke-trilium-mermaid-info": {
- "glyph": "",
- "terms": [
- "trilium-mermaid-info"
- ]
- },
"cke-trilium-mermaid-insert": {
- "glyph": "",
+ "glyph": "",
"terms": [
"trilium-mermaid-insert"
]
},
- "cke-trilium-mermaid-preview-mode": {
- "glyph": "",
- "terms": [
- "trilium-mermaid-preview-mode"
- ]
- },
- "cke-trilium-mermaid-source-mode": {
- "glyph": "",
- "terms": [
- "trilium-mermaid-source-mode"
- ]
- },
- "cke-trilium-mermaid-split-mode": {
- "glyph": "",
- "terms": [
- "trilium-mermaid-split-mode"
- ]
- },
"cke-trilium-multicolumn": {
- "glyph": "",
+ "glyph": "",
"terms": [
"trilium-multicolumn"
]
},
"cke-trilium-note": {
- "glyph": "",
+ "glyph": "",
"terms": [
"trilium-note"
]
},
"cke-trilium-scissors": {
- "glyph": "",
+ "glyph": "",
"terms": [
"trilium-scissors"
]
},
"cke-trilium-tabs-bottom": {
- "glyph": "",
+ "glyph": "",
"terms": [
"trilium-tabs-bottom"
]
},
"cke-trilium-tabs": {
- "glyph": "",
+ "glyph": "",
"terms": [
"trilium-tabs"
]
},
"cke-trilium": {
- "glyph": "",
+ "glyph": "",
"terms": [
"trilium"
]
},
"cke-trilium-ai": {
- "glyph": "",
+ "glyph": "",
"terms": [
"trilium-ai"
]
},
"cke-trilium-template": {
- "glyph": "",
+ "glyph": "",
"terms": [
"trilium-template"
]