Bug: Can't capture the image node and data when dragging an image into the editor
function onDrop(event: DragEvent, editor: LexicalEditor): boolean {
const node = getImageNodeInSelection();
console.log("[onDrop] Image node : ", node); // node was not captured.
if (!node) {
return false;
}
const data = getDragImageData(event);
console.log("onDrop data: ", data); // data was not captured.
if (!data) {
return false;
}
event.preventDefault();
if (canDropImage(event)) {
console.log("canDropImage event: ", event);
const range = getDragSelection(event);
node.remove();
const rangeSelection = $createRangeSelection();
if (range !== null && range !== undefined) {
rangeSelection.applyDOMRange(range);
}
$setSelection(rangeSelection);
editor.dispatchCommand(INSERT_IMAGE_COMMAND, data);
}
return true;
}
Lexical version: 0.12.4
The current behavior
Can't capture the dragged image node and data
The expected behavior
Image node and data get captured.
If you copy/pasted from the Playground, you might be missing the DragDropPastePlugin https://github.com/facebook/lexical/blob/main/packages/lexical-playground/src/plugins/DragDropPastePlugin/index.ts
I encountered a similar issue when a user was drag-dropping an image from a local server or an image from a website.
The image will display in the editor but is intercepted in CONTROLLED_TEXT_INSERTION_COMMAND as its type is text/uri-list in event.dataTransfer. The image will be inserted in the editor with its original url and bypass the Drag And Drop Paste Plugin.
I added a method in DragDropPaste to catch these image URLs. My understanding of Lexical is still rudimentary, so there might be better ways.
useEffect(() => {
return editor.registerCommand(
CONTROLLED_TEXT_INSERTION_COMMAND,
(event) => {
if (typeof event === 'string') {
return false;
}
const url = event.dataTransfer?.getData('text/uri-list');
if (!url) {
return false;
}
// Custom application logic here
// handleSaveImageInDBAndInsert(url);
return true;
},
COMMAND_PRIORITY_LOW,
);
}, [editor, handleSaveImageInDBAndInsert]);