-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
49 lines (37 loc) · 1 KB
/
index.js
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
/**
* Module exports.
*/
module.exports = RangeAtIndex;
/**
* Returns a Range instance selecting text within HTML Element `el`,
* at the given `start` and `end` offsets.
*
* @param {HTMLElement} el - DOM element to select text within
* @public
*/
function RangeAtIndex (el, index, offset, range) {
var doc = el.ownerDocument;
if (!range) range = doc.createRange();
let iterator = doc.createNodeIterator(el, NodeFilter.SHOW_TEXT, null, false);
let start = {};
let end = {};
let node, val, len;
while (node = iterator.nextNode()) {
val = node.nodeValue;
len = val.length;
if (!start.node && len > index) {
start.node = node;
start.offset = index;
}
if (!end.node && len >= offset) {
end.node = node;
end.offset = offset;
}
index -= len;
offset -= len;
}
// update the range with the start and end offsets
if (start.node) range.setStart(start.node, start.offset);
if (end.node) range.setEnd(end.node, end.offset);
return range;
}