The posting related to tinyMCE is receiving higher views than expected, so I will continue to write follow-up posts. This post explains how to create custom toolbar buttons and dialogs in tinyMCE.
Creating Custom Toolbar Buttons
To create a button, use the addButton function. Since buttons are typically added during the setup phase, you can set it up within the setup function. A condensed version of the example from the official documentation is as follows:
tinymce.init({
setup: (editor) => {
editor.ui.registry.addButton('customInsertButton', {
text: 'My Button',
onAction: (_) => editor.insertContent(` <strong>It's my button!</strong> `)
});
});
You can define the action when the button is clicked in the onAction option of this example. Since we need to create a dialog for this post, let's first create the dialog and then connect a function to open the dialog in onAction.
Creating Custom Dialogs
In tinyMCE, dialogs are defined as objects. Quoting from the official documentation, an example would be as follows:
const dialogConfig = {
title: 'Pet Name Machine',
body: {
type: 'panel',
items: [
{
type: 'input',
name: 'catdata',
label: 'enter the name of a cat'
},
{
type: 'checkbox',
name: 'isdog',
label: 'tick if cat is actually a dog'
}
]
},
buttons: [
{
type: 'cancel',
name: 'closeButton',
text: 'Cancel'
},
{
type: 'submit',
name: 'submitButton',
text: 'Do Cat Thing',
buttonType: 'primary'
}
],
initialData: {
catdata: 'initial Cat',
isdog: false
},
onSubmit: (api) => {
const data = api.getData();
const pet = data.isdog ? 'dog' : 'cat';
tinymce.activeEditor.execCommand('mceInsertContent', false, `<p>My ${pet}'s name is: <strong>${data.catdata}</strong></p>`);
api.close();
}
};
For detailed information on each option such as title, body, button, initialData, and onSubmit, please refer to the official documentation link. Once you've created the dialog object, you can add a function to open the dialog in onAction as described earlier. The function to open the dialog is editor.windowManager.open.
tinymce.init({
setup: (editor) => {
editor.ui.registry.addButton('customInsertButton', {
text: 'My Button',
onAction: (_) => editor.windowManager.open({...dialogConfig})
});
});