UNPKG

1.78 kBJavaScriptView Raw
1/**
2 * Copyright (c) Facebook, Inc. and its affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 * @format
8 *
9 * @emails oncall+draft_js
10 */
11'use strict';
12
13var _require = require("./draftKeyUtils"),
14 notEmptyKey = _require.notEmptyKey;
15/**
16 * Return the entity key that should be used when inserting text for the
17 * specified target selection, only if the entity is `MUTABLE`. `IMMUTABLE`
18 * and `SEGMENTED` entities should not be used for insertion behavior.
19 */
20
21
22function getEntityKeyForSelection(contentState, targetSelection) {
23 var entityKey;
24
25 if (targetSelection.isCollapsed()) {
26 var key = targetSelection.getAnchorKey();
27 var offset = targetSelection.getAnchorOffset();
28
29 if (offset > 0) {
30 entityKey = contentState.getBlockForKey(key).getEntityAt(offset - 1);
31
32 if (entityKey !== contentState.getBlockForKey(key).getEntityAt(offset)) {
33 return null;
34 }
35
36 return filterKey(contentState.getEntityMap(), entityKey);
37 }
38
39 return null;
40 }
41
42 var startKey = targetSelection.getStartKey();
43 var startOffset = targetSelection.getStartOffset();
44 var startBlock = contentState.getBlockForKey(startKey);
45 entityKey = startOffset === startBlock.getLength() ? null : startBlock.getEntityAt(startOffset);
46 return filterKey(contentState.getEntityMap(), entityKey);
47}
48/**
49 * Determine whether an entity key corresponds to a `MUTABLE` entity. If so,
50 * return it. If not, return null.
51 */
52
53
54function filterKey(entityMap, entityKey) {
55 if (notEmptyKey(entityKey)) {
56 var entity = entityMap.__get(entityKey);
57
58 return entity.getMutability() === 'MUTABLE' ? entityKey : null;
59 }
60
61 return null;
62}
63
64module.exports = getEntityKeyForSelection;
\No newline at end of file