RichEditor 豐富文字編輯器
HuiRichEditor 編輯 HTML 或 Tiptap JSON,提供工具列、連結、表格、圖片上傳、字數限制和全螢幕,並接入 HuiForm。正文排版沿用 .hui-prose;需要唯讀展示已保存的 HTML 時,可以使用同包的 HuiRichContent。
引入
使用 @nscode/handy-ui/editor 時請先安裝下列依賴。此入口同時提供富文本展示與編輯,應用程式中的 Tiptap 依賴應使用相同版本。
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
應用入口載入核心主題和編輯器樣式;同一應用共用一份 Vue、@nscode/handy-ui 和 Tiptap。Tiptap 相關 peer 依賴保持同一版本,不混用多份 @tiptap/core 或 @tiptap/pm。
import '@nscode/handy-ui/style.css'
import { HuiRichEditor } from '@nscode/handy-ui/editor'
import type { RichEditorExpose, RichEditorValue } from '@nscode/handy-ui/editor'
示例
HTML、建立完成與事件
預設 valueFormat="html"。update:modelValue 跟隨實際編輯事務;change 在焦點離開整個編輯器後,比較本次獲得焦點時的內容再觸發。正文、工具列和目前編輯器的子浮層屬於同一個焦點範圍,切換到顏色或連結面板不會單獨提交一次 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>選取文字,嘗試<strong>加粗</strong>或插入連結。</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="請輸入正文"
show-count
aria-label="基礎富文字正文"
@ready="ready = true"
@update:model-value="updates++"
@change="changes++"
@focus="focuses++"
@blur="blurs++"
/>
<p role="status">
已建立:{{ ready }};更新:{{ updates }};失焦提交:{{ changes }};獲得焦點:{{
focuses
}};失焦:{{ blurs }}
</p>
<pre>{{ value }}</pre>
</HuiSpace>
</template>
HTML 與 JSON
HTML 的空值為 '',JSON 的空值為 null。JSON 使用目前編輯器 schema,段落、標題等節點可能帶預設屬性。讀取與更新事件中的 JSON 是快照,不會直接修改傳入的物件。
空表格、圖片、清單和帶格式的空塊仍有結構意義,不會因為沒有純文字就變成空值。只有預設的空段落殼等普通空內容折疊為空值。
<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>這是 HTML 模型。</p>')
const json = ref<RichEditorValue | null>({
type: 'doc',
content: [
{
type: 'paragraph',
content: [{ type: 'text', text: '這是 JSON 模型。' }]
}
]
})
</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>
受控拒絕與僅監聽
是否傳入 modelValue 決定受控狀態,顯式 undefined 也表示受控空值。父級拒絕候選時,正文回到父級的實際值;只監聽更新而不傳模型時,元件自行保存內容。不要把 update:modelValue 當成父級已接受候選的證明。
<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>('尚未收到候選')
const listened = ref<RichEditorValue | null>('尚未編輯')
const emptyCandidate = ref<RichEditorValue | null>('尚未收到候選')
</script>
<template>
<HuiSpace direction="vertical" fill>
<p>固定父值:輸入會產生候選,但父級不回填。</p>
<HuiRichEditor
model-value="<p>父級保留這段實際正文。</p>"
:toolbar="false"
:min-height="90"
@update:model-value="rejected = $event"
/>
<pre>最近被拒絕的候選:{{ rejected }}</pre>
<p>僅監聽:沒有 modelValue,輸入會保留。</p>
<HuiRichEditor :toolbar="false" :min-height="90" @update:model-value="listened = $event" />
<pre>最近更新:{{ listened }}</pre>
<p>顯式 undefined:受控空值,父級仍拒絕輸入。</p>
<HuiRichEditor
:model-value="undefined"
:toolbar="false"
:min-height="90"
@update:model-value="emptyCandidate = $event"
/>
<pre>空值控制項的候選:{{ emptyCandidate }}</pre>
</HuiSpace>
</template>
尺寸、禁用、唯讀與正文高度
size 控制工具列控制項尺寸。readonly 保留正文但隱藏工具列,disabled 保留禁用的工具列;兩者都禁止通過元件方法或普通 Tiptap 編輯事務修改內容。外部模型回填仍然有效。
<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 }};正文 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} 尺寸正文`"
placeholder="輸入多段內容觀察正文捲動"
/>
</div>
</HuiSpace>
</template>
工具列全部內建項
工具列陣列按順序呈現,'|' 是分隔線。下面額外列出預設工具列沒有展示的 code 和 horizontalRule。先選擇文字,再選擇格式;也可以用“選擇全部正文”設定選區。
標題包含正文及 1~4 級標題;字級為 .75em、預設、1.5em、2.5em;對齊包含左、中、右、兩端。段落和標題支援 0~8 級縮排,清單縮排沿清單自身的巢狀結構處理。
<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>選取這段正文,比較標題、字級、標記與段落格式。</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')">選擇全部正文</HuiButton>
<HuiRichEditor ref="editor" v-model="value" :toolbar="toolbar" />
<pre>{{ value }}</pre>
</HuiSpace>
</template>
顏色、段落對齊與表格
文字色和背景色分別設定;面板裡的“預設”只移除對應顏色,不清除另一種顏色。顏色面板同時提供預設色和自訂顏色。序列化後的顏色可能從十六進位變為等值 rgb(...),不應按原 HTML 位元組判斷是否改變。
點擊表格內的單元格後,表格工具展示插入行列、合併、拆分和刪除操作;不在表格中時展示最大 8×8 的插入網格。刪除行、列或整表會先確認範圍與內容,等待期間文件變化會使舊刪除失效。
<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">選取文字後分別修改前景色和背景色。</span></p>',
'<p style="text-align:center">這段正文初始置中。</p>',
'<table><tbody>',
'<tr><th><p>事項</p></th><th><p>負責人</p></th></tr>',
'<tr><td><p>檢查正文</p></td><td><p>陳晨</p></td></tr>',
'<tr><td><p>核對附件</p></td><td><p>李寧</p></td></tr>',
'</tbody></table><p>點擊任意儲存格後打開「表格」。</p>'
].join('')
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiRichEditor
v-model="value"
:toolbar="['color', 'backgroundColor', 'align', '|', 'table', 'undo', 'redo']"
/>
<pre>{{ value }}</pre>
</HuiSpace>
</template>
連結
連結面板支援地址、顯示文字和新視窗選項。支援 http:、https:、mailto:、tel:、以 / 開頭的地址和 # 錨點;去掉首尾空白後仍含內部空白或控制符的地址會被拒絕,不會通過拼接或刪字元修成另一個地址。新視窗連結寫入 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>選取文字後打開連結工具;也可點擊這裡的<a href="#link-preview">頁內連結</a>再修改。</p>'
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiRichEditor v-model="value" :toolbar="['link', 'bold', 'italic']" :min-height="120" />
<p id="link-preview">編輯區內點擊連結用於編輯,不直接導航。</p>
<pre>{{ value }}</pre>
</HuiSpace>
</template>
自訂工具與關閉工具列
自訂項的 shortcut 只顯示提示與 aria-keyshortcuts,不會自動註冊新的快捷鍵。run 收到真實 Editor;元件會先核對禁用、唯讀、實例和焦點歸屬。自己直接呼叫原始 Editor 或編寫替換插槽時,也要保留相應的互動保護。
<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>選取文字後使用自訂行內程式碼工具。</p>')
const commands = ref(0)
const toolbar: RichEditorToolbarItem[] = [
'bold',
'|',
{
name: 'custom-code',
label: '切換行內程式碼',
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">自訂命令呼叫:{{ commands }}</p>
<p>toolbar=false:仍可編輯正文,不顯示工具列。</p>
<HuiRichEditor :toolbar="false" :min-height="90" placeholder="沒有工具列的編輯區" />
</HuiSpace>
</template>
吸頂工具列
stickyToolbar=true 的頂部距離為 0,數字為像素偏移,false 關閉。吸頂相對實際捲動容器生效;它不會自行建立新的頁面捲動區域。
<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>第 ${index + 1} 段:捲動此容器觀察工具列。</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>
字數限制與統計
maxLength 接受非負有限整數,0 只允許空內容。字數按文件提取文字的 JavaScript 長度計數,部分 Unicode 字元會占兩個計數單位,不是按 HTML 長度或單詞數計數。超限使用者事務被攔截並觸發 exceed;外部回填不會被靜默截短,已經超限的文件仍允許不增加計數的修正。
<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 }};最近上限:{{ lastLimit ?? '未觸發' }}</p>
<p>maxLength=0:嘗試輸入不會保留內容。</p>
<HuiRichEditor :max-length="0" :toolbar="false" :min-height="80" @exceed="onExceed" />
</HuiSpace>
</template>
表單驗證
編輯器從表單繼承尺寸、禁用和唯讀。標籤與說明關聯到真實正文,錯誤標記落在編輯器邊框;工具列裡的輸入框不登記成額外的業務欄位。validateEvent=false 只關閉編輯器主動觸發表單驗證,不取消整表手動驗證。
<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('尚未驗證')
const rules: Record<string, FormRule[]> = {
content: [{ required: true, message: '請輸入正文', trigger: ['change', 'blur'] }]
}
const validate = async () => {
const validation = await form.value?.validate()
result.value = validation?.valid ? '驗證通過' : '正文未滿足規則'
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<label>表單 readonly <HuiSwitch v-model="readonly" /></label>
<label>表單 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="正文" prop="content" tip="輸入後移出編輯器,或點擊手動驗證。">
<HuiRichEditor v-model="model.content" :validate-event="validateEvent" :min-height="120" />
</HuiFormItem>
</HuiForm>
<HuiButton @click="validate">手動驗證</HuiButton>
<p role="status">{{ result }}</p>
</HuiSpace>
</template>
圖片上傳、驗證和遲到結果
圖片工具支援手填地址和說明;設定 uploadImage 後,可選擇、貼上或拖入檔案。適配器回傳 URL 或帶 src 的物件,失敗時 reject。下面使用 FileReader 讀取使用者實際選擇的圖片內容,回傳 Base64,因此顯式開啟 allowBase64Image;本例不傳送到伺服器,也不持久保存檔案。
上傳期間先顯示可回收的 blob 預覽,isUploading() 用於保存前檢查。多檔案保留插入次序,完成時替換各自的占位,失敗只移除對應任務的占位。替換和移除占位不算一步編輯:復原直接撤掉「插入圖片」,復原、重做都不會退回已回收的 blob 位址。任務通過私有狀態跟蹤節點位置,不把上傳 ID 寫進 HTML/JSON。編輯器卸載、變為唯讀/禁用或接受了另一份文件後,舊結果不能插回新文件;業務請求仍須由應用自行取消。
<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>使用圖片工具選擇檔案,或直接貼上圖片。</p>')
const failUpload = ref(false)
const readonly = ref(false)
const status = ref('尚未選擇圖片')
const pending = new Map<FileReader, (reason: Error) => void>()
const uploadImage = (file: File): Promise<RichEditorImage> =>
new Promise((resolve, reject) => {
if (failUpload.value) {
reject(new Error('本地演示讀取失敗'))
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('圖片內容讀取失敗'))
}
pending.set(reader, (error) => {
reader.abort()
finish(error)
})
reader.onload = () => finish()
reader.onerror = () => finish(reader.error ?? new Error('圖片內容讀取失敗'))
reader.onabort = () => finish(new Error('圖片讀取已取消'))
try {
reader.readAsDataURL(file)
} catch (error) {
finish(error instanceof Error ? error : new Error('圖片內容讀取失敗'))
}
})
const onError = (error: Error, file: File | null, reason: RichEditorImageErrorReason) => {
status.value = `${file?.name ?? '剪貼板圖片'}:${reason};${error.message}`
}
const inspect = () => {
status.value = editor.value?.isUploading()
? '仍有圖片任務或尚被文件引用的本地預覽'
: '沒有待處理的本地圖片'
}
onBeforeUnmount(() => {
for (const cancel of pending.values()) cancel(new Error('示例已卸載'))
pending.clear()
})
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<label>模擬失敗 <HuiSwitch v-model="failUpload" /></label>
<label>readonly <HuiSwitch v-model="readonly" /></label>
<HuiButton @click="inspect">讀取上傳狀態</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>僅接受 PNG/JPEG/WebP,單張最多 1 MiB;唯讀或卸載後,舊圖片結果不再回填。</p>
<p role="status">{{ status }}</p>
<pre>{{ value }}</pre>
</HuiSpace>
</template>
imageAccept、imageMaxSize 驗證實際檔案,不為手填的遠端 URL 發起探測請求。uploadImage 的優先級高於 Base64 回退;設定了適配器但上傳失敗時,不會自動改存 Base64。
Base64 回退與 Word 圖片貼上
沒有上傳適配器且 allowBase64Image=true 時,檔案通過 FileReader 轉成 Base64;預設關閉,避免模型體積過大。手填 data:image/...;base64,... 也受這個開關約束。
從支援的豐富文字剪貼簿貼上時,元件會匹配 HTML 中的 file: 圖片與 RTF \pict 的 PNG/JPEG 資料,再進入同一套檔案驗證和上傳流程。HTML 和剪貼簿檔案同時存在時,不會重複插圖。無法取得的資料會移除對應本機圖片、保留可解析正文,並觸發 imageError(error, null, 'upload')。
<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('可選擇圖片,或貼上帶 PNG/JPEG 圖片的正文')
const onError = (_error: Error, file: File | null, reason: RichEditorImageErrorReason) => {
status.value = `${file?.name ?? '剪貼板圖片'}:${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="在這裡貼上正文或圖片"
@image-error="onError"
/>
<p role="status">{{ status }}</p>
<p>沒有上傳介面,本例最多接受 400 KiB 檔案;輸出只展示前 240 個字元。</p>
<pre>{{ String(value ?? '').slice(0, 240) }}</pre>
</HuiSpace>
</template>
RTF 圖片能力不等於完整文件匯入:目前不轉換任意 RTF 排版、EMF/WMF 等圖片或不能匹配的私有剪貼簿格式。瀏覽器沒有提供對應資料時,不能讀取本機 file: 路徑。它也不是 HTML 安全過濾器。
工具列、浮動選單與底部插槽
五個插槽均拿到目前真實 Editor。toolbar 替換整個工具列,toolbar-prefix、toolbar-suffix 追加內容;沒有 bubble-menu 時不建立選區浮動選單。唯讀時隱藏工具列和選區選單,禁用時自訂按鈕仍應顯式禁止執行。
<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>選取文字,觀察自訂選區選單。</p>')
const note = ref('工具列中的原生輸入')
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="工具列備註"
style="width: 180px; flex: none"
/>
</template>
<template #toolbar-suffix="{ editor }">
<HuiButton :disabled="!editor.isEditable" size="small" @click="editor.commands.focus('end')"
>正文末尾</HuiButton
>
</template>
<template #bubble-menu="{ editor }">
<HuiButton
:disabled="!editor.isEditable"
size="small"
@mousedown.prevent
@click="
() => {
editor.chain().focus().toggleBold().run()
actions++
}
"
>切換加粗</HuiButton
>
</template>
<template #footer="{ count, maxLength }">
<span
>自訂底部:{{ count }} / {{ maxLength ?? '不限' }};浮動選單呼叫 {{ actions }} 次</span
>
</template>
</HuiRichEditor>
<p>完整替換 toolbar 插槽:</p>
<HuiRichEditor :min-height="100">
<template #toolbar="{ editor }">
<HuiButton
:disabled="!editor.isEditable"
@click="editor.chain().focus().toggleItalic().run()"
>自訂斜體</HuiButton
>
</template>
</HuiRichEditor>
</HuiSpace>
</template>
全螢幕與父彈窗
工具按鈕和 toggleFullscreen() 共用同一個 bar 層:切換時不重建 Editor、正文 DOM 或選區,也不會主動把已外移的焦點搶回來。全螢幕使用核心共享層棧和捲動鎖;先關閉目前子浮層,再由下一次 Esc 退出全螢幕。父彈窗關閉、禁用、唯讀或卸載都會退出,不會在父級重開時復活舊全螢幕。
<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>在彈窗中全螢幕,再打開連結或顏色面板試用 Esc。</p>')
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiButton @click="visible = true">打開編輯彈窗</HuiButton>
<HuiModal v-model:visible="visible" title="編輯正文" :width="720">
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @click="editor?.toggleFullscreen(true)">進入全螢幕</HuiButton>
<HuiButton @click="editor?.toggleFullscreen(false)">退出全螢幕</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>
實例方法與清除確認
clear() 是底層編輯方法,不內建彈窗。所有面向使用者的清除按鈕應先確認對象和影響範圍;確認等待期間不得提前清內容或取消圖片任務。下面同時檢查模型代次和真實文件快照,正文變過再變回、進入唯讀或卸載後,舊確認都不會清除目前文件。
<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>這是可查詢、追加和確認清除的正文。</p>')
const readonly = ref(false)
const pending = ref(false)
const status = ref('尚未呼叫實例方法')
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: '清除目前正文',
message: '確定清除目前正文嗎?文字、表格和圖片會一並移除;尚未完成的本地圖片任務將失效。',
type: 'warning',
confirmButtonText: '清除正文',
confirmButtonType: 'danger'
})
if (!alive) return
if (
readonly.value ||
revision !== request ||
editor.value?.editor !== instance ||
instance.isDestroyed ||
instance.state.doc !== snapshot
) {
status.value = '正文或編輯狀態已變化,請重新確認'
return
}
if (result.action !== 'confirm') {
status.value = '已取消或關閉,正文保留'
return
}
api.clear()
status.value = '已請求清除;實際結果仍遵循父級模型'
} catch {
if (alive) status.value = '已取消或關閉,正文保留'
} finally {
if (alive) pending.value = false
}
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @click="editor?.focus('start')">聚焦開頭</HuiButton>
<HuiButton @click="editor?.focus('end')">聚焦結尾</HuiButton>
<HuiButton @click="editor?.focus('all')">選擇全部</HuiButton>
<HuiButton @click="editor?.focus(1)">聚焦位置 1</HuiButton>
<HuiButton @mousedown.prevent @click="editor?.blur()">移出目前焦點</HuiButton>
<HuiButton :disabled="readonly" @click="editor?.insertContent('<strong>追加 HTML</strong>')"
>插入 HTML</HuiButton
>
<HuiButton
:disabled="readonly"
@click="editor?.insertContent({ type: 'text', text: '追加 JSON 文字' })"
>插入 JSON</HuiButton
>
<HuiButton @click="inspect">查詢 HTML / JSON / 文字 / 上傳狀態</HuiButton>
<HuiButton
type="danger"
:loading="pending"
:disabled="readonly || value === '' || value === null"
@click="clear"
>確認清除</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>
舊格式與建立設定
legacyFormat="quill" 僅在讀入 HTML 時先呼叫同包 convertQuillHtml,再交給目前 schema;更新輸出為目前編輯器格式。starterKit、extensions 只在建立時讀取,不支援運行中替換擴展而保留原實例。下面關閉標題和兩種清單擴展,同時不展示對應工具。
<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">讀入舊正文,輸出使用目前格式。</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>
簡體、繁體與英文介面
元件重用現有 HuiConfigProvider 語言鏈,內建簡體、繁體、英文資源。此處切換的是介面文案,不翻譯已輸入正文。自訂工具和插槽的文字仍由應用提供。
<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'">簡體中文</HuiButton>
<HuiButton @click="language = 'zh-tw'">繁體中文</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>
其他語言
主入口只帶簡體、繁體、英文三種富文本語言包。其餘 76 種從 @nscode/handy-ui/editor/locale/<語言> 匯入,預設匯出就是語言包,和核心語言包合在一起傳給 app.use 或 HuiConfigProvider 的 locale。只傳了核心語言包時,編輯器的文字退回簡體中文。
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'
// 核心語言包和富文本語言包合在一起傳
createApp(App)
.use(HandyUI, { locale: { ...jaJp, ...editorJaJp } })
.mount('#app')
Props
| 屬性 | 類型 | 預設值 | 說明 |
|---|---|---|---|
| modelValue / v-model | RichEditorValue | null | undefined | 按格式為空 | 按屬性存在性受控;只監聽更新不構成受控,顯式 undefined 是受控空值 |
| valueFormat | 'html' | 'json' | 'html' | 輸出格式,空值分別為 ''、null |
| placeholder | string | — | 提示文字;空字串是顯式覆蓋 |
| disabled | boolean | false | 禁止編輯,保留禁用的工具列;繼承表單禁用 |
| readonly | boolean | false | 禁止編輯並隱藏工具列、選區選單;繼承表單唯讀 |
| toolbar | RichEditorToolbarItem[] | false | 預設工具列 | 順序、分隔線、自訂工具;false 隱藏 |
| stickyToolbar | boolean | number | 關閉 | true 頂部偏移為 0,數字表示 px |
| height | number | string | — | 正文區高度;數值按 px |
| minHeight | number | string | 240 | 正文區最小高度;全螢幕時由剩餘空間分配 |
| maxHeight | number | string | — | 正文區最大高度,超出捲動 |
| maxLength | number | 不限 | 非負有限整數;0 只允許空內容;外部回填不裁剪 |
| showCount | boolean | false | 顯示字數;提供有效 maxLength 時也顯示計數 |
| uploadImage | RichEditorUploadImage | — | 檔案上傳適配器;回傳 URL 或圖片物件,reject 表示失敗 |
| imageAccept | string | 'image/*' | 檔案類型規則,支援 MIME、通配 MIME、副檔名 |
| imageMaxSize | number | 不限 | 單檔案最大位元組數,正數時生效 |
| allowBase64Image | boolean | false | 無上傳適配器時允許 Base64 回退,並允許相應圖片地址 |
| extensions | Extensions | [] | 追加 Tiptap 擴展,只在建立時讀取 |
| starterKit | Partial<StarterKitOptions> | 內建設定 | 建立時設定;不要與內建節點、mark 重複註冊同名擴展 |
| legacyFormat | 'quill' | — | HTML 先做舊格式轉換,不是 HTML 過濾開關 |
| size | ComponentSize | 繼承 | small、default、large;沿現有表單和全域尺寸鏈 |
| validateEvent | boolean | true | 是否主動觸發表單變化、失焦驗證 |
class、style 落在編輯器外框;id、ARIA、其他原生屬性和監聽落在實際正文。自訂 aria-label、aria-labelledby(包括空字串)優先於表單自動命名,aria-describedby 與表單說明、錯誤 ID 合併。
Events
| 事件 | 參數 | 說明 |
|---|---|---|
| update:modelValue | (value: RichEditorValue | null) | 提交編輯候選;不證明父級已接受 |
| change | (value: RichEditorValue | null) | 離開整個編輯器,實際內容相較獲得焦點時有變化;blur 先於此事件 |
| focus | (event: FocusEvent) | 焦點首次進入正文、工具列或本實例子浮層範圍 |
| blur | (event: FocusEvent) | 焦點離開整個範圍;內部面板切換不重複觸發 |
| ready | (editor: Editor) | 用戶端建立完成;SSR 不觸發 |
| imageError | (error: Error, file: File | null, reason: RichEditorImageErrorReason) | 類型、大小、上傳或缺少適配器;無法恢復的剪貼簿本機圖片 file=null |
| exceed | (maxLength: number) | 使用者事務被有效字數上限攔截 |
模板可用 @image-error 等短橫線監聽寫法,元件聲明的事件名保持駝峰。沒有額外的 clear 事件;清除遵循更新候選與失焦 change 約定。
Slots
| 插槽 | 參數 | 說明 |
|---|---|---|
| toolbar | { editor } | 替換整個工具列,toolbar=false 或唯讀時不呈現 |
| toolbar-prefix | { editor } | 預設工具列前部 |
| toolbar-suffix | { editor } | 預設工具列尾部 |
| bubble-menu | { editor } | 選區浮動選單;未提供則不建立 |
| footer | { editor, count, maxLength } | 替換計數區域;無有效上限時 maxLength 為 undefined |
方法
通過模板 ref 取得 RichEditorExpose。實例建立前 editor 為 undefined;其他方法按目前實例生命週期與禁用、唯讀邊界執行。
| 成員 | 類型 | 說明 |
|---|---|---|
| editor | readonly Editor | undefined | 真實 Tiptap 實例;進階命令需要應用自行遵守互動、確認規則 |
| focus | (position?: 'start' | 'end' | 'all' | number) => void | 聚焦正文並可調整選區;禁用時不聚焦 |
| blur | () => void | 只移出目前屬於本實例的焦點 |
| clear | () => void | 請求清除;受控父拒絕時恢復實際值;使用者入口須先確認 |
| getHTML | () => string | 查詢目前實際 HTML;普通空文件可能仍序列化為 <p></p> |
| getJSON | () => JSONContent | 查詢目前實際 JSON 快照 |
| getText | () => string | 查詢目前實際純文字;沒有文字不等於沒有結構內容 |
| insertContent | (content: string | JSONContent) => void | 在選區插入內容;遵守禁寫與字數限制 |
| toggleFullscreen | (value?: boolean) => void | 指定進入/退出,不傳反轉;禁用、唯讀、父層關閉時不能進入 |
| isUploading | () => boolean | 是否還有圖片任務或文件仍引用尚未完成保存的本地 blob |
類型
從 @nscode/handy-ui/editor 引入公開的 RichEditorProps、RichEditorEmits、RichEditorExpose、RichEditorSlots、RichEditorValueFormat、RichEditorValue、RichEditorToolName、RichEditorToolbarItem、RichEditorCustomTool、RichEditorImage、RichEditorUploadImage、RichEditorImageErrorReason。
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、Extensions 屬於 Tiptap;ComponentSize 來自 @nscode/utils。內建工具共 24 項,另有分隔線 '|'。預設不展示 code 和 horizontalRule,可以按需加入。
鍵盤操作
- 正文
Alt+F10進入工具列。工具列左右方向鍵移動,Home、End 到首尾,禁用項跳過;工具列自身只有一個 Tab 入口。插槽內輸入框保留原生文字編輯按鍵。 - 非全螢幕工具列按 Esc 回正文。全螢幕時先由目前子浮層處理 Esc,之後退出本實例全螢幕,不關閉兄弟編輯器;關閉子層後的焦點回到相應觸發器。
- 正文支援 Tiptap 的加粗、斜體等命令快捷鍵;
Ctrl+K/Meta+K打開連結工具。自訂項的shortcut只負責提示,不增加全域鍵盤監聽。 - 段落或標題中的 Tab、Shift+Tab 執行縮排、減少縮排;清單、程式碼塊沿自身擴展規則處理。IME 組合輸入不觸發工具列導航。