javascriptckeditordropdownckeditor5

Customizing dropdown button for CKeditor 5


Managed to add a custom dropdown button to the toolbar:
enter image description here But I don't know how to add a label or an icon to it.

Here's my code:

import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
import Model from '@ckeditor/ckeditor5-ui/src/model';

import { createDropdown, addListToDropdown } from '@ckeditor/ckeditor5-ui/src/dropdown/utils';
import Collection from '@ckeditor/ckeditor5-utils/src/collection';

import imageIcon from '@ckeditor/ckeditor5-core/theme/icons/image.svg';

export default class ImageDropdown extends Plugin {
    
    static get pluginName() {
        return 'ImageDropdown';
    }
    
    init() {
        const editor = this.editor;
        const t = editor.t;
        const defaultTitle = t('Add image');
        const dropdownTooltip = t('Image');

        // Register UI component
        editor.ui.componentFactory.add('imageDropdown', locale => {

            const dropdownView = createDropdown( locale );

            dropdownView.set({
                label: 'Image',
                tooltip: true
            });
            dropdownView.buttonView.set( {
				isOn: false,
				withText: true,
				tooltip: dropdownTooltip
            });
            dropdownView.extendTemplate( {
				attributes: {
					class: [
						'ck-image-dropdown'
					]
				}
			});

            // The collection of the list items.
            const items = new Collection();

            items.add( {
                type: 'button',
                model: new Model( {
                    label: 'Uppload image',
                    icon: imageIcon
                })
            });

            items.add( {
                type: 'button',
                model: new Model( {
                    label: 'Image URL',
                    icon: imageIcon
                })
            });

            // Create a dropdown with a list inside the panel.
            addListToDropdown( dropdownView, items );

            return dropdownView;
        });
    }
}


Solution

  • Setting labels, icons etc. for a dropdown button should take place on the dropdown's view instance:

    dropdownView.buttonView.set({
        label: 'some-label',
        icon: 'path/to/some/icon'
        tooltip: true
    });
    

    Note that these properties are observable and can be dynamically evaluated based on some state using the ObservableMixin#bind function.

    See an example here: https://github.com/ckeditor/ckeditor5-alignment/blob/894745ecb1e8bd94286b4089eb16079034eb8a0b/src/alignmentui.js#L107-L124