UNPKG

@terrible-lexical/react

Version:

This package provides Lexical components and hooks for React applications.

53 lines (46 loc) 1.32 kB
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ import {useLexicalComposerContext} from '@terrible-lexical/react/src/LexicalComposerContext'; import { $createParagraphNode, $getRoot, $getSelection, CLEAR_EDITOR_COMMAND, COMMAND_PRIORITY_EDITOR, } from 'terrible-lexical'; import useLayoutEffect from '@terrible-lexical/shared/src/useLayoutEffect'; type Props = Readonly<{ onClear?: () => void; }>; export function ClearEditorPlugin({onClear}: Props): JSX.Element | null { const [editor] = useLexicalComposerContext(); useLayoutEffect(() => { return editor.registerCommand( CLEAR_EDITOR_COMMAND, (payload) => { editor.update(() => { if (onClear == null) { const root = $getRoot(); const selection = $getSelection(); const paragraph = $createParagraphNode(); root.clear(); root.append(paragraph); if (selection !== null) { paragraph.select(); } } else { onClear(); } }); return true; }, COMMAND_PRIORITY_EDITOR, ); }, [editor, onClear]); return null; }