@musecanto/extension-image
图片上传、拖拽粘贴、远程转存、交互式尺寸调整与全屏大图预览。
让文档进入你的工作流
@musecanto/extension-image 为编辑器提供企业级图片解决方案。支持文件选择上传、拖拽与剪贴板粘贴上传(带加载中占位图与进度反馈)、远程外链图片自动转存、交互式边框拖拽缩放(Resize)、对齐调整以及内置的全屏大图预览模态框。
1. 包定位与依赖关系
- NPM 包名:
@musecanto/extension-image - 依赖说明:原生 Tiptap 模式下依赖
@tiptap/core与@musecanto/editor-schema;React UI 依赖为可选对等依赖。
pnpm add @musecanto/extension-image2. 开箱使用 (@musecanto/editor-kit)
在 @musecanto/editor-kit 中配置 features.image:
import { createEditor } from "@musecanto/editor-kit";
const editor = createEditor({
el: "#editor",
features: {
image: {
// 接入自定义上传函数
onUpload: async (file, onProgress) => {
const formData = new FormData();
formData.append("file", file);
// 模拟进度更新
onProgress?.({ progress: 50 });
const res = await fetch("/api/upload", {
method: "POST",
body: formData,
});
const { url, width, height } = await res.json();
return { src: url, width, height, alt: file.name };
},
// 可选:媒体防盗链代理前缀
proxyUrl: "https://my-cdn.com/proxy?url=",
onError: (err) => console.error("图片上传失败:", err),
},
},
});3. 原生 Tiptap 独立用法
在无 React 运行时的纯 Tiptap 项目中使用基础图片扩展:
import { Editor } from "@tiptap/core";
import StarterKit from "@tiptap/starter-kit";
import { BaseResizableImage } from "@musecanto/extension-image";
import "@musecanto/extension-image/style.css";
const editor = new Editor({
element: document.querySelector("#editor"),
extensions: [
StarterKit,
BaseResizableImage.configure({
onUpload: async (file) => ({
src: URL.createObjectURL(file),
}),
}),
],
});4. React UI 定制与 Contribution
从 @musecanto/extension-image/react 导入 imageUI 或 ResizableImageExtension。该组件支持四个方向的拖拽缩放手柄、居中/居左/居右对齐工具条以及点击大图预览:
import { EditorUIProvider } from "@musecanto/editor-react";
import { imageUI } from "@musecanto/extension-image/react";
<EditorUIProvider contributions={[imageUI]}>
{/* 渲染包含交互式图片缩放与工具栏上传的编辑器 */}
</EditorUIProvider>;5. 配置项与 API 参考
ImageOptions 接口
| 字段 | 类型 | 说明 |
|---|---|---|
onUpload | (file: File, onProgress?: (p: { progress: number }) => void) => Promise<ResizableImageHTMLAttributes> | 上传处理函数,返回包含 src、width 等属性的对象 |
proxyUrl | string | 可选媒体代理前缀,自动拼接展示 |
onPreview | (image: { src: string; alt: string }) => void | 自定义大图预览回调;缺省时使用内置弹窗 |
onError | (error: unknown) => void | 上传或解析异常错误处理器 |
核心辅助工具函数
import {
prepareJsonContentImagesForInsert,
rehostRemoteImagesInEditor,
} from "@musecanto/extension-image";
// 自动检测并转存粘贴内容中的远程图片至私有云存储
await rehostRemoteImagesInEditor(editor, uploadFunction);6. 样式规范
引入专属图片与交互手柄样式:
import "@musecanto/extension-image/style.css";包含样式:
- 上传中占位图骨架屏与旋转动画指示器。
- 选中间隙边框与四个角落的缩放拖拽控制点。
- 浮动居中/对齐操作条与大图预览模态框。