# All files / composer/utils/draft-js-custom-plugins/autocomplete/utils getFacebookAutocompleteEntities.js

5.26% Statements 1/19
0% Branches 0/4
0% Functions 0/4
5.56% Lines 1/18

    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

    7x

     import { getUnicodeAwareLength } from '../../../../utils/StringUtils';

    /**
     * Retrieve Facebook Autocomplete entities from the editor's contents.
     * The returned indices are unicode-aware.
     */
    const getFacebookAutocompleteEntities = function(editorState) {
      const entities = [];
      let entitiesBlockOffset = 0;

      const contentState = editorState.getCurrentContent();

      const filterFacebookAutocompleteEntities = (characterMetadata) => {
        const entityKey = characterMetadata.getEntity();
        if (entityKey === null) return false;

        const entityType = contentState.getEntity(entityKey).getType();
        return entityType === 'mention' || entityType === 'IMPORTED_MENTION';
      };

      contentState.getBlockMap().forEach((contentBlock) => {
        contentBlock.findEntityRanges(filterFacebookAutocompleteEntities, (start, end) => {
          const entityKey = contentBlock.getEntityAt(start);
          const mention = contentState.getEntity(entityKey).getData().mention;

          const leftHandText = contentBlock.getText().slice(0, start);
          const entitiesInlineOffset = getUnicodeAwareLength(leftHandText) - leftHandText.length;

          entities.push({
            indices: [
              entitiesBlockOffset + entitiesInlineOffset + start,
              entitiesBlockOffset + entitiesInlineOffset + end,
            ],
            content: mention.get('id'),
            text: mention.get('name'),
            url: mention.get('url'),
          });
        });

        entitiesBlockOffset += (getUnicodeAwareLength(contentBlock.getText()) + 1);
      });

      return entities;
    };

    export default getFacebookAutocompleteEntities;