@lobehub/editor
Version:
A powerful and extensible rich text editor built on Meta's Lexical framework, providing a modern editing experience with React integration.
30 lines • 1.32 kB
JavaScript
import { $wrapNodeInElement } from '@lexical/utils';
import { $createParagraphNode, $insertNodes, $isRootOrShadowRoot, COMMAND_PRIORITY_HIGH, createCommand } from 'lexical';
import { createDebugLogger } from "../../../utils/debug";
import { $createFileNode } from "../node/FileNode";
var logger = createDebugLogger('plugin', 'file');
export var INSERT_FILE_COMMAND = createCommand('INSERT_FILE_COMMAND');
export function registerFileCommand(editor, handleUpload) {
return editor.registerCommand(INSERT_FILE_COMMAND, function (payload) {
var file = payload.file;
editor.update(function () {
var fileNode = $createFileNode(file.name);
$insertNodes([fileNode]); // Insert a zero-width space to ensure the image is not the last child
if ($isRootOrShadowRoot(fileNode.getParentOrThrow())) {
$wrapNodeInElement(fileNode, $createParagraphNode).selectEnd();
}
handleUpload(file).then(function (url) {
editor.update(function () {
fileNode.setUploaded(url.url);
});
}).catch(function (error) {
logger.error('❌ File upload failed:', error);
editor.update(function () {
fileNode.setError('File upload failed : ' + error.message);
});
});
});
return false;
}, COMMAND_PRIORITY_HIGH // Priority
);
}