diff --git a/libs/tiptap-editor/src/index.ts b/libs/tiptap-editor/src/index.ts index c8aa8e7..e0218e1 100644 --- a/libs/tiptap-editor/src/index.ts +++ b/libs/tiptap-editor/src/index.ts @@ -87,8 +87,12 @@ class TiptapEditorInstance { TaskList, TaskItem.configure({ nested: true }), // 把宿主注入的图片上传回调透传给斜杠命令扩展,使 /上传图片 命令可用。 + // 注意:闭包延迟读取 this.coordinator(它在 editor 创建后才实例化)。 SlashCommand.configure({ onImageUpload: this.options.onImageUpload, + onInsertUploading: this.options.onImageUpload + ? (file) => this.coordinator?.insertUploading(file) + : undefined, }), FileHandler.configure({ allowedMimeTypes: ['image/jpeg', 'image/png', 'image/gif', 'image/webp'], diff --git a/libs/tiptap-editor/src/slash-command.ts b/libs/tiptap-editor/src/slash-command.ts index 20b4be1..beb5e2a 100644 --- a/libs/tiptap-editor/src/slash-command.ts +++ b/libs/tiptap-editor/src/slash-command.ts @@ -18,6 +18,8 @@ interface CommandItem { */ export interface SlashCommandOptions { onImageUpload?: (file: File) => Promise + /** 由 index.ts 注入:直接调 coordinator.insertUploading(走占位符 + 上传)。 */ + onInsertUploading?: (file: File) => void } const SlashCommandPluginKey = new PluginKey('slashCommand') @@ -33,6 +35,7 @@ export const SlashCommand = Extension.create({ addOptions() { return { onImageUpload: undefined, + onInsertUploading: undefined, } }, @@ -137,14 +140,19 @@ export const SlashCommand = Extension.create({ input.addEventListener('change', () => { const file = input.files?.[0] if (!file) return - uploadFn(file) - .then((url) => { - editor.chain().focus().setImage({ src: url }).run() - }) - .catch((err) => { - const msg = err instanceof Error ? err.message : String(err) - console.error('[SlashCommand] Upload failed:', msg) - }) + // 优先走 coordinator(占位符 + 上传),否则退回直接上传(无占位符) + if (this.options.onInsertUploading) { + this.options.onInsertUploading(file) + } else if (uploadFn) { + uploadFn(file) + .then((url) => { + editor.chain().focus().setImage({ src: url }).run() + }) + .catch((err) => { + const msg = err instanceof Error ? err.message : String(err) + console.error('[SlashCommand] Upload failed:', msg) + }) + } }) // click() 会立即触发原生文件选择器;回调在用户选择文件后异步执行。 input.click()