Categories
Code How-To Web Design

Create a Checklist Plugin for TinyMCE

The TinyMCE editor is a very useful and easy to implement add-on to your web app. For the most part it is free to use and develop with and is licensed with the LGPL license, but some plugins for different editor functions are only available under their Premium Features offering.

If you think the premium plugins give you what you want and you are going to make money from your work, it’d probably make you feel good to buy one of their plans.

Anyway, if you do want to have a play around with TinyMCE plugins and create your own, it’s not that hard.

Firstly, you need to have a basic HTML web page created with an element to use as your editor. This can be a <div> or a <textarea>. Here’s an example HTML page with a simple form and a Textarea element we want to target. We have also included our script tag to load the TinyMCE Javascript library.

<!doctype html>
<html lang='en'>
<head></head>
<body>
<form>
<textarea id='myEditor'></textarea>
<input type='submit' name='submitForm' value='Send'>
</form>
</body>
<script type='text/javascript' src="./tinymce/tinymce.min.js"></script>
</html>

If you load that page in a browser you should see your basic web form, but not much else. We need to define the JS code to tell TinyMCE to attach itself to that Textarea element and provide a configuration.

Add the following to the bottom of your HTML (you could also put it in a separate file and include that script again) above the closing </html> tag.

<script type='text/javascript'>
tinymce.init({
    selector: '#myEditor',
    menubar: false,
    statusbar: false,
    toolbar: 'bold italic underline bullist numlist mychecklist link image code',
    plugins: 'mychecklist code link lists advlist image'
});
</script>

This JS code will define the HTML page element (the one with id=’myEditor’) that TinyMCE will use as the editor. It will also disable the menu bar and the status bar and add some buttons to the toolbar. We have plugins defined that match our buttons. Not all plugins need to have buttons, but in this case they do.

For the checklists plugin to work, it actually uses some of the features from the Lists plugin so we need to ensure we have that.

If you load your web page now, you should see it with the Textarea behaving as an editor panel with the buttons showing above it. Something like this.

So far, so good, you have a functional TinyMCE editor. Now we need to create the plugin to be able to use the checklists feature.

Create a new folder and file in the TinyMCE folder structure under <your_folder>/tinymce/plugins/mychecklist/plugin.min.js

Copy and paste the following code into that new file called plugin.min.js. If you have the developer version of TinyMCE you may need to rename that file to plugin.js. By default the behaviour of TinyMCE changes with the dev version loading unminised files and the production version loading the minified versions.

(function () {
    var mychecklist = (function () {
        'use strict';
        tinymce.PluginManager.add("mychecklist", function (editor, url) {

            /**
             * Plugin behaviour for when the Toolbar or Menu item is selected
             *
             * @private
             */
            function _onAction()
            {
                var content = `<ul class="tox-checklist">
                    <li class="tox-checklist--checked">Task</li>
                    </ul>`;

                editor.insertContent(content);
            }

            // Define the Toolbar button
            editor.ui.registry.addButton('mychecklist', {
                icon: 'checklist',
                tooltip: 'Insert check list',
                onAction: _onAction
            });

            editor.on( 'NodeChange', function ( event ) {
                var node = editor.selection.getNode();
                var parent = node.parentElement;
                if (parent.className === "tox-checklist") {
                    if ((node.nodeName === "LI") && (node.className === "tox-checklist--checked")) {
                        node.className = "";
                    } else if ((node.nodeName === "LI") && (node.className === "")) {
                        node.className = "tox-checklist--checked";
                    }
                }
            });

        });
    }());
})();

That’s a lot to take on in one go so lets break it down a bit.

We define a new TinyMCE plugin and give it a name “mychecklist”. We also pass in “editor” which is an object representing the editor component and content in the page.

The function _onAction is what gets called after we click on the toolbar button. In our example code it’s very simple and only creates a small snippet of HTML that defines a list with one item. Both the <ul> and the <li> have custom CSS classes applied and these are the TinyMCE assets that we’re really leveraging here.

We also create define the toolbar button which has a name that matches what we used in our editor definition at the bottom of the HTML file. It links the button to the _onAction function.

Then we have an editor.on() code block which helps us make the checkboxes toggle between empty and ticked. You may have noticed by now that this checkbox display is a bit of TinyMCE and CSS trickery. They aren’t actually HTML checkbox input elements, they’re just styled list items.

The NodeChange event being used is triggered whenever the user moves their input cursor around in the editor panel. It effectively makes the element it lands in the active element and allows this code block to carry out actions. In our case it is trying to identify that we’re active in one of our check list items. We do this by confirming the parent element is an <ul> with class of tox-checklist, then that the <li> is either showing the checked style or it’s empty and then toggles the class to the other value.

If you reload your web page now you should see the checklist icon in the toolbar of the editor and when you click on it, there will be a chunk of new text added into the editor. If you click on the list item check box or the text label the status of the checkbox will toggle.

Excellent we have a new UI item and function in our TinyMCE toolbar that’ll insert a list item that behaves like a checkbox.

If you want to save this editor content to a database, you’ll need to use the following CSS to render it as normal output in elements outside the TinyMCE editor. The check boxes are SVG images.

This CSS and toolbox icon for a checklist are included in the TinyMCE library by default even though it is obviously used in their premium plugin. We use the JS above to toggle that CSS on or off.

.tox-checklist>li:not(.tox-checklist--hidden) {
    list-style: none;
    margin: .25em 0;
}
.tox-checklist>li:not(.tox-checklist--hidden)::before {
    background-image:url("data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2216%22%20height%3D%2216%22%20viewBox%3D%220%200%2016%2016%22%3E%3Cg%20id%3D%22checklist-unchecked%22%20fill%3D%22none%22%20fill-rule%3D%22evenodd%22%3E%3Crect%20id%3D%22Rectangle%22%20width%3D%2215%22%20height%3D%2215%22%20x%3D%22.5%22%20y%3D%22.5%22%20fill-rule%3D%22nonzero%22%20stroke%3D%22%234C4C4C%22%20rx%3D%222%22%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E%0A");
    background-size:100%;
    content:'';
    cursor:pointer;
    height:1em;
    margin-left:-1.5em;
    margin-top:.125em;
    position:absolute;
    width:1em;
}
.tox-checklist li:not(.tox-checklist--hidden).tox-checklist--checked::before {
    background-image:url("data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2216%22%20height%3D%2216%22%20viewBox%3D%220%200%2016%2016%22%3E%3Cg%20id%3D%22checklist-checked%22%20fill%3D%22none%22%20fill-rule%3D%22evenodd%22%3E%3Crect%20id%3D%22Rectangle%22%20width%3D%2216%22%20height%3D%2216%22%20fill%3D%22%234099FF%22%20fill-rule%3D%22nonzero%22%20rx%3D%222%22%2F%3E%3Cpath%20id%3D%22Path%22%20fill%3D%22%23FFF%22%20fill-rule%3D%22nonzero%22%20d%3D%22M11.5703186%2C3.14417309%20C11.8516238%2C2.73724603%2012.4164781%2C2.62829933%2012.83558%2C2.89774797%20C13.260121%2C3.17069355%2013.3759736%2C3.72932262%2013.0909105%2C4.14168582%20L7.7580587%2C11.8560195%20C7.43776896%2C12.3193404%206.76483983%2C12.3852142%206.35607322%2C11.9948725%20L3.02491697%2C8.8138662%20C2.66090143%2C8.46625845%202.65798871%2C7.89594698%203.01850234%2C7.54483354%20C3.373942%2C7.19866177%203.94940006%2C7.19592841%204.30829608%2C7.5386474%20L6.85276923%2C9.9684299%20L11.5703186%2C3.14417309%20Z%22%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E%0A")
}

To take this a few steps further there are some tidy up actions needed. Consider these optional extras that I may write up at a later time.

  • Notice when the checklist item is selected, the wrong toolbar item is highlighted in the editor.
  • If you’re displaying the editor content as HTML outside the editor (i.e. you’ve saved it for display), you won’t be able to toggle the checkbox status.