-
Notifications
You must be signed in to change notification settings - Fork 20
/
anode-compiler.ts
319 lines (279 loc) · 12.8 KB
/
anode-compiler.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
/**
* 把 ANode 编译成 SSR 代码块
*
* 每个组件的 template 对应于一个根 ANode。从它出发递归地编译整个 template。
* 这里要做的就是区分 ANode 类型,做不同的编译。
*/
import assert from 'assert'
import { camelCase } from 'lodash'
import { ANode, AIfNode, AForNode, ASlotNode, ATemplateNode, AFragmentNode, ATextNode } from 'san'
import { ComponentInfo } from '../models/component-info'
import { ElementCompiler } from './element-compiler'
import { getANodePropByName } from '../ast/san-ast-util'
import * as TypeGuards from '../ast/san-ast-type-guards'
import { IDGenerator } from '../utils/id-generator'
import { JSONStringify, RegexpReplace, Statement, SlotRendererDefinition, ElseIf, Else, MapAssign, Foreach, If, MapLiteral, ComponentRendererReference, FunctionCall, SlotRenderCall, Expression, GetRootCtxCall, ComponentReferenceLiteral, ComponentClassReference } from '../ast/renderer-ast-dfn'
import { CTX_DATA, createHTMLExpressionAppend, createHTMLLiteralAppend, L, I, ASSIGN, STATEMENT, UNARY, DEF, BINARY, RETURN } from '../ast/renderer-ast-util'
import { sanExpr, OutputType } from './san-expr-compiler'
import type { RenderOptions } from './renderer-options'
/**
* ANode 编译
*
* 负责单个 ComponentClass 的编译,每个 ANodeCompiler 对应于一个 ComponentInfo。
*/
export class ANodeCompiler<T extends 'none' | 'typed'> {
private elementCompiler: ElementCompiler
private inScript = false
/**
* @param componentInfo 要被编译的节点所在组件的信息
* @param ssrOnly san-ssr 当做模板引擎来使用(产出 HTML 更简单,但无法反解)
* @param id 抗冲突变量名产生器
*/
constructor (
private componentInfo: ComponentInfo,
private ssrOnly: boolean,
private id: IDGenerator,
private useProvidedComponentClass: RenderOptions['useProvidedComponentClass'] = false
) {
this.elementCompiler = new ElementCompiler(this, this.id)
}
compile (aNode: ANode, isRootElement: boolean): Generator<Statement> {
if (TypeGuards.isATextNode(aNode)) return this.compileText(aNode)
if (TypeGuards.isAIfNode(aNode)) return this.compileIf(aNode)
if (TypeGuards.isAForNode(aNode)) return this.compileFor(aNode)
if (TypeGuards.isASlotNode(aNode)) return this.compileSlot(aNode)
if (TypeGuards.isATemplateNode(aNode)) return this.compileTemplate(aNode)
if (TypeGuards.isAFragmentNode(aNode)) return this.compileFragment(aNode)
const childComponentReference = this.generateRef(aNode)
if (childComponentReference) {
return this.compileComponent(aNode, childComponentReference, isRootElement)
}
return this.compileElement(aNode, isRootElement)
}
private generateRef (aNode: ANode) {
if (aNode.directives.is) {
const refs = BINARY(I('ctx'), '.', I('refs'))
return BINARY(refs, '[]', sanExpr(aNode.directives.is.value))
}
if (this.componentInfo.childComponents.has(aNode.tagName)) {
return new ComponentReferenceLiteral(this.componentInfo.childComponents.get(aNode.tagName)!)
}
}
private * compileText (aNode: ATextNode): Generator<Statement> {
const shouldEmitComment = (TypeGuards.isExprTextNode(aNode.textExpr) || TypeGuards.isExprInterpNode(aNode.textExpr)) &&
aNode.textExpr.original && !this.ssrOnly && !this.inScript
const outputType = this.inScript ? OutputType.HTML : OutputType.ESCAPE_HTML
if (shouldEmitComment) yield createHTMLLiteralAppend('<!--s-text-->')
yield createHTMLExpressionAppend(sanExpr(aNode.textExpr, outputType))
if (shouldEmitComment) yield createHTMLLiteralAppend('<!--/s-text-->')
}
private * compileTemplate (aNode: ATemplateNode) {
// if、for 等区块 wrap,只渲染内容。
// 注意:<template> 为组件根节点时,tagName=null, isATemplateNode=false
yield * this.elementCompiler.inner(aNode)
}
private * compileFragment (aNode: AFragmentNode) {
if (TypeGuards.isATextNode(aNode.children[0]) && !this.ssrOnly && !this.inScript) {
yield createHTMLLiteralAppend('<!--s-frag-->')
}
yield * this.elementCompiler.inner(aNode)
if (TypeGuards.isATextNode(aNode.children[aNode.children.length - 1]) && !this.ssrOnly && !this.inScript) {
yield createHTMLLiteralAppend('<!--/s-frag-->')
}
}
private * compileIf (aNode: AIfNode): Generator<Statement> {
const ifDirective = aNode.directives.if
const aNodeWithoutIf = Object.assign({}, aNode)
// 防止重新进入 compileIf:删掉 if 指令,再递归进入当前 aNode
// @ts-ignore
delete aNodeWithoutIf.directives.if
yield new If(sanExpr(ifDirective.value), this.compile(aNodeWithoutIf, false))
for (const elseANode of aNode.elses || []) {
const elifDirective = elseANode.directives.elif
const body = this.compile(elseANode, false)
yield elifDirective ? new ElseIf(sanExpr(elifDirective.value), body) : new Else(body)
}
}
private * compileFor (aNode: AForNode): Generator<Statement> {
const { id } = this
const forElementANode = {
children: aNode.children,
props: aNode.props,
events: aNode.events,
tagName: aNode.tagName,
directives: { ...aNode.directives }
}
// 防止重新进入 compileFor
// @ts-ignore
delete forElementANode.directives.for
const { item, index, value } = aNode.directives.for
const key = I(id.next('key'))
const val = I(id.next('val'))
const list = id.next('list')
yield DEF(list, sanExpr(value))
yield new Foreach(key, val, I(list), [
...index ? [ASSIGN(BINARY(CTX_DATA, '[]', L(index)), key)] : [],
ASSIGN(BINARY(CTX_DATA, '[]', L(item!)), val),
...this.compile(forElementANode, false)
])
}
private * compileSlot (aNode: ASlotNode): Generator<Statement> {
const { id } = this
assert(!this.inScript, '<slot> is not allowed inside <script>')
const defaultRender = I(id.next('defaultRender'))
yield DEF(defaultRender.name, this.compileSlotRenderer(aNode.children))
const slotData = I(id.next('slotData'))
yield DEF(slotData.name, new MapLiteral([]))
if (aNode.directives.bind) {
yield STATEMENT(new MapAssign(slotData, [sanExpr(aNode.directives.bind.value)]))
}
const props = aNode.vars || []
if (props.length) {
yield STATEMENT(new MapAssign(
slotData,
[new MapLiteral(props.map(prop => [L(prop.name), sanExpr(prop.expr)]))]
))
}
const slotName = I(id.next('slotName'))
const render = I(id.next('render'))
const nameProp = getANodePropByName(aNode, 'name')
yield DEF(slotName.name, nameProp ? sanExpr(nameProp.expr) : L(''))
yield (DEF(render.name, BINARY(
BINARY(BINARY(I('ctx'), '.', I('slots')), '[]', slotName),
'||',
defaultRender
)))
yield createHTMLExpressionAppend(new SlotRenderCall(render, [I('parentCtx'), slotData]))
}
private * compileElement (aNode: ANode, isRootElement: boolean): Generator<Statement> {
yield * this.elementCompiler.tagStart(aNode)
if (aNode.tagName === 'script') this.inScript = true
if (isRootElement && !this.ssrOnly && !this.inScript) {
yield new If(UNARY('!', I('noDataOutput')), this.createDataComment())
}
yield * this.elementCompiler.inner(aNode)
this.inScript = false
yield * this.elementCompiler.tagEnd(aNode)
}
private createDataComment () {
const dataExpr = BINARY(new GetRootCtxCall([I('ctx')]), '.', I('data'))
return [
createHTMLLiteralAppend('<!--s-data:'),
createHTMLExpressionAppend(new RegexpReplace(new JSONStringify(dataExpr), '(?<=-)-', L('\\-'))),
createHTMLLiteralAppend('-->')
]
}
private * compileComponent (aNode: ANode, ref: Expression, isRootElement: boolean) {
assert(!this.inScript, 'component reference is not allowed inside <script>')
// slot
const defaultSlotContents: ANode[] = []
const namedSlotContents = new Map()
for (const child of aNode.children!) { // nodes without children (like pATextNode) has been taken over by other methods
const slotBind = !child.textExpr && getANodePropByName(child, 'slot')
if (slotBind) {
const slotName = slotBind.expr.value
if (!namedSlotContents.has(slotName)) {
namedSlotContents.set(slotName, { children: [], prop: slotBind })
}
namedSlotContents.get(slotName).children.push(child)
} else {
defaultSlotContents.push(child)
}
}
const childSlots = I(this.id.next('childSlots'))
yield DEF(childSlots.name, new MapLiteral([]))
if (defaultSlotContents.length) {
yield ASSIGN(
BINARY(childSlots, '[]', L('')),
this.compileSlotRenderer(defaultSlotContents)
)
}
for (const sourceSlotCode of namedSlotContents.values()) {
yield ASSIGN(
BINARY(childSlots, '[]', sanExpr(sourceSlotCode.prop.expr)),
this.compileSlotRenderer(sourceSlotCode.children)
)
}
// data output
const ndo = isRootElement ? I('noDataOutput') : L(true)
// child component class
let ChildComponentClassName = ''
if (this.useProvidedComponentClass) {
ChildComponentClassName = this.id.next('ChildComponentClass')
yield DEF(ChildComponentClassName, new ComponentClassReference(ref, L(aNode.tagName)))
}
// get and call renderer
const mapItems = [
[I('noDataOutput'), ndo],
[I('parentCtx'), I('parentCtx')],
[I('tagName'), L(aNode.tagName)],
[I('slots'), childSlots]
] as ConstructorParameters<typeof MapLiteral>[0]
if (this.useProvidedComponentClass) {
assert(ChildComponentClassName !== '')
mapItems.push([I('ComponentClass'), I(ChildComponentClassName)])
}
const args = [this.childRenderData(aNode), new MapLiteral(mapItems)]
const childRenderCall = new FunctionCall(
new ComponentRendererReference(ref, L(aNode.tagName)),
args
)
yield createHTMLExpressionAppend(childRenderCall)
}
private compileSlotRenderer (content: ANode[]) {
const args = [DEF('parentCtx'), DEF('data')]
const body: Statement[] = []
if (content.length) {
const shouldEmitComment = emitComment(content)
body.push(DEF('html', L('')))
if (shouldEmitComment) {
body.push(createHTMLLiteralAppend('<!--s-slot-->'))
}
const compData = this.id.next('compData')
body.push(DEF(compData, CTX_DATA))
body.push(STATEMENT(new MapAssign(CTX_DATA, [I('data')])))
for (const child of content) body.push(...this.compile(child, false))
if (shouldEmitComment) {
body.push(createHTMLLiteralAppend('<!--/s-slot-->'))
}
body.push(ASSIGN(CTX_DATA, I(compData)))
body.push(RETURN(I('html')))
} else {
body.push(RETURN(L('')))
}
return new SlotRendererDefinition('', args, body)
// 第一个或最后一个,不为空的节点为 text node
function emitComment (content: ANode[]) {
let i = 0
while (i < content.length) {
const c = content[i]
if (!TypeGuards.isATextNode(c)) {
break
}
if (!c.textExpr.value || c.textExpr.value.trim() !== '') {
return true
}
i++
}
let j = content.length - 1
while (j > i) {
const c = content[j]
if (!TypeGuards.isATextNode(c)) {
break
}
if (!c.textExpr.value || c.textExpr.value.trim() !== '') {
return true
}
j--
}
return false
}
}
private childRenderData (aNode: ANode) {
const propData = new MapLiteral(
aNode.props.map(prop => [L(camelCase(prop.name)), sanExpr(prop.expr)])
)
const bindDirective = aNode.directives.bind
return bindDirective ? new MapAssign(sanExpr(bindDirective.value), [propData]) : propData
}
}