import { type EditorProps as DraftEditorProps, type DraftHandleValue, EditorState, Modifier, RichUtils, } from 'draft-js'; import { useCallback } from 'react'; type UsePastedTextHandlerRes = Exclude< DraftEditorProps['handlePastedText'], undefined >; /** * Pastes only text if the current block is atomic. */ const usePastedTextHandler = ( onChange: (value: EditorState) => void, handler: UsePastedTextHandlerRes ): UsePastedTextHandlerRes => useCallback( (text, html, editorState): DraftHandleValue => { const currentBlockType = RichUtils.getCurrentBlockType(editorState); if (currentBlockType.startsWith('atomic')) { const contentState = editorState.getCurrentContent(); const nextContentState = Modifier.insertText( contentState, editorState.getSelection(), text ); const nextEditorState = EditorState.push( editorState, nextContentState, 'insert-characters' ); onChange(nextEditorState); return 'handled'; } return handler(text, html, editorState); }, [onChange, handler] ); export default usePastedTextHandler;