# UI Components

> Editor42 UI Components API — register custom toolbar buttons, menu items, context menus, sidebars, and dialogs for the WYSIWYG editor.

Source: https://editor42.com/api/ui-components  
Every page of editor42.com has a Markdown copy at its URL + `.md` (`index.md` after a URL that ends in `/`); all of them are in one file: https://editor42.com/llms-full.txt

The UI Registry API lets you register custom toolbar buttons, menu items, context menus, autocompleters, sidebars, and other UI components. All methods are available on `editor.ui.registry` inside the `setup` callback.

```js
editor42.init({
  selector: 'textarea',
  setup: (editor) => {
    editor.ui.registry.addButton('mybutton', {
      text: 'My Button',
      onAction: () => editor.insertContent('Hello!')
    });
  },
  toolbar: 'undo redo | mybutton'
});
```

## Toolbar Buttons

### Basic Button

Registers a toolbar button that executes a command when clicked.

```js
editor.ui.registry.addButton(name, spec)
```

| Property | Type | Description |
|---|---|---|
| `text` | string? | Button label text. |
| `icon` | string? | Icon name (registered or built-in). |
| `tooltip` | string? | Tooltip shown on hover. |
| `enabled` | boolean? | Initial enabled state. Defaults to `true`. |
| `onSetup` | function? | Called when the button is rendered. Return a teardown function. |
| `onAction` | function | Called when the button is clicked. |

```js
editor.ui.registry.addButton('insertdate', {
  icon: 'insert-time',
  tooltip: 'Insert date',
  onAction: () => {
    editor.insertContent(new Date().toDateString());
  }
});
```

### Toggle Button

Registers a toggle button whose state can be switched on/off. Useful for format buttons like bold or italic that reflect the current selection state.

```js
editor.ui.registry.addToggleButton(name, spec)
```

| Property | Type | Description |
|---|---|---|
| `text` | string? | Button label text. |
| `icon` | string? | Icon name. |
| `tooltip` | string? | Tooltip shown on hover. |
| `enabled` | boolean? | Initial enabled state. |
| `active` | boolean? | Initial toggle state. Defaults to `false`. |
| `onSetup` | function? | Called when the button is rendered. Use `api.setActive(state)` to update the toggle. |
| `onAction` | function | Called when the button is clicked. Receives `api` with `isActive()` and `setActive()`. |

```js
editor.ui.registry.addToggleButton('customformat', {
  icon: 'highlight-bg-color',
  tooltip: 'Toggle highlight',
  onAction: (api) => {
    editor.execCommand('editor42ToggleFormat', false, 'hilitecolor');
  },
  onSetup: (api) => {
    const changed = editor.formatter.formatChanged('hilitecolor', (state) => {
      api.setActive(state);
    });
    return changed;
  }
});
```

### Menu Button

Registers a toolbar button that opens a dropdown menu when clicked.

```js
editor.ui.registry.addMenuButton(name, spec)
```

| Property | Type | Description |
|---|---|---|
| `text` | string? | Button label text. |
| `icon` | string? | Icon name. |
| `tooltip` | string? | Tooltip shown on hover. |
| `fetch` | function | `(callback) => void` — call `callback` with an array of menu items. |
| `onSetup` | function? | Called when the button is rendered. |

```js
editor.ui.registry.addMenuButton('myinsert', {
  text: 'Insert',
  fetch: (callback) => {
    const items = [
      { type: 'menuitem', text: 'Horizontal rule', onAction: () => editor.insertContent('<hr>') },
      { type: 'menuitem', text: 'Page break', onAction: () => editor.insertContent('<!-- pagebreak -->') }
    ];
    callback(items);
  }
});
```

### Split Button

Registers a split button — the main area executes a default action, and the arrow opens a dropdown menu. Used by the advlist plugin for list styles.

```js
editor.ui.registry.addSplitButton(name, spec)
```

| Property | Type | Description |
|---|---|---|
| `text` | string? | Button label text. |
| `icon` | string? | Icon name. |
| `tooltip` | string? | Tooltip shown on hover. |
| `onAction` | function | Called when the main button area is clicked. |
| `onItemAction` | function | Called when a dropdown item is selected. Receives the item value. |
| `fetch` | function | `(callback) => void` — call `callback` with an array of choice items. |
| `onSetup` | function? | Called when the button is rendered. |

```js
editor.ui.registry.addSplitButton('mycolors', {
  text: 'Color',
  onAction: () => {
    editor.execCommand('ForeColor', false, '#000000');
  },
  onItemAction: (_api, value) => {
    editor.execCommand('ForeColor', false, value);
  },
  fetch: (callback) => {
    callback([
      { type: 'choiceitem', text: 'Red', value: '#FF0000' },
      { type: 'choiceitem', text: 'Green', value: '#00FF00' },
      { type: 'choiceitem', text: 'Blue', value: '#0000FF' }
    ]);
  }
});
```

### Group Toolbar Button

Registers a button that opens a floating toolbar containing other buttons when clicked. Only available when `toolbar_mode` is set to `floating`.

```js
editor.ui.registry.addGroupToolbarButton(name, spec)
```

| Property | Type | Description |
|---|---|---|
| `text` | string? | Button label text. |
| `icon` | string? | Icon name. |
| `tooltip` | string? | Tooltip shown on hover. |
| `items` | string | Space-separated list of toolbar button names. |
| `onSetup` | function? | Called when the button is rendered. |

```js
editor.ui.registry.addGroupToolbarButton('formatting', {
  icon: 'more-drawer',
  tooltip: 'Formatting',
  items: 'bold italic underline | forecolor backcolor'
});
```

## Menu Items

### Basic Menu Item

Registers a menu item that executes a command when clicked.

```js
editor.ui.registry.addMenuItem(name, spec)
```

| Property | Type | Description |
|---|---|---|
| `text` | string? | Menu item label. |
| `icon` | string? | Icon name. |
| `shortcut` | string? | Keyboard shortcut hint displayed beside the label. |
| `enabled` | boolean? | Initial enabled state. |
| `onSetup` | function? | Called when the item is rendered. |
| `onAction` | function | Called when the item is clicked. |

```js
editor.ui.registry.addMenuItem('inserthr', {
  text: 'Horizontal rule',
  icon: 'horizontal-rule',
  onAction: () => editor.insertContent('<hr>')
});
```

### Nested Menu Item

Registers a menu item that reveals a submenu on hover or click.

```js
editor.ui.registry.addNestedMenuItem(name, spec)
```

| Property | Type | Description |
|---|---|---|
| `text` | string? | Menu item label. |
| `icon` | string? | Icon name. |
| `getSubmenuItems` | function | Returns a string of registered item names or an array of `MenuItemSpec` objects. |
| `onSetup` | function? | Called when the item is rendered. |

```js
editor.ui.registry.addNestedMenuItem('mysubmenu', {
  text: 'Insert template',
  getSubmenuItems: () => [
    { type: 'menuitem', text: 'Header', onAction: () => editor.insertContent('<h2>Header</h2>') },
    { type: 'menuitem', text: 'Footer', onAction: () => editor.insertContent('<footer>Footer</footer>') }
  ]
});
```

### Toggle Menu Item

Registers a menu item with a checkmark that toggles state on click. Useful for boolean settings like "Paste as text".

```js
editor.ui.registry.addToggleMenuItem(name, spec)
```

| Property | Type | Description |
|---|---|---|
| `text` | string? | Menu item label. |
| `icon` | string? | Icon name. |
| `active` | boolean? | Initial toggle state. |
| `onSetup` | function? | Called when the item is rendered. Use `api.setActive(state)` to update the checkmark. |
| `onAction` | function | Called when the item is clicked. |

```js
editor.ui.registry.addToggleMenuItem('darkmode', {
  text: 'Dark mode',
  onAction: (api) => {
    const newState = !api.isActive();
    api.setActive(newState);
    editor.getBody().classList.toggle('dark', newState);
  }
});
```

## Context UI

### Context Menu

Registers a context menu section that appears on right-click when a content condition is met. Add the registered name to the `contextmenu` option.

```js
editor.ui.registry.addContextMenu(name, spec)
```

| Property | Type | Description |
|---|---|---|
| `update` | function | \`(element) => string |

```js
editor.ui.registry.addContextMenu('mycontext', {
  update: (element) => {
    return element.nodeName === 'IMG' ? 'link image' : '';
  }
});
```

```js
editor42.init({
  selector: 'textarea',
  contextmenu: 'mycontext'
});
```

### Context Toolbar

Registers a floating toolbar that appears when a content predicate matches. For example, the quickbars plugin uses this to show a toolbar when the cursor is on an image.

```js
editor.ui.registry.addContextToolbar(name, spec)
```

| Property | Type | Description |
|---|---|---|
| `predicate` | function | `(node) => boolean` — return `true` to show the toolbar. |
| `items` | string | Space-separated list of toolbar button names. |
| `position` | string? | Positioning: `selection`, `node`, or `line`. |
| `scope` | string? | `node` (default) or `editor`. |

```js
editor.ui.registry.addContextToolbar('imagetools', {
  predicate: (node) => node.nodeName === 'IMG',
  items: 'alignleft aligncenter alignright',
  position: 'node'
});
```

### Context Form

Registers a contextual form with an input field that appears when a content predicate matches. Used by the link plugin for inline URL editing when `link_context_toolbar: true`.

```js
editor.ui.registry.addContextForm(name, spec)
```

| Property | Type | Description |
|---|---|---|
| `predicate` | function | `(node) => boolean` — return `true` to show the form. |
| `initValue` | function | Returns the initial value for the input field. |
| `commands` | ContextFormButtonSpec[] | Action buttons displayed beside the input. |
| `position` | string? | Positioning: `selection`, `node`, or `line`. |
| `scope` | string? | `node` (default) or `editor`. |

```js
editor.ui.registry.addContextForm('quicklink', {
  predicate: (node) => node.nodeName === 'A',
  initValue: () => {
    const node = editor.selection.getNode();
    return node.nodeName === 'A' ? node.href : '';
  },
  commands: [
    {
      type: 'contextformbutton',
      icon: 'checkmark',
      tooltip: 'Apply',
      primary: true,
      onAction: (formApi) => {
        const value = formApi.getValue();
        editor.execCommand('editor42InsertLink', false, { href: value });
        formApi.hide();
      }
    },
    {
      type: 'contextformbutton',
      icon: 'remove',
      tooltip: 'Remove',
      onAction: (formApi) => {
        editor.execCommand('Unlink');
        formApi.hide();
      }
    }
  ]
});
```

## Autocompleters

Registers an autocompleter triggered by a character pattern. When the user types the trigger string followed by text, a dropdown appears with matching options. Used by the emoticons plugin (triggered by `:`) and the charmap plugin.

```js
editor.ui.registry.addAutocompleter(name, spec)
```

| Property | Type | Description |
|---|---|---|
| `trigger` | string | Character(s) that activate the autocompleter (e.g., `:`, `/`). |
| `minChars` | number? | Minimum characters after the trigger before fetching. Defaults to `1`. |
| `fetch` | function | `(pattern, maxResults, fetchOptions) => Promise` — returns a promise resolving to an array of autocomplete items. |
| `onAction` | function | `(autocompleterApi, range, value) => void` — called when an item is selected. |
| `columns` | number/string? | Number of columns for grid layout. Use `auto` or `1` for a list. |

```js
editor.ui.registry.addAutocompleter('mentions', {
  trigger: '@',
  minChars: 1,
  fetch: (pattern) => {
    const users = [
      { text: 'Alice', value: 'alice' },
      { text: 'Bob', value: 'bob' },
      { text: 'Carol', value: 'carol' }
    ];
    const filtered = users.filter((u) => u.text.toLowerCase().includes(pattern.toLowerCase()));
    return Promise.resolve(
      filtered.map((u) => ({
        type: 'autocompleteitem',
        value: u.value,
        text: u.text
      }))
    );
  },
  onAction: (api, rng, value) => {
    editor.selection.setRng(rng);
    editor.insertContent(`<span class="mention">@${value}</span>&nbsp;`);
    api.hide();
  }
});
```

## Icons

Registers a custom SVG icon that can be referenced by name in any UI component.

```js
editor.ui.registry.addIcon(name, svgData)
```

| Property | Type | Description |
|---|---|---|
| `name` | string | Unique icon name to reference in buttons and menu items. |
| `svgData` | string | SVG markup string. |

```js
editor.ui.registry.addIcon('custom-star', '<svg width="24" height="24"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87L18.18 22 12 18.27 5.82 22 7 14.14 2 9.27l6.91-1.01L12 2z"/></svg>');

editor.ui.registry.addButton('star', {
  icon: 'custom-star',
  tooltip: 'Insert star',
  onAction: () => editor.insertContent('&#9733;')
});
```

## Sidebars and Views

### Sidebar

Registers a sidebar panel attached to the right side of the editor. A toggle toolbar button is created automatically. The sidebar can also be controlled via the `ToggleSidebar` command.

```js
editor.ui.registry.addSidebar(name, spec)
```

| Property | Type | Description |
|---|---|---|
| `tooltip` | string? | Tooltip for the auto-generated toolbar toggle button. |
| `icon` | string? | Icon for the toggle button. |
| `onSetup` | function? | Called when the sidebar is first rendered. Receives `api`. |
| `onShow` | function? | Called each time the sidebar becomes visible. Receives `api` with `element()`. |
| `onHide` | function? | Called each time the sidebar is hidden. |

```js
editor.ui.registry.addSidebar('comments', {
  tooltip: 'Comments',
  icon: 'comment',
  onShow: (api) => {
    const el = api.element();
    el.innerHTML = '<div style="padding: 10px">No comments yet.</div>';
  },
  onHide: () => {}
});
```

Toggle the sidebar programmatically:

```js
editor.execCommand('ToggleSidebar', false, 'comments');
```

### View

Registers a view that replaces the editor content area when toggled on. Useful for alternate editing modes like source code views. Controlled via the `ToggleView` command.

```js
editor.ui.registry.addView(name, spec)
```

| Property | Type | Description |
|---|---|---|
| `buttons` | ViewButtonSpec[] | Action buttons shown in the view header. |
| `onShow` | function | `(api) => void` — called when the view becomes visible. Use `api.getContainer()` to access the view DOM. |
| `onHide` | function | `(api) => void` — called when the view is hidden. |

```js
editor.ui.registry.addView('codeview', {
  buttons: [
    {
      type: 'button',
      text: 'Back to editor',
      buttonType: 'primary',
      onAction: () => editor.execCommand('ToggleView', false, 'codeview')
    }
  ],
  onShow: (api) => {
    const container = api.getContainer();
    const textarea = document.createElement('textarea');
    textarea.style.width = '100%';
    textarea.style.height = '100%';
    textarea.value = editor.getContent();
    container.appendChild(textarea);
  },
  onHide: (api) => {
    const textarea = api.getContainer().querySelector('textarea');
    if (textarea) {
      editor.setContent(textarea.value);
    }
  }
});
```

Toggle the view programmatically:

```js
editor.execCommand('ToggleView', false, 'codeview');
```

## Built-in Toolbar Buttons

These buttons are registered by default and can be used in the `toolbar` option without additional setup.

### Format toggle buttons

| Button | Description |
|---|---|
| `bold` | Toggles bold formatting. |
| `italic` | Toggles italic formatting. |
| `underline` | Toggles underline formatting. |
| `strikethrough` | Toggles strikethrough formatting. |
| `subscript` | Toggles subscript formatting. |
| `superscript` | Toggles superscript formatting. |
| `h1` | Toggles heading level 1. |
| `h2` | Toggles heading level 2. |
| `h3` | Toggles heading level 3. |
| `h4` | Toggles heading level 4. |
| `h5` | Toggles heading level 5. |
| `h6` | Toggles heading level 6. |
| `blockquote` | Toggles blockquote formatting. |

### Command buttons

| Button | Description |
|---|---|
| `copy` | Copies the selection to the clipboard. |
| `cut` | Cuts the selection to the clipboard. |
| `paste` | Pastes from the clipboard. |
| `selectall` | Selects all content. |
| `newdocument` | Clears the editor content. |
| `print` | Opens the browser print dialog. |
| `removeformat` | Removes formatting from the selection. |
| `remove` | Deletes the selected content. |
| `hr` | Inserts a horizontal rule. |
| `help` | Opens the help dialog. |

### Other core buttons

| Button | Description |
|---|---|
| `undo` | Undoes the last action. |
| `redo` | Redoes the last undone action. |
| `outdent` | Decreases indentation. |
| `indent` | Increases indentation. |
| `alignleft` | Aligns content to the left. |
| `aligncenter` | Centers content. |
| `alignright` | Aligns content to the right. |
| `alignjustify` | Justifies content. |
| `alignnone` | Removes alignment. |
| `pastetext` | Toggles paste-as-plain-text mode. |
| `visualaid` | Toggles visual aids for invisible elements. |

### Bespoke controls

| Button | Type | Description |
|---|---|---|
| `fontfamily` | Nested menu | Font family selector. |
| `fontsize` | Nested menu | Font size selector. |
| `blocks` | Nested menu | Block format selector (paragraph, headings, etc.). |
| `align` | Nested menu | Text alignment selector. |
| `styles` | Nested menu | Custom styles selector. |
| `forecolor` | Split button | Text color picker. |
| `hilitecolor` | Split button | Highlight color picker. |
| `backcolor` | Split button | Background color picker. |

## Built-in Menu Items

These items are registered by default and can be used in the `menu` option.

| Menu Item | Description |
|---|---|
| `newdocument` | Clears the editor content. |
| `undo` | Undoes the last action. |
| `redo` | Redoes the last undone action. |
| `copy` | Copies the selection. |
| `cut` | Cuts the selection. |
| `paste` | Pastes from the clipboard. |
| `selectall` | Selects all content. |
| `print` | Opens the print dialog. |
| `bold` | Toggles bold. |
| `italic` | Toggles italic. |
| `underline` | Toggles underline. |
| `strikethrough` | Toggles strikethrough. |
| `subscript` | Toggles subscript. |
| `superscript` | Toggles superscript. |
| `codeformat` | Toggles inline code formatting. |
| `removeformat` | Removes formatting. |
| `hr` | Inserts a horizontal rule. |
| `align` | Text alignment submenu. |
| `blocks` | Block format submenu. |
| `fontfamily` | Font family submenu. |
| `fontsize` | Font size submenu. |
| `styles` | Custom styles submenu. |
| `pastetext` | Toggles paste-as-plain-text. |
| `visualaid` | Toggles visual aids. |
