-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.js
58 lines (41 loc) · 1.33 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
50
51
52
53
54
55
56
57
58
import seek from 'dom-seek'
import rangeToString from './range-to-string'
const SHOW_TEXT = 4
export function fromRange(root, range) {
if (root === undefined) {
throw new Error('missing required parameter "root"')
}
if (range === undefined) {
throw new Error('missing required parameter "range"')
}
let document = root.ownerDocument
let prefix = document.createRange()
let startNode = range.startContainer
let startOffset = range.startOffset
prefix.setStart(root, 0)
prefix.setEnd(startNode, startOffset)
let start = rangeToString(prefix).length
let end = start + rangeToString(range).length
return {
start: start,
end: end,
}
}
export function toRange(root, selector = {}) {
if (root === undefined) {
throw new Error('missing required parameter "root"')
}
const document = root.ownerDocument
const range = document.createRange()
const iter = document.createNodeIterator(root, SHOW_TEXT)
const start = selector.start || 0
const end = selector.end || start
const startOffset = start - seek(iter, start);
const startNode = iter.referenceNode;
const remainder = end - start + startOffset;
const endOffset = remainder - seek(iter, remainder);
const endNode = iter.referenceNode;
range.setStart(startNode, startOffset)
range.setEnd(endNode, endOffset)
return range
}