-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathgetPosFromRange2.js
More file actions
46 lines (39 loc) · 1.04 KB
/
getPosFromRange2.js
File metadata and controls
46 lines (39 loc) · 1.04 KB
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
// Gets the cursor from a range. Code based on innerText.
function getPosFromRange2(rootNode, node, offset) {
const pos = {
x: 0, // The character index (of the current paragraph)
y: 0, // The paragraph index
pos: 0, // The cursor position
}
// NOTE: Gecko/Firefox can select the end element node
if (node.nodeType === Node.ELEMENT_NODE && offset && !(offset < node.childNodes.length)) {
// return getPosFromRange2(rootNode, null, 0)
node = null
offset = 0
}
let walker = document.createTreeWalker(rootNode, NodeFilter.SHOW_ALL, null, false);
while(walker.nextNode()){
var cur = walker.currentNode;
if(cur.nodeType === Node.ELEMENT_NODE &&
(cur.hasAttribute("data-node") || cur.hasAttribute("data-compound-node"))
) {
pos.x = 0;
if(pos.pos !== 0){
pos.y += 1;
pos.pos += 1;
}
}
if(cur === node) {
pos.x += offset;
pos.pos += offset;
return pos;
}
if(cur.nodeValue){
const len = cur.nodeValue.length;
pos.x += len;
pos.pos += len;
}
}
return pos
}
export default getPosFromRange2