Editor 에디터
TipTap 기반의 리치 텍스트 편집기 컴포넌트예요. Markdown·HTML·JSON 콘텐츠 형식을 지원하고, 커스터마이즈 가능한 툴바·드래그 앤 드롭 블록 재정렬·슬래시 명령·멘션·이모지 선택기와 확장 가능한 구조를 제공해요.
출처: Nuxt UI
본문
Markdown, HTML, JSON 콘텐츠 형식을 지원하는 TipTap 기반 리치 텍스트 편집기 컴포넌트예요.
사용법 (Usage)
Editor 컴포넌트는 TipTap 기반의 강력한 리치 텍스트 편집 경험을 제공해요. 여러 콘텐츠 형식(JSON, HTML, Markdown), 커스터마이즈 가능한 툴바, 드래그 앤 드롭 블록 재정렬, 슬래시 명령, 멘션, 이모지 선택기, 그리고 커스텀 기능을 추가할 수 있는 확장 가능한 구조를 지원해요.
<script setup lang="ts">
import type { EditorCustomHandlers, EditorToolbarItem, EditorSuggestionMenuItem, EditorMentionMenuItem, EditorEmojiMenuItem, DropdownMenuItem } from '@nuxt/ui'
import type { Editor, JSONContent } from '@tiptap/vue-3'
import { upperFirst } from 'scule'
import { mapEditorItems } from '@nuxt/ui/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 { useEditorCompletion } from './EditorUseCompletion'
import EditorLinkPopover from './EditorLinkPopover.vue'
const editorRef = useTemplateRef('editorRef')
const value = ref(`# Building Modern Interfaces with Nuxt UI
Welcome to the **Nuxt UI Editor** — a powerful rich text editing experience built on [TipTap](https://tiptap.dev). This editor combines *flexibility* with ease of use, making content creation a breeze.

## Rich Formatting Options
The editor supports all common text formatting including **bold**, *italic*, <u>underline</u>, ~~strikethrough~~, and \`inline code\`. You can also combine them for **_bold and italic_** text.
### Interactive Features
Try out these powerful capabilities:
- **Bubble Menu** — Select any text to see formatting options appear
- **Slash Commands** — Type \`/\` for quick access to blocks and formatting
- **Mentions** — Use \`@\` to tag people or entities
- **Emoji Picker** — Type \`:\` followed by an emoji name like :smile:
- **Drag & Drop** — Hover over any block to see the drag handle
> **Pro tip:** You can use keyboard shortcuts like Cmd/Ctrl + B for bold, Cmd/Ctrl + I for italic, and more!
### Advanced Capabilities
1. **Custom Extensions** — Add your own TipTap extensions seamlessly
2. **Multiple Content Types** — Support for JSON, HTML, and Markdown
3. **Customizable Toolbars** — Fixed, bubble, and floating layouts
4. **Theme Integration** — Fully styled with Nuxt UI theme system
#### Code Blocks
Perfect for technical documentation:
\`\`\`vue
<template>
<UEditor v-model="value" content-type="markdown" />
</template>
\`\`\`
---
Whether you're building a blog, documentation site, or content management system, the Nuxt UI Editor provides everything you need for a professional editing experience. Visit [ui.nuxt.com](https://ui.nuxt.com) to explore more components.`)
const { extension: completionExtension, handlers: aiHandlers, isLoading: aiLoading } = useEditorCompletion(editorRef)
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
},
...aiHandlers
} satisfies EditorCustomHandlers
const fixedToolbarItems = [[{
kind: 'undo',
icon: 'i-lucide-undo',
tooltip: { text: 'Undo' }
}, {
kind: 'redo',
icon: 'i-lucide-redo',
tooltip: { text: 'Redo' }
}], [{
icon: 'i-lucide-heading',
tooltip: { text: 'Headings' },
content: {
align: 'start'
},
items: [{
kind: 'heading',
level: 1,
icon: 'i-lucide-heading-1',
label: 'Heading 1'
}, {
kind: 'heading',
level: 2,
icon: 'i-lucide-heading-2',
label: 'Heading 2'
}, {
kind: 'heading',
level: 3,
icon: 'i-lucide-heading-3',
label: 'Heading 3'
}, {
kind: 'heading',
level: 4,
icon: 'i-lucide-heading-4',
label: 'Heading 4'
}]
}, {
icon: 'i-lucide-list',
tooltip: { text: 'Lists' },
content: {
align: 'start'
},
items: [{
kind: 'bulletList',
icon: 'i-lucide-list',
label: 'Bullet List'
}, {
kind: 'orderedList',
icon: 'i-lucide-list-ordered',
label: 'Ordered List'
}]
}, {
kind: 'blockquote',
icon: 'i-lucide-text-quote',
tooltip: { text: 'Blockquote' }
}, {
kind: 'codeBlock',
icon: 'i-lucide-square-code',
tooltip: { text: 'Code Block' }
}], [{
kind: 'mark',
mark: 'bold',
icon: 'i-lucide-bold',
tooltip: { text: 'Bold' }
}, {
kind: 'mark',
mark: 'italic',
icon: 'i-lucide-italic',
tooltip: { text: 'Italic' }
}, {
kind: 'mark',
mark: 'underline',
icon: 'i-lucide-underline',
tooltip: { text: 'Underline' }
}, {
kind: 'mark',
mark: 'strike',
icon: 'i-lucide-strikethrough',
tooltip: { text: 'Strikethrough' }
}, {
kind: 'mark',
mark: 'code',
icon: 'i-lucide-code',
tooltip: { text: 'Code' }
}], [{
slot: 'link' as const,
icon: 'i-lucide-link'
}, {
kind: 'imageUpload',
icon: 'i-lucide-image',
tooltip: { text: 'Image' }
}], [{
icon: 'i-lucide-align-justify',
tooltip: { text: 'Text Align' },
content: {
align: 'end'
},
items: [{
kind: 'textAlign',
align: 'left',
icon: 'i-lucide-align-left',
label: 'Align Left'
}, {
kind: 'textAlign',
align: 'center',
icon: 'i-lucide-align-center',
label: 'Align Center'
}, {
kind: 'textAlign',
align: 'right',
icon: 'i-lucide-align-right',
label: 'Align Right'
}, {
kind: 'textAlign',
align: 'justify',
icon: 'i-lucide-align-justify',
label: 'Align Justify'
}]
}]] satisfies EditorToolbarItem<typeof customHandlers>[][]
const bubbleToolbarItems = computed(() => [[{
icon: 'i-lucide-sparkles',
label: 'Improve',
activeColor: 'neutral',
activeVariant: 'ghost',
loading: aiLoading.value,
content: {
align: 'start'
},
items: [{
kind: 'aiFix',
icon: 'i-lucide-spell-check',
label: 'Fix spelling & grammar'
}, {
kind: 'aiExtend',
icon: 'i-lucide-unfold-vertical',
label: 'Extend text'
}, {
kind: 'aiReduce',
icon: 'i-lucide-fold-vertical',
label: 'Reduce text'
}, {
kind: 'aiSimplify',
icon: 'i-lucide-lightbulb',
label: 'Simplify text'
}, {
kind: 'aiContinue',
icon: 'i-lucide-text',
label: 'Continue sentence'
}, {
kind: 'aiSummarize',
icon: 'i-lucide-list',
label: 'Summarize'
}, {
icon: 'i-lucide-languages',
label: 'Translate',
children: [{
kind: 'aiTranslate',
language: 'English',
label: 'English'
}, {
kind: 'aiTranslate',
language: 'French',
label: 'French'
}, {
kind: 'aiTranslate',
language: 'Spanish',
label: 'Spanish'
}, {
kind: 'aiTranslate',
language: 'German',
label: 'German'
}]
}]
}], [{
label: 'Turn into',
trailingIcon: 'i-lucide-chevron-down',
activeColor: 'neutral',
activeVariant: 'ghost',
tooltip: { text: 'Turn into' },
content: {
align: 'start'
},
ui: {
label: 'text-xs'
},
items: [{
type: 'label',
label: 'Turn into'
}, {
kind: 'paragraph',
label: 'Paragraph',
icon: 'i-lucide-type'
}, {
kind: 'heading',
level: 1,
icon: 'i-lucide-heading-1',
label: 'Heading 1'
}, {
kind: 'heading',
level: 2,
icon: 'i-lucide-heading-2',
label: 'Heading 2'
}, {
kind: 'heading',
level: 3,
icon: 'i-lucide-heading-3',
label: 'Heading 3'
}, {
kind: 'heading',
level: 4,
icon: 'i-lucide-heading-4',
label: 'Heading 4'
}, {
kind: 'bulletList',
icon: 'i-lucide-list',
label: 'Bullet List'
}, {
kind: 'orderedList',
icon: 'i-lucide-list-ordered',
label: 'Ordered List'
}, {
kind: 'blockquote',
icon: 'i-lucide-text-quote',
label: 'Blockquote'
}, {
kind: 'codeBlock',
icon: 'i-lucide-square-code',
label: 'Code Block'
}]
}], [{
kind: 'mark',
mark: 'bold',
icon: 'i-lucide-bold',
tooltip: { text: 'Bold' }
}, {
kind: 'mark',
mark: 'italic',
icon: 'i-lucide-italic',
tooltip: { text: 'Italic' }
}, {
kind: 'mark',
mark: 'underline',
icon: 'i-lucide-underline',
tooltip: { text: 'Underline' }
}, {
kind: 'mark',
mark: 'strike',
icon: 'i-lucide-strikethrough',
tooltip: { text: 'Strikethrough' }
}, {
kind: 'mark',
mark: 'code',
icon: 'i-lucide-code',
tooltip: { text: 'Code' }
}], [{
slot: 'link' as const,
icon: 'i-lucide-link'
}, {
kind: 'imageUpload',
icon: 'i-lucide-image',
tooltip: { text: 'Image' }
}], [{
icon: 'i-lucide-align-justify',
tooltip: { text: 'Text Align' },
content: {
align: 'end'
},
items: [{
kind: 'textAlign',
align: 'left',
icon: 'i-lucide-align-left',
label: 'Align Left'
}, {
kind: 'textAlign',
align: 'center',
icon: 'i-lucide-align-center',
label: 'Align Center'
}, {
kind: 'textAlign',
align: 'right',
icon: 'i-lucide-align-right',
label: 'Align Right'
}, {
kind: 'textAlign',
align: 'justify',
icon: 'i-lucide-align-justify',
label: 'Align Justify'
}]
}]] satisfies EditorToolbarItem<typeof customHandlers>[][])
const imageToolbarItems = (editor: Editor): EditorToolbarItem[][] => {
const node = editor.state.doc.nodeAt(editor.state.selection.from)
return [[{
icon: 'i-lucide-download',
to: node?.attrs?.src,
download: true,
tooltip: { text: 'Download' }
}, {
icon: 'i-lucide-refresh-cw',
tooltip: { text: 'Replace' },
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: 'i-lucide-trash',
tooltip: { text: 'Delete' },
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: 'Turn into',
icon: 'i-lucide-repeat-2',
children: [
{ kind: 'paragraph', label: 'Paragraph', icon: 'i-lucide-type' },
{ kind: 'heading', level: 1, label: 'Heading 1', icon: 'i-lucide-heading-1' },
{ kind: 'heading', level: 2, label: 'Heading 2', icon: 'i-lucide-heading-2' },
{ kind: 'heading', level: 3, label: 'Heading 3', icon: 'i-lucide-heading-3' },
{ kind: 'heading', level: 4, label: 'Heading 4', icon: 'i-lucide-heading-4' },
{ kind: 'bulletList', label: 'Bullet List', icon: 'i-lucide-list' },
{ kind: 'orderedList', label: 'Ordered List', icon: 'i-lucide-list-ordered' },
{ kind: 'blockquote', label: 'Blockquote', icon: 'i-lucide-text-quote' },
{ kind: 'codeBlock', label: 'Code Block', icon: 'i-lucide-square-code' }
]
},
{
kind: 'clearFormatting',
pos: selectedNode.value?.pos,
label: 'Reset formatting',
icon: 'i-lucide-rotate-ccw'
}
], [
{
kind: 'duplicate',
pos: selectedNode.value?.pos,
label: 'Duplicate',
icon: 'i-lucide-copy'
},
{
label: 'Copy to clipboard',
icon: 'i-lucide-clipboard',
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: 'Move up',
icon: 'i-lucide-arrow-up'
},
{
kind: 'moveDown',
pos: selectedNode.value?.pos,
label: 'Move down',
icon: 'i-lucide-arrow-down'
}
], [
{
kind: 'delete',
pos: selectedNode.value?.pos,
label: 'Delete',
icon: 'i-lucide-trash'
}
]], customHandlers) as DropdownMenuItem[][]
}
const suggestionItems = [[{
type: 'label',
label: 'AI'
}, {
kind: 'aiContinue',
label: 'Continue writing',
icon: 'i-lucide-sparkles'
}], [{
type: 'label',
label: 'Style'
}, {
kind: 'paragraph',
label: 'Paragraph',
icon: 'i-lucide-type'
}, {
kind: 'heading',
level: 1,
label: 'Heading 1',
icon: 'i-lucide-heading-1'
}, {
kind: 'heading',
level: 2,
label: 'Heading 2',
icon: 'i-lucide-heading-2'
}, {
kind: 'heading',
level: 3,
label: 'Heading 3',
icon: 'i-lucide-heading-3'
}, {
kind: 'bulletList',
label: 'Bullet List',
icon: 'i-lucide-list'
}, {
kind: 'orderedList',
label: 'Numbered List',
icon: 'i-lucide-list-ordered'
}, {
kind: 'blockquote',
label: 'Blockquote',
icon: 'i-lucide-text-quote'
}, {
kind: 'codeBlock',
label: 'Code Block',
icon: 'i-lucide-square-code'
}], [{
type: 'label',
label: 'Insert'
}, {
kind: 'mention',
label: 'Mention',
icon: 'i-lucide-at-sign'
}, {
kind: 'emoji',
label: 'Emoji',
icon: 'i-lucide-smile-plus'
}, {
kind: 'imageUpload',
label: 'Image',
icon: 'i-lucide-image'
}, {
kind: 'horizontalRule',
label: 'Horizontal Rule',
icon: 'i-lucide-separator-horizontal'
}]] satisfies EditorSuggestionMenuItem<typeof customHandlers>[][]
const mentionItems: EditorMentionMenuItem[] = [{
label: 'benjamincanac',
avatar: { src: 'https://avatars.githubusercontent.com/u/739984?v=4', loading: 'lazy' as const }
}, {
label: 'HugoRCD',
avatar: { src: 'https://avatars.githubusercontent.com/u/71938701?v=4', loading: 'lazy' as const }
}, {
label: 'atinux',
avatar: { src: 'https://avatars.githubusercontent.com/u/904724?v=4', loading: 'lazy' as const }
}, {
label: 'romhml',
avatar: { src: 'https://avatars.githubusercontent.com/u/25613751?v=4', loading: 'lazy' as const }
}, {
label: 'sandros94',
avatar: { src: 'https://avatars.githubusercontent.com/u/13056429?v=4', loading: 'lazy' as const }
}, {
label: 'J-Michalek',
avatar: { src: 'https://avatars.githubusercontent.com/u/71264422?v=4', loading: 'lazy' as const }
}, {
label: 'hywax',
avatar: { src: 'https://avatars.githubusercontent.com/u/149865959?v=4', loading: 'lazy' as const }
}]
const emojiItems: EditorEmojiMenuItem[] = gitHubEmojis.filter(emoji => !emoji.name.startsWith('regional_indicator_'))
</script>
<template>
<UEditor
ref="editorRef"
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'
}
}),
completionExtension
]"
:handlers="customHandlers"
placeholder="Write, type '/' for commands..."
:ui="{ base: 'p-8 sm:px-16 py-13.5' }"
class="w-full"
>
<UEditorToolbar :editor="editor" :items="fixedToolbarItems" class="border-b border-muted sticky top-0 inset-x-0 px-8 sm:px-16 py-2 z-50 bg-default overflow-x-auto">
<template #link>
<EditorLinkPopover :editor="editor" auto-open />
</template>
</UEditorToolbar>
<UEditorToolbar
: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>
</UEditorToolbar>
<UEditorToolbar
:editor="editor"
:items="imageToolbarItems(editor)"
layout="bubble"
:should-show="({ editor, view }) => {
return editor.isActive('image') && view.hasFocus()
}"
/>
<UEditorSuggestionMenu :editor="editor" :items="suggestionItems" />
<UEditorMentionMenu :editor="editor" :items="mentionItems" />
<UEditorEmojiMenu :editor="editor" :items="emojiItems" />
<UEditorDragHandle v-slot="{ ui, onClick }" :editor="editor" @node-change="selectedNode = $event">
<UButton
icon="i-lucide-plus"
color="neutral"
variant="ghost"
size="sm"
:class="ui.handle()"
@click="(e) => {
e.stopPropagation()
const selected = onClick()
handlers.suggestion?.execute(editor, { pos: selected?.pos }).run()
}"
/>
<UDropdownMenu
v-slot="{ open }"
:modal="false"
:items="handleItems(editor)"
:content="{ side: 'left' }"
:ui="{ content: 'w-48', label: 'text-xs' }"
@update:open="editor.chain().setMeta('lockDragHandle', $event).run()"
>
<UButton
color="neutral"
variant="ghost"
active-variant="soft"
size="sm"
icon="i-lucide-grip-vertical"
:active="open"
:class="ui.handle()"
/>
</UDropdownMenu>
</UEditorDragHandle>
</UEditor>
</template>
<style>
html.dark .tiptap .shiki,
html.dark .tiptap .shiki span {
color: var(--shiki-dark) !important;
background-color: var(--ui-bg-muted) !important;
}
</style>
[!NOTE] See: https://github.com/nuxt/ui/blob/v4/docs/app/components/content/examples/editor/EditorExample.vue
이 예시는 프로덕션에 바로 쓸 수 있는 Editor 컴포넌트를 보여줘요. GitHub에서 소스 코드를 확인하세요.
[!WARNING]
Editor 컴포넌트나 그 확장 기능을 사용할 때
Adding different instances of a keyed plugin같은 prosemirror 관련 오류가 발생하면,nuxt.config.ts의vite.optimizeDeps.include목록에 prosemirror 패키지들을 추가해야 할 수 있어요. 이렇게 하면 Vite가 이 의존성들을 사전 번들링해 여러 인스턴스가 로드되는 것을 방지해요.export default defineNuxtConfig({ vite: { optimizeDeps: { include: [ '@nuxt/ui > prosemirror-state', '@nuxt/ui > prosemirror-transform', '@nuxt/ui > prosemirror-model', '@nuxt/ui > prosemirror-view', '@nuxt/ui > prosemirror-gapcursor' ] } } })
Content
v-model 지시자로 Editor의 값을 제어해요.
<script setup lang="ts">
const value = ref({
type: "doc",
content: [
{
type: "heading",
attrs: {
level: 1
},
content: [
{
type: "text",
text: "Hello World"
}
]
},
{
type: "paragraph",
content: [
{
type: "text",
text: "This is a "
},
{
type: "text",
marks: [
{
type: "bold"
}
],
text: "rich text"
},
{
type: "text",
text: " editor."
}
]
}
]
})
</script>
<template>
<UEditor v-model="value" class="w-full min-h-21" />
</template>
Content Type
Editor는 v-model의 유형에 따라 콘텐츠 형식을 자동으로 감지해요. 문자열은 html, 객체는 json으로 취급해요.
content-type prop으로 형식을 명시적으로 설정할 수 있어요: json, html, 또는 markdown.
<script setup lang="ts">
const value = ref("<h1>Hello World</h1>\n<p>This is a <strong>rich text</strong> editor.</p>\n")
</script>
<template>
<UEditor v-model="value" content-type="html" class="w-full min-h-21" />
</template>
Extensions
Editor는 기본적으로 다음 확장 기능을 포함해요.
- StarterKit - 핵심 편집 기능(굵게, 기울임, 제목, 목록 등)
- Placeholder - 플레이스홀더 텍스트 표시(
placeholderprop 제공 시) - Image - 이미지 삽입 및 표시
- Mention - @ 멘션 지원
- Markdown - 마크다운 파싱 및 직렬화(콘텐츠 형식이 markdown일 때)
[!NOTE]
각 내장 확장 기능은 해당 prop(
starter-kit,placeholder,image,mention,markdown)으로 TipTap 옵션을 전달해 동작을 커스터마이즈할 수 있어요.
extensions prop을 사용해 추가 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>
<UEditor
v-model="value"
:extensions="[
Emoji,
TextAlign.configure({
types: ['heading', 'paragraph']
})
]"
/>
</template>
[!TIP] See: #with-image-upload
커스텀 TipTap 확장 기능을 만드는 방법은 이미지 업로드 예시를 확인하세요.
Placeholder
placeholder prop으로 빈 문단에 표시할 플레이스홀더 텍스트를 설정할 수 있어요.
<script setup lang="ts">
const value = ref("")
</script>
<template>
<UEditor placeholder="Start writing..." class="w-full min-h-7" />
</template>
[!NOTE]
placeholderprop은 문자열 또는 PlaceholderOptions와 추가mode속성을 가진 객체를 받아요.
everyLine: 포커스되었을 때 모든 빈 줄에 플레이스홀더를 표시해요(기본값).firstLine: 에디터가 비어 있을 때 첫 줄에만 플레이스홀더를 표시해요.<template> <UEditor :placeholder="{ placeholder: 'Start writing...', mode: 'firstLine' }" /> </template>
[!TIP]
기본적으로 플레이스홀더는 최상위 빈 노드에만 나타나요. 목록 항목 같은 중첩 요소에도 표시하려면
includeChildren을true로 설정하세요.<template> <UEditor :placeholder="{ placeholder: 'Start writing...', includeChildren: true }" /> </template>
[!NOTE] See: https://tiptap.dev/docs/editor/extensions/functionality/placeholder
Placeholder 확장 기능에 대해 TipTap 문서에서 자세히 알아보세요.
Starter Kit
starter-kit prop으로 기본 포함된 TipTap StarterKit 확장을 설정할 수 있어요. 여기에는 굵게, 기울임, 제목, 목록, 인용구, 코드 블록 등 일반적인 편집 기능이 포함돼요.
<script setup lang="ts">
const value = ref('<h1>Hello World</h1>\n')
</script>
<template>
<UEditor
v-model="value"
:starter-kit="{
blockquote: false,
headings: {
levels: [1, 2, 3, 4]
},
dropcursor: {
color: 'var(--ui-primary)',
width: 2
},
link: {
openOnClick: false
}
}"
/>
</template>
[!TIP]
일반 텍스트 에디터를 원하면
starter-kit을false로 설정하세요. 그러면 필수 노드(문단, 텍스트, 히스토리)는 유지하고 굵게, 기울임, 제목, 목록, 코드, 인용구, 링크, 가로 구분선 같은 모든 서식 기능을 비활성화해요.
[!NOTE] See: https://tiptap.dev/docs/editor/extensions/functionality/starterkit
StarterKit 확장 기능에 대해 TipTap 문서에서 자세히 알아보세요.
Handlers
Handlers는 TipTap의 내장 명령을 감싸 에디터 동작을 위한 통일된 인터페이스를 제공해요. EditorToolbar 또는 EditorSuggestionMenu 항목에 kind 속성을 추가하면, 해당 handler가 TipTap 명령을 실행하고 그 상태(활성, 비활성 등)를 관리해요.
기본 핸들러 (Default handlers)
Editor 컴포넌트는 다음 기본 핸들러를 제공하며, 툴바나 제안 메뉴 항목에서 kind 속성으로 참조할 수 있어요.
| Handler | Description | Usage |
|---|---|---|
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에 포함되어 있지 않기 때문이에요.
툴바나 제안 메뉴 항목에서 기본 핸들러를 사용하는 방법은 다음과 같아요.
<script setup lang="ts">
import type { EditorToolbarItem } from '@nuxt/ui'
const value = ref('<h1>Hello World</h1>\n')
const items: EditorToolbarItem[] = [
{ kind: 'mark', mark: 'bold', icon: 'i-lucide-bold' },
{ kind: 'mark', mark: 'italic', icon: 'i-lucide-italic' },
{ kind: 'heading', level: 1, icon: 'i-lucide-heading-1' },
{ kind: 'heading', level: 2, icon: 'i-lucide-heading-2' },
{ kind: 'textAlign', align: 'left', icon: 'i-lucide-align-left' },
{ kind: 'textAlign', align: 'center', icon: 'i-lucide-align-center' },
{ kind: 'bulletList', icon: 'i-lucide-list' },
{ kind: 'orderedList', icon: 'i-lucide-list-ordered' },
{ kind: 'blockquote', icon: 'i-lucide-quote' },
{ kind: 'link', icon: 'i-lucide-link' }
]
</script>
<template>
<UEditor v-slot="{ editor }" v-model="value">
<UEditorToolbar :editor="editor" :items="items" />
</UEditor>
</template>
커스텀 핸들러 (Custom handlers)
handlers prop을 사용해 기본 핸들러를 확장하거나 덮어쓸 수 있어요. 커스텀 핸들러는 기본 핸들러와 병합되므로 새 동작을 추가하거나 기존 동작을 수정할 수 있어요.
각 핸들러는 EditorHandler 인터페이스를 구현해요.
interface EditorHandler {
/* Checks if the command can be executed in the current editor state */
canExecute: (editor: Editor, item?: any) => boolean
/* Executes the command and returns a Tiptap chain */
execute: (editor: Editor, item?: any) => any
/* Determines if the item should appear active (used for toggle states) */
isActive: (editor: Editor, item?: any) => boolean
/* Optional additional check to disable the item (combined with `canExecute`) */
isDisabled?: (editor: Editor, item?: any) => boolean
}
커스텀 핸들러를 만드는 예시예요.
<script setup lang="ts">
import type { Editor } from '@tiptap/vue-3'
import type { EditorCustomHandlers, EditorToolbarItem } from '@nuxt/ui'
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 = [
// Built-in handler
{ kind: 'mark', mark: 'bold', icon: 'i-lucide-bold' },
// Custom handler
{ kind: 'highlight', icon: 'i-lucide-highlighter' }
] satisfies EditorToolbarItem<typeof customHandlers>[]
</script>
<template>
<UEditor v-slot="{ editor }" v-model="value" :handlers="customHandlers">
<UEditorToolbar :editor="editor" :items="items" />
</UEditor>
</template>
[!TIP] See: #with-image-upload
커스텀 핸들러를 완전하게 구현한 예시는 이미지 업로드 예시를 확인하세요.
예시 (Examples)
[!NOTE] See: https://github.com/nuxt-ui-templates/editor
GitHub의 Editor 템플릿 소스 코드에서 실제 사용 예시를 확인하세요.
툴바 사용하기 (With toolbar)
EditorToolbar 컴포넌트를 사용해 fixed, bubble, 또는 floating 툴바를 Editor에 추가하고 일반적인 포맷팅 동작을 실행할 수 있어요.
<script setup lang="ts">
import type { EditorToolbarItem } from '@nuxt/ui'
const value = ref(`# Toolbar
Select some text to see the formatting toolbar appear above your selection.`)
const items: EditorToolbarItem[][] = [[{
icon: 'i-lucide-heading',
tooltip: { text: 'Headings' },
content: {
align: 'start'
},
items: [{
kind: 'heading',
level: 1,
icon: 'i-lucide-heading-1',
label: 'Heading 1'
}, {
kind: 'heading',
level: 2,
icon: 'i-lucide-heading-2',
label: 'Heading 2'
}, {
kind: 'heading',
level: 3,
icon: 'i-lucide-heading-3',
label: 'Heading 3'
}, {
kind: 'heading',
level: 4,
icon: 'i-lucide-heading-4',
label: 'Heading 4'
}]
}], [{
kind: 'mark',
mark: 'bold',
icon: 'i-lucide-bold',
tooltip: { text: 'Bold' }
}, {
kind: 'mark',
mark: 'italic',
icon: 'i-lucide-italic',
tooltip: { text: 'Italic' }
}, {
kind: 'mark',
mark: 'underline',
icon: 'i-lucide-underline',
tooltip: { text: 'Underline' }
}, {
kind: 'mark',
mark: 'strike',
icon: 'i-lucide-strikethrough',
tooltip: { text: 'Strikethrough' }
}, {
kind: 'mark',
mark: 'code',
icon: 'i-lucide-code',
tooltip: { text: 'Code' }
}]]
</script>
<template>
<UEditor
v-slot="{ editor }"
v-model="value"
content-type="markdown"
class="w-full min-h-21"
>
<UEditorToolbar :editor="editor" :items="items" layout="bubble" />
</UEditor>
</template>
드래그 핸들 사용하기 (With drag handle)
EditorDragHandle 컴포넌트를 사용해 블록 재정렬을 위한 드래그 가능한 핸들을 추가할 수 있어요.
<script setup lang="ts">
const value = ref(`# Drag Handle
Hover over the left side of this block to see the drag handle appear and reorder blocks.`)
</script>
<template>
<UEditor
v-slot="{ editor }"
v-model="value"
content-type="markdown"
class="w-full min-h-21"
>
<UEditorDragHandle :editor="editor" />
</UEditor>
</template>
제안 메뉴 사용하기 (With suggestion menu)
EditorSuggestionMenu 컴포넌트를 사용해 빠른 포맷팅과 삽입을 위한 슬래시 명령을 추가할 수 있어요.
<script setup lang="ts">
import type { EditorSuggestionMenuItem } from '@nuxt/ui'
const value = ref(`# Suggestion Menu
Type / to open the suggestion menu and browse available formatting commands.`)
const items: EditorSuggestionMenuItem[][] = [[{
type: 'label',
label: 'Text'
}, {
kind: 'paragraph',
label: 'Paragraph',
icon: 'i-lucide-type'
}, {
kind: 'heading',
level: 1,
label: 'Heading 1',
icon: 'i-lucide-heading-1'
}, {
kind: 'heading',
level: 2,
label: 'Heading 2',
icon: 'i-lucide-heading-2'
}, {
kind: 'heading',
level: 3,
label: 'Heading 3',
icon: 'i-lucide-heading-3'
}], [{
type: 'label',
label: 'Lists'
}, {
kind: 'bulletList',
label: 'Bullet List',
icon: 'i-lucide-list'
}, {
kind: 'orderedList',
label: 'Numbered List',
icon: 'i-lucide-list-ordered'
}], [{
type: 'label',
label: 'Insert'
}, {
kind: 'blockquote',
label: 'Blockquote',
icon: 'i-lucide-text-quote'
}, {
kind: 'codeBlock',
label: 'Code Block',
icon: 'i-lucide-square-code'
}, {
kind: 'horizontalRule',
label: 'Divider',
icon: 'i-lucide-separator-horizontal'
}]]
// SSR-safe function to append menus to body (avoids z-index issues in docs)
const appendToBody = false ? () => document.body : undefined
</script>
<template>
<UEditor
v-slot="{ editor }"
v-model="value"
content-type="markdown"
placeholder="Type / for commands..."
class="w-full min-h-21"
>
<UEditorSuggestionMenu :editor="editor" :items="items" :append-to="appendToBody" />
</UEditor>
</template>
멘션 메뉴 사용하기 (With mention menu)
EditorMentionMenu 컴포넌트를 사용해 사용자나 엔티티를 태그하는 @ 멘션을 추가할 수 있어요.
<script setup lang="ts">
import type { EditorMentionMenuItem } from '@nuxt/ui'
const value = ref(`# Mention Menu
Type @ to mention someone and select from the list of available users.`)
const items: EditorMentionMenuItem[] = [{
label: 'benjamincanac',
avatar: {
src: 'https://avatars.githubusercontent.com/u/739984?v=4',
loading: 'lazy' as const
}
}, {
label: 'atinux',
avatar: {
src: 'https://avatars.githubusercontent.com/u/904724?v=4',
loading: 'lazy' as const
}
}, {
label: 'danielroe',
avatar: {
src: 'https://avatars.githubusercontent.com/u/28706372?v=4',
loading: 'lazy' as const
}
}, {
label: 'pi0',
avatar: {
src: 'https://avatars.githubusercontent.com/u/5158436?v=4',
loading: 'lazy' as const
}
}]
// SSR-safe function to append menus to body (avoids z-index issues in docs)
const appendToBody = false ? () => document.body : undefined
</script>
<template>
<UEditor
v-slot="{ editor }"
v-model="value"
content-type="markdown"
placeholder="Type @ to mention someone..."
class="w-full min-h-21"
>
<UEditorMentionMenu :editor="editor" :items="items" :append-to="appendToBody" />
</UEditor>
</template>
이모지 메뉴 사용하기 (With emoji menu)
EditorEmojiMenu 컴포넌트를 사용해 이모지 선택기 지원을 추가할 수 있어요.
<script setup lang="ts">
import type { EditorEmojiMenuItem } from '@nuxt/ui'
import { Emoji, gitHubEmojis } from '@tiptap/extension-emoji'
const value = ref(`# Emoji Menu
Type : to insert emojis and select from the list of available emojis.`)
const items: EditorEmojiMenuItem[] = gitHubEmojis.filter(emoji => !emoji.name.startsWith('regional_indicator_'))
// SSR-safe function to append menus to body (avoids z-index issues in docs)
const appendToBody = false ? () => document.body : undefined
</script>
<template>
<UEditor
v-slot="{ editor }"
v-model="value"
:extensions="[Emoji]"
content-type="markdown"
placeholder="Type : to add emojis..."
class="w-full min-h-21"
>
<UEditorEmojiMenu :editor="editor" :items="items" :append-to="appendToBody" />
</UEditor>
</template>
이미지 업로드 (With image upload)
이 예시는 extensions prop으로 커스텀 TipTap 노드를 등록하고 handlers prop으로 툴바 버튼이 업로드 흐름을 트리거하는 방식을 정의해 이미지 업로드 기능을 만드는 방법을 보여줘요.
- FileUpload 컴포넌트를 사용하는 Vue 컴포넌트를 만드세요.
<script setup lang="ts">
import type { NodeViewProps } from '@tiptap/vue-3'
import { NodeViewWrapper } from '@tiptap/vue-3'
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
}
// Simulate upload delay
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>
<UFileUpload
v-model="file"
accept="image/*"
label="Upload an image"
description="SVG, PNG, JPG or GIF (max. 2MB)"
:preview="false"
class="min-h-48"
>
<template #leading>
<UAvatar
:icon="loading ? 'i-lucide-loader-circle' : 'i-lucide-image'"
size="xl"
:ui="{ icon: [loading && 'animate-spin'] }"
/>
</template>
</UFileUpload>
</NodeViewWrapper>
</template>
- 노드를 등록하는 커스텀 TipTap 확장 기능을 만드세요.
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
- Editor에서 커스텀 확장 기능을 사용하세요.
<script setup lang="ts">
import type { EditorCustomHandlers, EditorToolbarItem } from '@nuxt/ui'
import type { Editor } from '@tiptap/vue-3'
import { ImageUpload } from './EditorImageUploadExtension'
const value = ref(`# Image Upload
This editor demonstrates how to create a custom TipTap extension with handlers. Click the image button in the toolbar to upload a file — it will show a custom [FileUpload](/docs/components/file-upload) interface before inserting the image.
Try uploading an image below:
`)
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: 'i-lucide-image',
label: 'Add image',
variant: 'soft'
}], [{
icon: 'i-lucide-heading',
content: {
align: 'start'
},
items: [{
kind: 'heading',
level: 1,
icon: 'i-lucide-heading-1',
label: 'Heading 1'
}, {
kind: 'heading',
level: 2,
icon: 'i-lucide-heading-2',
label: 'Heading 2'
}, {
kind: 'heading',
level: 3,
icon: 'i-lucide-heading-3',
label: 'Heading 3'
}, {
kind: 'heading',
level: 4,
icon: 'i-lucide-heading-4',
label: 'Heading 4'
}]
}], [{
kind: 'mark',
mark: 'bold',
icon: 'i-lucide-bold'
}, {
kind: 'mark',
mark: 'italic',
icon: 'i-lucide-italic'
}, {
kind: 'mark',
mark: 'underline',
icon: 'i-lucide-underline'
}, {
kind: 'mark',
mark: 'strike',
icon: 'i-lucide-strikethrough'
}, {
kind: 'mark',
mark: 'code',
icon: 'i-lucide-code'
}]] satisfies EditorToolbarItem<typeof customHandlers>[][]
</script>
<template>
<UEditor
v-slot="{ editor }"
v-model="value"
:extensions="[ImageUpload]"
:handlers="customHandlers"
content-type="markdown"
:ui="{ base: 'p-8 sm:px-16' }"
class="w-full min-h-74"
>
<UEditorToolbar :editor="editor" :items="items" class="border-b border-muted py-2 px-8 sm:px-16 overflow-x-auto" />
</UEditor>
</template>
[!NOTE] See: https://tiptap.dev/docs/editor/extensions/custom-extensions
커스텀 확장 기능을 만드는 방법에 대해 TipTap 문서에서 자세히 알아보세요.
AI 완성 기능 (With AI completion)
이 예시는 Vercel AI SDK를 사용해 Editor에 AI 기능을 추가하는 방법을 보여줘요. 특히 스트리밍 텍스트 완성을 위한 useCompletion 컴포저블과, 중앙 집중식 엔드포인트를 통해 AI 모델에 접근하는 Vercel AI Gateway를 결합한 방식이에요. 유령 텍스트(ghost text) 자동 완성과 텍스트 변환 동작(문법 수정, 확장, 축소, 단순화, 번역 등)을 포함해요.
[!NOTE]
이 예시를 사용하려면 먼저 다음 의존성들을 설치해야 해요.
pnpm add ai @ai-sdk/vueyarn add ai @ai-sdk/vuenpm install ai @ai-sdk/vuebun add ai @ai-sdk/vue
- 인라인 유령 텍스트 제안을 처리하는 커스텀 TipTap 확장 기능을 만드세요.
import { Extension } from '@tiptap/core'
import { Decoration, DecorationSet } from '@tiptap/pm/view'
import { Plugin, PluginKey } from '@tiptap/pm/state'
import type { Editor } from '@tiptap/vue-3'
import { useDebounceFn } from '@vueuse/core'
export interface CompletionOptions {
/**
* Debounce delay in ms before triggering completion
* @defaultValue 250
*/
debounce?: number
/**
* Whether to automatically trigger completion while typing
* @defaultValue false
*/
autoTrigger?: boolean
/**
* Characters that should prevent completion from triggering
* @defaultValue ['/', ':', '@']
*/
triggerCharacters?: string[]
/**
* Called when completion should be triggered, receives the editor instance
*/
onTrigger?: (editor: Editor) => void
/**
* Called when suggestion is accepted
*/
onAccept?: () => void
/**
* Called when suggestion is dismissed
*/
onDismiss?: () => void
}
export interface CompletionStorage {
suggestion: string
position: number | undefined
visible: boolean
debouncedTrigger: ((editor: Editor) => void) | null
setSuggestion: (text: string) => void
clearSuggestion: () => void
}
export const completionPluginKey = new PluginKey('completion')
export const Completion = Extension.create<CompletionOptions, CompletionStorage>({
name: 'completion',
addOptions() {
return {
debounce: 250,
autoTrigger: false,
triggerCharacters: ['/', ':', '@'],
onTrigger: undefined,
onAccept: undefined,
onDismiss: undefined
}
},
addStorage() {
return {
suggestion: '',
position: undefined as number | undefined,
visible: false,
debouncedTrigger: null as ((editor: Editor) => void) | null,
setSuggestion(text: string) {
this.suggestion = text
},
clearSuggestion() {
this.suggestion = ''
this.position = undefined
this.visible = false
}
}
},
addProseMirrorPlugins() {
const storage = this.storage
return [
new Plugin({
key: completionPluginKey,
props: {
decorations(state) {
if (!storage.visible || !storage.suggestion || storage.position === undefined) {
return DecorationSet.empty
}
const widget = Decoration.widget(storage.position, () => {
const span = document.createElement('span')
span.className = 'completion-suggestion'
span.textContent = storage.suggestion
span.style.cssText = 'color: var(--ui-text-muted); opacity: 0.6; pointer-events: none;'
return span
}, { side: 1 })
return DecorationSet.create(state.doc, [widget])
}
}
})
]
},
addKeyboardShortcuts() {
return {
'Mod-j': ({ editor }) => {
// Clear any existing suggestion first to avoid flickering
if (this.storage.visible) {
this.storage.clearSuggestion()
this.options.onDismiss?.()
}
// Manually trigger completion
this.storage.debouncedTrigger?.(editor as Editor)
return true
},
'Tab': ({ editor }) => {
if (!this.storage.visible || !this.storage.suggestion || this.storage.position === undefined) {
return false
}
// Store values before clearing
const suggestion = this.storage.suggestion
const position = this.storage.position
// Clear suggestion first
this.storage.clearSuggestion()
// Force decoration update
editor.view.dispatch(editor.state.tr.setMeta('completionUpdate', true))
// Insert the suggestion text
editor.chain().focus().insertContentAt(position, suggestion).run()
this.options.onAccept?.()
return true
},
'Escape': ({ editor }) => {
if (this.storage.visible) {
this.storage.clearSuggestion()
// Force decoration update
editor.view.dispatch(editor.state.tr.setMeta('completionUpdate', true))
this.options.onDismiss?.()
return true
}
return false
}
}
},
onUpdate({ editor }) {
// Clear suggestion on any edit
if (this.storage.visible) {
this.storage.clearSuggestion()
// Force decoration update
editor.view.dispatch(editor.state.tr.setMeta('completionUpdate', true))
this.options.onDismiss?.()
}
// Debounced trigger check (only if autoTrigger is enabled)
if (this.options.autoTrigger) {
this.storage.debouncedTrigger?.(editor as Editor)
}
},
onSelectionUpdate({ editor }) {
if (this.storage.visible) {
this.storage.clearSuggestion()
// Force decoration update
editor.view.dispatch(editor.state.tr.setMeta('completionUpdate', true))
this.options.onDismiss?.()
}
},
onCreate() {
const storage = this.storage
const options = this.options
// Create debounced trigger function for this instance
this.storage.debouncedTrigger = useDebounceFn((editor: Editor) => {
if (!options.onTrigger) return
const { state } = editor
const { selection } = state
const { $from } = selection
// Only suggest at end of block with content
const isAtEndOfBlock = $from.parentOffset === $from.parent.content.size
const hasContent = $from.parent.textContent.trim().length > 0
const textContent = $from.parent.textContent
// Don't trigger if sentence is complete (ends with punctuation)
const endsWithPunctuation = /[.!?]\s*$/.test(textContent)
// Don't trigger if text ends with trigger characters
const triggerChars = options.triggerCharacters || []
const endsWithTrigger = triggerChars.some(char => textContent.endsWith(char))
if (!isAtEndOfBlock || !hasContent || endsWithPunctuation || endsWithTrigger) {
return
}
// Set position and mark as visible
storage.position = selection.from
storage.visible = true
// Pass editor to let the handler extract content (e.g., as markdown)
options.onTrigger(editor)
}, options.debounce || 250)
},
onDestroy() {
this.storage.debouncedTrigger = null
}
})
export default Completion
- AI 완성 상태와 핸들러를 관리하는 컴포저블을 만드세요.
import { useCompletion } from '@ai-sdk/vue'
import type { Editor } from '@tiptap/vue-3'
import { Completion } from './EditorCompletionExtension'
import type { CompletionStorage } from './EditorCompletionExtension'
type CompletionMode = 'continue' | 'fix' | 'extend' | 'reduce' | 'simplify' | 'summarize' | 'translate'
export interface UseEditorCompletionOptions {
api?: string
}
export function useEditorCompletion(editorRef: Ref<{ editor: Editor | undefined } | null | undefined>, options: UseEditorCompletionOptions = {}) {
// State for direct insertion/transform mode
const insertState = ref<{
pos: number
deleteRange?: { from: number, to: number }
}>()
const mode = ref<CompletionMode>('continue')
const language = ref<string>()
// Helper to get completion storage
function getCompletionStorage() {
const storage = editorRef.value?.editor?.storage as Record<string, CompletionStorage> | undefined
return storage?.completion
}
const { completion, complete, isLoading, stop, setCompletion } = useCompletion({
api: options.api || '/api/completion',
streamProtocol: 'text',
body: computed(() => ({
mode: mode.value,
language: language.value
})),
onFinish: (_prompt, completionText) => {
// For inline suggestion mode, don't clear - let user accept with Tab
const storage = getCompletionStorage()
if (mode.value === 'continue' && storage?.visible) {
return
}
// For transform modes, insert the full completion with markdown parsing
const transformModes = ['fix', 'extend', 'reduce', 'simplify', 'summarize', 'translate']
if (transformModes.includes(mode.value) && insertState.value && completionText) {
const editor = editorRef.value?.editor
if (editor) {
// Delete the original selection if not already done
if (insertState.value.deleteRange) {
editor.chain()
.focus()
.deleteRange(insertState.value.deleteRange)
.run()
}
// Insert with markdown parsing
editor.chain()
.focus()
.insertContentAt(insertState.value.pos, completionText, { contentType: 'markdown' })
.run()
}
}
insertState.value = undefined
},
onError: (error) => {
console.error('AI completion error:', error)
insertState.value = undefined
getCompletionStorage()?.clearSuggestion()
}
})
// Watch completion for inline suggestion updates
watch(completion, (newCompletion, oldCompletion) => {
const editor = editorRef.value?.editor
if (!editor || !newCompletion) return
const storage = getCompletionStorage()
if (storage?.visible) {
// Update inline suggestion
// Add space prefix if needed (so preview matches what will be inserted)
let suggestionText = newCompletion
if (storage.position !== undefined) {
const textBefore = editor.state.doc.textBetween(Math.max(0, storage.position - 1), storage.position)
if (textBefore && !/\s/.test(textBefore) && !suggestionText.startsWith(' ')) {
suggestionText = ' ' + suggestionText
}
}
storage.setSuggestion(suggestionText)
editor.view.dispatch(editor.state.tr.setMeta('completionUpdate', true))
} else if (insertState.value) {
// Direct insertion/transform mode (from toolbar actions)
// Transform modes use markdown insertion - wait for full completion
const transformModes = ['fix', 'extend', 'reduce', 'simplify', 'summarize', 'translate']
if (transformModes.includes(mode.value)) {
// Don't stream - will be handled in onFinish
return
}
// If this is the first chunk and we have a selection to replace, delete it first
if (insertState.value.deleteRange && !oldCompletion) {
editor.chain()
.focus()
.deleteRange(insertState.value.deleteRange)
.run()
insertState.value.deleteRange = undefined
}
let delta = newCompletion.slice(oldCompletion?.length || 0)
if (delta) {
// For single-paragraph transforms, replace all line breaks with spaces
if (['fix', 'simplify', 'translate'].includes(mode.value)) {
delta = delta.replace(/[\r\n]+/g, ' ').replace(/\s{2,}/g, ' ')
}
// For "continue" mode, add a space before if needed (first chunk only)
if (mode.value === 'continue' && !oldCompletion) {
const textBefore = editor.state.doc.textBetween(Math.max(0, insertState.value.pos - 1), insertState.value.pos)
if (textBefore && !/\s/.test(textBefore)) {
delta = ' ' + delta
}
}
editor.chain().focus().command(({ tr }) => {
tr.insertText(delta, insertState.value!.pos)
return true
}).run()
insertState.value.pos += delta.length
}
}
})
function triggerTransform(editor: Editor, transformMode: Exclude<CompletionMode, 'continue'>, lang?: string) {
if (isLoading.value) return
getCompletionStorage()?.clearSuggestion()
const { state } = editor
const { selection } = state
if (selection.empty) return
mode.value = transformMode
language.value = lang
const selectedText = state.doc.textBetween(selection.from, selection.to)
// Replace the selected text with the transformed version
insertState.value = { pos: selection.from, deleteRange: { from: selection.from, to: selection.to } }
complete(selectedText)
}
function getMarkdownBefore(editor: Editor, pos: number): string {
const { state } = editor
const serializer = (editor.storage.markdown as { serializer?: { serialize: (content: unknown) => string } })?.serializer
if (serializer) {
const slice = state.doc.slice(0, pos)
return serializer.serialize(slice.content)
}
// Fallback to plain text
return state.doc.textBetween(0, pos, '\n')
}
function triggerContinue(editor: Editor) {
if (isLoading.value) return
mode.value = 'continue'
getCompletionStorage()?.clearSuggestion()
const { state } = editor
const { selection } = state
if (selection.empty) {
// No selection: continue from cursor position
const textBefore = getMarkdownBefore(editor, selection.from)
insertState.value = { pos: selection.from }
complete(textBefore)
} else {
// Text selected: append completion after the selection
const textBefore = getMarkdownBefore(editor, selection.to)
insertState.value = { pos: selection.to }
complete(textBefore)
}
}
// Configure Completion extension
const extension = Completion.configure({
onTrigger: (editor) => {
if (isLoading.value) return
mode.value = 'continue'
const textBefore = getMarkdownBefore(editor, editor.state.selection.from)
complete(textBefore)
},
onAccept: () => {
setCompletion('')
},
onDismiss: () => {
stop()
setCompletion('')
}
})
// Create handlers for toolbar
const handlers = {
aiContinue: {
canExecute: () => !isLoading.value,
execute: (editor: Editor) => {
triggerContinue(editor)
return editor.chain()
},
isActive: () => !!(isLoading.value && mode.value === 'continue'),
isDisabled: () => !!isLoading.value
},
aiFix: {
canExecute: (editor: Editor) => !editor.state.selection.empty && !isLoading.value,
execute: (editor: Editor) => {
triggerTransform(editor, 'fix')
return editor.chain()
},
isActive: () => !!(isLoading.value && mode.value === 'fix'),
isDisabled: (editor: Editor) => editor.state.selection.empty || !!isLoading.value
},
aiExtend: {
canExecute: (editor: Editor) => !editor.state.selection.empty && !isLoading.value,
execute: (editor: Editor) => {
triggerTransform(editor, 'extend')
return editor.chain()
},
isActive: () => !!(isLoading.value && mode.value === 'extend'),
isDisabled: (editor: Editor) => editor.state.selection.empty || !!isLoading.value
},
aiReduce: {
canExecute: (editor: Editor) => !editor.state.selection.empty && !isLoading.value,
execute: (editor: Editor) => {
triggerTransform(editor, 'reduce')
return editor.chain()
},
isActive: () => !!(isLoading.value && mode.value === 'reduce'),
isDisabled: (editor: Editor) => editor.state.selection.empty || !!isLoading.value
},
aiSimplify: {
canExecute: (editor: Editor) => !editor.state.selection.empty && !isLoading.value,
execute: (editor: Editor) => {
triggerTransform(editor, 'simplify')
return editor.chain()
},
isActive: () => !!(isLoading.value && mode.value === 'simplify'),
isDisabled: (editor: Editor) => editor.state.selection.empty || !!isLoading.value
},
aiSummarize: {
canExecute: (editor: Editor) => !editor.state.selection.empty && !isLoading.value,
execute: (editor: Editor) => {
triggerTransform(editor, 'summarize')
return editor.chain()
},
isActive: () => !!(isLoading.value && mode.value === 'summarize'),
isDisabled: (editor: Editor) => editor.state.selection.empty || !!isLoading.value
},
aiTranslate: {
canExecute: (editor: Editor) => !editor.state.selection.empty && !isLoading.value,
execute: (editor: Editor, cmd: { language?: string } | undefined) => {
triggerTransform(editor, 'translate', cmd?.language)
return editor.chain()
},
isActive: (_editor: Editor, cmd: { language?: string } | undefined) => !!(isLoading.value && mode.value === 'translate' && language.value === cmd?.language),
isDisabled: (editor: Editor) => editor.state.selection.empty || !!isLoading.value
}
}
return {
extension,
handlers,
isLoading,
mode
}
}
streamText를 사용해 완성 요청을 처리하는 서버 API 엔드포인트를 만드세요.
import { streamText, createTextStreamResponse } from 'ai'
export default defineEventHandler(async (event) => {
const { prompt, mode, language } = await readBody(event)
if (!prompt) {
throw createError({ statusCode: 400, message: 'Prompt is required' })
}
let instructions: string
let maxOutputTokens: number
const preserveMarkdown = 'IMPORTANT: Preserve all markdown formatting (bold, italic, links, etc.) exactly as in the original.'
switch (mode) {
case 'fix':
instructions = `You are a writing assistant. Fix all spelling and grammar errors in the given text. ${preserveMarkdown} Only output the corrected text, nothing else.`
maxOutputTokens = 500
break
case 'extend':
instructions = `You are a writing assistant. Extend the given text with more details, examples, and explanations while maintaining the same style. ${preserveMarkdown} Only output the extended text, nothing else.`
maxOutputTokens = 500
break
case 'reduce':
instructions = `You are a writing assistant. Make the given text more concise by removing unnecessary words while keeping the meaning. ${preserveMarkdown} Only output the reduced text, nothing else.`
maxOutputTokens = 300
break
case 'simplify':
instructions = `You are a writing assistant. Simplify the given text to make it easier to understand, using simpler words and shorter sentences. ${preserveMarkdown} Only output the simplified text, nothing else.`
maxOutputTokens = 400
break
case 'summarize':
instructions = 'You are a writing assistant. Summarize the given text concisely while keeping the key points. Only output the summary, nothing else.'
maxOutputTokens = 200
break
case 'translate':
instructions = `You are a writing assistant. Translate the given text to ${language || 'English'}. ${preserveMarkdown} Only output the translated text, nothing else.`
maxOutputTokens = 500
break
case 'continue':
default:
instructions = `You are a writing assistant providing inline autocompletions.
CRITICAL RULES:
- Output ONLY the NEW text that comes AFTER the user's input
- NEVER repeat any words from the end of the user's text
- Keep completions short (1 sentence max)
- Match the tone and style of the existing text
- ${preserveMarkdown}`
maxOutputTokens = 25
break
}
const result = streamText({
model: 'anthropic/claude-haiku-4.5',
instructions,
prompt,
maxOutputTokens
})
return createTextStreamResponse({ stream: result.textStream })
})
- Editor에서 컴포저블을 사용하세요.
<script setup lang="ts">
import type { EditorCustomHandlers, EditorToolbarItem } from '@nuxt/ui'
import { useEditorCompletion } from './EditorUseCompletion'
const editorRef = useTemplateRef('editorRef')
const value = ref(`# AI Completion
This editor demonstrates how to add AI-powered features using the [Vercel AI SDK](https://ai-sdk.dev/). It includes ghost text autocompletion that appears as you type (press Tab to accept) and text transformation actions.
Try selecting some text and using the AI dropdown to fix grammar, extend, or simplify it.`)
const { extension: completionExtension, handlers: aiHandlers, isLoading: aiLoading } = useEditorCompletion(editorRef)
const customHandlers = {
...aiHandlers
} satisfies EditorCustomHandlers
const items = computed(() => [[{
icon: 'i-lucide-sparkles',
label: 'Improve',
variant: 'soft',
loading: aiLoading.value,
content: {
align: 'start'
},
items: [{
kind: 'aiFix',
icon: 'i-lucide-spell-check',
label: 'Fix spelling & grammar'
}, {
kind: 'aiExtend',
icon: 'i-lucide-unfold-vertical',
label: 'Extend text'
}, {
kind: 'aiReduce',
icon: 'i-lucide-fold-vertical',
label: 'Reduce text'
}, {
kind: 'aiSimplify',
icon: 'i-lucide-lightbulb',
label: 'Simplify text'
}, {
kind: 'aiContinue',
icon: 'i-lucide-text',
label: 'Continue sentence'
}, {
kind: 'aiSummarize',
icon: 'i-lucide-list',
label: 'Summarize'
}, {
icon: 'i-lucide-languages',
label: 'Translate',
children: [{
kind: 'aiTranslate',
language: 'English',
label: 'English'
}, {
kind: 'aiTranslate',
language: 'French',
label: 'French'
}, {
kind: 'aiTranslate',
language: 'Spanish',
label: 'Spanish'
}, {
kind: 'aiTranslate',
language: 'German',
label: 'German'
}]
}]
}], [{
icon: 'i-lucide-heading',
content: {
align: 'start'
},
items: [{
kind: 'heading',
level: 1,
icon: 'i-lucide-heading-1',
label: 'Heading 1'
}, {
kind: 'heading',
level: 2,
icon: 'i-lucide-heading-2',
label: 'Heading 2'
}, {
kind: 'heading',
level: 3,
icon: 'i-lucide-heading-3',
label: 'Heading 3'
}]
}], [{
kind: 'mark',
mark: 'bold',
icon: 'i-lucide-bold'
}, {
kind: 'mark',
mark: 'italic',
icon: 'i-lucide-italic'
}, {
kind: 'mark',
mark: 'underline',
icon: 'i-lucide-underline'
}]] satisfies EditorToolbarItem<typeof customHandlers>[][])
</script>
<template>
<UEditor
ref="editorRef"
v-slot="{ editor }"
v-model="value"
:extensions="[completionExtension]"
:handlers="customHandlers"
content-type="markdown"
:ui="{ base: 'p-8 sm:px-16' }"
class="w-full min-h-74"
>
<UEditorToolbar :editor="editor" :items="items" class="border-b border-muted py-2 px-8 sm:px-16 overflow-x-auto" />
</UEditor>
</template>
[!NOTE]
완성 확장 기능은
autoTrigger: true로 설정해 입력 중 자동으로 완성을 제안할 수 있어요(기본적으로 비활성).Metaj로 수동으로 트리거할 수도 있어요.
[!NOTE] See: https://ai-sdk.dev/
Vercel AI SDK와 사용 가능한 공급자들에 대해 자세히 알아보세요.
API
Props
/**
* 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?: "everyLine" | "firstLine" | 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;
ui?: { root?: SlotClass; content?: SlotClass; base?: SlotClass; } | undefined;
/**
* The extensions to use
*/
extensions?: Extensions | 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;
}
Slots
/**
* Slots for the Editor component
*/
interface EditorSlots {
default(): any;
}
Emits
/**
* Emitted events for the Editor component
*/
interface EditorEmits {
update:modelValue: (payload: [value: T]) => void;
}
Expose
템플릿 ref로 컴포넌트에 접근할 때 다음을 사용할 수 있어요.
| Name | Type |
|---|---|
editor |
Ref<Editor | undefined> |
[!NOTE] See: https://tiptap.dev/docs/editor/api/editor
노출된 editor 인스턴스는 TipTap Editor API예요. 사용 가능한 모든 메서드와 속성은 TipTap 문서를 확인하세요.
테마 (Theme)
export default defineAppConfig({
ui: {
editor: {
slots: {
root: '',
content: 'relative size-full flex-1',
base: [
'w-full outline-none *:my-5 *:first:mt-0 *:last:mb-0 sm:px-8 selection:bg-primary/20',
'[&_p]:leading-7',
'[&_a]:text-primary [&_a]:border-b [&_a]:border-transparent [&_a]:hover:border-primary [&_a]:font-medium',
'[&_a]:transition-colors',
'[&_a>code]:border-dashed [&_a:hover>code]:border-primary [&_a:hover>code]:text-primary',
'[&_a>code]:transition-colors',
'[&_.mention]:text-primary [&_.mention]:font-medium',
'[&_:is(h1,h2,h3,h4,h5,h6)]:text-highlighted [&_:is(h1,h2,h3,h4,h5,h6)]:font-bold',
'[&_h1]:text-3xl',
'[&_h2]:text-2xl',
'[&_h3]:text-xl',
'[&_h4]:text-lg',
'[&_h5]:text-base',
'[&_h6]:text-base',
'[&_:is(h1,h2,h3,h4,h5,h6)>code]:border-dashed [&_:is(h1,h2,h3,h4,h5,h6)>code]:font-bold',
'[&_h2>code]:text-xl/6',
'[&_h3>code]:text-lg/5',
'[&_blockquote]:border-s-4 [&_blockquote]:border-accented [&_blockquote]:ps-4 [&_blockquote]:italic',
'[&_[data-type=horizontalRule]]:my-8 [&_[data-type=horizontalRule]]:py-2',
'[&_hr]:border-t [&_hr]:border-default',
'[&_pre]:text-sm/6 [&_pre]:border [&_pre]:border-muted [&_pre]:bg-muted [&_pre]:rounded-md [&_pre]:px-4 [&_pre]:py-3 [&_pre]:whitespace-pre-wrap [&_pre]:break-words [&_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-mono [&_code]:font-medium [&_code]:rounded-md [&_code]:inline-block [&_code]:border [&_code]:border-muted [&_code]:text-highlighted [&_code]:bg-muted',
'[&_:is(ul,ol)]:ps-6',
'[&_ul]:list-disc [&_ul]:marker:text-(--ui-border-accented)',
'[&_ol]:list-decimal [&_ol]:marker:text-muted',
'[&_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-primary',
'[&_.ProseMirror-selectednode:not(img):not(pre):not([data-node-view-wrapper])]:bg-primary/20'
]
},
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-dimmed [&_: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-dimmed [&_: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'
}
}
}
})