@musecanto/extension-attachment
文档附件卡片、拖拽上传、进度指示、下载操作与只读态注水。
让文档进入你的工作流
@musecanto/extension-attachment 提供了结构化文件附件卡片功能。支持各类文档、压缩包、音视频等文件的选择与拖拽上传,以美观的卡片形式呈现文件类型图标、文件名称、文件体积与上传进度,并支持直接下载与重命名。
1. 包定位与依赖关系
- NPM 包名:
@musecanto/extension-attachment - 依赖说明:原生 Tiptap 模式下依赖
@tiptap/core与@musecanto/editor-schema;React UI 依赖为可选对等依赖。
pnpm add @musecanto/extension-attachment2. 开箱使用 (@musecanto/editor-kit)
在 @musecanto/editor-kit 中配置 features.attachment:
import { createEditor } from "@musecanto/editor-kit";
const editor = createEditor({
el: "#editor",
features: {
attachment: {
onUpload: async (file, onProgress) => {
const formData = new FormData();
formData.append("file", file);
// 模拟进度更新
onProgress?.({ progress: 60 });
const res = await fetch("/api/upload-file", {
method: "POST",
body: formData,
});
const data = await res.json();
return {
src: data.url,
fileName: file.name,
fileSize: file.size,
fileType: file.type,
};
},
onError: (err) => console.error("附件上传失败:", err),
},
},
});3. 原生 Tiptap 独立用法
import { Editor } from "@tiptap/core";
import StarterKit from "@tiptap/starter-kit";
import { BaseAttachment } from "@musecanto/extension-attachment";
import "@musecanto/extension-attachment/style.css";
const editor = new Editor({
element: document.querySelector("#editor"),
extensions: [
StarterKit,
BaseAttachment.configure({
onUpload: async (file) => ({
src: "/files/" + file.name,
fileName: file.name,
fileSize: file.size,
}),
}),
],
});4. React UI 定制与 Contribution
从 @musecanto/extension-attachment/react 导入 attachmentUI:
import { EditorUIProvider } from "@musecanto/editor-react";
import { attachmentUI } from "@musecanto/extension-attachment/react";
<EditorUIProvider contributions={[attachmentUI]}>
{/* 渲染包含附件卡片界面的编辑器 */}
</EditorUIProvider>;5. 只读态 SSR 注水支持
在服务端渲染(SSR)或静态导出的 HTML 页面中,可使用注水工具为静态附件节点绑定下载与点击事件:
import { hydrateReadonlyAttachments } from "@musecanto/extension-attachment/hydrate-readonly-attachments";
// 在客户端挂载时调用,指定容器元素
hydrateReadonlyAttachments(document.querySelector("#content")!);6. 配置项参考 (AttachmentOptions)
| 字段 | 类型 | 说明 |
|---|---|---|
onUpload | (file: File, onProgress?: (p: { progress: number }) => void) => Promise<AttachmentHTMLAttributes> | 核心上传回调函数,返回文件地址与元信息 |
proxyUrl | string | 可选附件代理前缀 |
onError | (error: unknown) => void | 异常处理回调 |
7. 样式规范
引入专属附件卡片样式:
import "@musecanto/extension-attachment/style.css";包含样式:
- 文件卡片外框、悬浮阴影与激活态边框。
- 不同文件后缀(PDF、ZIP、DOCX 等)对应的格式图标着色。
- 上传中进度环与操作下拉菜单。