RichEditor
HuiRichEditor edits HTML or Tiptap JSON, with a toolbar, links, tables, image uploads, character limits, fullscreen mode and HuiForm integration. Body typography uses .hui-prose. Use HuiRichContent from the same package to display saved HTML without editing it.
Import
Install the following dependencies to use @nscode/handy-ui/editor. This entry provides both rich text display and editing. Keep the Tiptap dependencies on the same version.
pnpm add @floating-ui/dom@^1 dompurify@^3.4.18 @tiptap/core@3.34.0 @tiptap/pm@3.34.0 @tiptap/vue-3@3.34.0 @tiptap/starter-kit@3.34.0 @tiptap/extensions@3.34.0 @tiptap/extension-text-style@3.34.0 @tiptap/extension-text-align@3.34.0 @tiptap/extension-table@3.34.0 @tiptap/extension-image@3.34.0 @tiptap/extension-file-handler@3.34.0
Load the core theme and editor stylesheet at the application entry. Share one Vue, @nscode/handy-ui and Tiptap installation within the application. Keep all Tiptap peers on the same version rather than loading multiple copies of @tiptap/core or @tiptap/pm.
import '@nscode/handy-ui/style.css'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorExpose, RichEditorValue } from '@nscode/handy-ui/editor'
Examples
HTML, creation and events
valueFormat defaults to "html". update:modelValue follows actual editing transactions. After focus leaves the entire editor, change compares the content with the value captured when focus entered. The body, toolbar and this editor's child overlays form one focus region, so switching to a color or link panel does not submit a separate change.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorValue } from '@nscode/handy-ui/editor'
const value = ref<RichEditorValue | null>(
'<p>Select text and try <strong>bold</strong> or insert a link.</p>'
)
const ready = ref(false)
const updates = ref(0)
const changes = ref(0)
const focuses = ref(0)
const blurs = ref(0)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiRichEditor
v-model="value"
placeholder="Enter content"
show-count
aria-label="Basic rich-text content"
@ready="ready = true"
@update:model-value="updates++"
@change="changes++"
@focus="focuses++"
@blur="blurs++"
/>
<p role="status">
Created: {{ ready }}; updates: {{ updates }}; blur commits: {{ changes }}; focus entries:
{{ focuses }}; blur events: {{ blurs }}
</p>
<pre>{{ value }}</pre>
</HuiSpace>
</template>
HTML and JSON
HTML uses '' as its empty value; JSON uses null. JSON follows the current editor schema, so nodes such as paragraphs and headings may include default attributes. JSON returned by getters or update events is a snapshot and does not mutate the supplied object.
Empty tables, images, lists and formatted empty blocks still carry structure and do not become an empty value merely because they contain no plain text. Only ordinary empty content, such as the default empty-paragraph shell, collapses to an empty value.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorValue } from '@nscode/handy-ui/editor'
const html = ref<RichEditorValue | null>('<p>This is an HTML model.</p>')
const json = ref<RichEditorValue | null>({
type: 'doc',
content: [
{
type: 'paragraph',
content: [{ type: 'text', text: 'This is a JSON model.' }]
}
]
})
</script>
<template>
<HuiSpace direction="vertical" fill>
<p>valueFormat=html</p>
<HuiRichEditor v-model="html" :toolbar="['bold', 'italic']" :min-height="100" />
<pre>{{ html }}</pre>
<p>valueFormat=json</p>
<HuiRichEditor
v-model="json"
value-format="json"
:toolbar="['bold', 'italic']"
:min-height="100"
/>
<pre>{{ JSON.stringify(json, null, 2) }}</pre>
</HuiSpace>
</template>
Controlled rejection and listening without a model
The presence of modelValue determines whether the editor is controlled. Explicit undefined also means a controlled empty value. When the parent rejects a candidate, the body returns to the parent's actual value. If updates are observed without supplying a model, the component retains its own content. An update:modelValue event does not prove that the parent accepted the candidate.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorValue } from '@nscode/handy-ui/editor'
const rejected = ref<RichEditorValue | null>('No candidate received')
const listened = ref<RichEditorValue | null>('Not edited yet')
const emptyCandidate = ref<RichEditorValue | null>('No candidate received')
</script>
<template>
<HuiSpace direction="vertical" fill>
<p>Fixed parent value: editing produces candidates, but the parent does not accept them.</p>
<HuiRichEditor
model-value="<p>The parent retains this actual content.</p>"
:toolbar="false"
:min-height="90"
@update:model-value="rejected = $event"
/>
<pre>Last rejected candidate: {{ rejected }}</pre>
<p>Listener only: modelValue is omitted, so edits are retained.</p>
<HuiRichEditor :toolbar="false" :min-height="90" @update:model-value="listened = $event" />
<pre>Latest update: {{ listened }}</pre>
<p>Explicit undefined: a controlled empty value; the parent still rejects edits.</p>
<HuiRichEditor
:model-value="undefined"
:toolbar="false"
:min-height="90"
@update:model-value="emptyCandidate = $event"
/>
<pre>Empty-control candidate: {{ emptyCandidate }}</pre>
</HuiSpace>
</template>
Size, disabled, readonly and body height
size controls the toolbar's control size. readonly retains the body and hides the toolbar; disabled retains a disabled toolbar. Both prevent modifications through component methods and ordinary Tiptap editing transactions. External model updates still apply.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiSwitch } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
const disabled = ref(false)
const readonly = ref(false)
const sizes = ['small', 'default', 'large'] as const
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<label>disabled <HuiSwitch v-model="disabled" /></label>
<label>readonly <HuiSwitch v-model="readonly" /></label>
</HuiSpace>
<div v-for="size in sizes" :key="size">
<p>size={{ size }}; body height=120, minHeight=80, maxHeight=180</p>
<HuiRichEditor
:size="size"
:disabled="disabled"
:readonly="readonly"
:toolbar="['bold', 'italic', 'link', 'fullscreen']"
:height="120"
:min-height="80"
:max-height="180"
:aria-label="`${size}-sized body`"
placeholder="Enter several paragraphs to observe body scrolling"
/>
</div>
</HuiSpace>
</template>
Every built-in toolbar item
Toolbar items render in array order; '|' is a separator. This example also includes code and horizontalRule, which are not shown by the default toolbar. Select text before applying a format, or use “Select all content” to set the selection.
Heading choices include body text and levels 1–4. Font sizes are .75em, default, 1.5em and 2.5em; alignment choices are left, center, right and justified. Paragraphs and headings support indentation levels 0–8. List indentation follows the list's own nesting structure.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSpace } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type {
RichEditorExpose,
RichEditorToolbarItem,
RichEditorValue
} from '@nscode/handy-ui/editor'
const editor = ref<RichEditorExpose>()
const value = ref<RichEditorValue | null>(
'<p>Select this content to compare headings, text sizes, marks and paragraph formatting.</p>'
)
const toolbar: RichEditorToolbarItem[] = [
'undo',
'redo',
'|',
'heading',
'fontSize',
'|',
'bold',
'italic',
'underline',
'strike',
'code',
'color',
'backgroundColor',
'|',
'bulletList',
'orderedList',
'indent',
'outdent',
'align',
'|',
'blockquote',
'codeBlock',
'horizontalRule',
'link',
'image',
'table',
'|',
'clearFormat',
'fullscreen'
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiButton @click="editor?.focus('all')">Select all content</HuiButton>
<HuiRichEditor ref="editor" v-model="value" :toolbar="toolbar" />
<pre>{{ value }}</pre>
</HuiSpace>
</template>
Colors, paragraph alignment and tables
Text and background colors are independent. “Default” removes only the corresponding color, retaining the other one. The panel offers presets and custom colors. Serialization may convert a hexadecimal color into an equivalent rgb(...) value, so original HTML bytes are not a reliable change comparison.
After selecting a table cell, the table tool offers row/column insertion, merging, splitting and removal. Outside a table, it offers an insertion grid up to 8×8. Removing rows, columns or the whole table first confirms the affected content and scope. A document change while confirmation is pending invalidates the old removal.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorValue } from '@nscode/handy-ui/editor'
const value = ref<RichEditorValue | null>(
[
'<p><span style="color:#1677ff;background-color:#fff2b8">Select text to change its foreground and background colors independently.</span></p>',
'<p style="text-align:center">This paragraph starts centered.</p>',
'<table><tbody>',
'<tr><th><p>Task</p></th><th><p>Owner</p></th></tr>',
'<tr><td><p>Review content</p></td><td><p>陈晨</p></td></tr>',
'<tr><td><p>Check attachments</p></td><td><p>李宁</p></td></tr>',
'</tbody></table><p>Click any cell, then open the table tool.</p>'
].join('')
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiRichEditor
v-model="value"
:toolbar="['color', 'backgroundColor', 'align', '|', 'table', 'undo', 'redo']"
/>
<pre>{{ value }}</pre>
</HuiSpace>
</template>
Links
The link panel supports an address, display text and a new-window option. Accepted addresses include http:, https:, mailto:, tel:, paths starting with / and # anchors. After trimming surrounding whitespace, addresses containing internal whitespace or control characters are rejected rather than repaired into another address by concatenation or character removal. New-window links include noopener noreferrer.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorValue } from '@nscode/handy-ui/editor'
const value = ref<RichEditorValue | null>(
'<p>Select text and open the link tool, or click this <a href="#link-preview">page anchor</a> to edit it.</p>'
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiRichEditor v-model="value" :toolbar="['link', 'bold', 'italic']" :min-height="120" />
<p id="link-preview">Clicking a link inside the editor edits it rather than navigating.</p>
<pre>{{ value }}</pre>
</HuiSpace>
</template>
Custom tools and hiding the toolbar
A custom item's shortcut supplies a hint and aria-keyshortcuts only; it does not register a new keyboard shortcut. run receives the real Editor after the component checks disabled/readonly state, instance identity and focus ownership. Applications calling the raw Editor or providing replacement slots must preserve the corresponding interaction guards themselves.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorToolbarItem, RichEditorValue } from '@nscode/handy-ui/editor'
const value = ref<RichEditorValue | null>(
'<p>Select text and use the custom inline-code tool.</p>'
)
const commands = ref(0)
const toolbar: RichEditorToolbarItem[] = [
'bold',
'|',
{
name: 'custom-code',
label: 'Toggle inline code',
icon: 'code-block',
shortcut: 'Mod-Shift-C',
isActive: (editor) => editor.isActive('code'),
isDisabled: (editor) => !editor.can().toggleCode(),
run: (editor) => {
editor.commands.toggleCode()
commands.value++
}
}
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiRichEditor v-model="value" :toolbar="toolbar" :min-height="110" />
<p role="status">Custom command calls: {{ commands }}</p>
<p>toolbar=false: content remains editable without a toolbar.</p>
<HuiRichEditor :toolbar="false" :min-height="90" placeholder="Editor without a toolbar" />
</HuiSpace>
</template>
Sticky toolbar
stickyToolbar=true uses a top offset of 0; a number supplies a pixel offset and false disables it. Sticky positioning follows the actual scroll container and does not create another page-scrolling region.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSpace } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
const sticky = ref<boolean | number>(true)
const html = Array.from(
{ length: 14 },
(_, index) => `<p>Paragraph ${index + 1}: scroll this container to observe the toolbar.</p>`
).join('')
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @click="sticky = true">true</HuiButton>
<HuiButton @click="sticky = 24">24px</HuiButton>
<HuiButton @click="sticky = false">false</HuiButton>
</HuiSpace>
<div style="height: 280px; overflow: auto">
<HuiRichEditor
:model-value="html"
:sticky-toolbar="sticky"
:toolbar="['bold', 'italic', 'link']"
/>
</div>
<p>stickyToolbar={{ sticky }}</p>
</HuiSpace>
</template>
Character limits and counting
maxLength accepts a non-negative finite integer. 0 allows only empty content. The count uses the JavaScript length of text extracted from the document; some Unicode characters occupy two units. It is not an HTML-length or word count. User transactions exceeding the limit are rejected and emit exceed. External values are not silently truncated, and an already oversized document still permits corrections that do not increase its count.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorValue } from '@nscode/handy-ui/editor'
const value = ref<RichEditorValue | null>('')
const rejected = ref(0)
const lastLimit = ref<number>()
const onExceed = (limit: number) => {
rejected.value++
lastLimit.value = limit
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiRichEditor
v-model="value"
:max-length="12"
show-count
:min-height="100"
@exceed="onExceed"
/>
<p role="status">
Rejected transactions: {{ rejected }}; last limit: {{ lastLimit ?? 'not triggered' }}
</p>
<p>maxLength=0: attempted input is not retained.</p>
<HuiRichEditor :max-length="0" :toolbar="false" :min-height="80" @exceed="onExceed" />
</HuiSpace>
</template>
Form validation
The editor inherits form size, disabled and readonly state. Labels and descriptions connect to the actual body, and validation styling reaches the editor border. Inputs inside the toolbar do not register additional business fields. validateEvent=false disables only validation actively requested by the editor; manual validation of the entire form still runs.
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { HuiButton, HuiForm, HuiFormItem, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
import type { FormRule } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorValue } from '@nscode/handy-ui/editor'
const form = ref<InstanceType<typeof HuiForm>>()
const model = reactive({ content: '' as RichEditorValue | null })
const readonly = ref(false)
const disabled = ref(false)
const validateEvent = ref(true)
const result = ref('Not validated yet')
const rules: Record<string, FormRule[]> = {
content: [{ required: true, message: 'Enter content', trigger: ['change', 'blur'] }]
}
const validate = async () => {
const validation = await form.value?.validate()
result.value = validation?.valid
? 'Validation passed'
: 'The content does not satisfy the rules'
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<label>Form readonly <HuiSwitch v-model="readonly" /></label>
<label>Form disabled <HuiSwitch v-model="disabled" /></label>
<label>validateEvent <HuiSwitch v-model="validateEvent" /></label>
</HuiSpace>
<HuiForm
ref="form"
:model="model"
:rules="rules"
:readonly="readonly"
:disabled="disabled"
size="small"
>
<HuiFormItem
label="Content"
prop="content"
tip="Edit and leave the editor, or validate manually."
>
<HuiRichEditor v-model="model.content" :validate-event="validateEvent" :min-height="120" />
</HuiFormItem>
</HuiForm>
<HuiButton @click="validate">Validate manually</HuiButton>
<p role="status">{{ result }}</p>
</HuiSpace>
</template>
Image uploads, validation and late results
The image tool accepts an address and description. With uploadImage configured, users can also choose, paste or drop files. The adapter returns a URL or an object containing src, and rejects on failure. This example uses FileReader to read the image actually selected by the user and returns Base64, so it explicitly enables allowBase64Image. It sends nothing to a server and does not persist files.
A revocable blob preview appears during upload. Use isUploading() before saving. Multiple files retain insertion order, with each completion replacing its own placeholder; a failure removes only that task's placeholder. Replacing or removing a placeholder is not an edit step: undo removes the inserted image directly, and neither undo nor redo brings back a revoked blob URL. Private state tracks node positions without storing upload IDs in HTML/JSON. Results from an old editor cannot enter a new document after unmounting, becoming readonly/disabled or accepting another document. The application still owns cancellation of its business requests.
<script setup lang="ts">
import { onBeforeUnmount, ref } from 'vue'
import { HuiButton, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type {
RichEditorExpose,
RichEditorImage,
RichEditorImageErrorReason,
RichEditorValue
} from '@nscode/handy-ui/editor'
const editor = ref<RichEditorExpose>()
const value = ref<RichEditorValue | null>(
'<p>Choose a file with the image tool, or paste an image directly.</p>'
)
const failUpload = ref(false)
const readonly = ref(false)
const status = ref('No image selected')
const pending = new Map<FileReader, (reason: Error) => void>()
const uploadImage = (file: File): Promise<RichEditorImage> =>
new Promise((resolve, reject) => {
if (failUpload.value) {
reject(new Error('Local demo read failed'))
return
}
const reader = new FileReader()
const finish = (error?: Error) => {
pending.delete(reader)
reader.onload = reader.onerror = reader.onabort = null
if (error) reject(error)
else if (typeof reader.result === 'string')
resolve({ src: reader.result, alt: file.name, width: 240 })
else reject(new Error('Failed to read image content'))
}
pending.set(reader, (error) => {
reader.abort()
finish(error)
})
reader.onload = () => finish()
reader.onerror = () => finish(reader.error ?? new Error('Failed to read image content'))
reader.onabort = () => finish(new Error('Image reading was cancelled'))
try {
reader.readAsDataURL(file)
} catch (error) {
finish(error instanceof Error ? error : new Error('Failed to read image content'))
}
})
const onError = (error: Error, file: File | null, reason: RichEditorImageErrorReason) => {
status.value = `${file?.name ?? 'Clipboard image'}: ${reason}; ${error.message}`
}
const inspect = () => {
status.value = editor.value?.isUploading()
? 'Image tasks or referenced local previews are still pending'
: 'No pending local images'
}
onBeforeUnmount(() => {
for (const cancel of pending.values()) cancel(new Error('Example unmounted'))
pending.clear()
})
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<label>Simulate failure <HuiSwitch v-model="failUpload" /></label>
<label>readonly <HuiSwitch v-model="readonly" /></label>
<HuiButton @click="inspect">Inspect upload status</HuiButton>
</HuiSpace>
<HuiRichEditor
ref="editor"
v-model="value"
:toolbar="['image', 'bold', 'undo', 'redo']"
:upload-image="uploadImage"
allow-base64-image
image-accept="image/png,image/jpeg,image/webp"
:image-max-size="1048576"
:readonly="readonly"
@image-error="onError"
/>
<p>
Accepts PNG/JPEG/WebP, up to 1 MiB per image; old results cannot return after readonly or
unmounting.
</p>
<p role="status">{{ status }}</p>
<pre>{{ value }}</pre>
</HuiSpace>
</template>
imageAccept and imageMaxSize validate actual files; they do not send probe requests for manually entered remote URLs. uploadImage takes precedence over Base64 fallback. If an adapter is configured and fails, the component does not automatically store Base64 instead.
Base64 fallback and images pasted from Word
Without an upload adapter, allowBase64Image=true converts files to Base64 through FileReader. It is disabled by default to avoid oversized models. Manually entered data:image/...;base64,... addresses follow the same switch.
For supported rich-text clipboard data, the component matches file: images in HTML with PNG/JPEG data in RTF \pict, then uses the same file-validation and upload flow. HTML and clipboard files appearing together do not insert duplicate images. Unrecoverable local images are removed while parsable text is retained, and imageError(error, null, 'upload') is emitted.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorImageErrorReason, RichEditorValue } from '@nscode/handy-ui/editor'
const value = ref<RichEditorValue | null>('')
const status = ref('Choose an image or paste content containing PNG/JPEG images')
const onError = (_error: Error, file: File | null, reason: RichEditorImageErrorReason) => {
status.value = `${file?.name ?? 'Clipboard image'}: ${reason}`
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiRichEditor
v-model="value"
allow-base64-image
image-accept="image/png,image/jpeg"
:image-max-size="409600"
:toolbar="['image', 'bold', 'italic', 'table']"
placeholder="Paste content or images here"
@image-error="onError"
/>
<p role="status">{{ status }}</p>
<p>
No upload service; this example accepts files up to 400 KiB and displays only the first 240
output characters.
</p>
<pre>{{ String(value ?? '').slice(0, 240) }}</pre>
</HuiSpace>
</template>
RTF image support is not full-document import. Arbitrary RTF layout, EMF/WMF images and unmatched private clipboard formats are not converted. If the browser does not expose the required data, the component cannot read a local file: path. This feature is also not an HTML security sanitizer.
Toolbar, bubble menu and footer slots
All five slots receive the current real Editor. toolbar replaces the entire toolbar, while toolbar-prefix and toolbar-suffix append content. No selection bubble menu is created without bubble-menu. Readonly mode hides the toolbar and selection menu. In disabled mode, custom buttons must still explicitly prevent execution.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiInput, HuiSpace } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorValue } from '@nscode/handy-ui/editor'
const value = ref<RichEditorValue | null>(
'<p>Select text to inspect the custom selection menu.</p>'
)
const note = ref('Native input in the toolbar')
const actions = ref(0)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiRichEditor v-model="value" :toolbar="['bold', 'italic']" show-count>
<template #toolbar-prefix>
<HuiInput
v-model="note"
:validate-event="false"
size="small"
aria-label="Toolbar note"
style="width: 180px; flex: none"
/>
</template>
<template #toolbar-suffix="{ editor }">
<HuiButton :disabled="!editor.isEditable" size="small" @click="editor.commands.focus('end')"
>End of content</HuiButton
>
</template>
<template #bubble-menu="{ editor }">
<HuiButton
:disabled="!editor.isEditable"
size="small"
@mousedown.prevent
@click="
() => {
editor.chain().focus().toggleBold().run()
actions++
}
"
>Toggle bold</HuiButton
>
</template>
<template #footer="{ count, maxLength }">
<span
>Custom footer: {{ count }} / {{ maxLength ?? 'unlimited' }}; bubble-menu calls:
{{ actions }} times</span
>
</template>
</HuiRichEditor>
<p>Replace the entire toolbar slot:</p>
<HuiRichEditor :min-height="100">
<template #toolbar="{ editor }">
<HuiButton
:disabled="!editor.isEditable"
@click="editor.chain().focus().toggleItalic().run()"
>Custom italic</HuiButton
>
</template>
</HuiRichEditor>
</HuiSpace>
</template>
Fullscreen inside a parent modal
The toolbar button and toggleFullscreen() share one bar layer. Switching does not recreate the Editor, body DOM or selection, and does not reclaim focus that has moved elsewhere. Fullscreen uses the core layer stack and scroll lock: Esc first closes the active child overlay, then a subsequent Esc exits fullscreen. Closing the parent modal, disabling, becoming readonly or unmounting exits fullscreen; reopening the parent does not restore an old fullscreen session.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiModal, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorExpose, RichEditorValue } from '@nscode/handy-ui/editor'
const visible = ref(false)
const readonly = ref(false)
const editor = ref<RichEditorExpose>()
const value = ref<RichEditorValue | null>(
'<p>Enter fullscreen inside a modal, then open a link or color panel to try Esc.</p>'
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiButton @click="visible = true">Open the editor modal</HuiButton>
<HuiModal v-model:visible="visible" title="Edit content" :width="720">
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @click="editor?.toggleFullscreen(true)">Enter fullscreen</HuiButton>
<HuiButton @click="editor?.toggleFullscreen(false)">Exit fullscreen</HuiButton>
<label>readonly <HuiSwitch v-model="readonly" /></label>
</HuiSpace>
<HuiRichEditor
ref="editor"
v-model="value"
:readonly="readonly"
:toolbar="['bold', 'color', 'link', 'fullscreen']"
/>
</HuiSpace>
</HuiModal>
<pre>{{ value }}</pre>
</HuiSpace>
</template>
Instance methods and confirmation before clearing
clear() is a low-level editing method without a built-in dialog. User-facing clear buttons must first confirm the target and scope. Do not clear content or cancel image tasks while awaiting confirmation. The example checks both the model revision and actual document snapshot. A document that changed and changed back, a readonly transition or unmounting invalidates the old confirmation instead of clearing the current document.
<script setup lang="ts">
import { onBeforeUnmount, ref, watch } from 'vue'
import { HuiButton, HuiMessageBox, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorExpose, RichEditorValue } from '@nscode/handy-ui/editor'
const editor = ref<RichEditorExpose>()
const value = ref<RichEditorValue | null>(
'<p>This content can be inspected, extended and cleared after confirmation.</p>'
)
const readonly = ref(false)
const pending = ref(false)
const status = ref('No instance method called yet')
let alive = true
let revision = 0
watch(
[value, readonly],
() => {
revision++
},
{ deep: true, flush: 'sync' }
)
onBeforeUnmount(() => {
alive = false
revision++
})
const inspect = () => {
const api = editor.value
if (!api) return
status.value = JSON.stringify(
{
html: api.getHTML(),
json: api.getJSON(),
text: api.getText(),
uploading: api.isUploading(),
ready: !!api.editor
},
null,
2
)
}
const clear = async () => {
const api = editor.value
const instance = api?.editor
if (
!api ||
!instance ||
instance.isDestroyed ||
readonly.value ||
pending.value ||
value.value === '' ||
value.value === null
)
return
const request = revision
const snapshot = instance.state.doc
pending.value = true
try {
const result = await HuiMessageBox.confirm({
title: 'Clear the current content',
message:
'Clear the current content? Text, tables and images will all be removed, and pending local image tasks will become invalid.',
type: 'warning',
confirmButtonText: 'Clear content',
confirmButtonType: 'danger'
})
if (!alive) return
if (
readonly.value ||
revision !== request ||
editor.value?.editor !== instance ||
instance.isDestroyed ||
instance.state.doc !== snapshot
) {
status.value = 'Content or editing state changed; confirm again'
return
}
if (result.action !== 'confirm') {
status.value = 'Cancelled or closed; content retained'
return
}
api.clear()
status.value = 'Clear requested; the actual result still follows the parent model'
} catch {
if (alive) status.value = 'Cancelled or closed; content retained'
} finally {
if (alive) pending.value = false
}
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @click="editor?.focus('start')">Focus the start</HuiButton>
<HuiButton @click="editor?.focus('end')">Focus the end</HuiButton>
<HuiButton @click="editor?.focus('all')">Select all</HuiButton>
<HuiButton @click="editor?.focus(1)">Focus position 1</HuiButton>
<HuiButton @mousedown.prevent @click="editor?.blur()">Move focus out</HuiButton>
<HuiButton
:disabled="readonly"
@click="editor?.insertContent('<strong>Appended HTML</strong>')"
>Insert HTML</HuiButton
>
<HuiButton
:disabled="readonly"
@click="editor?.insertContent({ type: 'text', text: 'Appended JSON text' })"
>Insert JSON</HuiButton
>
<HuiButton @click="inspect">Inspect HTML / JSON / text / upload status</HuiButton>
<HuiButton
type="danger"
:loading="pending"
:disabled="readonly || value === '' || value === null"
@click="clear"
>Confirm clearing</HuiButton
>
<label>readonly <HuiSwitch v-model="readonly" /></label>
</HuiSpace>
<HuiRichEditor
ref="editor"
v-model="value"
:readonly="readonly"
:toolbar="['bold', 'image', 'table', 'fullscreen']"
/>
<pre role="status">{{ status }}</pre>
</HuiSpace>
</template>
Legacy content and creation-time configuration
When reading HTML, legacyFormat="quill" first calls this package's convertQuillHtml, then passes the result to the current schema. Updates use the current editor format. starterKit and extensions are read only at creation; replacing extensions at runtime while retaining the original instance is unsupported. The example disables headings and both list extensions and omits their tools.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace } from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorValue } from '@nscode/handy-ui/editor'
const value = ref<RichEditorValue | null>(
'<p class="ql-align-center"><span class="ql-size-large">Read legacy content and output the current format.</span></p>'
)
const starterKit = { heading: false, bulletList: false, orderedList: false } as const
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiRichEditor
v-model="value"
legacy-format="quill"
:starter-kit="starterKit"
:toolbar="['bold', 'italic', 'fontSize', 'align', 'link']"
/>
<pre>{{ value }}</pre>
</HuiSpace>
</template>
Simplified Chinese, Traditional Chinese and English UI
The component uses the existing HuiConfigProvider locale chain and includes Simplified Chinese, Traditional Chinese and English resources. Switching here changes interface text, not content already entered. Applications supply the text for custom tools and slots.
<script setup lang="ts">
import { computed, ref } from 'vue'
import {
HuiButton,
HuiConfigProvider,
HuiSpace,
localeEn,
localeZhCn,
localeZhTw
} from '@nscode/handy-ui'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
const language = ref<'zh-cn' | 'zh-tw' | 'en'>('zh-cn')
const locale = computed(
() => ({ 'zh-cn': localeZhCn, 'zh-tw': localeZhTw, en: localeEn })[language.value]
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @click="language = 'zh-cn'">Simplified Chinese</HuiButton>
<HuiButton @click="language = 'zh-tw'">Traditional Chinese</HuiButton>
<HuiButton @click="language = 'en'">English</HuiButton>
</HuiSpace>
<HuiConfigProvider :locale="locale">
<HuiRichEditor
show-count
:max-length="80"
:toolbar="['heading', 'color', 'link', 'image', 'table', 'fullscreen']"
/>
</HuiConfigProvider>
</HuiSpace>
</template>
Other languages
The main entry includes only the Simplified Chinese, Traditional Chinese and English rich text packs. Import any of the other 76 from @nscode/handy-ui/editor/locale/<language>; the default export is the pack. Merge it with the core locale and pass the result as locale to app.use or HuiConfigProvider. When only the core locale is passed, the editor text falls back to Simplified Chinese.
import { createApp } from 'vue'
import HandyUI from '@nscode/handy-ui'
import jaJp from '@nscode/handy-ui/locale/ja-jp'
import editorJaJp from '@nscode/handy-ui/editor/locale/ja-jp'
import App from './App.vue'
// Pass the core locale and the rich text pack together
createApp(App)
.use(HandyUI, { locale: { ...jaJp, ...editorJaJp } })
.mount('#app')
Props
| Property | Type | Default | Description |
|---|---|---|---|
| modelValue / v-model | RichEditorValue | null | undefined | Empty for the chosen format | Controlled by property presence; an update listener alone is uncontrolled; explicit undefined is a controlled empty value |
| valueFormat | 'html' | 'json' | 'html' | Output format; empty values are '' and null, respectively |
| placeholder | string | — | Placeholder; an empty string is an explicit override |
| disabled | boolean | false | Prevents editing and retains a disabled toolbar; inherits form disabled state |
| readonly | boolean | false | Prevents editing and hides the toolbar and selection menu; inherits form readonly state |
| toolbar | RichEditorToolbarItem[] | false | Default toolbar | Order, separators and custom tools; false hides it |
| stickyToolbar | boolean | number | Off | true uses top offset 0; a number is in px |
| height | number | string | — | Body height; numbers are pixels |
| minHeight | number | string | 240 | Minimum body height; fullscreen allocates the remaining space |
| maxHeight | number | string | — | Maximum body height, with scrolling beyond it |
| maxLength | number | Unlimited | Non-negative finite integer; 0 permits only empty content; external updates are not truncated |
| showCount | boolean | false | Displays the count; a valid maxLength also enables it |
| uploadImage | RichEditorUploadImage | — | File-upload adapter returning a URL or image object; rejects on failure |
| imageAccept | string | 'image/*' | File-type rules supporting MIME, MIME wildcards and extensions |
| imageMaxSize | number | Unlimited | Maximum bytes per file; applies when positive |
| allowBase64Image | boolean | false | Allows Base64 fallback without an upload adapter and permits corresponding image addresses |
| extensions | Extensions | [] | Additional Tiptap extensions, read only at creation |
| starterKit | Partial<StarterKitOptions> | Built-in configuration | Creation-time options; avoid registering duplicate names for built-in nodes or marks |
| legacyFormat | 'quill' | — | Converts legacy HTML first; not an HTML-sanitization switch |
| size | ComponentSize | Inherited | small, default, large; follows the existing form and global size chain |
| validateEvent | boolean | true | Whether to actively request change/blur form validation |
class and style reach the editor frame. id, ARIA attributes, other native attributes and listeners reach the actual body. User aria-label and aria-labelledby, including empty strings, take precedence over automatic form naming. aria-describedby merges with form description and error IDs.
Events
| Event | Arguments | Description |
|---|---|---|
| update:modelValue | (value: RichEditorValue | null) | Proposes an edited value; does not prove parental acceptance |
| change | (value: RichEditorValue | null) | Content differs from the focus-entry value when leaving the entire editor; blur is emitted first |
| focus | (event: FocusEvent) | Focus first enters the body, toolbar or this instance's child overlays |
| blur | (event: FocusEvent) | Focus leaves the entire region; internal panel switches do not emit it repeatedly |
| ready | (editor: Editor) | Client editor creation has completed; not emitted during SSR |
| imageError | (error: Error, file: File | null, reason: RichEditorImageErrorReason) | Type, size, upload or missing-adapter errors; file is null for unrecoverable local clipboard images |
| exceed | (maxLength: number) | A user transaction was blocked by a valid character limit |
Templates can use kebab-case listeners such as @image-error; declared event names remain camelCase. There is no extra clear event. Clearing follows the candidate-update and blur-time change contract.
Slots
| Slot | Arguments | Description |
|---|---|---|
| toolbar | { editor } | Replaces the whole toolbar; not rendered with toolbar=false or readonly |
| toolbar-prefix | { editor } | Before the default toolbar |
| toolbar-suffix | { editor } | After the default toolbar |
| bubble-menu | { editor } | Selection bubble menu; not created when omitted |
| footer | { editor, count, maxLength } | Replaces the count area; maxLength is undefined without a valid limit |
Methods
Obtain RichEditorExpose through a template ref. editor is undefined before creation. Other methods follow the current instance's lifecycle and disabled/readonly boundaries.
| Member | Type | Description |
|---|---|---|
| editor | readonly Editor | undefined | Real Tiptap instance; applications own interaction and confirmation guards for advanced commands |
| focus | (position?: 'start' | 'end' | 'all' | number) => void | Focuses the body and optionally changes the selection; does not focus while disabled |
| blur | () => void | Moves focus out only when it currently belongs to this instance |
| clear | () => void | Requests clearing; controlled rejection restores the actual value; user-facing entries require confirmation |
| getHTML | () => string | Returns actual HTML; an ordinary empty document may still serialize as <p></p> |
| getJSON | () => JSONContent | Returns an actual JSON snapshot |
| getText | () => string | Returns actual plain text; no text does not imply no structural content |
| insertContent | (content: string | JSONContent) => void | Inserts at the selection, respecting write restrictions and character limits |
| toggleFullscreen | (value?: boolean) => void | Enters/exits explicitly, or toggles when omitted; cannot enter while disabled, readonly or its parent layer is closed |
| isUploading | () => boolean | Reports pending image tasks or local blobs still referenced by the document without a saved replacement |
Types
Import RichEditorProps, RichEditorEmits, RichEditorExpose, RichEditorSlots, RichEditorValueFormat, RichEditorValue, RichEditorToolName, RichEditorToolbarItem, RichEditorCustomTool, RichEditorImage, RichEditorUploadImage and RichEditorImageErrorReason from @nscode/handy-ui/editor.
type RichEditorValueFormat = 'html' | 'json'
type RichEditorValue = string | JSONContent
type RichEditorImageErrorReason = 'type' | 'size' | 'upload' | 'missing'
interface RichEditorImage {
src: string
alt?: string
title?: string
width?: number
height?: number
}
type RichEditorUploadImage = (file: File) => Promise<string | RichEditorImage>
JSONContent, Editor and Extensions belong to Tiptap; ComponentSize comes from @nscode/utils. There are 24 built-in tools plus the '|' separator. code and horizontalRule are omitted by default and can be added when needed.
Keyboard interaction
- In the body,
Alt+F10enters the toolbar. Left/Right move between tools, Home/End select the first/last, and disabled tools are skipped. The toolbar has one Tab entry. Inputs inside slots retain native text-editing keys. - Esc returns a non-fullscreen toolbar to the body. In fullscreen, the active child overlay handles Esc first, followed by this instance's fullscreen exit; sibling editors remain open. Closing a child layer restores focus to its trigger.
- The body supports Tiptap command shortcuts such as bold and italic.
Ctrl+K/Meta+Kopens the link tool. A custom item'sshortcutis only a hint and adds no global keyboard listener. - In paragraphs and headings, Tab/Shift+Tab indent/outdent. Lists and code blocks follow their own extensions. IME composition does not trigger toolbar navigation.