Skip to content

Commit 57a494a

Browse files
committed
update:Change screen state to "Generate render function based on AST"
1 parent 5c088f5 commit 57a494a

File tree

2 files changed

+30
-19
lines changed

2 files changed

+30
-19
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,33 @@
1+
import { ElementNode, NodeTypes, TemplateChildNode, TextNode } from './ast'
2+
13
export const generate = ({
2-
tag,
3-
props,
4-
textContent,
4+
children,
55
}: {
6-
tag: string
7-
props: Record<string, string>
8-
textContent: string
6+
children: TemplateChildNode[]
97
}): string => {
10-
return `return () => {
8+
return `return function render() {
119
const { h } = ChibiVue;
12-
return h("${tag}", { ${Object.entries(props)
13-
.map(([k, v]) => `${k}: "${v}"`)
14-
.join(', ')} }, ["${textContent}"]);
10+
return ${genNode(children[0])};
1511
}`
1612
}
13+
14+
const genNode = (node: TemplateChildNode): string => {
15+
switch (node.type) {
16+
case NodeTypes.ELEMENT:
17+
return genElement(node)
18+
case NodeTypes.TEXT:
19+
return genText(node)
20+
default:
21+
return ''
22+
}
23+
}
24+
25+
const genElement = (el: ElementNode): string => {
26+
return `h("${el.tag}", {${el.props
27+
.map(({ name, value }) => `${name}: "${value?.content}"`)
28+
.join(', ')}}, [${el.children.map(it => genNode(it)).join(', ')}])`
29+
}
30+
31+
const genText = (text: TextNode): string => {
32+
return `\`${text.content}\``
33+
}
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,8 @@
1+
import { generate } from './codegen'
12
import { baseParse } from './parse'
23

34
export function baseCompile(template: string) {
45
const parseResult = baseParse(template.trim())
5-
console.log(
6-
'🚀 ~ file: compile.ts:6 ~ baseCompile ~ parseResult:',
7-
parseResult,
8-
)
9-
10-
// TODO: codegen
11-
// const code = generate(parseResult);
12-
// return code;
13-
return ''
6+
const code = generate(parseResult)
7+
return code
148
}

0 commit comments

Comments
 (0)