/**
 * Adds a sticker to an editor state
 */ import { BlockMapBuilder , CharacterMetadata , ContentBlock , EditorState , genKey , Modifier , } from 'draft-js' ; import { List , Repeat } from 'immutable' ; export default ( editorState , stickerId ) : EditorState => { const currentContentState = editorState . getCurrentContent ( ) ; const currentSelectionState = editorState . getSelection ( ) ; const afterRemovalContentState = Modifier . removeRange ( currentContentState , currentSelectionState , 'backward' ) ; const targetSelection = afterRemovalContentState . getSelectionAfter ( ) ; const blockKeyForTarget = targetSelection . get ( 'focusKey' ) ; const block = currentContentState . getBlockForKey ( blockKeyForTarget ) ; let insertionTargetSelection ; let insertionTargetBlock ; const isEmptyBlock = block . getLength ( ) === 0 && block . getEntityAt ( 0 ) === null ; const selectedFromStart = currentSelectionState . getStartOffset ( ) === 0 ; if ( isEmptyBlock || selectedFromStart ) { insertionTargetSelection = targetSelection ; insertionTargetBlock = afterRemovalContentState ; } else { insertionTargetBlock = Modifier . splitBlock ( afterRemovalContentState , targetSelection ) ; insertionTargetSelection = insertionTargetBlock . getSelectionAfter ( ) ; } const newContentStateAfterSplit = Modifier . setBlockType ( insertionTargetBlock , insertionTargetSelection , 'sticker' ) ; const contentStateWithEntity = newContentStateAfterSplit . createEntity ( 'sticker' , 'IMMUTABLE' , { id : stickerId } ) ; const entityKey = contentStateWithEntity . getLastCreatedEntityKey ( ) ; const charDataOfSticker = CharacterMetadata . create ( { entity : entityKey } ) ; const fragmentArray = [ new ContentBlock ( { key : genKey ( ) , type : 'sticker' , text : ' ' , characterList : List ( Repeat ( charDataOfSticker , 1 ) ) , } ) , new ContentBlock ( { key : genKey ( ) , type : 'unstyled' , text : '' , characterList : List ( ) , } ) , ] ; const fragment = BlockMapBuilder . createFromArray ( fragmentArray ) ; const contentStateWithSticker = Modifier . replaceWithFragment ( newContentStateAfterSplit , insertionTargetSelection , fragment ) ; const newState = EditorState . push ( editorState , contentStateWithSticker , 'insert-fragment' ) ; return EditorState . forceSelection ( newState , contentStateWithSticker . getSelectionAfter ( ) ) ; } ;