Skip to content

Build your personal knowledge base with Trilium Notes

text editor/formatting toolbar: allow the user to select a template before inserting a diagram

Adorian Doranff2b012313f9
diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.ts
index 93e0aa0e97..4dc4192663 100644
--- a/apps/client/src/widgets/type_widgets/text/config.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.ts
@@ -44,7 +44,8 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
},
mermaid: {
lazyLoad: async () => (await import("mermaid")).default, // FIXME
- config: getMermaidConfig()
+ config: getMermaidConfig(),
+ samples: SAMPLE_DIAGRAMS
},
image: {
styles: {
diff --git a/packages/ckeditor5-mermaid/src/augmentation.ts b/packages/ckeditor5-mermaid/src/augmentation.ts
index 4aa8398c82..60b27e96b4 100644
--- a/packages/ckeditor5-mermaid/src/augmentation.ts
+++ b/packages/ckeditor5-mermaid/src/augmentation.ts
@@ -1,7 +1,7 @@
import type { Mermaid } from './index.js';
import MermaidEditing from './mermaidediting.js';
import MermaidToolbar from './mermaidtoolbar.js';
-import MermaidUI from './mermaidui.js';
+import MermaidUI, { type MermaidSample } from './mermaidui.js';
declare global {
interface MermaidInstance {
@@ -28,6 +28,8 @@ declare module 'ckeditor5' {
"mermaid"?: {
lazyLoad?: () => Promise<MermaidInstance> | MermaidInstance;
config: MermaidConfig;
+ /** Diagram templates listed in the insert-diagram split button's dropdown. */
+ samples?: MermaidSample[];
}
}
diff --git a/packages/ckeditor5-mermaid/src/index.ts b/packages/ckeditor5-mermaid/src/index.ts
index 6d52b31ae7..604bcc5376 100644
--- a/packages/ckeditor5-mermaid/src/index.ts
+++ b/packages/ckeditor5-mermaid/src/index.ts
@@ -2,6 +2,7 @@ import './augmentation.js';
export { default as Mermaid } from './mermaid.js';
export { INSERT_MERMAID_COMMAND } from './commands/insertMermaidCommand.js';
+export type { MermaidSample } from './mermaidui.js';
import infoIcon from './../theme/icons/info.svg?raw';
import insertMermaidIcon from './../theme/icons/insert.svg?raw';
import previewModeIcon from './../theme/icons/preview-mode.svg?raw';
diff --git a/packages/ckeditor5-mermaid/src/mermaidui.ts b/packages/ckeditor5-mermaid/src/mermaidui.ts
index 0edc9c8337..7b11892733 100644
--- a/packages/ckeditor5-mermaid/src/mermaidui.ts
+++ b/packages/ckeditor5-mermaid/src/mermaidui.ts
@@ -7,11 +7,20 @@ import previewModeIcon from '../theme/icons/preview-mode.svg?raw';
import splitModeIcon from '../theme/icons/split-mode.svg?raw';
import sourceModeIcon from '../theme/icons/source-mode.svg?raw';
import infoIcon from '../theme/icons/info.svg?raw';
-import { ButtonView, Editor, ModelElement, Locale, Observable, Plugin } from 'ckeditor5';
-import InsertMermaidCommand from './commands/insertMermaidCommand.js';
+import { addListToDropdown, ButtonView, Collection, createDropdown, Editor, ListDropdownItemDefinition, Locale, ModelElement, Observable, Plugin, SplitButtonView, ViewModel } from 'ckeditor5';
+import InsertMermaidCommand, { INSERT_MERMAID_COMMAND } from './commands/insertMermaidCommand.js';
/* global window, document */
+/**
+ * A selectable Mermaid diagram template (a localized name and its source
+ * markup), listed in the insert-diagram split button's dropdown.
+ */
+export interface MermaidSample {
+ name: string;
+ content: string;
+}
+
export default class MermaidUI extends Plugin {
/**
* @inheritDoc
@@ -43,49 +52,97 @@ export default class MermaidUI extends Plugin {
}
/**
- * Adds the button for inserting mermaid.
+ * Adds the split button for inserting mermaid.
+ *
+ * The main action inserts a blank diagram, while the dropdown lists the
+ * configured diagram templates (see the `mermaid.samples` config). Picking
+ * a template inserts a diagram pre-filled with its source.
*
* @private
*/
_addInsertMermaidButton() {
const editor = this.editor;
const t = editor.t;
- const view = editor.editing.view;
+ const command = editor.commands.get( INSERT_MERMAID_COMMAND ) as InsertMermaidCommand;
+ if (!command) {
+ throw new Error("Missing command.");
+ }
+
+ const samples = editor.config.get( 'mermaid.samples' ) ?? [];
editor.ui.componentFactory.add( 'mermaid', (locale: Locale) => {
- const buttonView = new ButtonView( locale );
- const command = editor.commands.get( 'insertMermaidCommand' ) as InsertMermaidCommand;
- if (!command) {
- throw new Error("Missing command.");
- }
+ const dropdownView = createDropdown( locale, SplitButtonView );
+ const splitButtonView = dropdownView.buttonView;
- buttonView.set( {
+ splitButtonView.set( {
label: t( 'Insert Mermaid diagram' ),
icon: insertMermaidIcon,
tooltip: true
} );
- buttonView.bind( 'isOn', 'isEnabled' ).to( command as (Observable & { value: boolean; } & { isEnabled: boolean; }), 'value', 'isEnabled' );
+ // Main action: insert a blank diagram.
+ splitButtonView.on( 'execute', () => this._insertDiagram() );
+
+ // Dropdown: insert a diagram pre-filled with the picked template.
+ // `createDropdown` already binds the split button's `isEnabled` to the
+ // dropdown, so binding the dropdown alone disables both parts.
+ addListToDropdown( dropdownView, this._getSampleDropdownItems( samples ) );
+ dropdownView.bind( 'isEnabled' ).to( command, 'isEnabled' );
+ dropdownView.on( 'execute', evt => {
+ const source = (evt.source as { commandParam?: string }).commandParam;
+ this._insertDiagram( { source } );
+ } );
- // Execute the command when the button is clicked.
- command.listenTo( buttonView, 'execute', () => {
- const mermaidItem = editor.execute( 'insertMermaidCommand' ) as ModelElement;
- const mermaidItemViewElement = editor.editing.mapper.toViewElement( mermaidItem );
+ return dropdownView;
+ } );
+ }
- view.scrollToTheSelection();
- view.focus();
+ /**
+ * Inserts a mermaid diagram — blank by default, or pre-filled with the given
+ * template source — and moves the focus into its editing view.
+ *
+ * @private
+ */
+ _insertDiagram( options: { source?: string } = {} ) {
+ const editor = this.editor;
+ const view = editor.editing.view;
+
+ const mermaidItem = editor.execute( INSERT_MERMAID_COMMAND, options ) as ModelElement;
+ const mermaidItemViewElement = editor.editing.mapper.toViewElement( mermaidItem );
- if ( mermaidItemViewElement ) {
- const mermaidItemDomElement = view.domConverter.viewToDom( mermaidItemViewElement );
+ view.scrollToTheSelection();
+ view.focus();
- if ( mermaidItemDomElement ) {
- (mermaidItemDomElement.querySelector( '.ck-mermaid__editing-view' ) as HTMLElement)?.focus();
- }
- }
+ if ( mermaidItemViewElement ) {
+ const mermaidItemDomElement = view.domConverter.viewToDom( mermaidItemViewElement );
+
+ if ( mermaidItemDomElement ) {
+ (mermaidItemDomElement.querySelector( '.ck-mermaid__editing-view' ) as HTMLElement)?.focus();
+ }
+ }
+ }
+
+ /**
+ * Builds the dropdown list of diagram templates.
+ *
+ * @private
+ */
+ _getSampleDropdownItems( samples: MermaidSample[] ) {
+ const itemDefinitions = new Collection<ListDropdownItemDefinition>();
+
+ for ( const sample of samples ) {
+ itemDefinitions.add( {
+ type: 'button',
+ model: new ViewModel( {
+ commandParam: sample.content,
+ label: sample.name,
+ role: 'menuitem',
+ withText: true
+ } )
} );
+ }
- return buttonView;
- } );
+ return itemDefinitions;
}
/**
diff --git a/packages/ckeditor5-mermaid/tests/mermaidui.ts b/packages/ckeditor5-mermaid/tests/mermaidui.ts
index 3eaac8588f..7a7fd4ef3b 100644
--- a/packages/ckeditor5-mermaid/tests/mermaidui.ts
+++ b/packages/ckeditor5-mermaid/tests/mermaidui.ts
@@ -1,5 +1,6 @@
-import { ClassicEditor, _setModelData as setModelData } from 'ckeditor5';
+import { ClassicEditor, Paragraph, _getModelData as getModelData, _setModelData as setModelData } from 'ckeditor5';
+import '../src/augmentation.js';
import Mermaid from '../src/mermaid.js';
import MermaidUI from '../src/mermaidui.js';
import { afterEach, beforeEach, describe, it } from 'vitest';
@@ -37,11 +38,11 @@ describe( 'MermaidUI', () => {
} );
it( 'has the base properties', () => {
- const button = editor.ui.componentFactory.create( 'mermaid' );
+ const dropdown = editor.ui.componentFactory.create( 'mermaid' );
- expect( button ).to.have.property( 'label', 'Insert Mermaid diagram' );
- expect( button ).to.have.property( 'icon' );
- expect( button ).to.have.property( 'tooltip', true );
+ expect( dropdown.buttonView ).to.have.property( 'label', 'Insert Mermaid diagram' );
+ expect( dropdown.buttonView ).to.have.property( 'icon' );
+ expect( dropdown.buttonView ).to.have.property( 'tooltip', true );
} );
describe( 'UI components', () => {
@@ -66,25 +67,85 @@ describe( 'MermaidUI', () => {
} );
it( 'should set focus inside textarea of a newly created mermaid', () => {
- const button = editor.ui.componentFactory.create( 'mermaid' );
+ const dropdown = editor.ui.componentFactory.create( 'mermaid' );
- button.fire( 'execute' );
+ dropdown.buttonView.fire( 'execute' );
expect( document.activeElement.tagName ).to.equal( 'TEXTAREA' );
} );
it( 'should not crash if the button is fired inside model.change()', () => {
- const button = editor.ui.componentFactory.create( 'mermaid' );
+ const dropdown = editor.ui.componentFactory.create( 'mermaid' );
setModelData( editor.model, '[]' );
editor.model.change( () => {
- button.fire( 'execute' );
+ 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();
+ } );
+ } );
} );
diff --git a/packages/ckeditor5/src/extra_slash_commands.ts b/packages/ckeditor5/src/extra_slash_commands.ts
index f787152c8a..e4502b660c 100644
--- a/packages/ckeditor5/src/extra_slash_commands.ts
+++ b/packages/ckeditor5/src/extra_slash_commands.ts
@@ -18,23 +18,13 @@ import internalLinkIcon from './icons/trilium.svg?raw';
import noteIcon from './icons/note.svg?raw';
import importMarkdownIcon from './icons/markdown-mark.svg?raw';
import { icons as mathIcons, MathUI } from '@triliumnext/ckeditor5-math';
-import { INSERT_MERMAID_COMMAND } from '@triliumnext/ckeditor5-mermaid';
+import { INSERT_MERMAID_COMMAND, type MermaidSample } from '@triliumnext/ckeditor5-mermaid';
import { BookmarkUI } from "ckeditor5";
import bxBookmark from "boxicons/svg/regular/bx-bookmark.svg?raw";
import bxNetworkChart from "boxicons/svg/regular/bx-network-chart.svg?raw";
type SlashCommandDefinition = SlashCommandEditorConfig["extraCommands"][number];
-/**
- * A Mermaid sample diagram (name + source). Mirrors the client's
- * `NoteContentTemplate`; redeclared here because this package cannot import
- * from the client app.
- */
-export interface MermaidSampleTemplate {
- name: string;
- content: string;
-}
-
/**
* Localizable labels for the `/Mermaid Diagram: …` sample commands. Supplied by
* the client (which owns i18n); the English defaults keep this package standalone.
@@ -50,7 +40,7 @@ const DEFAULT_MERMAID_LABELS: MermaidSampleLabels = {
};
export default function buildExtraCommands(
- mermaidSamples: MermaidSampleTemplate[] = [],
+ mermaidSamples: MermaidSample[] = [],
mermaidLabels: MermaidSampleLabels = DEFAULT_MERMAID_LABELS
): SlashCommandDefinition[] {
return [
@@ -132,7 +122,7 @@ export default function buildExtraCommands(
];
}
-function buildMermaidSampleCommands(samples: MermaidSampleTemplate[], labels: MermaidSampleLabels): SlashCommandDefinition[] {
+function buildMermaidSampleCommands(samples: MermaidSample[], labels: MermaidSampleLabels): SlashCommandDefinition[] {
return samples.map((sample, index) => ({
id: `mermaid-sample-${index}`,
title: labels.title(sample.name),