UNPKG

@lobehub/editor

Version:

A powerful and extensible rich text editor built on Meta's Lexical framework, providing a modern editing experience with React integration.

48 lines 1.93 kB
import { $wrapNodeInElement } from '@lexical/utils'; import { $createParagraphNode, $createRangeSelection, $insertNodes, $isRootOrShadowRoot, $setSelection, COMMAND_PRIORITY_EDITOR, createCommand } from 'lexical'; import { createDebugLogger } from "../../../utils/debug"; import { $createImageNode } from "../node/image-node"; var logger = createDebugLogger('plugin', 'image'); export var INSERT_IMAGE_COMMAND = createCommand('INSERT_IMAGE_COMMAND'); function isImageFile(file) { return file.type.startsWith('image/'); } export function registerImageCommand(editor, handleUpload) { return editor.registerCommand(INSERT_IMAGE_COMMAND, function (payload) { var file = payload.file, range = payload.range; if (!isImageFile(file)) { return false; // Not an image file } var placeholderURL = URL.createObjectURL(file); // Create a local URL for the image editor.update(function () { if (range) { var rangeSelection = $createRangeSelection(); if (range !== null && range !== undefined) { rangeSelection.applyDOMRange(range); } $setSelection(rangeSelection); } var imageNode = $createImageNode({ altText: file.name, src: placeholderURL }); $insertNodes([imageNode]); // Insert a zero-width space to ensure the image is not the last child if ($isRootOrShadowRoot(imageNode.getParentOrThrow())) { $wrapNodeInElement(imageNode, $createParagraphNode).selectEnd(); } handleUpload(file).then(function (res) { editor.update(function () { imageNode.setUploaded(res.url); }); }).catch(function (error) { logger.error('❌ Image upload failed:', error); editor.update(function () { imageNode.setError('Image upload failed : ' + error.message); }); }); }); return true; }, COMMAND_PRIORITY_EDITOR // Priority ); }