# All files / composer/utils/draft-js-custom-plugins/prepopulated-autocomplete-hashtag/modifiers addPrepopulatedHashtag.js

9.09% Statements 1/11
100% Branches 0/0
0% Functions 0/1
9.09% Lines 1/11

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55

    7x

     /**
     * Annotate #hashtags with entities. Only executed once when the editor loads,
     * in order to decorate hashtags that could be present in the prepopulated text.
     * Hashtags written by users after the editor loads are handled by
     * draft-js-mention-plugin.
     *
     * This process is completely seamless for users: it doesn't impact the undo
     * stack, nor does it change the editor's SelectionState.
     */
    import { EditorState, Modifier, SelectionState } from '@bufferapp/draft-js';

    const addPrepopulatedHashtag = (editorState, contentBlock, indices) => {
      const blockKey = contentBlock.getKey();
      let contentState = editorState.getCurrentContent();
      const originalSelectionBefore = contentState.getSelectionBefore();
      const originalSelection = editorState.getSelection();

      contentState = contentState.createEntity('PREPOPULATED_HASHTAG', 'IMMUTABLE');
      const entityKey = contentState.getLastCreatedEntityKey();

      const targetRange = new SelectionState({
        anchorKey: blockKey,
        anchorOffset: indices[0],
        focusKey: blockKey,
        focusOffset: indices[1],
      });

      let newContentState = Modifier.applyEntity(contentState, targetRange, entityKey);

      /**
       * Set selectionBefore/After back to what they were before they were changed
       * by Modifier.applyEntity for proper undo/redo behavior.
       */
      newContentState = newContentState.merge({
        selectionBefore: originalSelectionBefore,
        selectionAfter: originalSelection,
      });

      /**
       * Instead of using EditorState.push() which normally should be used for pushing
       * new actions to the editor, we update the editor's state directly in order
       * to keep the undo stack as is. The original SelectionState is also preserved
       * for the process to be completely seamless to users, and lastChangeType is
       * udpated to 'apply-entity' so that future keystrokes/changes are considered
       * boundary states for undo/redo.
       */
      return EditorState.set(editorState, {
        currentContent: newContentState,
        lastChangeType: 'apply-hashtag',
        selection: originalSelection,
      });
    };

    export default addPrepopulatedHashtag;