@ap666/office-word
v0.2.10
Published
A reusable Vue 3 rich text editor component built with Tiptap 3.
Downloads
249
Maintainers
Readme
@ap666/office-word
个人开发,未全方位测试,用于生产请多测试一下
中文 | English
中文
@ap666/office-word 是一个基于 Vue 3 和 Tiptap 3 的富文本编辑器组件,内置文档式编辑界面、图片/视频/文件块、表格、公式、倒计时、高亮块、大纲、预览模式、导出能力,以及可选的 Yjs 协同编辑。
安装
npm install @ap666/office-word组件样式会作为独立 CSS 文件发布。建议在应用入口显式引入:
import '@ap666/office-word/style.css'如果你的包管理器没有自动安装 peer dependencies,请同时安装运行时 peer 包:
npm install vue @tiptap/core @tiptap/vue-3 @tiptap/pm @tiptap/starter-kit @tiptap/extension-placeholder @tiptap/extension-code-block @tiptap/extension-code-block-lowlight @tiptap/extension-collaboration @tiptap/extension-collaboration-caret @tiptap/extension-font-family @tiptap/extension-subscript @tiptap/extension-superscript @tiptap/extension-table @tiptap/extension-table-cell @tiptap/extension-table-header @tiptap/extension-table-row @tiptap/extension-task-item @tiptap/extension-task-list @tiptap/extension-text-style @tiptap/extension-underline @tiptap/y-tiptap lowlight y-prosemirror yjshtml2canvas、jspdf、katex、marked、plyr 已作为普通 dependencies 随包安装。
快速开始
<script setup lang="ts">
import { ref } from 'vue'
import type { JSONContent } from '@tiptap/core'
import { RichTextEditor } from '@ap666/office-word'
import '@ap666/office-word/style.css'
const content = ref<JSONContent | null>(null)
</script>
<template>
<RichTextEditor v-model="content" />
</template>也可以使用默认导出:
import RichTextEditor from '@ap666/office-word'Props
| Prop | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| modelValue | JSONContent \| null | null | 编辑器内容,支持 v-model。 |
| editable | boolean | true | 是否允许编辑。 |
| mode | 'edit' \| 'preview' | 'edit' | 编辑模式或预览模式。 |
| outlinePlacement | 'left' \| 'right' | 'right' | 大纲面板位置。 |
| messages | RichTextEditorMessages \| null | null | 覆盖内置 UI 文案。 |
| enabledExportItems | RichTextEditorExportItemKey[] \| null | null | 导出菜单白名单。 |
| enabledInsertMenuItems | RichTextEditorInsertMenuItemKey[] \| null | null | 插入菜单白名单。 |
| enabledToolbarActions | RichTextEditorToolbarActionKey[] \| null | null | 工具栏能力白名单。 |
| placeholder | string | '' | 空内容占位文案。 |
| collaboration | RichTextEditorCollaborationOptions \| null | null | Yjs 协同配置。 |
白名单 props 不传时表示启用全部内置项;传入数组后,仅数组里的项目会显示并可用。
<RichTextEditor
v-model="content"
:enabled-export-items="['html', 'image']"
:enabled-insert-menu-items="['image', 'local-file', 'blockquote']"
:enabled-toolbar-actions="['blockquote']"
/>可用 Key
导出菜单:
type RichTextEditorExportItemKey = 'pdf' | 'html' | 'image' | 'print'插入菜单:
type RichTextEditorInsertMenuItemKey =
| 'image'
| 'video'
| 'table'
| 'local-file'
| 'columns'
| 'highlight-block'
| 'date'
| 'code-block'
| 'formula'
| 'blockquote'
| 'emoji'
| 'link'
| 'divider'
| 'countdown'
| 'markdown-import'工具栏:
type RichTextEditorToolbarActionKey = 'blockquote'事件
| 事件 | Payload | 说明 |
| --- | --- | --- |
| update:modelValue | JSONContent | 内容更新,用于 v-model。 |
| change | JSONContent | 内容更新事件。 |
| local-file-upload | RichTextEditorLocalFilePayload | 用户通过本地文件选择器插入文件后触发。 |
| local-file-download | RichTextEditorLocalFilePayload | 用户点击本地文件卡片下载按钮时触发。 |
自定义文案
编辑器默认 UI 文案为中文。你可以用 messages 覆盖任意 key:
<RichTextEditor
v-model="content"
:messages="{
'insert.localFile': '附件',
'export.label': '下载',
}"
/>常用文案 key:
| Key | 默认中文 |
| --- | --- |
| insert.label | 插入 |
| insert.section.general | 通用 |
| insert.section.apps | 小应用 |
| insert.section.external | 外部内容 |
| insert.image | 图片 |
| insert.video | 视频 |
| insert.table | 表格 |
| insert.localFile | 本地文件 |
| insert.columns | 分栏 |
| insert.highlightBlock | 高亮块 |
| insert.date | 日期 |
| insert.codeBlock | 代码块 |
| insert.formula | 公式 |
| insert.blockquote | 引用 |
| insert.emoji | 表情符号 |
| insert.link | 超链接 |
| insert.divider | 分隔线 |
| insert.countdown | 倒计时 |
| insert.markdownImport | Markdown 导入 |
| export.label | 导出 |
| export.pdf | 导出 PDF |
| export.pdf.loading | 导出 PDF 中... |
| export.html | 导出 HTML |
| export.html.loading | 导出 HTML 中... |
| export.image | 导出图片 |
| export.image.loading | 导出图片中... |
| print.label | 打印 |
| print.loading | 打印中... |
| quote.apply | 应用引用 |
| quote.cancel | 取消引用 |
| quote.borderColor | 边框颜色 |
| quote.backgroundColor | 背景颜色 |
| outline.label | 大纲 |
| outline.collapse | 收起大纲 |
| outline.empty.description | 对文档内容应用“标题”样式,即可自动生成大纲。 |
| outline.empty.tip | 点击左下角“大纲”按钮可以随时展开或收起。 |
| status.wordCountUnit | 个字 |
| status.presentation.enter | 演示 |
| status.presentation.exit | 退出演示 |
| status.fullscreen.enter | 全屏 |
| status.fullscreen.exit | 退出全屏 |
| countdown.selectTime | 请选择时间 |
| countdown.settingsTitle | 倒计时设置 |
| formula.insertTitle | 插入 LaTeX 公式 |
预览模式
mode="preview" 会切换到只读预览外壳。预览模式下工具栏隐藏,编辑禁用,大纲仍可放在左侧或右侧。
<RichTextEditor
v-model="content"
mode="preview"
outline-placement="right"
/>窄屏下预览模式会自动缩放页面画布,让文档在手机上保持可读。
协同编辑
组件支持普通单人编辑,也支持可选的 Yjs 协同编辑。
<script setup lang="ts">
import { ref } from 'vue'
import * as Y from 'yjs'
import { WebsocketProvider } from 'y-websocket'
import type { JSONContent } from '@tiptap/core'
import { RichTextEditor } from '@ap666/office-word'
import '@ap666/office-word/style.css'
const ydoc = new Y.Doc()
const provider = new WebsocketProvider('ws://localhost:1234', 'office-word-demo', ydoc)
const content = ref<JSONContent | null>(null)
</script>
<template>
<RichTextEditor
v-model="content"
:collaboration="{
document: ydoc,
field: 'content',
provider,
user: {
name: '张三',
color: '#3b82f6',
},
}"
/>
</template>协同模式下,Yjs fragment 是内容的事实来源。组件仍会 emit JSON 更新,但外部 modelValue 的变化不会再反向写入编辑器。如果需要远程光标,请在宿主项目安装 y-websocket,并传入 provider 和 user。
不要把 modelValue 当作协同房间的初始化种子。如果房间需要默认内容,请在挂载编辑器之前先初始化 Yjs 文档。
内置 Yjs 服务示例
发布包内包含一个最小 Yjs WebSocket 服务示例:
cd node_modules/@ap666/office-word/yjs
npm install
npm run start默认监听地址为 ws://0.0.0.0:1234。客户端需要使用相同 WebSocket 地址和房间名:
import * as Y from 'yjs'
import { WebsocketProvider } from 'y-websocket'
const ydoc = new Y.Doc()
const provider = new WebsocketProvider('ws://127.0.0.1:1234', 'office-word-demo', ydoc)实例 API
通过 Vue ref 获取组件实例方法:
<script setup lang="ts">
import { ref } from 'vue'
import { RichTextEditor } from '@ap666/office-word'
import type { RichTextEditorInstance } from '@ap666/office-word'
const editorRef = ref<RichTextEditorInstance | null>(null)
</script>
<template>
<RichTextEditor ref="editorRef" />
</template>可用方法:
| 方法 | 返回值 | 说明 |
| --- | --- | --- |
| exportPdf() | Promise<Blob \| null> | 导出 PDF。 |
| exportImage(options?) | Promise<Blob \| null> | 导出图片,支持 PNG/JPEG。 |
| exportHtml() | string \| null | 导出 HTML 字符串。 |
| insertImage(payload) | boolean | 插入 1 到 4 张图片。 |
| insertVideo(payload) | boolean | 插入视频块。 |
| insertFile(payload) | boolean | 插入链接/文件预览块。 |
| insertLocalFile(payload) | boolean | 插入本地文件卡片。 |
| openLocalFilePicker() | void | 打开本地文件选择器。 |
| focus() | void | 聚焦编辑器。 |
| getJSON() | JSONContent \| null | 获取当前 JSON 内容。 |
上传并插入
推荐集成流程:
- 在业务层上传文件。
- 等待接口返回可访问 URL。
- 调用组件实例方法插入返回内容。
插入图片:
async function uploadImage(file: File) {
const imageUrl = await yourUploadApi(file)
editorRef.value?.insertImage({
src: imageUrl,
name: file.name,
alt: file.name,
description: '',
})
}一次最多插入 4 张图片:
editorRef.value?.insertImage([
{ src: 'https://cdn.example.com/a.png', name: 'a.png' },
{ src: 'https://cdn.example.com/b.png', name: 'b.png' },
])插入视频:
async function uploadVideo(file: File) {
const videoUrl = await yourUploadApi(file)
editorRef.value?.insertVideo({
src: videoUrl,
name: file.name,
mimeType: file.type || 'video/mp4',
description: 'video description',
})
}插入文件链接/预览块:
async function uploadFile(file: File) {
const fileUrl = await yourUploadApi(file)
editorRef.value?.insertFile({
url: fileUrl,
name: file.name,
displayMode: 'text',
})
}插入本地文件卡片:
editorRef.value?.insertLocalFile({
url: 'https://cdn.example.com/files/demo.txt',
name: 'demo.txt',
size: 2048,
mimeType: 'text/plain',
})导出示例
async function handleExportPdf() {
const blob = await editorRef.value?.exportPdf()
if (!blob) return
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = 'demo.pdf'
link.click()
URL.revokeObjectURL(url)
}
async function handleExportImage() {
const blob = await editorRef.value?.exportImage({
type: 'image/png',
})
if (!blob) return
const url = URL.createObjectURL(blob)
window.open(url, '_blank')
}
function handleExportHtml() {
const html = editorRef.value?.exportHtml()
if (!html) return
console.log(html)
}类型导入
import type {
RichTextEditorCollaborationProvider,
RichTextEditorCollaborationUser,
RichTextEditorCollaborationOptions,
RichTextEditorExportItemKey,
RichTextEditorFilePayload,
RichTextEditorImageExportOptions,
RichTextEditorImagePayload,
RichTextEditorInsertMenuItemKey,
RichTextEditorInstance,
RichTextEditorLocalFilePayload,
RichTextEditorMessages,
RichTextEditorProps,
RichTextEditorToolbarActionKey,
RichTextEditorVideoPayload,
} from '@ap666/office-word'包内文档
- 使用指南:
docs/usage.md - Yjs 服务示例:
yjs/README.md
English
@ap666/office-word is a reusable rich text editor component for Vue 3 and Tiptap 3. It ships with a document-style editing UI, image/video/file blocks, tables, formulas, countdown blocks, highlight blocks, outline navigation, preview mode, export APIs, and optional Yjs collaboration.
Installation
npm install @ap666/office-wordThe component styles are published as a separate CSS file. Import it in your application entry:
import '@ap666/office-word/style.css'If your package manager does not auto-install peer dependencies, install the runtime peer packages as well:
npm install vue @tiptap/core @tiptap/vue-3 @tiptap/pm @tiptap/starter-kit @tiptap/extension-placeholder @tiptap/extension-code-block @tiptap/extension-code-block-lowlight @tiptap/extension-collaboration @tiptap/extension-collaboration-caret @tiptap/extension-font-family @tiptap/extension-subscript @tiptap/extension-superscript @tiptap/extension-table @tiptap/extension-table-cell @tiptap/extension-table-header @tiptap/extension-table-row @tiptap/extension-task-item @tiptap/extension-task-list @tiptap/extension-text-style @tiptap/extension-underline @tiptap/y-tiptap lowlight y-prosemirror yjshtml2canvas, jspdf, katex, marked, and plyr are regular dependencies and are installed with the package.
Quick Start
<script setup lang="ts">
import { ref } from 'vue'
import type { JSONContent } from '@tiptap/core'
import { RichTextEditor } from '@ap666/office-word'
import '@ap666/office-word/style.css'
const content = ref<JSONContent | null>(null)
</script>
<template>
<RichTextEditor v-model="content" />
</template>Default import is also supported:
import RichTextEditor from '@ap666/office-word'Props
| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| modelValue | JSONContent \| null | null | Editor content. Supports v-model. |
| editable | boolean | true | Enables or disables editing. |
| mode | 'edit' \| 'preview' | 'edit' | Edit mode or read-only preview mode. |
| outlinePlacement | 'left' \| 'right' | 'right' | Outline panel placement. |
| messages | RichTextEditorMessages \| null | null | Overrides built-in UI labels. |
| enabledExportItems | RichTextEditorExportItemKey[] \| null | null | Export menu whitelist. |
| enabledInsertMenuItems | RichTextEditorInsertMenuItemKey[] \| null | null | Insert menu whitelist. |
| enabledToolbarActions | RichTextEditorToolbarActionKey[] \| null | null | Toolbar action whitelist. |
| placeholder | string | '' | Placeholder text for empty content. |
| collaboration | RichTextEditorCollaborationOptions \| null | null | Yjs collaboration options. |
When whitelist props are omitted, all built-in options remain enabled. Once a list is passed, only listed items are visible and usable.
<RichTextEditor
v-model="content"
:enabled-export-items="['html', 'image']"
:enabled-insert-menu-items="['image', 'local-file', 'blockquote']"
:enabled-toolbar-actions="['blockquote']"
/>Available Keys
Export menu:
type RichTextEditorExportItemKey = 'pdf' | 'html' | 'image' | 'print'Insert menu:
type RichTextEditorInsertMenuItemKey =
| 'image'
| 'video'
| 'table'
| 'local-file'
| 'columns'
| 'highlight-block'
| 'date'
| 'code-block'
| 'formula'
| 'blockquote'
| 'emoji'
| 'link'
| 'divider'
| 'countdown'
| 'markdown-import'Toolbar:
type RichTextEditorToolbarActionKey = 'blockquote'Events
| Event | Payload | Description |
| --- | --- | --- |
| update:modelValue | JSONContent | Content update event used by v-model. |
| change | JSONContent | Content update event. |
| local-file-upload | RichTextEditorLocalFilePayload | Emitted after a local file is picked and inserted. |
| local-file-download | RichTextEditorLocalFilePayload | Emitted when the local file card download button is clicked. |
Custom Labels
The default UI labels are Chinese. Use messages to override only the keys you need:
<RichTextEditor
v-model="content"
:messages="{
'insert.localFile': 'Attachment',
'export.label': 'Download',
}"
/>Common message keys:
| Key | Default Chinese | English meaning |
| --- | --- | --- |
| insert.label | 插入 | Insert |
| insert.section.general | 通用 | General |
| insert.section.apps | 小应用 | Apps |
| insert.section.external | 外部内容 | External content |
| insert.image | 图片 | Image |
| insert.video | 视频 | Video |
| insert.table | 表格 | Table |
| insert.localFile | 本地文件 | Local file |
| insert.columns | 分栏 | Columns |
| insert.highlightBlock | 高亮块 | Highlight block |
| insert.date | 日期 | Date |
| insert.codeBlock | 代码块 | Code block |
| insert.formula | 公式 | Formula |
| insert.blockquote | 引用 | Quote |
| insert.emoji | 表情符号 | Emoji |
| insert.link | 超链接 | Link |
| insert.divider | 分隔线 | Divider |
| insert.countdown | 倒计时 | Countdown |
| insert.markdownImport | Markdown 导入 | Markdown import |
| export.label | 导出 | Export |
| export.pdf | 导出 PDF | Export PDF |
| export.pdf.loading | 导出 PDF 中... | Exporting PDF... |
| export.html | 导出 HTML | Export HTML |
| export.html.loading | 导出 HTML 中... | Exporting HTML... |
| export.image | 导出图片 | Export image |
| export.image.loading | 导出图片中... | Exporting image... |
| print.label | 打印 | Print |
| print.loading | 打印中... | Printing... |
| quote.apply | 应用引用 | Apply quote |
| quote.cancel | 取消引用 | Cancel quote |
| quote.borderColor | 边框颜色 | Border color |
| quote.backgroundColor | 背景颜色 | Background color |
| outline.label | 大纲 | Outline |
| outline.collapse | 收起大纲 | Collapse outline |
| outline.empty.description | 对文档内容应用“标题”样式,即可自动生成大纲。 | Apply heading styles to generate an outline. |
| outline.empty.tip | 点击左下角“大纲”按钮可以随时展开或收起。 | Use the Outline button to show or hide the outline. |
| status.wordCountUnit | 个字 | characters |
| status.presentation.enter | 演示 | Present |
| status.presentation.exit | 退出演示 | Exit presentation |
| status.fullscreen.enter | 全屏 | Fullscreen |
| status.fullscreen.exit | 退出全屏 | Exit fullscreen |
| countdown.selectTime | 请选择时间 | Select time |
| countdown.settingsTitle | 倒计时设置 | Countdown settings |
| formula.insertTitle | 插入 LaTeX 公式 | Insert LaTeX formula |
Preview Mode
Use mode="preview" to switch the component into a read-only preview shell. In preview mode, the toolbar is hidden, editing is disabled, and the outline can be placed on either side.
<RichTextEditor
v-model="content"
mode="preview"
outline-placement="right"
/>On narrow screens, preview mode automatically scales the page canvas so the document stays readable on phones.
Collaboration
The component supports both normal single-user editing and optional Yjs collaboration.
<script setup lang="ts">
import { ref } from 'vue'
import * as Y from 'yjs'
import { WebsocketProvider } from 'y-websocket'
import type { JSONContent } from '@tiptap/core'
import { RichTextEditor } from '@ap666/office-word'
import '@ap666/office-word/style.css'
const ydoc = new Y.Doc()
const provider = new WebsocketProvider('ws://localhost:1234', 'office-word-demo', ydoc)
const content = ref<JSONContent | null>(null)
</script>
<template>
<RichTextEditor
v-model="content"
:collaboration="{
document: ydoc,
field: 'content',
provider,
user: {
name: 'Zhang San',
color: '#3b82f6',
},
}"
/>
</template>In collaboration mode, the shared Yjs fragment becomes the source of truth. The component still emits JSON updates, but external modelValue changes are not pushed back into the editor. If you want remote cursors, install y-websocket in the host project and pass provider plus user.
Do not use modelValue as the initial seed source for a collaborative room. Seed the Yjs document before mounting the editor if the room needs default content.
Bundled Yjs Server Example
The published package includes a minimal Yjs WebSocket server example under yjs/.
cd node_modules/@ap666/office-word/yjs
npm install
npm run startThe default address is ws://0.0.0.0:1234. Use the same WebSocket address and room name on every client:
import * as Y from 'yjs'
import { WebsocketProvider } from 'y-websocket'
const ydoc = new Y.Doc()
const provider = new WebsocketProvider('ws://127.0.0.1:1234', 'office-word-demo', ydoc)Instance API
Use a Vue ref to access the editor instance methods:
<script setup lang="ts">
import { ref } from 'vue'
import { RichTextEditor } from '@ap666/office-word'
import type { RichTextEditorInstance } from '@ap666/office-word'
const editorRef = ref<RichTextEditorInstance | null>(null)
</script>
<template>
<RichTextEditor ref="editorRef" />
</template>Available methods:
| Method | Return | Description |
| --- | --- | --- |
| exportPdf() | Promise<Blob \| null> | Exports a PDF. |
| exportImage(options?) | Promise<Blob \| null> | Exports an image as PNG or JPEG. |
| exportHtml() | string \| null | Exports an HTML string. |
| insertImage(payload) | boolean | Inserts 1 to 4 images. |
| insertVideo(payload) | boolean | Inserts a video block. |
| insertFile(payload) | boolean | Inserts a link/file preview block. |
| insertLocalFile(payload) | boolean | Inserts a local file card. |
| openLocalFilePicker() | void | Opens the local file picker. |
| focus() | void | Focuses the editor. |
| getJSON() | JSONContent \| null | Returns the current JSON document. |
Upload And Insert
Recommended integration flow:
- Upload the asset from your own business layer.
- Wait for the API to return the final accessible URL.
- Call the editor instance method to insert the returned content.
Insert image:
async function uploadImage(file: File) {
const imageUrl = await yourUploadApi(file)
editorRef.value?.insertImage({
src: imageUrl,
name: file.name,
alt: file.name,
description: '',
})
}You can insert up to 4 images in one call:
editorRef.value?.insertImage([
{ src: 'https://cdn.example.com/a.png', name: 'a.png' },
{ src: 'https://cdn.example.com/b.png', name: 'b.png' },
])Insert video:
async function uploadVideo(file: File) {
const videoUrl = await yourUploadApi(file)
editorRef.value?.insertVideo({
src: videoUrl,
name: file.name,
mimeType: file.type || 'video/mp4',
description: 'video description',
})
}Insert file link or preview:
async function uploadFile(file: File) {
const fileUrl = await yourUploadApi(file)
editorRef.value?.insertFile({
url: fileUrl,
name: file.name,
displayMode: 'text',
})
}Insert a local file card:
editorRef.value?.insertLocalFile({
url: 'https://cdn.example.com/files/demo.txt',
name: 'demo.txt',
size: 2048,
mimeType: 'text/plain',
})Export Example
async function handleExportPdf() {
const blob = await editorRef.value?.exportPdf()
if (!blob) return
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = 'demo.pdf'
link.click()
URL.revokeObjectURL(url)
}
async function handleExportImage() {
const blob = await editorRef.value?.exportImage({
type: 'image/png',
})
if (!blob) return
const url = URL.createObjectURL(blob)
window.open(url, '_blank')
}
function handleExportHtml() {
const html = editorRef.value?.exportHtml()
if (!html) return
console.log(html)
}Type Imports
import type {
RichTextEditorCollaborationProvider,
RichTextEditorCollaborationUser,
RichTextEditorCollaborationOptions,
RichTextEditorExportItemKey,
RichTextEditorFilePayload,
RichTextEditorImageExportOptions,
RichTextEditorImagePayload,
RichTextEditorInsertMenuItemKey,
RichTextEditorInstance,
RichTextEditorLocalFilePayload,
RichTextEditorMessages,
RichTextEditorProps,
RichTextEditorToolbarActionKey,
RichTextEditorVideoPayload,
} from '@ap666/office-word'Package Docs
- Usage guide:
docs/usage.md - Bundled Yjs server example:
yjs/README.md
