/
RangeUtility.ts
55 lines (46 loc) · 1.38 KB
/
RangeUtility.ts
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
48
49
50
51
52
53
54
55
import INode from '../nodes/node/INode';
import NodeUtility from '../nodes/node/NodeUtility';
type BoundaryPoint = { node: INode; offset: number };
/**
* Range utility.
*
* Based on:
* https://github.com/jsdom/jsdom/blob/master/lib/jsdom/living/range/boundary-point.js.
*/
export default class RangeUtility {
/**
* Compares boundary points.
*
* @see https://dom.spec.whatwg.org/#concept-range-bp-after
* @param pointA Point A.
* @param pointB Point B.
* @returns A number, -1, 0, or 1, indicating whether the corresponding boundary-point of the Range is respectively before, equal to, or after the corresponding boundary-point of sourceRange.
*/
public static compareBoundaryPointsPosition(
pointA: BoundaryPoint,
pointB: BoundaryPoint
): number {
if (pointA.node === pointB.node) {
if (pointA.offset === pointB.offset) {
return 0;
} else if (pointA.offset < pointB.offset) {
return -1;
}
return 1;
}
if (NodeUtility.isFollowing(pointA.node, pointB.node)) {
return this.compareBoundaryPointsPosition(pointB, pointA) === -1 ? 1 : -1;
}
if (NodeUtility.isInclusiveAncestor(pointA.node, pointB.node)) {
let child = pointB.node;
while (child.parentNode !== pointA.node) {
child = child.parentNode;
}
const index = child.parentNode.childNodes.indexOf(child);
if (index < pointA.offset) {
return 1;
}
}
return -1;
}
}