-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
hast-processing.js
74 lines (67 loc) · 1.47 KB
/
hast-processing.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
63
64
65
66
67
68
69
70
71
72
73
74
function duplicateNode(node) {
return {
type: node.type,
children: [],
tagName: node.tagName,
value: node.value,
properties: node.properties,
}
}
function getConcatenatedValue(node) {
if (!node) {
return ``
}
if (node.type === `text`) {
return node.value
} else if (node.children && node.children.length) {
return node.children
.map(getConcatenatedValue)
.filter(value => value)
.join(``)
}
return ``
}
function cloneTreeUntil(root, endCondition) {
let clonedRoot
let endConditionMet = false
function preOrderTraversal(node) {
if (endConditionMet || endCondition({ root: clonedRoot, nextNode: node })) {
endConditionMet = true
return
}
const newNode = duplicateNode(node)
if (clonedRoot) {
clonedRoot.children.push(newNode)
} else {
clonedRoot = newNode
}
if (node.children) {
node.children.forEach(child => {
clonedRoot = newNode
preOrderTraversal(child)
})
clonedRoot = newNode
}
}
preOrderTraversal(root)
return clonedRoot
}
function findLastTextNode(node, textNode) {
if (node.type === `text`) {
textNode = node
}
if (node.children) {
node.children.forEach(child => {
const laterTextNode = findLastTextNode(child)
if (laterTextNode !== textNode) {
textNode = laterTextNode
}
})
}
return textNode
}
module.exports = {
getConcatenatedValue,
cloneTreeUntil,
findLastTextNode,
}