import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
import { FC, useEffect } from 'react';
import { COMMAND_PRIORITY_HIGH, EditorState, KEY_ENTER_COMMAND } from 'lexical';

export const OnSubmit: FC<OnSubmitProps> = ({ onSubmit }) => {
  const [editor] = useLexicalComposerContext();

  useEffect(() => {
    return editor.registerCommand(
      KEY_ENTER_COMMAND,
      (payload: KeyboardEvent) => {
        const event: KeyboardEvent = payload;
        event.preventDefault();
        onSubmit(editor.getEditorState());
        editor.focus();
        return true;
      },
      COMMAND_PRIORITY_HIGH
    );
  }, [editor, onSubmit]);

  return <></>;
};

interface OnSubmitProps {
  onSubmit: (editorState: EditorState) => void;
}
