Использование
Компонент EditorToolbar показывает панель кнопок форматирования, состояние которых автоматически синхронизируется с содержимым редактора. Он поддерживает три режима раскладки через пакет @tiptap/vue-3/menus:
fixed— всегда на виду;bubble— появляется при выделении текста;floating— появляется на пустых строках.
<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>
<script setup lang="ts">
import { ref } from 'vue'
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>
BubbleMenu и FloatingMenu.Элементы
Пропс items — массив объектов со свойствами:
label?: stringicon?: IconComponentcolor?: ButtonProps['color']activeColor?: ButtonProps['color']size?: ButtonProps['size']kind?: "mark" | "textAlign" | "heading" | "link" | "image" | "blockquote" | "bulletList" | "orderedList" | "taskList" | "codeBlock" | "horizontalRule" | "paragraph" | "undo" | "redo" | "clearFormatting" | "duplicate" | "delete" | "moveUp" | "moveDown" | "suggestion" | "mention" | "emoji"disabled?: booleanloading?: booleanactive?: booleantooltip?: TooltipPropsslot?: stringonClick?: (e: MouseEvent) => voiditems?: EditorToolbarItem[] | EditorToolbarItem[][]class?: any
Можно передать любое свойство компонента Button: color, size и другие.
<script setup lang="ts">
import type { EditorToolbarItem } from '@bxshefby/b24ui-nuxt'
import { TextAlign } from '@tiptap/extension-text-align'
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 HrIcon from '@bitrix24/b24icons-vue/editor/HrIcon'
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 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'
const value = ref(`Эта панель инструментов показывает **все доступные параметры форматирования** со встроенными обработчиками. Попробуйте разные элементы управления в действии!
К тексту можно применить **жирный**, *курсив*, <u>подчёркнутый</u>, ~~зачёркнутый~~ и \`строчный код\`.
`)
const items: EditorToolbarItem[][] = [
// Управление историей
[
{
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: 'horizontalRule',
icon: HrIcon,
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: 'Код' }
}
],
// Ссылка
[
{
kind: 'link',
icon: LinkIcon,
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: 'По ширине'
}
]
}
]
]
</script>
<template>
<B24Editor
v-slot="{ editor }"
v-model="value"
content-type="markdown"
:extensions="[TextAlign.configure({ types: ['heading', 'paragraph'] })]"
class="w-full min-h-37 flex flex-col gap-4"
>
<B24EditorToolbar :editor="editor" :items="items" class="sm:px-8 overflow-x-auto bg-default" />
</B24Editor>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import type { EditorToolbarItem } from '@bxshefby/b24ui-nuxt'
import { TextAlign } from '@tiptap/extension-text-align'
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 HrIcon from '@bitrix24/b24icons-vue/editor/HrIcon'
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 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'
const value = ref(`Эта панель инструментов показывает **все доступные параметры форматирования** со встроенными обработчиками. Попробуйте разные элементы управления в действии!
К тексту можно применить **жирный**, *курсив*, <u>подчёркнутый</u>, ~~зачёркнутый~~ и \`строчный код\`.
`)
const items: EditorToolbarItem[][] = [
// Управление историей
[
{
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: 'horizontalRule',
icon: HrIcon,
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: 'Код' }
}
],
// Ссылка
[
{
kind: 'link',
icon: LinkIcon,
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: 'По ширине'
}
]
}
]
]
</script>
<template>
<B24Editor
v-slot="{ editor }"
v-model="value"
content-type="markdown"
:extensions="[TextAlign.configure({ types: ['heading', 'paragraph'] })]"
class="w-full min-h-37 flex flex-col gap-4"
>
<B24EditorToolbar :editor="editor" :items="items" class="sm:px-8 overflow-x-auto bg-default" />
</B24Editor>
</template>
items массив массивов.items с такими же свойствами, как у пропса items.Раскладка
Пропс layout меняет способ показа панели. По умолчанию fixed.
<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 DeveloperResourcesIcon from '@bitrix24/b24icons-vue/outline/DeveloperResourcesIcon'
defineProps<{
layout: 'fixed' | 'bubble' | 'floating'
}>()
const value = ref(`Переключайте раскладки, чтобы увидеть разные режимы панели инструментов.
Раскладка **fixed** показывает панель инструментов над редактором. Раскладка **bubble** показывает панель при выделении текста. Раскладка **floating** появляется на пустых строках.`)
const items: EditorToolbarItem[][] = [
[
{
kind: 'mark',
mark: 'bold',
icon: BoldIcon
},
{
kind: 'mark',
mark: 'italic',
icon: ItalicIcon
},
{
kind: 'mark',
mark: 'code',
icon: DeveloperResourcesIcon
}
]
]
</script>
<template>
<B24Editor v-slot="{ editor }" v-model="value" content-type="markdown" class="w-full min-h-26 flex flex-col gap-4">
<B24EditorToolbar
:key="layout"
:editor="editor"
:items="items"
:layout="layout"
:data-layout="layout"
class="data-[layout=fixed]:sm:px-8"
/>
</B24Editor>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import type { EditorToolbarItem } from '@bxshefby/b24ui-nuxt'
import BoldIcon from '@bitrix24/b24icons-vue/outline/BoldIcon'
import ItalicIcon from '@bitrix24/b24icons-vue/outline/ItalicIcon'
import DeveloperResourcesIcon from '@bitrix24/b24icons-vue/outline/DeveloperResourcesIcon'
defineProps<{
layout: 'fixed' | 'bubble' | 'floating'
}>()
const value = ref(`Переключайте раскладки, чтобы увидеть разные режимы панели инструментов.
Раскладка **fixed** показывает панель инструментов над редактором. Раскладка **bubble** показывает панель при выделении текста. Раскладка **floating** появляется на пустых строках.`)
const items: EditorToolbarItem[][] = [
[
{
kind: 'mark',
mark: 'bold',
icon: BoldIcon
},
{
kind: 'mark',
mark: 'italic',
icon: ItalicIcon
},
{
kind: 'mark',
mark: 'code',
icon: DeveloperResourcesIcon
}
]
]
</script>
<template>
<B24Editor v-slot="{ editor }" v-model="value" content-type="markdown" class="w-full min-h-26 flex flex-col gap-4">
<B24EditorToolbar
:key="layout"
:editor="editor"
:items="items"
:layout="layout"
:data-layout="layout"
class="data-[layout=fixed]:sm:px-8"
/>
</B24Editor>
</template>
Параметры
В раскладках bubble и floating пропс options настраивает позиционирование с помощью параметров Floating UI.
<template>
<B24Editor v-slot="{ editor }">
<B24EditorToolbar
:editor="editor"
:items="items"
layout="bubble"
:options="{
placement: 'top',
offset: 8,
flip: { padding: 8 },
shift: { padding: 8 }
}"
/>
</B24Editor>
</template>
Условие показа
В раскладках bubble и floating пропс should-show определяет, когда появляется панель. Функция получает контекст состояния редактора и возвращает булево значение.
<template>
<B24Editor v-slot="{ editor }">
<B24EditorToolbar
:editor="editor"
:items="items"
layout="bubble"
:should-show="({ view, state }) => {
const { selection } = state
const { from, to } = selection
const text = state.doc.textBetween(from, to)
return view.hasFocus() && !selection.empty && text.length > 10
}"
/>
</B24Editor>
</template>
Примеры
С панелью для изображений
Пропс should-show позволяет сделать панели, которые появляются только для определённых типов узлов. В этом примере панель bubble с действиями «скачать» и «удалить» появляется только при выборе изображения.
<script setup lang="ts">
import type { Editor } from '@tiptap/vue-3'
import type { EditorToolbarItem } from '@bxshefby/b24ui-nuxt'
import DownloadIcon from '@bitrix24/b24icons-vue/outline/DownloadIcon'
import TrashcanIcon from '@bitrix24/b24icons-vue/outline/TrashcanIcon'
const value = ref(`Нажмите на изображение ниже, чтобы увидеть панель инструментов для изображений:
`)
const items = (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: 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()
}
}
}
]
]
}
</script>
<template>
<B24Editor
v-slot="{ editor }"
v-model="value"
content-type="markdown"
class="w-full min-h-113"
>
<B24EditorToolbar
:editor="editor"
:items="items(editor)"
layout="bubble"
:should-show="({ editor, view }) => {
return editor.isActive('image') && view.hasFocus()
}"
/>
</B24Editor>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import type { Editor } from '@tiptap/vue-3'
import type { EditorToolbarItem } from '@bxshefby/b24ui-nuxt'
import DownloadIcon from '@bitrix24/b24icons-vue/outline/DownloadIcon'
import TrashcanIcon from '@bitrix24/b24icons-vue/outline/TrashcanIcon'
const value = ref(`Нажмите на изображение ниже, чтобы увидеть панель инструментов для изображений:
`)
const items = (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: 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()
}
}
}
]
]
}
</script>
<template>
<B24Editor
v-slot="{ editor }"
v-model="value"
content-type="markdown"
class="w-full min-h-113"
>
<B24EditorToolbar
:editor="editor"
:items="items(editor)"
layout="bubble"
:should-show="({ editor, view }) => {
return editor.isActive('image') && view.hasFocus()
}"
/>
</B24Editor>
</template>
С выпадающим окном для ссылки
Этот пример показывает, как собрать своё выпадающее окно для ссылки через свойство slot у элементов панели и компонент Popover.
- Создайте Vue-компонент, который оборачивает Popover и позволяет редактировать ссылку:
<script setup lang="ts">
import type { Editor } from '@tiptap/vue-3'
import LinkIcon from '@bitrix24/b24icons-vue/outline/LinkIcon'
import LowerRightArrowIcon from '@bitrix24/b24icons-vue/outline/LowerRightArrowIcon'
import GoToLIcon from '@bitrix24/b24icons-vue/outline/GoToLIcon'
import TrashcanIcon from '@bitrix24/b24icons-vue/outline/TrashcanIcon'
const props = defineProps<{
editor: Editor
autoOpen?: boolean
}>()
const open = ref(false)
const url = ref('')
const active = computed(() => props.editor.isActive('link'))
const disabled = computed(() => {
if (!props.editor.isEditable) return true
const { selection } = props.editor.state
return selection.empty && !props.editor.isActive('link')
})
watch(() => props.editor, (editor, _, onCleanup) => {
if (!editor) return
const updateUrl = () => {
const { href } = editor.getAttributes('link')
url.value = href || ''
}
updateUrl()
editor.on('selectionUpdate', updateUrl)
onCleanup(() => {
editor.off('selectionUpdate', updateUrl)
})
}, { immediate: true })
watch(active, (isActive) => {
if (isActive && props.autoOpen) {
open.value = true
}
})
function setLink() {
if (!url.value) return
const { selection } = props.editor.state
const isEmpty = selection.empty
const hasCode = props.editor.isActive('code')
let chain = props.editor.chain().focus()
// При добавлении ссылки к коду сначала расширяем диапазон метки кода, чтобы выделить весь код
if (hasCode && !isEmpty) {
chain = chain.extendMarkRange('code').setLink({ href: url.value })
} else {
chain = chain.extendMarkRange('link').setLink({ href: url.value })
if (isEmpty) {
chain = chain.insertContent({ type: 'text', text: url.value })
}
}
chain.run()
open.value = false
}
function removeLink() {
props.editor
.chain()
.focus()
.extendMarkRange('link')
.unsetLink()
.setMeta('preventAutolink', true)
.run()
url.value = ''
open.value = false
}
function openLink() {
if (!url.value) return
window.open(url.value, '_blank', 'noopener,noreferrer')
}
function handleKeyDown(event: KeyboardEvent) {
if (event.key === 'Enter') {
event.preventDefault()
setLink()
}
}
</script>
<template>
<B24Popover v-model:open="open" :b24ui="{ content: 'p-0.5' }">
<B24Tooltip text="Ссылка">
<B24Button
:icon="LinkIcon"
color="air-tertiary-no-accent"
active-color="air-primary"
size="sm"
:active="active"
:disabled="disabled"
/>
</B24Tooltip>
<template #content>
<B24Input
v-model="url"
no-border
autofocus
name="url"
type="url"
size="sm"
placeholder="Вставьте ссылку..."
@keydown="handleKeyDown"
>
<div class="flex items-center me-0.5">
<B24Button
:icon="LowerRightArrowIcon"
color="air-tertiary-accent"
size="sm"
:disabled="!url && !active"
title="Применить ссылку"
@click="setLink"
/>
<B24Separator orientation="vertical" class="h-6 mx-1" />
<B24Button
:icon="GoToLIcon"
color="air-tertiary-no-accent"
size="sm"
:disabled="!url && !active"
title="Открыть в новом окне"
@click="openLink"
/>
<B24Button
:icon="TrashcanIcon"
color="air-tertiary-no-accent"
size="sm"
:disabled="!url && !active"
title="Удалить ссылку"
@click="removeLink"
/>
</div>
</B24Input>
</template>
</B24Popover>
</template>
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import type { Editor } from '@tiptap/vue-3'
import LinkIcon from '@bitrix24/b24icons-vue/outline/LinkIcon'
import LowerRightArrowIcon from '@bitrix24/b24icons-vue/outline/LowerRightArrowIcon'
import GoToLIcon from '@bitrix24/b24icons-vue/outline/GoToLIcon'
import TrashcanIcon from '@bitrix24/b24icons-vue/outline/TrashcanIcon'
const props = defineProps<{
editor: Editor
autoOpen?: boolean
}>()
const open = ref(false)
const url = ref('')
const active = computed(() => props.editor.isActive('link'))
const disabled = computed(() => {
if (!props.editor.isEditable) return true
const { selection } = props.editor.state
return selection.empty && !props.editor.isActive('link')
})
watch(() => props.editor, (editor, _, onCleanup) => {
if (!editor) return
const updateUrl = () => {
const { href } = editor.getAttributes('link')
url.value = href || ''
}
updateUrl()
editor.on('selectionUpdate', updateUrl)
onCleanup(() => {
editor.off('selectionUpdate', updateUrl)
})
}, { immediate: true })
watch(active, (isActive) => {
if (isActive && props.autoOpen) {
open.value = true
}
})
function setLink() {
if (!url.value) return
const { selection } = props.editor.state
const isEmpty = selection.empty
const hasCode = props.editor.isActive('code')
let chain = props.editor.chain().focus()
// При добавлении ссылки к коду сначала расширяем диапазон метки кода, чтобы выделить весь код
if (hasCode && !isEmpty) {
chain = chain.extendMarkRange('code').setLink({ href: url.value })
} else {
chain = chain.extendMarkRange('link').setLink({ href: url.value })
if (isEmpty) {
chain = chain.insertContent({ type: 'text', text: url.value })
}
}
chain.run()
open.value = false
}
function removeLink() {
props.editor
.chain()
.focus()
.extendMarkRange('link')
.unsetLink()
.setMeta('preventAutolink', true)
.run()
url.value = ''
open.value = false
}
function openLink() {
if (!url.value) return
window.open(url.value, '_blank', 'noopener,noreferrer')
}
function handleKeyDown(event: KeyboardEvent) {
if (event.key === 'Enter') {
event.preventDefault()
setLink()
}
}
</script>
<template>
<B24Popover v-model:open="open" :b24ui="{ content: 'p-0.5' }">
<B24Tooltip text="Ссылка">
<B24Button
:icon="LinkIcon"
color="air-tertiary-no-accent"
active-color="air-primary"
size="sm"
:active="active"
:disabled="disabled"
/>
</B24Tooltip>
<template #content>
<B24Input
v-model="url"
no-border
autofocus
name="url"
type="url"
size="sm"
placeholder="Вставьте ссылку..."
@keydown="handleKeyDown"
>
<div class="flex items-center me-0.5">
<B24Button
:icon="LowerRightArrowIcon"
color="air-tertiary-accent"
size="sm"
:disabled="!url && !active"
title="Применить ссылку"
@click="setLink"
/>
<B24Separator orientation="vertical" class="h-6 mx-1" />
<B24Button
:icon="GoToLIcon"
color="air-tertiary-no-accent"
size="sm"
:disabled="!url && !active"
title="Открыть в новом окне"
@click="openLink"
/>
<B24Button
:icon="TrashcanIcon"
color="air-tertiary-no-accent"
size="sm"
:disabled="!url && !active"
title="Удалить ссылку"
@click="removeLink"
/>
</div>
</B24Input>
</template>
</B24Popover>
</template>
- Используйте этот компонент в панели через именованный слот:
<script setup lang="ts">
import type { EditorToolbarItem } from '@bxshefby/b24ui-nuxt'
import EditorLinkPopover from './EditorLinkPopover.vue'
import BoldIcon from '@bitrix24/b24icons-vue/outline/BoldIcon'
import ItalicIcon from '@bitrix24/b24icons-vue/outline/ItalicIcon'
const value = ref(`Выделите текст и нажмите кнопку ссылки, чтобы добавить ссылку через собственный поповер.
Можно также изменять существующие ссылки, например [эту](https://bitrix24.github.io/b24ui/).`)
const toolbarItems = [
[
{
kind: 'mark',
mark: 'bold',
icon: BoldIcon
},
{
kind: 'mark',
mark: 'italic',
icon: ItalicIcon
},
{
slot: 'link' as const
}
]
] satisfies EditorToolbarItem[][]
</script>
<template>
<B24Editor
v-slot="{ editor }"
v-model="value"
content-type="markdown"
class="w-full min-h-30 flex flex-col gap-4"
>
<B24EditorToolbar :editor="editor" :items="toolbarItems" class="sm:px-8">
<template #link>
<EditorLinkPopover :editor="editor" auto-open />
</template>
</B24EditorToolbar>
</B24Editor>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import type { EditorToolbarItem } from '@bxshefby/b24ui-nuxt'
import EditorLinkPopover from './EditorLinkPopover.vue'
import BoldIcon from '@bitrix24/b24icons-vue/outline/BoldIcon'
import ItalicIcon from '@bitrix24/b24icons-vue/outline/ItalicIcon'
const value = ref(`Выделите текст и нажмите кнопку ссылки, чтобы добавить ссылку через собственный поповер.
Можно также изменять существующие ссылки, например [эту](https://bitrix24.github.io/b24ui/).`)
const toolbarItems = [
[
{
kind: 'mark',
mark: 'bold',
icon: BoldIcon
},
{
kind: 'mark',
mark: 'italic',
icon: ItalicIcon
},
{
slot: 'link' as const
}
]
] satisfies EditorToolbarItem[][]
</script>
<template>
<B24Editor
v-slot="{ editor }"
v-model="value"
content-type="markdown"
class="w-full min-h-30 flex flex-col gap-4"
>
<B24EditorToolbar :editor="editor" :items="toolbarItems" class="sm:px-8">
<template #link>
<EditorLinkPopover :editor="editor" auto-open />
</template>
</B24EditorToolbar>
</B24Editor>
</template>
API
Пропсы
| Prop | Default | Type |
|---|---|---|
as | 'div' | anyThe element or component this component should render as. |
editor | Editor | |
color | 'air-tertiary-no-accent' | "air-primary" | "air-primary-success" | "air-primary-alert" | "air-primary-copilot" | "air-secondary" | "air-secondary-alert" | "air-secondary-accent" | "air-secondary-accent-1" | "air-secondary-accent-2" | "air-secondary-no-accent" | "air-tertiary" | "air-tertiary-accent" | "air-tertiary-no-accent" | "air-selection" | "air-boost" | "link"The color of the toolbar controls. |
activeColor | 'air-tertiary-accent' | "air-primary" | "air-primary-success" | "air-primary-alert" | "air-primary-copilot" | "air-secondary" | "air-secondary-alert" | "air-secondary-accent" | "air-secondary-accent-1" | "air-secondary-accent-2" | "air-secondary-no-accent" | "air-tertiary" | "air-tertiary-accent" | "air-tertiary-no-accent" | "air-selection" | "air-boost" | "link"The color of the active toolbar control. |
size | 'sm' | "xs" | "md" | "xss" | "sm" | "lg" | "xl"The size of the toolbar controls. |
items | T | |
layout | 'fixed' | "fixed" | "floating" | "bubble" |
pluginKey | unknownThe plugin key. The plugin key for the floating menu. | |
updateDelay | unknownThe delay in milliseconds before the menu should be updated. This can be useful to prevent performance issues. | |
resizeDelay | unknownThe delay in milliseconds before the menu position should be updated on window resize. This can be useful to prevent performance issues. | |
shouldShow | unknownA function that determines whether the menu should be shown or not.
If this function returns | |
appendTo | unknownThe DOM element to append your menu to. Default is the editor's parent element. Sometimes the menu needs to be appended to a different DOM context due to accessibility, clipping, or z-index issues. | |
getReferencedVirtualElement | unknownA function that returns the virtual element for the menu. This is useful when the menu needs to be positioned relative to a specific DOM element. | |
options | unknownThe options for the bubble menu. Those are passed to Floating UI and include options for the placement, offset, flip, shift, arrow, size, autoPlacement, hide, and inline middlewares. The options for the floating menu. Those are passed to Floating UI and include options for the placement, offset, flip, shift, arrow, size, autoPlacement, hide, and inline middlewares. | |
b24ui | { root?: SlotClass; base?: SlotClass; group?: SlotClass; separator?: SlotClass; } |
Слоты
| Slot | Type |
|---|---|
item | { item: NestedItem<T>; } & SlotPropsProps |
Тема
export default {
slots: {
root: 'focus:outline-none',
base: 'flex items-stretch gap-1.5',
group: 'flex items-center gap-0.5',
separator: 'w-px self-stretch bg-(--ui-color-design-tinted-na-stroke)'
},
variants: {
layout: {
bubble: {
base: 'backdrop-blur-3xl bg-(--ui-color-bg-content-primary) border border-(--ui-color-divider-default) rounded-md p-1'
},
floating: {
base: 'backdrop-blur-3xl bg-(--ui-color-bg-content-primary) border border-(--ui-color-divider-default) rounded-md p-1'
},
fixed: {
base: ''
}
}
}
}