Search code examples
draftjsdraft-js-plugins

How to change order of ContentBlock render in draftjs?


Got an question about draft js.

How i can change an order of ContentBlocks? Im trying to add an external link to content and render video inside of Editor.

Creating current state:

createEditorState(source) {
        if (!source) {
          return EditorState.createEmpty();
        }

        const contentState = stateFromMarkdown(source);
        const editorState = EditorState.createWithContent(contentState);

        return addVideoContent(source, editorState)
 }

Add block with video content (supported to be rendered via video-plugin):

addVideoContent(source, editorState) {
    function buildNewEditorState(state, src) {
      const currentContentState = state.getCurrentContent();
      const contentStateWithEntity = currentContentState
        .createEntity(VIDEO_PLUGIN_TYPE, 'IMMUTABLE', { src });
      const entityKey = contentStateWithEntity.getLastCreatedEntityKey();

      return AtomicBlockUtils.insertAtomicBlock(state, entityKey, ' ');
    }

    //defining video urls
    ...

    return videoUrls.reduce(buildNewEditorState, editorState);
}

Problem is in render order: 1. Video block; 2. Link block.

How to change this order to: 1. Link block; 2. Video block.


Solution

  • OK. issue was in selectionState.

    When initial state initialized, selectionState (position of anchor and focus) is equals to first character of first block. So AtomicBlockUtils.insertAtomicBlock method will split blocks between selectionState and insert 'atomic'.

    Decision: EditorsState.moveSelectionToEnd(editorState).