UNPKG

lexical-remark

Version:

This package contains Markdown helpers and functionality for Lexical using remark-parse.

49 lines (48 loc) 2.62 kB
import { jsx as _jsx } from "react/jsx-runtime"; import lexicalComposerContext from '@lexical/react/LexicalComposerContext.js'; import lexicalNodeSelection from '@lexical/react/useLexicalNodeSelection.js'; import lexicalUtils from '@lexical/utils'; import lexical 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] = lexicalNodeSelection.useLexicalNodeSelection(nodeKey); const [editor] = lexicalComposerContext.useLexicalComposerContext(); const activeEditorRef = useRef(null); const onDelete = useCallback((event) => { if (isSelected && lexical.$isNodeSelection(lexical.$getSelection())) { event.preventDefault(); const node = lexical.$getNodeByKey(nodeKey); if ($isImageNode(node)) { node.remove(); } setSelected(false); } return false; }, [isSelected, nodeKey, setSelected]); useEffect(() => { const unregister = lexicalUtils.mergeRegister(editor.registerCommand(lexical.SELECTION_CHANGE_COMMAND, (_, activeEditor) => { activeEditorRef.current = activeEditor; return false; }, lexical.COMMAND_PRIORITY_LOW), editor.registerCommand(lexical.CLICK_COMMAND, (payload) => { const event = payload; if (event.target === imageRef.current) { if (event.shiftKey) { setSelected(!isSelected); } else { clearSelection(); setSelected(true); } return true; } return false; }, lexical.COMMAND_PRIORITY_LOW), editor.registerCommand(lexical.KEY_DELETE_COMMAND, onDelete, lexical.COMMAND_PRIORITY_LOW), editor.registerCommand(lexical.KEY_BACKSPACE_COMMAND, onDelete, lexical.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 }) })); }