import { ContentBlock, ContentState, EditorState, genKey } from 'draft-js'; import * as Immutable from 'immutable'; const addNewBlockAt = ( editorState: EditorState, pivotBlockKey: string, type = 'unstyled', data: Record = {} // eslint-disable-line @typescript-eslint/no-explicit-any ): EditorState => { const contentState = editorState.getCurrentContent(); const blockMap = contentState.getBlockMap(); const pivotBlock = blockMap.get(pivotBlockKey); if (!pivotBlock) throw new Error( `The pivot key - ${pivotBlockKey} is not present in blockMap` ); const blocksBefore = blockMap.toSeq().takeUntil((v) => v === pivotBlock); const blocksAfter = blockMap .toSeq() .skipUntil((v) => v === pivotBlock) .rest(); const key = genKey(); const block = new ContentBlock({ key, type, text: '', characterList: Immutable.List(), depth: 0, data: Immutable.Map(data), }); const selectionState = editorState.getSelection(); const nextBlockMap = blocksBefore .concat( [ [pivotBlockKey, pivotBlock], [key, block], ], blocksAfter ) .toOrderedMap(); const nextContentState = contentState.merge({ blockMap: nextBlockMap, selectionBefore: selectionState, selectionAfter: selectionState.merge({ anchorKey: key, anchorOffset: 0, focusKey: key, focusOffset: 0, isBackward: false, }), }) as ContentState; return EditorState.push(editorState, nextContentState, 'split-block'); }; export default addNewBlockAt;