Использование
Компонент Editor — мощный редактор форматированного текста на базе TipTap. Он поддерживает несколько форматов содержимого (JSON, HTML, Markdown), настраиваемые панели инструментов, перетаскивание блоков, слэш-команды, упоминания, выбор эмодзи и расширяемую архитектуру для своих возможностей.
Adding different instances of a keyed plugin, добавьте пакеты prosemirror в список vite.optimizeDeps.include в файле nuxt.config.ts. Тогда Vite предварительно собирает эти зависимости и не загружает несколько экземпляров.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.
<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>
<script setup lang="ts">
import { ref } from 'vue'
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.
<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>
<script setup lang="ts">
import { ref } from 'vue'
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 — базовые возможности редактирования (жирный, курсив, заголовки, списки и другое);
- Placeholder — текст плейсхолдера (если задан пропс placeholder);
- Image — вставка и показ изображений;
- Mention — поддержка упоминаний через @;
- Markdown — разбор и сериализация Markdown (если тип содержимого — markdown).
starter-kit, placeholder, image, mention, markdown) через параметры TipTap.Пропс extensions добавляет дополнительные расширения TipTap и расширяет возможности Editor:
<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>
Плейсхолдер
Пропс placeholder задаёт текст плейсхолдера, который показывается в пустых абзацах.
<script setup lang="ts">
const value = ref('')
</script>
<template>
<B24Editor v-model="value" placeholder="Начните писать..." class="w-full min-h-7" />
</template>
<script setup lang="ts">
import { ref } from 'vue'
const value = ref('')
</script>
<template>
<B24Editor v-model="value" placeholder="Начните писать..." class="w-full min-h-7" />
</template>
placeholder принимает строку или объект с PlaceholderOptions и дополнительным свойством mode:everyLine— плейсхолдер в каждой пустой строке при фокусе (по умолчанию);firstLine— плейсхолдер только в первой строке, когда редактор пуст.
<template>
<B24Editor :placeholder="{ placeholder: 'Start writing...', mode: 'firstLine' }" />
</template>
includeChildren: true:<template>
<B24Editor :placeholder="{ placeholder: 'Start writing...', includeChildren: true }" />
</template>
Starter Kit
Пропс starter-kit настраивает встроенное расширение TipTap StarterKit, в которое входят типичные возможности редактора: жирный текст, курсив, заголовки, списки, цитаты, блоки кода и другое.
<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>
false у starter-kit превращает Editor в редактор простого текста. Остаются только базовые узлы (абзац, текст, история), а все возможности форматирования отключаются: жирный текст, курсив, заголовки, списки, код, цитаты, ссылки и горизонтальные линии.Обработчики
Обработчики оборачивают встроенные команды TipTap и дают единый интерфейс для действий редактора. Если элементу EditorToolbar или EditorSuggestionMenu задать свойство kind, соответствующий обработчик выполнит команду TipTap и будет следить за её состоянием (активна, отключена и так далее).
Обработчики по умолчанию
В Editor есть такие обработчики по умолчанию. Их можно указывать в элементах панели инструментов или меню подсказок через свойство kind:
taskList и textAlign работают, только если установлены соответствующие расширения: в Editor их по умолчанию нет.Так обработчики по умолчанию используются в элементах панели инструментов или меню подсказок:
<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:
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
}
Пример собственных обработчиков:
<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>
Примеры
С панелью инструментов
Компонент EditorToolbar добавляет в Editor панель инструментов fixed, bubble или floating с типичными действиями форматирования.
С ручкой перетаскивания
Компонент EditorDragHandle добавляет ручку для перетаскивания блоков.
С меню подсказок
Компонент EditorSuggestionMenu добавляет слэш-команды для быстрого форматирования и вставки.
С меню упоминаний
Компонент EditorMentionMenu добавляет упоминания через @ для тегов пользователей и других сущностей.
С меню эмодзи
Компонент EditorEmojiMenu добавляет выбор эмодзи.
С загрузкой изображений
В этом примере загрузка изображений собрана так: пропс extensions регистрирует свой узел TipTap, а пропс handlers определяет, как кнопка панели запускает загрузку.
- Создайте Vue-компонент на основе FileUpload:
- Создайте своё расширение TipTap, которое регистрирует узел:
- Подключите своё расширение в Editor:
API
Пропсы
Слоты
События
Доступ через ref
Через ref шаблона доступно:
Тема
export default {
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'
}
}