Format style map

This example shows how to add custom format items and an add bar button that apply CSS classes to text blocks.

Code

<div id="entry-format-styles"></div>
const app = Redactor('#entry-format-styles', {
    formatItems: {
        lead: {
            title: 'Lead',
            icon: '<svg ...>',
            command: 'format.set',
            position: { after: 'text' },
            params: {
                type: 'text',
                classes: 'lead'
            }
        },
        small: {
            title: 'Small',
            icon: '<svg ...>',
            command: 'format.set',
            position: { after: 'lead' },
            params: {
                type: 'text',
                classes: 'small'
            }
        },
        note: {
            title: 'Note',
            icon: '<svg ...>',
            command: 'format.set',
            params: {
                type: 'text',
                classes: 'note'
            }
        }
    },
    addbarItems: {
        note: {
            title: 'Note',
            icon: '<svg ...>',
            command: 'block.insert',
            position: { after: 'text' },
            template: '<p class="note" data-placeholder="Type note here..."></p>'
        }
    },
    activeState: {
        blockRules: { text: [] },
        customRules: {
            text: ({ app }) => {
                const block = app.blocks.getCurrentBlock();
                if (!block?.isType('text')) return false;

                const el = block.getEl();
                const styledClasses = ['lead', 'small', 'note'];

                return Boolean(el) && styledClasses.every((c) => !el.classList.contains(c));
            },
            lead: ({ selection }) => Boolean(selection.getClosest?.('.lead')),
            small: ({ selection }) => Boolean(selection.getClosest?.('.small')),
            note: ({ selection }) => Boolean(selection.getClosest?.('.note'))
        }
    }
});