@mkljczk/lexical-remark
Version:
This package contains Markdown helpers and functionality for Lexical using remark-parse.
49 lines (48 loc) • 2.65 kB
JavaScript
import { jsx as _jsx } from "react/jsx-runtime";
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext.js';
import { useLexicalNodeSelection } from '@lexical/react/useLexicalNodeSelection.js';
import { mergeRegister } from '@lexical/utils';
import { CLICK_COMMAND, COMMAND_PRIORITY_LOW, KEY_BACKSPACE_COMMAND, KEY_DELETE_COMMAND, SELECTION_CHANGE_COMMAND, $getNodeByKey, $getSelection, $isNodeSelection, } from 'lexical';
import { Suspense, useCallback, useEffect, useRef } from 'react';
import { $isImageNode } from './node.js';
const LazyImage = ({ altText, className, height, imageRef, src, width, }) => (_jsx("img", { ref: imageRef, alt: altText, className: className, src: src, style: { height, width } }));
export default function EditorImageComponent({ altText, height, nodeKey, src, width, }) {
const imageRef = useRef(null);
const [isSelected, setSelected, clearSelection] = useLexicalNodeSelection(nodeKey);
const [editor] = useLexicalComposerContext();
const activeEditorRef = useRef(null);
const onDelete = useCallback((event) => {
if (isSelected && $isNodeSelection($getSelection())) {
event.preventDefault();
const node = $getNodeByKey(nodeKey);
if ($isImageNode(node)) {
node.remove();
}
setSelected(false);
}
return false;
}, [isSelected, nodeKey, setSelected]);
useEffect(() => {
const unregister = mergeRegister(editor.registerCommand(SELECTION_CHANGE_COMMAND, (_, activeEditor) => {
activeEditorRef.current = activeEditor;
return false;
}, COMMAND_PRIORITY_LOW), editor.registerCommand(CLICK_COMMAND, (payload) => {
const event = payload;
if (event.target === imageRef.current) {
if (event.shiftKey) {
setSelected(!isSelected);
}
else {
clearSelection();
setSelected(true);
}
return true;
}
return false;
}, COMMAND_PRIORITY_LOW), editor.registerCommand(KEY_DELETE_COMMAND, onDelete, COMMAND_PRIORITY_LOW), editor.registerCommand(KEY_BACKSPACE_COMMAND, onDelete, COMMAND_PRIORITY_LOW));
return () => {
unregister();
};
}, [clearSelection, editor, isSelected, nodeKey, onDelete, setSelected]);
return (_jsx(Suspense, { fallback: null, children: _jsx(LazyImage, { ...(isSelected ? { className: 'selected' } : {}), altText: altText, height: height, imageRef: imageRef, src: src, width: width }) }));
}