---
title: "Editor"
description: "Редактор форматированного текста на базе TipTap с поддержкой Markdown, HTML и JSON."
canonical_url: "https://b24-ui.bx-shef.by/docs/components/editor"
---
# Editor

> Редактор форматированного текста на базе TipTap с поддержкой Markdown, HTML и JSON.

## Использование

Компонент Editor — мощный редактор форматированного текста на базе [TipTap](https://tiptap.dev/). Он поддерживает несколько форматов содержимого (JSON, HTML, Markdown), настраиваемые панели инструментов, перетаскивание блоков, слэш-команды, упоминания, выбор эмодзи и расширяемую архитектуру для своих возможностей.

```vue [EditorExample.vue]
<script setup lang="ts">
import type { EditorCustomHandlers, EditorToolbarItem, EditorSuggestionMenuItem, EditorMentionMenuItem, EditorEmojiMenuItem, DropdownMenuItem } from '@bxshefby/b24ui-nuxt'
import type { Editor, JSONContent } from '@tiptap/vue-3'
import { upperFirst } from 'scule'
import { mapEditorItems } from '@bxshefby/b24ui-nuxt/utils/editor'
import { Emoji, gitHubEmojis } from '@tiptap/extension-emoji'
import { TextAlign } from '@tiptap/extension-text-align'
import { CodeBlockShiki } from 'tiptap-extension-code-block-shiki'
import { ImageUpload } from './EditorImageUploadExtension'
import EditorLinkPopover from './EditorLinkPopover.vue'
import UndoIcon from '@bitrix24/b24icons-vue/outline/UndoIcon'
import RedoIcon from '@bitrix24/b24icons-vue/outline/RedoIcon'
import HeaderIcon from '@bitrix24/b24icons-vue/editor/HeaderIcon'
import BulletedListIcon from '@bitrix24/b24icons-vue/outline/BulletedListIcon'
import NumberedListIcon from '@bitrix24/b24icons-vue/outline/NumberedListIcon'
import QuoteIcon from '@bitrix24/b24icons-vue/outline/QuoteIcon'
import CodeIcon from '@bitrix24/b24icons-vue/common-service/CodeIcon'
import BoldIcon from '@bitrix24/b24icons-vue/outline/BoldIcon'
import ItalicIcon from '@bitrix24/b24icons-vue/outline/ItalicIcon'
import UnderlineIcon from '@bitrix24/b24icons-vue/outline/UnderlineIcon'
import StrikethroughIcon from '@bitrix24/b24icons-vue/outline/StrikethroughIcon'
import DeveloperResourcesIcon from '@bitrix24/b24icons-vue/outline/DeveloperResourcesIcon'
import LinkIcon from '@bitrix24/b24icons-vue/outline/LinkIcon'
import ImageIcon from '@bitrix24/b24icons-vue/outline/ImageIcon'
import AlignLeftIcon from '@bitrix24/b24icons-vue/outline/AlignLeftIcon'
import AlignCenterIcon from '@bitrix24/b24icons-vue/outline/AlignCenterIcon'
import AlignRightIcon from '@bitrix24/b24icons-vue/outline/AlignRightIcon'
import AlignJustifyIcon from '@bitrix24/b24icons-vue/outline/AlignJustifyIcon'
import TextIcon from '@bitrix24/b24icons-vue/outline/TextIcon'
import DownloadIcon from '@bitrix24/b24icons-vue/outline/DownloadIcon'
import RefreshIcon from '@bitrix24/b24icons-vue/outline/RefreshIcon'
import TrashcanIcon from '@bitrix24/b24icons-vue/outline/TrashcanIcon'
import RepeatIcon from '@bitrix24/b24icons-vue/outline/RepeatIcon'
import ResumeIcon from '@bitrix24/b24icons-vue/outline/ResumeIcon'
import CopyIcon from '@bitrix24/b24icons-vue/outline/CopyIcon'
import CopyFileIcon from '@bitrix24/b24icons-vue/crm/CopyFileIcon'
import ArrowTopLIcon from '@bitrix24/b24icons-vue/outline/ArrowTopLIcon'
import ArrowDownLIcon from '@bitrix24/b24icons-vue/outline/ArrowDownLIcon'
import MentionIcon from '@bitrix24/b24icons-vue/outline/MentionIcon'
import SmileIcon from '@bitrix24/b24icons-vue/outline/SmileIcon'
import HrIcon from '@bitrix24/b24icons-vue/editor/HrIcon'
import PlusLIcon from '@bitrix24/b24icons-vue/outline/PlusLIcon'
import DragLIcon from '@bitrix24/b24icons-vue/outline/DragLIcon'

const value = ref(`# Создание современных интерфейсов с Bitrix24 UI

Добро пожаловать в **Bitrix24 UI Editor** — мощный редактор форматированного текста на основе [TipTap](https://tiptap.dev). Он сочетает *гибкость* и простоту использования, поэтому создавать контент легко.

![Placeholder](https://bitrix24.github.io/b24ui/assets/demo/b24rich_new.png)

## Богатые возможности форматирования

Редактор поддерживает всё привычное форматирование текста: **жирный**, *курсив*, <u>подчёркнутый</u>, ~~зачёркнутый~~ и \`строчный код\`. Их можно сочетать, например **_жирный курсив_**.

### Интерактивные возможности

Попробуйте эти возможности:

- **Всплывающее меню** — выделите текст, чтобы появились параметры форматирования
- **Слэш-команды** — введите \`/\` для быстрого доступа к блокам и форматированию
- **Упоминания** — используйте \`@\`, чтобы отметить людей или сущности
- **Выбор эмодзи** — введите \`:\` и название эмодзи, например :smile:
- **Перетаскивание** — наведите курсор на блок, чтобы увидеть ручку перетаскивания

> **Совет:** используйте сочетания клавиш, например Cmd/Ctrl + B для жирного, Cmd/Ctrl + I для курсива и другие!

### Расширенные возможности

1. **Собственные расширения** — добавляйте свои расширения TipTap без лишних усилий
2. **Разные типы содержимого** — поддержка JSON, HTML и Markdown
3. **Настраиваемые панели инструментов** — раскладки fixed, bubble и floating
4. **Интеграция с темами** — полностью оформлен системой тем Bitrix24 UI

#### Блоки кода

Подходит для технической документации:

\`\`\`vue
<template>
  <B24Editor v-model="value" content-type="markdown" />
</template>
\`\`\`

---

Строите ли вы блог, сайт документации или систему управления контентом, Bitrix24 UI Editor даёт всё необходимое для профессиональной работы с текстом. Загляните на [bitrix24.github.io/b24ui](https://bitrix24.github.io/b24ui/), чтобы познакомиться с другими компонентами.`)

const customHandlers = {
  imageUpload: {
    canExecute: (editor: Editor) => editor.can().insertContent({ type: 'imageUpload' }),
    execute: (editor: Editor) => editor.chain().focus().insertContent({ type: 'imageUpload' }),
    isActive: (editor: Editor) => editor.isActive('imageUpload'),
    isDisabled: undefined
  }
} satisfies EditorCustomHandlers

const fixedToolbarItems = [
  [
    {
      kind: 'undo',
      icon: UndoIcon,
      tooltip: { text: 'Отменить' }
    },
    {
      kind: 'redo',
      icon: RedoIcon,
      tooltip: { text: 'Повторить' }
    }
  ],
  [
    {
      icon: HeaderIcon,
      tooltip: { text: 'Заголовки' },
      content: { align: 'start' },
      items: [
        {
          kind: 'heading',
          level: 1,
          label: 'Заголовок 1'
        },
        {
          kind: 'heading',
          level: 2,
          label: 'Заголовок 2'
        }, {
          kind: 'heading',
          level: 3,
          label: 'Заголовок 3'
        }, {
          kind: 'heading',
          level: 4,
          label: 'Заголовок 4'
        }
      ]
    },
    {
      icon: BulletedListIcon,
      tooltip: { text: 'Списки' },
      content: { align: 'start' },
      items: [
        {
          kind: 'bulletList',
          icon: BulletedListIcon,
          label: 'Маркированный список'
        },
        {
          kind: 'orderedList',
          icon: NumberedListIcon,
          label: 'Нумерованный список'
        }
      ]
    },
    {
      kind: 'blockquote',
      icon: QuoteIcon,
      tooltip: { text: 'Цитата' }
    },
    {
      kind: 'codeBlock',
      icon: CodeIcon,
      tooltip: { text: 'Блок кода' }
    }
  ],
  [
    {
      kind: 'mark',
      mark: 'bold',
      icon: BoldIcon,
      tooltip: { text: 'Жирный' }
    },
    {
      kind: 'mark',
      mark: 'italic',
      icon: ItalicIcon,
      tooltip: { text: 'Курсив' }
    },
    {
      kind: 'mark',
      mark: 'underline',
      icon: UnderlineIcon,
      tooltip: { text: 'Подчёркнутый' }
    },
    {
      kind: 'mark',
      mark: 'strike',
      icon: StrikethroughIcon,
      tooltip: { text: 'Зачёркнутый' }
    },
    {
      kind: 'mark',
      mark: 'code',
      icon: DeveloperResourcesIcon,
      tooltip: { text: 'Код' }
    }
  ],
  [
    {
      slot: 'link' as const,
      icon: LinkIcon
    },
    {
      kind: 'imageUpload',
      icon: ImageIcon,
      tooltip: { text: 'Изображение' }
    }
  ],
  [
    {
      icon: AlignJustifyIcon,
      tooltip: { text: 'Выравнивание текста' },
      content: { align: 'end' },
      items: [
        {
          kind: 'textAlign',
          align: 'left',
          icon: AlignLeftIcon,
          label: 'По левому краю'
        },
        {
          kind: 'textAlign',
          align: 'center',
          icon: AlignCenterIcon,
          label: 'По центру'
        },
        {
          kind: 'textAlign',
          align: 'right',
          icon: AlignRightIcon,
          label: 'По правому краю'
        },
        {
          kind: 'textAlign',
          align: 'justify',
          icon: AlignJustifyIcon,
          label: 'По ширине'
        }
      ]
    }
  ]
] satisfies EditorToolbarItem<typeof customHandlers>[][]

const bubbleToolbarItems = computed(() => [
  [
    {
      label: 'Преобразовать в',
      useDropdown: true,
      activeColor: 'air-secondary-no-accent',
      tooltip: { text: 'Преобразовать в' },
      content: { align: 'start' },
      b24ui: { label: 'text-xs' },
      items: [
        {
          type: 'label',
          label: 'Преобразовать в'
        },
        {
          kind: 'paragraph',
          label: 'Абзац',
          icon: TextIcon
        },
        {
          kind: 'heading',
          level: 1,
          label: 'Заголовок 1'
        },
        {
          kind: 'heading',
          level: 2,
          label: 'Заголовок 2'
        },
        {
          kind: 'heading',
          level: 3,
          label: 'Заголовок 3'
        },
        {
          kind: 'heading',
          level: 4,
          label: 'Заголовок 4'
        },
        {
          kind: 'bulletList',
          icon: BulletedListIcon,
          label: 'Маркированный список'
        },
        {
          kind: 'orderedList',
          icon: NumberedListIcon,
          label: 'Нумерованный список'
        },
        {
          kind: 'blockquote',
          icon: QuoteIcon,
          label: 'Цитата'
        },
        {
          kind: 'codeBlock',
          icon: CodeIcon,
          label: 'Блок кода'
        }
      ]
    }
  ],
  [
    {
      kind: 'mark',
      mark: 'bold',
      icon: BoldIcon,
      tooltip: { text: 'Жирный' }
    }, {
      kind: 'mark',
      mark: 'italic',
      icon: ItalicIcon,
      tooltip: { text: 'Курсив' }
    }, {
      kind: 'mark',
      mark: 'underline',
      icon: UnderlineIcon,
      tooltip: { text: 'Подчёркнутый' }
    }, {
      kind: 'mark',
      mark: 'strike',
      icon: StrikethroughIcon,
      tooltip: { text: 'Зачёркнутый' }
    },
    {
      kind: 'mark',
      mark: 'code',
      icon: DeveloperResourcesIcon,
      tooltip: { text: 'Код' }
    }
  ],
  [
    {
      slot: 'link' as const,
      icon: LinkIcon
    },
    {
      kind: 'imageUpload',
      icon: ImageIcon,
      tooltip: { text: 'Изображение' }
    }
  ],
  [
    {
      icon: AlignJustifyIcon,
      tooltip: { text: 'Выравнивание текста' },
      content: {
        align: 'end'
      },
      items: [
        {
          kind: 'textAlign',
          align: 'left',
          icon: AlignLeftIcon,
          label: 'По левому краю'
        },
        {
          kind: 'textAlign',
          align: 'center',
          icon: AlignCenterIcon,
          label: 'По центру'
        },
        {
          kind: 'textAlign',
          align: 'right',
          icon: AlignRightIcon,
          label: 'По правому краю'
        },
        {
          kind: 'textAlign',
          align: 'justify',
          icon: AlignJustifyIcon,
          label: 'По ширине'
        }
      ]
    }
  ]
] satisfies EditorToolbarItem<typeof customHandlers>[][])

const imageToolbarItems = (editor: Editor): EditorToolbarItem[][] => {
  const node = editor.state.doc.nodeAt(editor.state.selection.from)

  return [
    [
      {
        icon: DownloadIcon,
        to: node?.attrs?.src,
        download: true,
        tooltip: { text: 'Скачать' }
      },
      {
        icon: RefreshIcon,
        tooltip: { text: 'Заменить' },
        onClick: () => {
          const { state } = editor
          const { selection } = state

          const pos = selection.from
          const node = state.doc.nodeAt(pos)

          if (node && node.type.name === 'image') {
            editor.chain().focus().deleteRange({ from: pos, to: pos + node.nodeSize }).insertContentAt(pos, { type: 'imageUpload' }).run()
          }
        }
      }
    ],
    [
      {
        icon: TrashcanIcon,
        tooltip: { text: 'Удалить' },
        onClick: () => {
          const { state } = editor
          const { selection } = state

          const pos = selection.from
          const node = state.doc.nodeAt(pos)

          if (node && node.type.name === 'image') {
            editor.chain().focus().deleteRange({ from: pos, to: pos + node.nodeSize }).run()
          }
        }
      }
    ]
  ]
}

const selectedNode = ref<{ node: JSONContent, pos: number }>()

const handleItems = (editor: Editor): DropdownMenuItem[][] => {
  if (!selectedNode.value?.node?.type) {
    return []
  }

  return mapEditorItems(editor, [
    [
      {
        type: 'label',
        label: upperFirst(selectedNode.value.node.type)
      },
      {
        label: 'Преобразовать в',
        icon: RepeatIcon,
        children: [
          { kind: 'paragraph', label: 'Абзац', icon: TextIcon },
          { kind: 'heading', level: 1, label: 'Заголовок 1' },
          { kind: 'heading', level: 2, label: 'Заголовок 2' },
          { kind: 'heading', level: 3, label: 'Заголовок 3' },
          { kind: 'heading', level: 4, label: 'Заголовок 4' },
          { kind: 'bulletList', label: 'Маркированный список', icon: BulletedListIcon },
          { kind: 'orderedList', label: 'Нумерованный список', icon: NumberedListIcon },
          { kind: 'blockquote', label: 'Цитата', icon: QuoteIcon },
          { kind: 'codeBlock', label: 'Блок кода', icon: CodeIcon }
        ]
      },
      {
        kind: 'clearFormatting',
        pos: selectedNode.value?.pos,
        label: 'Сбросить форматирование',
        icon: ResumeIcon
      }
    ],
    [
      {
        kind: 'duplicate',
        pos: selectedNode.value?.pos,
        label: 'Дублировать',
        icon: CopyIcon
      },
      {
        label: 'Копировать в буфер обмена',
        icon: CopyFileIcon,
        onSelect: async () => {
          if (!selectedNode.value) return

          const pos = selectedNode.value.pos
          const node = editor.state.doc.nodeAt(pos)
          if (node) {
            await navigator.clipboard.writeText(node.textContent)
          }
        }
      }
    ],
    [
      {
        kind: 'moveUp',
        pos: selectedNode.value?.pos,
        label: 'Переместить вверх',
        icon: ArrowTopLIcon
      },
      {
        kind: 'moveDown',
        pos: selectedNode.value?.pos,
        label: 'Переместить вниз',
        icon: ArrowDownLIcon
      }
    ],
    [
      {
        kind: 'delete',
        pos: selectedNode.value?.pos,
        label: 'Удалить',
        icon: TrashcanIcon
      }
    ]
  ], customHandlers) as DropdownMenuItem[][]
}

const suggestionItems = [
  [
    {
      type: 'label',
      label: 'Стиль'
    },
    {
      kind: 'paragraph',
      label: 'Абзац',
      icon: TextIcon
    },
    {
      kind: 'heading',
      level: 1,
      label: 'Заголовок 1'
    },
    {
      kind: 'heading',
      level: 2,
      label: 'Заголовок 2'
    },
    {
      kind: 'heading',
      level: 3,
      label: 'Заголовок 3'
    },
    {
      kind: 'bulletList',
      label: 'Маркированный список',
      icon: BulletedListIcon
    },
    {
      kind: 'orderedList',
      label: 'Нумерованный список',
      icon: NumberedListIcon
    },
    {
      kind: 'blockquote',
      label: 'Цитата',
      icon: QuoteIcon
    },
    {
      kind: 'codeBlock',
      label: 'Блок кода',
      icon: CodeIcon
    }
  ],
  [
    {
      type: 'label',
      label: 'Вставка'
    },
    {
      kind: 'mention',
      label: 'Упоминание',
      icon: MentionIcon
    },
    {
      kind: 'emoji',
      label: 'Эмодзи',
      icon: SmileIcon
    },
    {
      kind: 'imageUpload',
      label: 'Изображение',
      icon: ImageIcon
    },
    {
      kind: 'horizontalRule',
      label: 'Горизонтальная линия',
      icon: HrIcon
    }
  ]
] satisfies EditorSuggestionMenuItem<typeof customHandlers>[][]

const mentionItems: EditorMentionMenuItem[] = [
  {
    label: 'bitrix24',
    avatar: { src: 'https://github.com/bitrix24.png', loading: 'lazy' as const }
  },
  {
    label: 'Сотрудник',
    avatar: { src: '/b24ui/avatar/employee.png', loading: 'lazy' as const }
  },
  {
    label: 'Ассистент',
    avatar: { src: '/b24ui/avatar/assistant.png', loading: 'lazy' as const }
  }
]

const emojiItems: EditorEmojiMenuItem[] = gitHubEmojis.filter(emoji => !emoji.name.startsWith('regional_indicator_'))
</script>

<template>
  <B24Editor
    v-slot="{ editor, handlers }"
    v-model="value"
    content-type="markdown"
    :extensions="[
      Emoji,
      TextAlign.configure({ types: ['heading', 'paragraph'] }),
      ImageUpload,
      CodeBlockShiki.configure({
        defaultTheme: 'material-theme',
        themes: {
          light: 'material-theme-lighter',
          dark: 'material-theme-palenight'
        }
      })
    ]"
    :handlers="customHandlers"
    placeholder="Пишите, введите «/» для команд..."
    :b24ui="{ base: 'p-8 sm:px-16 py-24' }"
    class="w-full h-176 overflow-y-auto scrollbar-thin"
  >
    <B24EditorToolbar
      :editor="editor"
      :items="fixedToolbarItems"
      class="border-b border-(--ui-color-design-tinted-na-stroke) absolute top-0 inset-x-0 px-8 me-2 sm:px-16 py-2 z-20 bg-default overflow-x-auto rounded-t-md"
    >
      <template #link>
        <EditorLinkPopover :editor="editor" auto-open />
      </template>
    </B24EditorToolbar>

    <B24EditorToolbar
      :editor="editor"
      :items="bubbleToolbarItems"
      layout="bubble"
      :should-show="({ editor, view, state }) => {
        if (editor.isActive('imageUpload') || editor.isActive('image')) {
          return false
        }
        const { selection } = state
        return view.hasFocus() && !selection.empty
      }"
    >
      <template #link>
        <EditorLinkPopover :editor="editor" />
      </template>
    </B24EditorToolbar>

    <B24EditorToolbar
      :editor="editor"
      :items="imageToolbarItems(editor)"
      layout="bubble"
      :should-show="({ editor, view }) => {
        return editor.isActive('image') && view.hasFocus()
      }"
    />

    <B24EditorSuggestionMenu :editor="editor" :items="suggestionItems" />

    <B24EditorMentionMenu :editor="editor" :items="mentionItems" />

    <B24EditorEmojiMenu :editor="editor" :items="emojiItems" />

    <B24EditorDragHandle v-slot="{ b24ui, onClick }" :editor="editor" @node-change="selectedNode = $event">
      <B24Button
        :icon="PlusLIcon"
        color="air-tertiary"
        size="sm"
        :class="b24ui.handle()"
        @click="(e) => {
          e.stopPropagation()

          const selected = onClick()
          handlers.suggestion?.execute(editor, { pos: selected?.pos }).run()
        }"
      />

      <B24DropdownMenu
        v-slot="{ open }"
        :modal="false"
        :items="handleItems(editor)"
        :content="{ side: 'left' }"
        :b24ui="{ content: 'w-48', label: 'text-xs' }"
        @update:open="editor.chain().setMeta('lockDragHandle', $event).run()"
      >
        <B24Button
          color="air-tertiary"
          size="sm"
          :icon="DragLIcon"
          :active="open"
          :class="b24ui.handle()"
        />
      </B24DropdownMenu>
    </B24EditorDragHandle>
  </B24Editor>
</template>

<style>
html.dark .tiptap .shiki,
html.dark .tiptap .shiki span {
  color: var(--shiki-dark) !important;
  background-color: var(--ui-color-g-plastic-bluish-bg) !important;
}
</style>
```

> [!NOTE]
> See: https://github.com/bitrix24/b24ui/blob/main/docs/app/components/content/examples/editor/EditorExample.vue
> В этом примере показан Editor, готовый к использованию в продакшене. Исходный код — на GitHub.

> [!WARNING]
> Если при работе с Editor или его расширениями возникают ошибки prosemirror вроде `Adding different instances of a keyed plugin`, добавьте пакеты prosemirror в список `vite.optimizeDeps.include` в файле `nuxt.config.ts`. Тогда Vite предварительно собирает эти зависимости и не загружает несколько экземпляров.
> ```ts [nuxt.config.ts]
> export default defineNuxtConfig({
>   vite: {
>     optimizeDeps: {
>       include: [
>         '@bxshefby/b24ui-nuxt > prosemirror-state',
>         '@bxshefby/b24ui-nuxt > prosemirror-transform',
>         '@bxshefby/b24ui-nuxt > prosemirror-model',
>         '@bxshefby/b24ui-nuxt > prosemirror-view',
>         '@bxshefby/b24ui-nuxt > prosemirror-gapcursor'
>       ]
>     }
>   }
> })
> ```

### Содержимое

Директива `v-model` управляет значением Editor.

```vue
<script setup lang="ts">
const value = ref({
  type: 'doc',
  content: [
    {
      type: 'heading',
      attrs: {
        level: 1
      },
      content: [
        {
          type: 'text',
          text: 'Привет, мир'
        }
      ]
    },
    {
      type: 'paragraph',
      content: [
        {
          type: 'text',
          text: 'Это редактор '
        },
        {
          type: 'text',
          marks: [
            {
              type: 'bold'
            }
          ],
          text: 'форматированного текста'
        },
        {
          type: 'text',
          text: '.'
        }
      ]
    }
  ]
})
</script>

<template>
  <B24Editor v-model="value" class="w-full min-h-21" />
</template>
```

### Тип содержимого

Editor сам определяет формат содержимого по типу `v-model`: строки считаются `html`, объекты — `json`.

Формат можно задать явно пропсом `content-type`: `json`, `html` или `markdown`.

```vue
<script setup lang="ts">
const value = ref('<h1>Привет, мир</h1>\n<p>Это редактор <strong>форматированного текста</strong>.</p>\n')
</script>

<template>
  <B24Editor v-model="value" content-type="html" class="w-full min-h-21" />
</template>
```

### Расширения

В Editor по умолчанию включены расширения:

- [**StarterKit**](#starter-kit) — базовые возможности редактирования (жирный, курсив, заголовки, списки и другое);
- [**Placeholder**](#placeholder) — текст плейсхолдера (если задан пропс placeholder);
- **Image** — вставка и показ изображений;
- **Mention** — поддержка упоминаний через @;
- **Markdown** — разбор и сериализация Markdown (если тип содержимого — markdown).

> [!NOTE]
> Каждое встроенное расширение настраивается своим пропсом (`starter-kit`, `placeholder`, `image`, `mention`, `markdown`) через параметры TipTap.

Пропс `extensions` добавляет дополнительные расширения TipTap и расширяет возможности Editor:

```vue
<script setup lang="ts">
import { Emoji } from '@tiptap/extension-emoji'
import { TextAlign } from '@tiptap/extension-text-align'

const value = ref('<h1>Hello World</h1>\n')
</script>

<template>
  <B24Editor
    v-model="value"
    :extensions="[
      Emoji,
      TextAlign.configure({
        types: ['heading', 'paragraph']
      })
    ]"
  />
</template>
```

> [!TIP]
> See: #with-image-upload
> Пример загрузки изображений показывает, как создавать собственные расширения TipTap.

### Плейсхолдер

Пропс `placeholder` задаёт текст плейсхолдера, который показывается в пустых абзацах.

```vue
<script setup lang="ts">
const value = ref('')
</script>

<template>
  <B24Editor v-model="value" placeholder="Начните писать..." class="w-full min-h-7" />
</template>
```

> [!NOTE]
> Пропс `placeholder` принимает строку или объект с [PlaceholderOptions](https://tiptap.dev/docs/editor/extensions/functionality/placeholder) и дополнительным свойством `mode`:
> - `everyLine` — плейсхолдер в каждой пустой строке при фокусе (по умолчанию);
> - `firstLine` — плейсхолдер только в первой строке, когда редактор пуст.
> ```vue
> <template>
>   <B24Editor :placeholder="{ placeholder: 'Start writing...', mode: 'firstLine' }" />
> </template>
> ```

> [!TIP]
> По умолчанию плейсхолдеры показываются только в пустых узлах верхнего уровня. Чтобы показывать их во вложенных элементах, например в пунктах списка, задайте `includeChildren: true`:
> ```vue
> <template>
>   <B24Editor :placeholder="{ placeholder: 'Start writing...', includeChildren: true }" />
> </template>
> ```

> [!NOTE]
> See: https://tiptap.dev/docs/editor/extensions/functionality/placeholder
> Подробнее о расширении Placeholder — в документации TipTap.

### Starter Kit

Пропс `starter-kit` настраивает встроенное расширение TipTap StarterKit, в которое входят типичные возможности редактора: жирный текст, курсив, заголовки, списки, цитаты, блоки кода и другое.

```vue
<script setup lang="ts">
const value = ref('<h1>Hello World</h1>\n')
</script>

<template>
  <B24Editor
    v-model="value"
    :starter-kit="{
      blockquote: false,
      headings: {
        levels: [1, 2, 3, 4]
      },
      dropcursor: {
        color: 'var(--ui-color-accent-main-primary)',
        width: 2
      },
      link: {
        openOnClick: false
      }
    }"
  />
</template>
```

> [!TIP]
> Значение `false` у `starter-kit` превращает Editor в редактор простого текста. Остаются только базовые узлы (абзац, текст, история), а все возможности форматирования отключаются: жирный текст, курсив, заголовки, списки, код, цитаты, ссылки и горизонтальные линии.

> [!NOTE]
> See: https://tiptap.dev/docs/editor/extensions/functionality/starterkit
> Подробнее о расширении StarterKit — в документации TipTap.

### Обработчики

Обработчики оборачивают встроенные команды TipTap и дают единый интерфейс для действий редактора. Если элементу [EditorToolbar](https://b24-ui.bx-shef.by/raw/docs/components/editor-toolbar.md) или [EditorSuggestionMenu](https://b24-ui.bx-shef.by/raw/docs/components/editor-suggestion-menu.md) задать свойство `kind`, соответствующий обработчик выполнит команду TipTap и будет следить за её состоянием (активна, отключена и так далее).

#### Обработчики по умолчанию

В Editor есть такие обработчики по умолчанию. Их можно указывать в элементах панели инструментов или меню подсказок через свойство `kind`:

| Обработчик | Описание | Использование |
| --- | --- | --- |
| `mark` | Переключает текстовые выделения (жирный, курсив, зачёркнутый, код, подчёркнутый) | Нужно свойство `mark` в элементе |
| `textAlign` | Задаёт выравнивание текста (слева, по центру, справа, по ширине) | Нужно свойство `align` в элементе |
| `heading` | Переключает уровни заголовков (1–6) | Нужно свойство `level` в элементе |
| `link` | Добавляет, редактирует или удаляет ссылки | Если URL не задан, запрашивает его |
| `image` | Вставляет изображения | Если URL не задан, запрашивает его |
| `blockquote` | Переключает цитаты | |
| `bulletList` | Переключает маркированные списки | Преобразует списки |
| `orderedList` | Переключает нумерованные списки | Преобразует списки |
| `taskList` | Переключает списки задач | Преобразует списки |
| `codeBlock` | Переключает блоки кода | |
| `horizontalRule` | Вставляет горизонтальные линии | |
| `paragraph` | Задаёт формат абзаца | |
| `undo` | Отменяет последнее изменение | |
| `redo` | Возвращает отменённое изменение | |
| `clearFormatting` | Убирает всё форматирование | Работает с выделением или позицией |
| `duplicate` | Дублирует узел | Нужно свойство `pos` в элементе |
| `delete` | Удаляет узел | Нужно свойство `pos` в элементе |
| `moveUp` | Перемещает узел вверх | Нужно свойство `pos` в элементе |
| `moveDown` | Перемещает узел вниз | Нужно свойство `pos` в элементе |
| `suggestion` | Вызывает меню подсказок | Вставляет символ `/` |
| `mention` | Вызывает меню упоминаний | Вставляет символ `@` |
| `emoji` | Вызывает выбор эмодзи | Вставляет символ `:` |

> [!WARNING]
> Обработчики `taskList` и `textAlign` работают, только если установлены соответствующие расширения: в Editor их по умолчанию нет.

Так обработчики по умолчанию используются в элементах панели инструментов или меню подсказок:

```vue
<script setup lang="ts">
import type { EditorToolbarItem } from '@bxshefby/b24ui-nuxt'
import BoldIcon from '@bitrix24/b24icons-vue/outline/BoldIcon'
import ItalicIcon from '@bitrix24/b24icons-vue/outline/ItalicIcon'
import AlignLeftIcon from '@bitrix24/b24icons-vue/outline/AlignLeftIcon'
import AlignCenterIcon from '@bitrix24/b24icons-vue/outline/AlignCenterIcon'
import BulletedListIcon from '@bitrix24/b24icons-vue/outline/BulletedListIcon'
import NumberedListIcon from '@bitrix24/b24icons-vue/outline/NumberedListIcon'
import QuoteIcon from '@bitrix24/b24icons-vue/outline/QuoteIcon'
import LinkIcon from '@bitrix24/b24icons-vue/outline/LinkIcon'

const value = ref('<h1>Hello World</h1>\n')

const items: EditorToolbarItem[] = [
  { kind: 'mark', mark: 'bold', icon: BoldIcon },
  { kind: 'mark', mark: 'italic', icon: ItalicIcon },
  { kind: 'heading', level: 1 },
  { kind: 'heading', level: 2 },
  { kind: 'textAlign', align: 'left', icon: AlignLeftIcon },
  { kind: 'textAlign', align: 'center', icon: AlignCenterIcon },
  { kind: 'bulletList', icon: BulletedListIcon },
  { kind: 'orderedList', icon: NumberedListIcon },
  { kind: 'blockquote', icon: QuoteIcon },
  { kind: 'link', icon: LinkIcon }
]
</script>

<template>
  <B24Editor v-slot="{ editor }" v-model="value">
    <B24EditorToolbar :editor="editor" :items="items" />
  </B24Editor>
</template>
```

#### Свои обработчики

Пропс `handlers` расширяет или переопределяет обработчики по умолчанию. Свои обработчики объединяются со стандартными, поэтому можно добавлять новые действия и менять поведение существующих.

Каждый обработчик реализует интерфейс `EditorHandler`:

```ts
interface EditorHandler {
  /* Проверяет, можно ли выполнить команду в текущем состоянии редактора */
  canExecute: (editor: Editor, item?: any) => boolean
  /* Выполняет команду и возвращает цепочку Tiptap */
  execute: (editor: Editor, item?: any) => any
  /* Определяет, выглядит ли элемент активным (для переключателей) */
  isActive: (editor: Editor, item?: any) => boolean
  /* Дополнительная проверка для отключения элемента (объединяется с `canExecute`) */
  isDisabled?: (editor: Editor, item?: any) => boolean
}
```

Пример собственных обработчиков:

```vue
<script setup lang="ts">
import type { Editor } from '@tiptap/vue-3'
import type { EditorCustomHandlers, EditorToolbarItem } from '@bxshefby/b24ui-nuxt'
import BoldIcon from '@bitrix24/b24icons-vue/outline/BoldIcon'
import TextColorIcon from '@bitrix24/b24icons-vue/editor/TextColorIcon'

const value = ref('<h1>Hello World</h1>\n')

const customHandlers = {
  highlight: {
    canExecute: (editor: Editor) => editor.can().toggleHighlight(),
    execute: (editor: Editor) => editor.chain().focus().toggleHighlight(),
    isActive: (editor: Editor) => editor.isActive('highlight'),
    isDisabled: (editor: Editor) => !editor.isEditable
  }
} satisfies EditorCustomHandlers

const items = [
  // Встроенный обработчик
  { kind: 'mark', mark: 'bold', icon: BoldIcon },
  // Свой обработчик
  { kind: 'highlight', icon: TextColorIcon }
] satisfies EditorToolbarItem<typeof customHandlers>[]
</script>

<template>
  <B24Editor v-slot="{ editor }" v-model="value" :handlers="customHandlers">
    <B24EditorToolbar :editor="editor" :items="items" />
  </B24Editor>
</template>
```

> [!TIP]
> See: #with-image-upload
> Полный пример с собственными обработчиками показывает загрузка изображений.

## Примеры

### С панелью инструментов

Компонент [EditorToolbar](https://b24-ui.bx-shef.by/raw/docs/components/editor-toolbar.md) добавляет в Editor панель инструментов `fixed`, `bubble` или `floating` с типичными действиями форматирования.

```vue [EditorToolbarExample.vue]
<script setup lang="ts">
import type { EditorToolbarItem } from '@bxshefby/b24ui-nuxt'
import HeaderIcon from '@bitrix24/b24icons-vue/editor/HeaderIcon'
import BoldIcon from '@bitrix24/b24icons-vue/outline/BoldIcon'
import ItalicIcon from '@bitrix24/b24icons-vue/outline/ItalicIcon'
import UnderlineIcon from '@bitrix24/b24icons-vue/outline/UnderlineIcon'
import StrikethroughIcon from '@bitrix24/b24icons-vue/outline/StrikethroughIcon'
import DeveloperResourcesIcon from '@bitrix24/b24icons-vue/outline/DeveloperResourcesIcon'

const value = ref(`# Панель инструментов

Выделите текст, чтобы над выделением появилась панель форматирования.`)

const items: EditorToolbarItem[][] = [
  [
    {
      icon: HeaderIcon,
      tooltip: { text: 'Заголовки' },
      content: { align: 'start' },
      items: [
        {
          kind: 'heading',
          level: 1,
          label: 'Заголовок 1'
        },
        {
          kind: 'heading',
          level: 2,
          label: 'Заголовок 2'
        },
        {
          kind: 'heading',
          level: 3,
          label: 'Заголовок 3'
        },
        {
          kind: 'heading',
          level: 4,
          label: 'Заголовок 4'
        }
      ]
    }
  ],
  [
    {
      kind: 'mark',
      mark: 'bold',
      icon: BoldIcon,
      tooltip: { text: 'Жирный' }
    }, {
      kind: 'mark',
      mark: 'italic',
      icon: ItalicIcon,
      tooltip: { text: 'Курсив' }
    }, {
      kind: 'mark',
      mark: 'underline',
      icon: UnderlineIcon,
      tooltip: { text: 'Подчёркнутый' }
    }, {
      kind: 'mark',
      mark: 'strike',
      icon: StrikethroughIcon,
      tooltip: { text: 'Зачёркнутый' }
    },
    {
      kind: 'mark',
      mark: 'code',
      icon: DeveloperResourcesIcon,
      tooltip: { text: 'Код' }
    }
  ]
]
</script>

<template>
  <B24Editor
    v-slot="{ editor }"
    v-model="value"
    content-type="markdown"
    class="w-full min-h-21"
  >
    <B24EditorToolbar :editor="editor" :items="items" layout="bubble" />
  </B24Editor>
</template>
```

### С ручкой перетаскивания

Компонент [EditorDragHandle](https://b24-ui.bx-shef.by/raw/docs/components/editor-drag-handle.md) добавляет ручку для перетаскивания блоков.

```vue [EditorDragHandleExample.vue]
<script setup lang="ts">
const value = ref(`# Ручка перетаскивания

Наведите курсор на левую сторону блока, чтобы появилась ручка перетаскивания, и меняйте порядок блоков.`)
</script>

<template>
  <B24Editor
    v-slot="{ editor }"
    v-model="value"
    content-type="markdown"
    class="w-full min-h-21"
  >
    <B24EditorDragHandle :editor="editor" />
  </B24Editor>
</template>
```

### С меню подсказок

Компонент [EditorSuggestionMenu](https://b24-ui.bx-shef.by/raw/docs/components/editor-suggestion-menu.md) добавляет слэш-команды для быстрого форматирования и вставки.

```vue [EditorSuggestionMenuExample.vue]
<script setup lang="ts">
import type { EditorSuggestionMenuItem } from '@bxshefby/b24ui-nuxt'
import TextIcon from '@bitrix24/b24icons-vue/outline/TextIcon'
import BulletedListIcon from '@bitrix24/b24icons-vue/outline/BulletedListIcon'
import NumberedListIcon from '@bitrix24/b24icons-vue/outline/NumberedListIcon'
import QuoteIcon from '@bitrix24/b24icons-vue/outline/QuoteIcon'
import CodeIcon from '@bitrix24/b24icons-vue/common-service/CodeIcon'
import HrIcon from '@bitrix24/b24icons-vue/editor/HrIcon'

const value = ref(`# Меню подсказок

Введите /, чтобы открыть меню подсказок и посмотреть доступные команды форматирования.`)

const items: EditorSuggestionMenuItem[][] = [
  [
    {
      type: 'label',
      label: 'Текст'
    },
    {
      kind: 'paragraph',
      label: 'Абзац',
      icon: TextIcon
    },
    {
      kind: 'heading',
      level: 1,
      label: 'Заголовок 1'
    },
    {
      kind: 'heading',
      level: 2,
      label: 'Заголовок 2'
    },
    {
      kind: 'heading',
      level: 3,
      label: 'Заголовок 3'
    }
  ],
  [
    {
      type: 'label',
      label: 'Списки'
    },
    {
      kind: 'bulletList',
      label: 'Маркированный список',
      icon: BulletedListIcon
    },
    {
      kind: 'orderedList',
      label: 'Нумерованный список',
      icon: NumberedListIcon
    }
  ],
  [
    {
      type: 'label',
      label: 'Вставка'
    },
    {
      kind: 'blockquote',
      label: 'Цитата',
      icon: QuoteIcon
    },
    {
      kind: 'codeBlock',
      label: 'Блок кода',
      icon: CodeIcon
    },
    {
      kind: 'horizontalRule',
      label: 'Разделитель',
      icon: HrIcon
    }
  ]
]

// Безопасная для SSR функция, добавляющая меню в body (чтобы не было проблем с z-index в документации)
const appendToBody = import.meta.client ? () => document.body : undefined
</script>

<template>
  <B24Editor
    v-slot="{ editor }"
    v-model="value"
    content-type="markdown"
    placeholder="Введите / для команд..."
    class="w-full min-h-21"
  >
    <B24EditorSuggestionMenu :editor="editor" :items="items" :append-to="appendToBody" />
  </B24Editor>
</template>
```

### С меню упоминаний

Компонент [EditorMentionMenu](https://b24-ui.bx-shef.by/raw/docs/components/editor-mention-menu.md) добавляет упоминания через @ для тегов пользователей и других сущностей.

```vue [EditorMentionMenuExample.vue]
<script setup lang="ts">
import type { EditorMentionMenuItem } from '@bxshefby/b24ui-nuxt'

const value = ref(`# Меню упоминаний

Введите @, чтобы упомянуть пользователя, и выберите его из списка.`)

const items: EditorMentionMenuItem[] = [
  {
    label: 'bitrix24',
    avatar: {
      src: 'https://github.com/bitrix24.png',
      loading: 'lazy' as const
    }
  },
  {
    label: 'Сотрудник',
    avatar: {
      src: '/b24ui/avatar/employee.png',
      loading: 'lazy' as const
    }
  },
  {
    label: 'Ассистент',
    avatar: {
      src: '/b24ui/avatar/assistant.png',
      loading: 'lazy' as const
    }
  }
]

// Безопасная для SSR функция, добавляющая меню в body (чтобы не было проблем с z-index в документации)
const appendToBody = import.meta.client ? () => document.body : undefined
</script>

<template>
  <B24Editor
    v-slot="{ editor }"
    v-model="value"
    content-type="markdown"
    placeholder="Введите @, чтобы упомянуть пользователя..."
    class="w-full min-h-21"
  >
    <B24EditorMentionMenu :editor="editor" :items="items" :append-to="appendToBody" />
  </B24Editor>
</template>
```

### С меню эмодзи

Компонент [EditorEmojiMenu](https://b24-ui.bx-shef.by/raw/docs/components/editor-emoji-menu.md) добавляет выбор эмодзи.

```vue [EditorEmojiMenuExample.vue]
<script setup lang="ts">
import type { EditorEmojiMenuItem } from '@bxshefby/b24ui-nuxt'
import { Emoji, gitHubEmojis } from '@tiptap/extension-emoji'

const value = ref(`# Меню эмодзи

Введите :, чтобы вставить эмодзи, и выберите нужный из списка.`)

const items: EditorEmojiMenuItem[] = gitHubEmojis.filter(emoji => !emoji.name.startsWith('regional_indicator_'))

// Безопасная для SSR функция, добавляющая меню в body (чтобы не было проблем с z-index в документации)
const appendToBody = import.meta.client ? () => document.body : undefined
</script>

<template>
  <B24Editor
    v-slot="{ editor }"
    v-model="value"
    :extensions="[Emoji]"
    content-type="markdown"
    placeholder="Введите : для добавления эмодзи..."
    class="w-full min-h-21"
  >
    <B24EditorEmojiMenu :editor="editor" :items="items" :append-to="appendToBody" />
  </B24Editor>
</template>
```

### С загрузкой изображений

В этом примере загрузка изображений собрана так: пропс `extensions` регистрирует свой узел TipTap, а пропс `handlers` определяет, как кнопка панели запускает загрузку.

1. Создайте Vue-компонент на основе [FileUpload](https://b24-ui.bx-shef.by/raw/docs/components/file-upload.md):

```vue [EditorImageUploadNode.vue]
<script setup lang="ts">
import type { NodeViewProps } from '@tiptap/vue-3'
import { NodeViewWrapper } from '@tiptap/vue-3'
import SpinnerIcon from '@bitrix24/b24icons-vue/specialized/SpinnerIcon'
import ImageIcon from '@bitrix24/b24icons-vue/outline/ImageIcon'

const props = defineProps<NodeViewProps>()

const file = ref<File | null>(null)
const loading = ref(false)

watch(file, async (newFile) => {
  if (!newFile) return

  loading.value = true

  const reader = new FileReader()
  reader.onload = async (e) => {
    const dataUrl = e.target?.result as string
    if (!dataUrl) {
      loading.value = false
      return
    }

    // Имитируем задержку загрузки
    await new Promise(resolve => setTimeout(resolve, 1000))

    const pos = props.getPos()
    if (typeof pos !== 'number') {
      loading.value = false
      return
    }

    props.editor
      .chain()
      .focus()
      .deleteRange({ from: pos, to: pos + 1 })
      .setImage({ src: dataUrl })
      .run()

    loading.value = false
  }
  reader.readAsDataURL(newFile)
})
</script>

<template>
  <NodeViewWrapper>
    <B24FileUpload
      v-model="file"
      accept="image/*"
      label="Загрузите изображение"
      description="SVG, PNG, JPG или GIF (не более 2 МБ)"
      :preview="false"
      class="min-h-48"
    >
      <template #leading>
        <B24Avatar
          :icon="loading ? SpinnerIcon : ImageIcon"
          size="md"
          :b24ui="{ icon: [loading && 'animate-spin'] }"
        />
      </template>
    </B24FileUpload>
  </NodeViewWrapper>
</template>
```

1. Создайте своё расширение TipTap, которое регистрирует узел:

```ts [EditorImageUploadExtension.vue]
import { Node, mergeAttributes } from '@tiptap/core'
import type { CommandProps, NodeViewRenderer } from '@tiptap/core'
import { VueNodeViewRenderer } from '@tiptap/vue-3'
import ImageUploadNodeComponent from './EditorImageUploadNode.vue'

declare module '@tiptap/core' {
  interface Commands<ReturnType> {
    imageUpload: {
      insertImageUpload: () => ReturnType
    }
  }
}

export const ImageUpload = Node.create({
  name: 'imageUpload',
  group: 'block',
  atom: true,
  draggable: true,
  addAttributes() {
    return {}
  },
  parseHTML() {
    return [{
      tag: 'div[data-type="image-upload"]'
    }]
  },
  renderHTML({ HTMLAttributes }) {
    return ['div', mergeAttributes(HTMLAttributes, { 'data-type': 'image-upload' })]
  },
  addNodeView(): NodeViewRenderer {
    return VueNodeViewRenderer(ImageUploadNodeComponent)
  },
  addCommands() {
    return {
      insertImageUpload: () => ({ commands }: CommandProps) => {
        return commands.insertContent({ type: this.name })
      }
    }
  }
})

export default ImageUpload
```

1. Подключите своё расширение в Editor:

```vue [EditorImageUploadExample.vue]
<script setup lang="ts">
import type { EditorCustomHandlers, EditorToolbarItem } from '@bxshefby/b24ui-nuxt'
import type { Editor } from '@tiptap/vue-3'
import { ImageUpload } from './EditorImageUploadExtension'
import HeaderIcon from '@bitrix24/b24icons-vue/editor/HeaderIcon'
import BoldIcon from '@bitrix24/b24icons-vue/outline/BoldIcon'
import ItalicIcon from '@bitrix24/b24icons-vue/outline/ItalicIcon'
import UnderlineIcon from '@bitrix24/b24icons-vue/outline/UnderlineIcon'
import StrikethroughIcon from '@bitrix24/b24icons-vue/outline/StrikethroughIcon'
import DeveloperResourcesIcon from '@bitrix24/b24icons-vue/outline/DeveloperResourcesIcon'
import ImageIcon from '@bitrix24/b24icons-vue/outline/ImageIcon'

const value = ref(`# Загрузка изображений

Этот редактор показывает, как создать собственное расширение TipTap с обработчиками. Нажмите кнопку изображения на панели инструментов, чтобы загрузить файл: перед вставкой изображения откроется собственный интерфейс [FileUpload](/docs/components/file-upload).

Попробуйте загрузить изображение ниже:

`)

const customHandlers = {
  imageUpload: {
    canExecute: (editor: Editor) => editor.can().insertContent({ type: 'imageUpload' }),
    execute: (editor: Editor) => editor.chain().focus().insertContent({ type: 'imageUpload' }),
    isActive: (editor: Editor) => editor.isActive('imageUpload'),
    isDisabled: undefined
  }
} satisfies EditorCustomHandlers

const items = [
  [
    {
      kind: 'imageUpload',
      icon: ImageIcon,
      label: 'Добавить изображение'
    }
  ],
  [
    {
      icon: HeaderIcon,
      content: { align: 'start' },
      items: [{
        kind: 'heading',
        level: 1,
        label: 'Заголовок 1'
      }, {
        kind: 'heading',
        level: 2,
        label: 'Заголовок 2'
      }, {
        kind: 'heading',
        level: 3,
        label: 'Заголовок 3'
      }, {
        kind: 'heading',
        level: 4,
        label: 'Заголовок 4'
      }]
    }
  ],
  [
    {
      kind: 'mark',
      mark: 'bold',
      icon: BoldIcon
    }, {
      kind: 'mark',
      mark: 'italic',
      icon: ItalicIcon
    }, {
      kind: 'mark',
      mark: 'underline',
      icon: UnderlineIcon
    }, {
      kind: 'mark',
      mark: 'strike',
      icon: StrikethroughIcon
    }, {
      kind: 'mark',
      mark: 'code',
      icon: DeveloperResourcesIcon
    }
  ]
] satisfies EditorToolbarItem<typeof customHandlers>[][]
</script>

<template>
  <B24Editor
    v-slot="{ editor }"
    v-model="value"
    :extensions="[ImageUpload]"
    :handlers="customHandlers"
    content-type="markdown"
    :b24ui="{ base: 'p-8 sm:px-16' }"
    class="w-full min-h-74"
  >
    <B24EditorToolbar :editor="editor" :items="items" class="border-b border-muted bg-default py-2 px-8 sm:px-16 overflow-x-auto" />
  </B24Editor>
</template>
```

> [!NOTE]
> See: https://tiptap.dev/docs/editor/extensions/custom-extensions
> Подробнее о создании своих расширений — в документации TipTap.

## API

### Пропсы

```ts
/**
 * Props for the Editor component
 */
interface EditorProps {
  /**
   * The element or component this component should render as.
   * @default 'div'
   */
  as?: any;
  modelValue?: null | string | JSONContent | JSONContent[];
  /**
   * The content type the content is provided as.
   * When not specified, it's automatically inferred: strings are treated as 'html', objects as 'json'.
   */
  contentType?: "markdown" | "json" | "html" | undefined;
  /**
   * The starter kit options to configure the editor.
   * Set to `false` for a plain-text editor: keeps the essential nodes (paragraph, text, history) and disables all rich-text formatting.
   * @default true
   */
  starterKit?: boolean | Partial<StarterKitOptions> | undefined;
  /**
   * The placeholder text to show in empty paragraphs. Can be a string or PlaceholderOptions from `@tiptap/extension-placeholder`.
   * @default { showOnlyWhenEditable: false, showOnlyCurrent: true, mode: 'everyLine' }
   */
  placeholder?: string | Partial<PlaceholderOptions> & { mode?: "firstLine" | "everyLine" | undefined; } | undefined;
  /**
   * The markdown extension options to configure markdown parsing and serialization.
   * @default { markedOptions: { gfm: true } }
   */
  markdown?: Partial<MarkdownExtensionOptions> | undefined;
  /**
   * The image extension options to configure image handling. Set to `false` to disable the extension.
   * @default true
   */
  image?: boolean | Partial<ImageOptions> | undefined;
  /**
   * The mention extension options to configure mention handling. Set to `false` to disable the extension.
   * The `suggestion` and `suggestions` options are omitted as they are managed by the `EditorMentionMenu` component.
   * @default true
   */
  mention?: boolean | Partial<Omit<MentionOptions<any, MentionNodeAttrs>, "suggestion" | "suggestions">> | undefined;
  /**
   * Custom item handlers to override or extend the default handlers.
   * These handlers are provided to all child components (toolbar, suggestion menu, etc.).
   */
  handlers?: H | undefined;
  b24ui?: { root?: SlotClass; content?: SlotClass; base?: SlotClass; } | undefined;
  /**
   * The extensions to use
   */
  extensions?: Extensions | undefined;
  /**
   * A complete ProseMirror specification applied when the editor is created.
   * Its structure replaces local node, mark and attribute definitions.
   * Local extensions retain parsing, rendering, commands and plugins.
   * Every node and mark must have a matching local extension, and vice versa.
   * Changing this option on an existing editor does not rebuild its schema.
   */
  schemaSpec?: SchemaSpec<any, any> | undefined;
  /**
   * Whether to inject base CSS styles
   */
  injectCSS?: boolean | undefined;
  /**
   * A nonce to use for CSP while injecting styles
   */
  injectNonce?: string | undefined;
  /**
   * The editor's initial focus position
   */
  autofocus?: null | number | false | true | "start" | "end" | "all" | undefined;
  /**
   * Whether the editor is editable
   */
  editable?: boolean | undefined;
  /**
   * The default text direction for all content in the editor.
   * When set to 'ltr' or 'rtl', all nodes will have the corresponding dir attribute.
   * When set to 'auto', the dir attribute will be set based on content detection.
   * When undefined, no dir attribute will be added.
   */
  textDirection?: "ltr" | "rtl" | "auto" | undefined;
  /**
   * The editor's props
   */
  editorProps?: EditorProps<any> | undefined;
  parseOptions?: ParseOptions;
  /**
   * The editor's core extension options
   */
  coreExtensionOptions?: { clipboardTextSerializer?: { blockSeparator?: string | undefined; } | undefined; tabindex?: { value?: string | undefined; } | undefined; delete?: { async?: boolean | undefined; filterTransaction?: ((transaction: Transaction) => boolean) | undefined; } | undefined; } | undefined;
  /**
   * Whether to enable input rules behavior
   */
  enableInputRules?: false | true | (string | AnyExtension)[] | undefined;
  /**
   * Whether to enable paste rules behavior
   */
  enablePasteRules?: false | true | (string | AnyExtension)[] | undefined;
  /**
   * Determines whether core extensions are enabled.
   * 
   * If set to `false`, all core extensions will be disabled.
   * To disable specific core extensions, provide an object where the keys are the extension names and the values are `false`.
   * Extensions not listed in the object will remain enabled.
   */
  enableCoreExtensions?: boolean | Partial<Record<"editable" | "textDirection" | "clipboardTextSerializer" | "commands" | "focusEvents" | "keymap" | "tabindex" | "drop" | "paste" | "delete", false>> | undefined;
  /**
   * If `true`, the editor will check the content for errors on initialization.
   * Emitting the `contentError` event if the content is invalid.
   * Which can be used to show a warning or error message to the user.
   */
  enableContentCheck?: boolean | undefined;
  /**
   * If `true`, the editor will emit the `contentError` event if invalid content is
   * encountered but `enableContentCheck` is `false`. This lets you preserve the
   * invalid editor content while still showing a warning or error message to
   * the user.
   */
  emitContentError?: boolean | undefined;
  /**
   * Called before the editor is constructed.
   */
  onBeforeCreate?: (props: { editor: Editor; }): void | undefined;
  /**
   * Called after the editor is constructed.
   */
  onCreate?: (props: { editor: Editor; }): void | undefined;
  /**
   * Called when the editor is mounted.
   */
  onMount?: (props: { editor: Editor; }): void | undefined;
  /**
   * Called when the editor is unmounted.
   */
  onUnmount?: (props: { editor: Editor; }): void | undefined;
  /**
   * Called when the editor encounters an error while parsing the content.
   * Only enabled if `enableContentCheck` is `true`.
   */
  onContentError?: (props: { editor: Editor; error: Error; disableCollaboration: () => void; }): void | undefined;
  /**
   * Called when the editor's content is updated.
   */
  onUpdate?: (props: { editor: Editor; transaction: Transaction; appendedTransactions: Transaction[]; }): void | undefined;
  /**
   * Called when the editor's selection is updated.
   */
  onSelectionUpdate?: (props: { editor: Editor; transaction: Transaction; }): void | undefined;
  /**
   * Called after a transaction is applied to the editor.
   */
  onTransaction?: (props: { editor: Editor; transaction: Transaction; appendedTransactions: Transaction[]; }): void | undefined;
  /**
   * Called on focus events.
   */
  onFocus?: (props: { editor: Editor; event: FocusEvent; transaction: Transaction; }): void | undefined;
  /**
   * Called on blur events.
   */
  onBlur?: (props: { editor: Editor; event: FocusEvent; transaction: Transaction; }): void | undefined;
  /**
   * Called when the editor is destroyed.
   */
  onDestroy?: (props: void): void | undefined;
  /**
   * Called when content is pasted into the editor.
   */
  onPaste?: (e: ClipboardEvent, slice: Slice): void | undefined;
  /**
   * Called when content is dropped into the editor.
   */
  onDrop?: (e: DragEvent, slice: Slice, moved: boolean): void | undefined;
  /**
   * Called when content is deleted from the editor.
   */
  onDelete?: (props: { editor: Editor; deletedRange: Range; newRange: Range; transaction: Transaction; combinedTransform: Transform; partial: boolean; from: number; to: number; } & ({ ...; } | { ...; })): void | undefined;
  /**
   * Whether to enable extension-level dispatching of transactions.
   * If `false`, extensions cannot define their own `dispatchTransaction` hook.
   */
  enableExtensionDispatchTransaction?: boolean | undefined;
}
```

### Слоты

```ts
/**
 * Slots for the Editor component
 */
interface EditorSlots {
  default(): any;
}
```

### События

```ts
/**
 * Emitted events for the Editor component
 */
interface EditorEmits {
  update:modelValue: (payload: [value: T]) => void;
}
```

### Доступ через ref

Через ref шаблона доступно:

| Name | Type |
| --- | --- |
| `editor` | `Ref<Editor \| undefined>` |

> [!NOTE]
> See: https://tiptap.dev/docs/editor/api/editor
> Доступный через ref экземпляр — это API редактора TipTap. Все методы и свойства описаны в документации TipTap.

## Тема

```ts [app.config.ts]
export default defineAppConfig({
  b24ui: {
    editor: {
      slots: {
        root: '',
        content: 'relative size-full flex-1',
        base: 'text-label w-full outline-none *:my-5 *:first:mt-0 *:last:mb-0 sm:px-8 selection:bg-(--ui-color-design-selection-bg) [&_p]:leading-7 [&_a]:text-(--ui-color-accent-main-primary) [&_a]:border-b [&_a]:border-transparent [&_a]:hover:border-(--ui-color-accent-main-primary) [&_a]:focus-visible:border-transparent [&_a:has(>code)]:border-b-0 [&_a]:font-(--ui-font-weight-medium) [&_a]:transition-colors [&_a>code]:border-dashed [&_a:hover>code]:border-(--ui-color-accent-soft-element-blue) [&_a:hover>code]:text-(--ui-color-accent-main-primary) [&_a:focus-visible>code]:border-(--ui-color-accent-soft-element-blue) [&_a:focus-visible>code]:text-(--ui-color-accent-main-primary) [&_a>code]:transition-colors [&_.mention]:text-(--ui-color-accent-main-primary) [&_.mention]:font-(--ui-font-weight-medium) [&_:is(h1,h2,h3,h4,h5,h6)]:text-label [&_:is(h1,h2,h3,h4,h5,h6)]:font-(--ui-font-weight-bold) [&_h1]:text-3xl [&_h2]:text-2xl [&_h3]:text-xl [&_h4]:text-lg [&_h5]:text-md [&_h6]:text-md [&_:is(h1,h2,h3,h4,h5,h6)>code]:border-dashed [&_:is(h1,h2,h3,h4,h5,h6)>code]:font-(--ui-font-weight-bold) [&_h2>code]:text-xl/6 [&_h3>code]:text-lg/5 [&_blockquote]:border-s-4 [&_blockquote]:border-(--ui-color-accent-soft-element-blue) [&_blockquote]:ps-4 [&_blockquote]:italic [&_[data-type=horizontalRule]]:my-8 [&_[data-type=horizontalRule]]:py-2 [&_hr]:border-t [&_hr]:border-(--ui-color-divider-default) [&_pre]:text-sm/6 [&_pre]:border [&_pre]:border-(--ui-color-design-tinted-na-stroke) [&_pre]:bg-(--ui-color-design-tinted-na-bg) [&_pre]:rounded-md [&_pre]:px-4 [&_pre]:py-3 [&_pre]:whitespace-pre-wrap [&_pre]:wrap-break-word [&_pre]:overflow-x-auto [&_pre_code]:p-0 [&_pre_code]:text-inherit [&_pre_code]:rounded-none [&_pre_code]:inline [&_pre_code]:border-0 [&_pre_code]:bg-transparent [&_code]:px-1.5 [&_code]:py-0.5 [&_code]:text-sm [&_code]:font-[family-name:var(--ui-font-family-system-mono)] [&_code]:font-(--ui-font-weight-medium) [&_code]:rounded-md [&_code]:inline-block [&_code]:border [&_code]:border-(--ui-color-design-tinted-na-stroke) [&_code]:text-label [&_code]:bg-(--ui-color-design-tinted-na-bg) [&_:is(ul,ol)]:ps-6 [&_ul]:list-disc [&_ul]:marker:text-(--ui-color-accent-soft-element-blue) [&_ol]:list-decimal [&_ol]:marker:text-label [&_li]:my-1.5 [&_li]:ps-1.5 [&_img]:rounded-md [&_img]:block [&_img]:max-w-full [&_img.ProseMirror-selectednode]:outline-2 [&_img.ProseMirror-selectednode]:outline-(--ui-color-accent-main-primary) [&_.ProseMirror-selectednode:not(img):not(pre):not([data-node-view-wrapper])]:bg-(--ui-color-design-selection-bg)'
      },
      variants: {
        placeholderMode: {
          firstLine: {
            base: '[&_:is(p,h1,h2,h3,h4,h5,h6).is-editor-empty:first-child]:before:content-[attr(data-placeholder)] [&_:is(p,h1,h2,h3,h4,h5,h6).is-editor-empty:first-child]:before:text-description [&_:is(p,h1,h2,h3,h4,h5,h6).is-editor-empty:first-child]:before:float-start [&_:is(p,h1,h2,h3,h4,h5,h6).is-editor-empty:first-child]:before:h-0 [&_:is(p,h1,h2,h3,h4,h5,h6).is-editor-empty:first-child]:before:pointer-events-none'
          },
          everyLine: {
            base: '[&_:is(p,h1,h2,h3,h4,h5,h6).is-empty]:before:content-[attr(data-placeholder)] [&_:is(p,h1,h2,h3,h4,h5,h6).is-empty]:before:text-description [&_:is(p,h1,h2,h3,h4,h5,h6).is-empty]:before:float-start [&_:is(p,h1,h2,h3,h4,h5,h6).is-empty]:before:h-0 [&_:is(p,h1,h2,h3,h4,h5,h6).is-empty]:before:pointer-events-none'
          }
        }
      },
      defaultVariants: {
        placeholderMode: 'everyLine'
      }
    }
  }
})
```

## Sitemap

See the full [sitemap](/sitemap.md) for all pages.
