Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
81159 views
1
/**
2
* Copyright 2013-2014, Facebook, Inc.
3
* All rights reserved.
4
*
5
* This source code is licensed under the BSD-style license found in the
6
* LICENSE file in the root directory of this source tree. An additional grant
7
* of patent rights can be found in the PATENTS file in the same directory.
8
*
9
* @providesModule getNodeForCharacterOffset
10
*/
11
12
"use strict";
13
14
/**
15
* Given any node return the first leaf node without children.
16
*
17
* @param {DOMElement|DOMTextNode} node
18
* @return {DOMElement|DOMTextNode}
19
*/
20
function getLeafNode(node) {
21
while (node && node.firstChild) {
22
node = node.firstChild;
23
}
24
return node;
25
}
26
27
/**
28
* Get the next sibling within a container. This will walk up the
29
* DOM if a node's siblings have been exhausted.
30
*
31
* @param {DOMElement|DOMTextNode} node
32
* @return {?DOMElement|DOMTextNode}
33
*/
34
function getSiblingNode(node) {
35
while (node) {
36
if (node.nextSibling) {
37
return node.nextSibling;
38
}
39
node = node.parentNode;
40
}
41
}
42
43
/**
44
* Get object describing the nodes which contain characters at offset.
45
*
46
* @param {DOMElement|DOMTextNode} root
47
* @param {number} offset
48
* @return {?object}
49
*/
50
function getNodeForCharacterOffset(root, offset) {
51
var node = getLeafNode(root);
52
var nodeStart = 0;
53
var nodeEnd = 0;
54
55
while (node) {
56
if (node.nodeType == 3) {
57
nodeEnd = nodeStart + node.textContent.length;
58
59
if (nodeStart <= offset && nodeEnd >= offset) {
60
return {
61
node: node,
62
offset: offset - nodeStart
63
};
64
}
65
66
nodeStart = nodeEnd;
67
}
68
69
node = getLeafNode(getSiblingNode(node));
70
}
71
}
72
73
module.exports = getNodeForCharacterOffset;
74
75