-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransform.ts
76 lines (65 loc) · 1.67 KB
/
transform.ts
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
75
76
import { NodeTypes } from './ast'
import { TO_DISPLAY_STRING } from './runtimeHelpers'
export function transform(root, options = {}) {
const context = createTransformContext(root, options)
traverseNode(root, context)
createRootCodegen(root)
root.helpers = [...context.helpers.keys()] // render函数的参数
}
// 生成根节点的codegen
function createRootCodegen(root) {
const child = root.children[0]
if (child.type === NodeTypes.ELEMENT) {
root.codegenNode = child.codegenNode
} else {
root.codegenNode = root.children[0]
}
}
// 创建transform上下文
function createTransformContext(root, options) {
const context = {
root,
nodeTransforms: options.nodeTransforms || [],
helpers: new Map(),
helper(key) {
context.helpers.set(key, 1)
},
}
return context
}
// 遍历节点
function traverseNode(node, context) {
const nodeTransforms = context.nodeTransforms
const exitFns: any = []
// 执行transform
for (let i = 0; i < nodeTransforms.length; i++) {
const transform = nodeTransforms[i]
const onExit = transform(node, context)
if (onExit) exitFns.push(onExit)
}
switch (node.type) {
case NodeTypes.INTERPOLATION:
context.helper(TO_DISPLAY_STRING)
break
case NodeTypes.ROOT:
case NodeTypes.ELEMENT:
traverseChildren(node, context)
break
default:
break
}
let i = exitFns.length
while(i--){
exitFns[i]()
}
}
// 遍历子节点
function traverseChildren(node: any, context: any) {
const children = node.children
if (children) {
for (let i = 0; i < children.length; i++) {
const node = children[i]
traverseNode(node, context)
}
}
}