Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(editor): upload pasted image file instead of image-only HTML (#21168)

Lobehub Coderfae57cfd558b
diff --git a/src/features/EditorCanvas/InternalEditor.tsx b/src/features/EditorCanvas/InternalEditor.tsx
index 08644bdaca8..56e82c1f56b 100644
--- a/src/features/EditorCanvas/InternalEditor.tsx
+++ b/src/features/EditorCanvas/InternalEditor.tsx
@@ -26,6 +26,7 @@ import InlineToolbar from './InlineToolbar';
import LinearFilePlugin from './LinearFilePlugin';
import { registerAttachmentClickOpen } from './registerAttachmentClickOpen';
import { registerBlockDecoratorCaretGuard } from './registerBlockDecoratorCaretGuard';
+import { registerImageFilePastePreference } from './registerImageFilePastePreference';
import { needsImageRehost, rehostImage } from './rehostImage';
import { useFileUpload, useImageUpload } from './useImageUpload';
@@ -265,6 +266,14 @@ const InternalEditor = memo<InternalEditorProps>(
return () => unregister?.();
}, [editor]);
+ // Copy Image from apps like Discord puts an image-only HTML flavor next to
+ // the bitmap; upload the bitmap instead of rehosting the remote URL.
+ useEffect(() => {
+ if (!editor) return;
+ const unregister = registerImageFilePastePreference(editor);
+ return () => unregister?.();
+ }, [editor]);
+
// Opt-in (comment editors): keep the caret out of the root node around
// block images by pushing an empty paragraph next to the image instead of
// showing Lexical's horizontal root-level caret.
diff --git a/src/features/EditorCanvas/registerImageFilePastePreference.test.ts b/src/features/EditorCanvas/registerImageFilePastePreference.test.ts
new file mode 100644
index 00000000000..6ca3d5d386e
--- /dev/null
+++ b/src/features/EditorCanvas/registerImageFilePastePreference.test.ts
@@ -0,0 +1,49 @@
+import { createEditor, PASTE_COMMAND } from 'lexical';
+import { describe, expect, it, vi } from 'vitest';
+
+import { registerImageFilePastePreferenceOnLexical } from './registerImageFilePastePreference';
+
+const createPasteEvent = (files: File[], html: string) =>
+ ({
+ clipboardData: { files, getData: (type: string) => (type === 'text/html' ? html : '') },
+ preventDefault: vi.fn(),
+ }) as unknown as ClipboardEvent;
+
+const setup = () => {
+ const editor = createEditor({ onError: (error) => { throw error; } });
+ const onFiles = vi.fn();
+ registerImageFilePastePreferenceOnLexical(editor, onFiles);
+ return { editor, onFiles };
+};
+
+const image = new File(['png'], 'image.png', { type: 'image/png' });
+
+describe('registerImageFilePastePreference', () => {
+ it('uploads the image file instead of an image-only HTML flavor (Discord copy image)', () => {
+ const { editor, onFiles } = setup();
+ const event = createPasteEvent(
+ [image],
+ '<meta charset="utf-8"><img src="https://media.discordapp.net/attachments/1/2/image.png?ex=1">',
+ );
+
+ expect(editor.dispatchCommand(PASTE_COMMAND, event)).toBe(true);
+ expect(event.preventDefault).toHaveBeenCalled();
+ expect(onFiles).toHaveBeenCalledWith(image);
+ });
+
+ it('keeps the HTML paste when it carries text besides images', () => {
+ const { editor, onFiles } = setup();
+ const event = createPasteEvent([image], '<p>hello <img src="https://example.com/a.png"></p>');
+
+ expect(editor.dispatchCommand(PASTE_COMMAND, event)).toBe(false);
+ expect(onFiles).not.toHaveBeenCalled();
+ });
+
+ it('ignores pastes without image files', () => {
+ const { editor, onFiles } = setup();
+ const event = createPasteEvent([], '<img src="https://example.com/a.png">');
+
+ expect(editor.dispatchCommand(PASTE_COMMAND, event)).toBe(false);
+ expect(onFiles).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/EditorCanvas/registerImageFilePastePreference.ts b/src/features/EditorCanvas/registerImageFilePastePreference.ts
new file mode 100644
index 00000000000..89c94d83ceb
--- /dev/null
+++ b/src/features/EditorCanvas/registerImageFilePastePreference.ts
@@ -0,0 +1,58 @@
+import { type IEditor, IUploadService } from '@lobehub/editor';
+import { COMMAND_PRIORITY_CRITICAL, type LexicalEditor, PASTE_COMMAND } from 'lexical';
+
+/**
+ * True when the HTML flavor carries nothing but images — what apps such as
+ * Discord put next to the bitmap on "Copy Image".
+ */
+const isImageOnlyHtml = (html: string) => {
+ const body = new DOMParser().parseFromString(html, 'text/html').body;
+ if (!body.querySelector('img')) return false;
+
+ const clone = body.cloneNode(true) as HTMLElement;
+ clone.querySelectorAll('img').forEach((img) => img.remove());
+ return !clone.textContent?.trim() && !clone.querySelector('video, iframe, table, svg');
+};
+
+/**
+ * Prefer the clipboard's image file over an image-only HTML flavor.
+ *
+ * Lexical pastes `text/html` whenever it exists, so an image copied from
+ * Discord lands as `<img src="https://cdn.discordapp.com/...">`, which then
+ * has to be rehosted from a signed third-party URL and fails. The bitmap in
+ * the same clipboard is the real image, so upload that instead.
+ */
+export const registerImageFilePastePreferenceOnLexical = (
+ lexicalEditor: LexicalEditor,
+ uploadFile: (file: File) => void,
+) =>
+ lexicalEditor.registerCommand(
+ PASTE_COMMAND,
+ (event) => {
+ if (!('clipboardData' in event) || !event.clipboardData) return false;
+ const { clipboardData } = event;
+
+ const files = [...clipboardData.files];
+ if (files.length === 0 || !files.every((file) => file.type.startsWith('image/')))
+ return false;
+
+ const html = clipboardData.getData('text/html');
+ if (!html || !isImageOnlyHtml(html)) return false;
+
+ event.preventDefault();
+ for (const file of files) uploadFile(file);
+ return true;
+ },
+ COMMAND_PRIORITY_CRITICAL,
+ );
+
+export const registerImageFilePastePreference = (editor: IEditor): (() => void) | undefined => {
+ const lexicalEditor = editor.getLexicalEditor?.();
+ if (!lexicalEditor) return;
+ return registerImageFilePastePreferenceOnLexical(lexicalEditor, (file) => {
+ editor
+ .requireService(IUploadService)
+ ?.uploadFile(file, 'drag-drop-paste', null)
+ .catch((error) => console.error('[EditorCanvas] paste image upload failed:', error));
+ });
+};