forked from ianstormtaylor/slate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind-dom-point.js
50 lines (39 loc) · 1.16 KB
/
find-dom-point.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
import findDOMNode from './find-dom-node'
/**
* Find a native DOM selection point from a Slate `point`.
*
* @param {Point} point
* @param {Window} win (optional)
* @return {Object|Null}
*/
function findDOMPoint(point, win = window) {
const el = findDOMNode(point.key, win)
let start = 0
// For each leaf, we need to isolate its content, which means filtering to its
// direct text and zero-width spans. (We have to filter out any other siblings
// that may have been rendered alongside them.)
const texts = Array.from(
el.querySelectorAll('[data-slate-content], [data-slate-zero-width]')
)
for (const text of texts) {
const node = text.childNodes[0]
const domLength = node.textContent.length
let slateLength = domLength
if (text.hasAttribute('data-slate-length')) {
slateLength = parseInt(text.getAttribute('data-slate-length'), 10)
}
const end = start + slateLength
if (point.offset <= end) {
const offset = Math.min(domLength, Math.max(0, point.offset - start))
return { node, offset }
}
start = end
}
return null
}
/**
* Export.
*
* @type {Function}
*/
export default findDOMPoint