function getEntityKeyForSelection()

in src/model/entity/getEntityKeyForSelection.js [24:53]


function getEntityKeyForSelection(
  contentState: ContentState,
  targetSelection: SelectionState,
): ?string {
  let entityKey;

  if (targetSelection.isCollapsed()) {
    const key = targetSelection.getAnchorKey();
    const offset = targetSelection.getAnchorOffset();
    if (offset > 0) {
      entityKey = contentState.getBlockForKey(key).getEntityAt(offset - 1);
      if (entityKey !== contentState.getBlockForKey(key).getEntityAt(offset)) {
        return null;
      }
      return filterKey(contentState, entityKey);
    }
    return null;
  }

  const startKey = targetSelection.getStartKey();
  const startOffset = targetSelection.getStartOffset();
  const startBlock = contentState.getBlockForKey(startKey);

  entityKey =
    startOffset === startBlock.getLength()
      ? null
      : startBlock.getEntityAt(startOffset);

  return filterKey(contentState, entityKey);
}