-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
Copy pathtransformId.ts
80 lines (76 loc) · 2.26 KB
/
transformId.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
import {
type Expression,
callExpression,
identifier,
stringLiteral,
} from '@babel/types'
import {
type AttributeNode,
type DirectiveNode,
NodeTypes,
createSimpleExpression,
} from '@vue/compiler-core'
import { createBindDirectiveNode } from '@dcloudio/uni-cli-shared'
import { parseExpr } from '../ast'
import { genBabelExpr } from '../codegen'
import type { TransformContext } from '../transform'
import { GEN_UNI_ELEMENT_ID } from '../runtimeHelpers'
import { rewriteExpression } from './utils'
export function isIdBinding({ arg, exp }: DirectiveNode) {
return arg && arg.type === NodeTypes.SIMPLE_EXPRESSION && arg.content === 'id'
}
export function findStaticIdIndex(props: (AttributeNode | DirectiveNode)[]) {
return props.findIndex((prop) => prop.name === 'id')
}
export function rewriteId(
index: number,
idBindingProp: DirectiveNode,
props: (AttributeNode | DirectiveNode)[],
virtualHost: boolean,
context: TransformContext,
isX = false
) {
let expr = idBindingProp.exp
? parseExpr(idBindingProp.exp, context)
: undefined
let idBindingExpr: Expression
const staticIdPropIndex = findStaticIdIndex(props)
if (staticIdPropIndex > -1) {
idBindingExpr = stringLiteral(
(props[staticIdPropIndex] as AttributeNode).value!.content
)
} else if (expr) {
idBindingExpr =
isX || virtualHost
? expr
: identifier(rewriteExpression(idBindingProp.exp!, context).content)
} else {
idBindingExpr = stringLiteral('')
}
if (virtualHost) {
idBindingExpr = callExpression(
identifier(context.helperString(GEN_UNI_ELEMENT_ID)),
[identifier('_ctx'), idBindingExpr]
)
if (!isX) {
// 非uni-app-x id绑定表达式直接生成在了模板内
idBindingExpr = identifier(
rewriteExpression(
createSimpleExpression(genBabelExpr(idBindingExpr)),
context
).content
)
}
}
idBindingProp.exp = createSimpleExpression(genBabelExpr(idBindingExpr))
}
export function createVirtualHostId(
props: (AttributeNode | DirectiveNode)[],
context: TransformContext,
isX: boolean = false
) {
const idBindingProp = createBindDirectiveNode('id', '')
delete idBindingProp.exp
rewriteId(0, idBindingProp, props, true, context, isX)
return idBindingProp
}