-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapplyMarkup.js
62 lines (46 loc) · 1.18 KB
/
applyMarkup.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
59
60
61
62
'use strict';
var createInline = require('./inline').createInline
/**
* applyMarkup(elem, markup) applies the given markup to the given
* element.
*
* @param {Element} elem
* @param {Object} markup
*/
function applyMarkup (elem, markup) {
var node = elem.firstChild,
index = 0,
depth = 0,
markupElem,
next
while (node) {
if (node.nodeType === Node.ELEMENT_NODE) {
node = node.firstChild
depth += 1
continue
}
if (index + node.data.length > markup.start) {
if (index < markup.start) {
next = node.splitText(markup.start - index)
index += node.data.length
node = next
}
if (index + node.data.length > markup.end) {
node.splitText(markup.end - index)
}
markupElem = createInline(markup)
node.parentNode.replaceChild(markupElem, node)
markupElem.appendChild(node)
index += node.data.length
node = markupElem
} else index += node.data.length
if (index >= markup.end) break
while (!node.nextSibling) {
if (!depth) break
depth -= 1
node = node.parentNode
}
node = node.nextSibling
}
}
module.exports = applyMarkup