Skip to content

Commit dbdcf6e

Browse files
Fixed processing of the range totally outside the container
1 parent 8ad2afe commit dbdcf6e

File tree

1 file changed

+22
-4
lines changed

1 file changed

+22
-4
lines changed

packages/text-annotator/src/utils/trimRangeToContainer.ts

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,31 @@ export const trimRangeToContainer = (
44
): Range => {
55
const trimmedRange = range.cloneRange();
66

7-
// If the start is outside the container - set it to the start of the container
8-
if (!container.contains(trimmedRange.startContainer)) {
7+
const containsStart = container.contains(trimmedRange.startContainer);
8+
const containsEnd = container.contains(trimmedRange.endContainer);
9+
10+
/**
11+
* If both the start and the end are outside the container -
12+
* collapse such a range as irrelevant
13+
*/
14+
if (!containsStart && !containsEnd) {
15+
trimmedRange.collapse();
16+
return trimmedRange;
17+
}
18+
19+
/**
20+
* If the range starts outside the container -
21+
* trim it to the start of the container
22+
*/
23+
if (!containsStart) {
924
trimmedRange.setStart(container, 0);
1025
}
1126

12-
// If the end is outside the container - set it to the end of the container
13-
if (!container.contains(trimmedRange.endContainer)) {
27+
/**
28+
* If the range ends outside the container -
29+
* trim it to the end of the container
30+
*/
31+
if (!containsEnd) {
1432
trimmedRange.setEnd(container, container.childNodes.length);
1533
}
1634

0 commit comments

Comments
 (0)