0

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.

Ashhm
  • 15
  • 3
  • that's depends on how you render your atomic block. please show more codes – Jiang YD Aug 29 '18 at 12:45
  • render of atomic block is handled via draft-js-video-plugin. I found `AtomicBlockUtils.insertAtomicBlock` modify my contentState in next way: right before calling method, contentState had one block on index 0 - `{key: "dkdl8", text: "https://....", type: "unstyled"}`, after calling - 3 blocks: 0 - empty block `{key: "eih8o", text: "", type: "unstyled"}` 1 - atomic block `{key: "4694p", text: " ", type: "atomic"}` 2 - original block `{key: "dkdl8", text: "https://...", type: "unstyled"}`. So problem is `AtomicBlockUtils.insertAtomicBlock` changing order of blocks. – Ashhm Aug 29 '18 at 13:35
  • so just make your own video-plugin and change the block order. – Jiang YD Aug 30 '18 at 02:48

1 Answers1

1

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).

Ashhm
  • 15
  • 3