UNPKG

2.46 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
13/**
14 * Identify the range to delete from a segmented entity.
15 *
16 * Rules:
17 *
18 * Example: 'John F. Kennedy'
19 *
20 * - Deletion from within any non-whitespace (i.e. ['John', 'F.', 'Kennedy'])
21 * will return the range of that text.
22 *
23 * 'John F. Kennedy' -> 'John F.'
24 * ^
25 *
26 * - Forward deletion of whitespace will remove the following section:
27 *
28 * 'John F. Kennedy' -> 'John Kennedy'
29 * ^
30 *
31 * - Backward deletion of whitespace will remove the previous section:
32 *
33 * 'John F. Kennedy' -> 'F. Kennedy'
34 * ^
35 */
36var DraftEntitySegments = {
37 getRemovalRange: function getRemovalRange(selectionStart, selectionEnd, text, entityStart, direction) {
38 var segments = text.split(' ');
39 segments = segments.map(function (
40 /*string*/
41 segment,
42 /*number*/
43 ii) {
44 if (direction === 'forward') {
45 if (ii > 0) {
46 return ' ' + segment;
47 }
48 } else if (ii < segments.length - 1) {
49 return segment + ' ';
50 }
51
52 return segment;
53 });
54 var segmentStart = entityStart;
55 var segmentEnd;
56 var segment;
57 var removalStart = null;
58 var removalEnd = null;
59
60 for (var jj = 0; jj < segments.length; jj++) {
61 segment = segments[jj];
62 segmentEnd = segmentStart + segment.length; // Our selection overlaps this segment.
63
64 if (selectionStart < segmentEnd && segmentStart < selectionEnd) {
65 if (removalStart !== null) {
66 removalEnd = segmentEnd;
67 } else {
68 removalStart = segmentStart;
69 removalEnd = segmentEnd;
70 }
71 } else if (removalStart !== null) {
72 break;
73 }
74
75 segmentStart = segmentEnd;
76 }
77
78 var entityEnd = entityStart + text.length;
79 var atStart = removalStart === entityStart;
80 var atEnd = removalEnd === entityEnd;
81
82 if (!atStart && atEnd || atStart && !atEnd) {
83 if (direction === 'forward') {
84 if (removalEnd !== entityEnd) {
85 removalEnd++;
86 }
87 } else if (removalStart !== entityStart) {
88 removalStart--;
89 }
90 }
91
92 return {
93 start: removalStart,
94 end: removalEnd
95 };
96 }
97};
98module.exports = DraftEntitySegments;
\No newline at end of file