/
transformElement.ts
922 lines (868 loc) 路 26.9 KB
/
transformElement.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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
import { NodeTransform, TransformContext } from '../transform'
import {
NodeTypes,
ElementTypes,
CallExpression,
ObjectExpression,
ElementNode,
DirectiveNode,
ExpressionNode,
ArrayExpression,
createCallExpression,
createArrayExpression,
createObjectProperty,
createSimpleExpression,
createObjectExpression,
Property,
ComponentNode,
VNodeCall,
TemplateTextChildNode,
DirectiveArguments,
createVNodeCall,
ConstantTypes,
JSChildNode,
createFunctionExpression,
createBlockStatement
} from '../ast'
import {
PatchFlags,
PatchFlagNames,
isSymbol,
isOn,
isObject,
isReservedProp,
capitalize,
camelize
} from '@vue/shared'
import { createCompilerError, ErrorCodes } from '../errors'
import {
RESOLVE_DIRECTIVE,
RESOLVE_COMPONENT,
RESOLVE_DYNAMIC_COMPONENT,
MERGE_PROPS,
NORMALIZE_CLASS,
NORMALIZE_STYLE,
NORMALIZE_PROPS,
TO_HANDLERS,
TELEPORT,
KEEP_ALIVE,
SUSPENSE,
UNREF,
GUARD_REACTIVE_PROPS,
IS_REF
} from '../runtimeHelpers'
import {
getInnerRange,
toValidAssetId,
findProp,
isCoreComponent,
isBindKey,
findDir,
isStaticExp
} from '../utils'
import { buildSlots } from './vSlot'
import { getConstantType } from './hoistStatic'
import { BindingTypes } from '../options'
import {
checkCompatEnabled,
CompilerDeprecationTypes,
isCompatEnabled
} from '../compat/compatConfig'
// some directive transforms (e.g. v-model) may return a symbol for runtime
// import, which should be used instead of a resolveDirective call.
const directiveImportMap = new WeakMap<DirectiveNode, symbol>()
// generate a JavaScript AST for this element's codegen
export const transformElement: NodeTransform = (node, context) => {
// perform the work on exit, after all child expressions have been
// processed and merged.
return function postTransformElement() {
node = context.currentNode!
if (
!(
node.type === NodeTypes.ELEMENT &&
(node.tagType === ElementTypes.ELEMENT ||
node.tagType === ElementTypes.COMPONENT)
)
) {
return
}
const { tag, props } = node
const isComponent = node.tagType === ElementTypes.COMPONENT
// The goal of the transform is to create a codegenNode implementing the
// VNodeCall interface.
let vnodeTag = isComponent
? resolveComponentType(node as ComponentNode, context)
: `"${tag}"`
const isDynamicComponent =
isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT
let vnodeProps: VNodeCall['props']
let vnodeChildren: VNodeCall['children']
let vnodePatchFlag: VNodeCall['patchFlag']
let patchFlag: number = 0
let vnodeDynamicProps: VNodeCall['dynamicProps']
let dynamicPropNames: string[] | undefined
let vnodeDirectives: VNodeCall['directives']
let shouldUseBlock =
// dynamic component may resolve to plain elements
isDynamicComponent ||
vnodeTag === TELEPORT ||
vnodeTag === SUSPENSE ||
(!isComponent &&
// <svg> and <foreignObject> must be forced into blocks so that block
// updates inside get proper isSVG flag at runtime. (#639, #643)
// This is technically web-specific, but splitting the logic out of core
// leads to too much unnecessary complexity.
(tag === 'svg' ||
tag === 'foreignObject' ||
// #938: elements with dynamic keys should be forced into blocks
findProp(node, 'key', true)))
// props
if (props.length > 0) {
const propsBuildResult = buildProps(node, context)
vnodeProps = propsBuildResult.props
patchFlag = propsBuildResult.patchFlag
dynamicPropNames = propsBuildResult.dynamicPropNames
const directives = propsBuildResult.directives
vnodeDirectives =
directives && directives.length
? (createArrayExpression(
directives.map(dir => buildDirectiveArgs(dir, context))
) as DirectiveArguments)
: undefined
}
// children
if (node.children.length > 0) {
if (vnodeTag === KEEP_ALIVE) {
// Although a built-in component, we compile KeepAlive with raw children
// instead of slot functions so that it can be used inside Transition
// or other Transition-wrapping HOCs.
// To ensure correct updates with block optimizations, we need to:
// 1. Force keep-alive into a block. This avoids its children being
// collected by a parent block.
shouldUseBlock = true
// 2. Force keep-alive to always be updated, since it uses raw children.
patchFlag |= PatchFlags.DYNAMIC_SLOTS
if (__DEV__ && node.children.length > 1) {
context.onError(
createCompilerError(ErrorCodes.X_KEEP_ALIVE_INVALID_CHILDREN, {
start: node.children[0].loc.start,
end: node.children[node.children.length - 1].loc.end,
source: ''
})
)
}
}
const shouldBuildAsSlots =
isComponent &&
// Teleport is not a real component and has dedicated runtime handling
vnodeTag !== TELEPORT &&
// explained above.
vnodeTag !== KEEP_ALIVE
if (shouldBuildAsSlots) {
const { slots, hasDynamicSlots } = buildSlots(node, context)
vnodeChildren = slots
if (hasDynamicSlots) {
patchFlag |= PatchFlags.DYNAMIC_SLOTS
}
} else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
const child = node.children[0]
const type = child.type
// check for dynamic text children
const hasDynamicTextChild =
type === NodeTypes.INTERPOLATION ||
type === NodeTypes.COMPOUND_EXPRESSION
if (
hasDynamicTextChild &&
getConstantType(child, context) === ConstantTypes.NOT_CONSTANT
) {
patchFlag |= PatchFlags.TEXT
}
// pass directly if the only child is a text node
// (plain / interpolation / expression)
if (hasDynamicTextChild || type === NodeTypes.TEXT) {
vnodeChildren = child as TemplateTextChildNode
} else {
vnodeChildren = node.children
}
} else {
vnodeChildren = node.children
}
}
// patchFlag & dynamicPropNames
if (patchFlag !== 0) {
if (__DEV__) {
if (patchFlag < 0) {
// special flags (negative and mutually exclusive)
vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`
} else {
// bitwise flags
const flagNames = Object.keys(PatchFlagNames)
.map(Number)
.filter(n => n > 0 && patchFlag & n)
.map(n => PatchFlagNames[n])
.join(`, `)
vnodePatchFlag = patchFlag + ` /* ${flagNames} */`
}
} else {
vnodePatchFlag = String(patchFlag)
}
if (dynamicPropNames && dynamicPropNames.length) {
vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames)
}
}
node.codegenNode = createVNodeCall(
context,
vnodeTag,
vnodeProps,
vnodeChildren,
vnodePatchFlag,
vnodeDynamicProps,
vnodeDirectives,
!!shouldUseBlock,
false /* disableTracking */,
isComponent,
node.loc
)
}
}
export function resolveComponentType(
node: ComponentNode,
context: TransformContext,
ssr = false
) {
let { tag } = node
// 1. dynamic component
const isExplicitDynamic = isComponentTag(tag)
const isProp = findProp(node, 'is')
if (isProp) {
if (
isExplicitDynamic ||
(__COMPAT__ &&
isCompatEnabled(
CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT,
context
))
) {
const exp =
isProp.type === NodeTypes.ATTRIBUTE
? isProp.value && createSimpleExpression(isProp.value.content, true)
: isProp.exp
if (exp) {
return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
exp
])
}
} else if (
isProp.type === NodeTypes.ATTRIBUTE &&
isProp.value!.content.startsWith('vue:')
) {
// <button is="vue:xxx">
// if not <component>, only is value that starts with "vue:" will be
// treated as component by the parse phase and reach here, unless it's
// compat mode where all is values are considered components
tag = isProp.value!.content.slice(4)
}
}
// 1.5 v-is (TODO: Deprecate)
const isDir = !isExplicitDynamic && findDir(node, 'is')
if (isDir && isDir.exp) {
return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
isDir.exp
])
}
// 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag)
if (builtIn) {
// built-ins are simply fallthroughs / have special handling during ssr
// so we don't need to import their runtime equivalents
if (!ssr) context.helper(builtIn)
return builtIn
}
// 3. user component (from setup bindings)
// this is skipped in browser build since browser builds do not perform
// binding analysis.
if (!__BROWSER__) {
const fromSetup = resolveSetupReference(tag, context)
if (fromSetup) {
return fromSetup
}
const dotIndex = tag.indexOf('.')
if (dotIndex > 0) {
const ns = resolveSetupReference(tag.slice(0, dotIndex), context)
if (ns) {
return ns + tag.slice(dotIndex)
}
}
}
// 4. Self referencing component (inferred from filename)
if (
!__BROWSER__ &&
context.selfName &&
capitalize(camelize(tag)) === context.selfName
) {
context.helper(RESOLVE_COMPONENT)
// codegen.ts has special check for __self postfix when generating
// component imports, which will pass additional `maybeSelfReference` flag
// to `resolveComponent`.
context.components.add(tag + `__self`)
return toValidAssetId(tag, `component`)
}
// 5. user component (resolve)
context.helper(RESOLVE_COMPONENT)
context.components.add(tag)
return toValidAssetId(tag, `component`)
}
function resolveSetupReference(name: string, context: TransformContext) {
const bindings = context.bindingMetadata
if (!bindings || bindings.__isScriptSetup === false) {
return
}
const camelName = camelize(name)
const PascalName = capitalize(camelName)
const checkType = (type: BindingTypes) => {
if (bindings[name] === type) {
return name
}
if (bindings[camelName] === type) {
return camelName
}
if (bindings[PascalName] === type) {
return PascalName
}
}
const fromConst = checkType(BindingTypes.SETUP_CONST)
if (fromConst) {
return context.inline
? // in inline mode, const setup bindings (e.g. imports) can be used as-is
fromConst
: `$setup[${JSON.stringify(fromConst)}]`
}
const fromMaybeRef =
checkType(BindingTypes.SETUP_LET) ||
checkType(BindingTypes.SETUP_REF) ||
checkType(BindingTypes.SETUP_MAYBE_REF)
if (fromMaybeRef) {
return context.inline
? // setup scope bindings that may be refs need to be unrefed
`${context.helperString(UNREF)}(${fromMaybeRef})`
: `$setup[${JSON.stringify(fromMaybeRef)}]`
}
}
export type PropsExpression = ObjectExpression | CallExpression | ExpressionNode
export function buildProps(
node: ElementNode,
context: TransformContext,
props: ElementNode['props'] = node.props,
ssr = false
): {
props: PropsExpression | undefined
directives: DirectiveNode[]
patchFlag: number
dynamicPropNames: string[]
} {
const { tag, loc: elementLoc } = node
const isComponent = node.tagType === ElementTypes.COMPONENT
let properties: ObjectExpression['properties'] = []
const mergeArgs: PropsExpression[] = []
const runtimeDirectives: DirectiveNode[] = []
// patchFlag analysis
let patchFlag = 0
let hasRef = false
let hasClassBinding = false
let hasStyleBinding = false
let hasHydrationEventBinding = false
let hasDynamicKeys = false
let hasVnodeHook = false
const dynamicPropNames: string[] = []
const analyzePatchFlag = ({ key, value }: Property) => {
if (isStaticExp(key)) {
const name = key.content
const isEventHandler = isOn(name)
if (
!isComponent &&
isEventHandler &&
// omit the flag for click handlers because hydration gives click
// dedicated fast path.
name.toLowerCase() !== 'onclick' &&
// omit v-model handlers
name !== 'onUpdate:modelValue' &&
// omit onVnodeXXX hooks
!isReservedProp(name)
) {
hasHydrationEventBinding = true
}
if (isEventHandler && isReservedProp(name)) {
hasVnodeHook = true
}
if (
value.type === NodeTypes.JS_CACHE_EXPRESSION ||
((value.type === NodeTypes.SIMPLE_EXPRESSION ||
value.type === NodeTypes.COMPOUND_EXPRESSION) &&
getConstantType(value, context) > 0)
) {
// skip if the prop is a cached handler or has constant value
return
}
if (name === 'ref') {
hasRef = true
} else if (name === 'class') {
hasClassBinding = true
} else if (name === 'style') {
hasStyleBinding = true
} else if (name !== 'key' && !dynamicPropNames.includes(name)) {
dynamicPropNames.push(name)
}
// treat the dynamic class and style binding of the component as dynamic props
if (
isComponent &&
(name === 'class' || name === 'style') &&
!dynamicPropNames.includes(name)
) {
dynamicPropNames.push(name)
}
} else {
hasDynamicKeys = true
}
}
for (let i = 0; i < props.length; i++) {
// static attribute
const prop = props[i]
if (prop.type === NodeTypes.ATTRIBUTE) {
const { loc, name, value } = prop
let valueNode = createSimpleExpression(
value ? value.content : '',
true,
value ? value.loc : loc
) as JSChildNode
if (name === 'ref') {
hasRef = true
// in inline mode there is no setupState object, so we can't use string
// keys to set the ref. Instead, we need to transform it to pass the
// acrtual ref instead.
if (!__BROWSER__ && context.inline && value?.content) {
valueNode = createFunctionExpression(['_value', '_refs'])
valueNode.body = createBlockStatement(
processInlineRef(context, value.content)
)
}
}
// skip is on <component>, or is="vue:xxx"
if (
name === 'is' &&
(isComponentTag(tag) ||
(value && value.content.startsWith('vue:')) ||
(__COMPAT__ &&
isCompatEnabled(
CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT,
context
)))
) {
continue
}
properties.push(
createObjectProperty(
createSimpleExpression(
name,
true,
getInnerRange(loc, 0, name.length)
),
valueNode
)
)
} else {
// directives
const { name, arg, exp, loc } = prop
const isVBind = name === 'bind'
const isVOn = name === 'on'
// skip v-slot - it is handled by its dedicated transform.
if (name === 'slot') {
if (!isComponent) {
context.onError(
createCompilerError(ErrorCodes.X_V_SLOT_MISPLACED, loc)
)
}
continue
}
// skip v-once/v-memo - they are handled by dedicated transforms.
if (name === 'once' || name === 'memo') {
continue
}
// skip v-is and :is on <component>
if (
name === 'is' ||
(isVBind &&
isBindKey(arg, 'is') &&
(isComponentTag(tag) ||
(__COMPAT__ &&
isCompatEnabled(
CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT,
context
))))
) {
continue
}
// skip v-on in SSR compilation
if (isVOn && ssr) {
continue
}
// special case for v-bind and v-on with no argument
if (!arg && (isVBind || isVOn)) {
hasDynamicKeys = true
if (exp) {
if (properties.length) {
mergeArgs.push(
createObjectExpression(dedupeProperties(properties), elementLoc)
)
properties = []
}
if (isVBind) {
if (__COMPAT__) {
// 2.x v-bind object order compat
if (__DEV__) {
const hasOverridableKeys = mergeArgs.some(arg => {
if (arg.type === NodeTypes.JS_OBJECT_EXPRESSION) {
return arg.properties.some(({ key }) => {
if (
key.type !== NodeTypes.SIMPLE_EXPRESSION ||
!key.isStatic
) {
return true
}
return (
key.content !== 'class' &&
key.content !== 'style' &&
!isOn(key.content)
)
})
} else {
// dynamic expression
return true
}
})
if (hasOverridableKeys) {
checkCompatEnabled(
CompilerDeprecationTypes.COMPILER_V_BIND_OBJECT_ORDER,
context,
loc
)
}
}
if (
isCompatEnabled(
CompilerDeprecationTypes.COMPILER_V_BIND_OBJECT_ORDER,
context
)
) {
mergeArgs.unshift(exp)
continue
}
}
mergeArgs.push(exp)
} else {
// v-on="obj" -> toHandlers(obj)
mergeArgs.push({
type: NodeTypes.JS_CALL_EXPRESSION,
loc,
callee: context.helper(TO_HANDLERS),
arguments: [exp]
})
}
} else {
context.onError(
createCompilerError(
isVBind
? ErrorCodes.X_V_BIND_NO_EXPRESSION
: ErrorCodes.X_V_ON_NO_EXPRESSION,
loc
)
)
}
continue
}
const directiveTransform = context.directiveTransforms[name]
if (directiveTransform) {
// has built-in directive transform.
const { props, needRuntime } = directiveTransform(prop, node, context)
!ssr && props.forEach(analyzePatchFlag)
properties.push(...props)
if (needRuntime) {
runtimeDirectives.push(prop)
if (isSymbol(needRuntime)) {
directiveImportMap.set(prop, needRuntime)
}
}
} else {
// no built-in transform, this is a user custom directive.
runtimeDirectives.push(prop)
}
}
if (
__COMPAT__ &&
prop.type === NodeTypes.ATTRIBUTE &&
prop.name === 'ref' &&
context.scopes.vFor > 0 &&
checkCompatEnabled(
CompilerDeprecationTypes.COMPILER_V_FOR_REF,
context,
prop.loc
)
) {
properties.push(
createObjectProperty(
createSimpleExpression('refInFor', true),
createSimpleExpression('true', false)
)
)
}
}
let propsExpression: PropsExpression | undefined = undefined
// has v-bind="object" or v-on="object", wrap with mergeProps
if (mergeArgs.length) {
if (properties.length) {
mergeArgs.push(
createObjectExpression(dedupeProperties(properties), elementLoc)
)
}
if (mergeArgs.length > 1) {
propsExpression = createCallExpression(
context.helper(MERGE_PROPS),
mergeArgs,
elementLoc
)
} else {
// single v-bind with nothing else - no need for a mergeProps call
propsExpression = mergeArgs[0]
}
} else if (properties.length) {
propsExpression = createObjectExpression(
dedupeProperties(properties),
elementLoc
)
}
// patchFlag analysis
if (hasDynamicKeys) {
patchFlag |= PatchFlags.FULL_PROPS
} else {
if (hasClassBinding && !isComponent) {
patchFlag |= PatchFlags.CLASS
}
if (hasStyleBinding && !isComponent) {
patchFlag |= PatchFlags.STYLE
}
if (dynamicPropNames.length) {
patchFlag |= PatchFlags.PROPS
}
if (hasHydrationEventBinding) {
patchFlag |= PatchFlags.HYDRATE_EVENTS
}
}
if (
(patchFlag === 0 || patchFlag === PatchFlags.HYDRATE_EVENTS) &&
(hasRef || hasVnodeHook || runtimeDirectives.length > 0)
) {
patchFlag |= PatchFlags.NEED_PATCH
}
// pre-normalize props, SSR is skipped for now
if (!context.inSSR && propsExpression) {
switch (propsExpression.type) {
case NodeTypes.JS_OBJECT_EXPRESSION:
// means that there is no v-bind,
// but still need to deal with dynamic key binding
let classKeyIndex = -1
let styleKeyIndex = -1
let hasDynamicKey = false
for (let i = 0; i < propsExpression.properties.length; i++) {
const key = propsExpression.properties[i].key
if (isStaticExp(key)) {
if (key.content === 'class') {
classKeyIndex = i
} else if (key.content === 'style') {
styleKeyIndex = i
}
} else if (!key.isHandlerKey) {
hasDynamicKey = true
}
}
const classProp = propsExpression.properties[classKeyIndex]
const styleProp = propsExpression.properties[styleKeyIndex]
// no dynamic key
if (!hasDynamicKey) {
if (classProp && !isStaticExp(classProp.value)) {
classProp.value = createCallExpression(
context.helper(NORMALIZE_CLASS),
[classProp.value]
)
}
if (
styleProp &&
!isStaticExp(styleProp.value) &&
// the static style is compiled into an object,
// so use `hasStyleBinding` to ensure that it is a dynamic style binding
(hasStyleBinding ||
// v-bind:style and style both exist,
// v-bind:style with static literal object
styleProp.value.type === NodeTypes.JS_ARRAY_EXPRESSION)
) {
styleProp.value = createCallExpression(
context.helper(NORMALIZE_STYLE),
[styleProp.value]
)
}
} else {
// dynamic key binding, wrap with `normalizeProps`
propsExpression = createCallExpression(
context.helper(NORMALIZE_PROPS),
[propsExpression]
)
}
break
case NodeTypes.JS_CALL_EXPRESSION:
// mergeProps call, do nothing
break
default:
// single v-bind
propsExpression = createCallExpression(
context.helper(NORMALIZE_PROPS),
[
createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
propsExpression
])
]
)
break
}
}
return {
props: propsExpression,
directives: runtimeDirectives,
patchFlag,
dynamicPropNames
}
}
// Dedupe props in an object literal.
// Literal duplicated attributes would have been warned during the parse phase,
// however, it's possible to encounter duplicated `onXXX` handlers with different
// modifiers. We also need to merge static and dynamic class / style attributes.
// - onXXX handlers / style: merge into array
// - class: merge into single expression with concatenation
function dedupeProperties(properties: Property[]): Property[] {
const knownProps: Map<string, Property> = new Map()
const deduped: Property[] = []
for (let i = 0; i < properties.length; i++) {
const prop = properties[i]
// dynamic keys are always allowed
if (prop.key.type === NodeTypes.COMPOUND_EXPRESSION || !prop.key.isStatic) {
deduped.push(prop)
continue
}
const name = prop.key.content
const existing = knownProps.get(name)
if (existing) {
if (name === 'style' || name === 'class' || name.startsWith('on')) {
mergeAsArray(existing, prop)
}
// unexpected duplicate, should have emitted error during parse
} else {
knownProps.set(name, prop)
deduped.push(prop)
}
}
return deduped
}
function mergeAsArray(existing: Property, incoming: Property) {
if (existing.value.type === NodeTypes.JS_ARRAY_EXPRESSION) {
existing.value.elements.push(incoming.value)
} else {
existing.value = createArrayExpression(
[existing.value, incoming.value],
existing.loc
)
}
}
function buildDirectiveArgs(
dir: DirectiveNode,
context: TransformContext
): ArrayExpression {
const dirArgs: ArrayExpression['elements'] = []
const runtime = directiveImportMap.get(dir)
if (runtime) {
// built-in directive with runtime
dirArgs.push(context.helperString(runtime))
} else {
// user directive.
// see if we have directives exposed via <script setup>
const fromSetup =
!__BROWSER__ && resolveSetupReference('v-' + dir.name, context)
if (fromSetup) {
dirArgs.push(fromSetup)
} else {
// inject statement for resolving directive
context.helper(RESOLVE_DIRECTIVE)
context.directives.add(dir.name)
dirArgs.push(toValidAssetId(dir.name, `directive`))
}
}
const { loc } = dir
if (dir.exp) dirArgs.push(dir.exp)
if (dir.arg) {
if (!dir.exp) {
dirArgs.push(`void 0`)
}
dirArgs.push(dir.arg)
}
if (Object.keys(dir.modifiers).length) {
if (!dir.arg) {
if (!dir.exp) {
dirArgs.push(`void 0`)
}
dirArgs.push(`void 0`)
}
const trueExpression = createSimpleExpression(`true`, false, loc)
dirArgs.push(
createObjectExpression(
dir.modifiers.map(modifier =>
createObjectProperty(modifier, trueExpression)
),
loc
)
)
}
return createArrayExpression(dirArgs, dir.loc)
}
function stringifyDynamicPropNames(props: string[]): string {
let propsNamesString = `[`
for (let i = 0, l = props.length; i < l; i++) {
propsNamesString += JSON.stringify(props[i])
if (i < l - 1) propsNamesString += ', '
}
return propsNamesString + `]`
}
function isComponentTag(tag: string) {
return tag[0].toLowerCase() + tag.slice(1) === 'component'
}
function processInlineRef(
context: TransformContext,
raw: string
): JSChildNode[] {
const body = [createSimpleExpression(`_refs['${raw}'] = _value`)]
const { bindingMetadata, helperString } = context
const type = bindingMetadata[raw]
if (type === BindingTypes.SETUP_REF) {
body.push(createSimpleExpression(`${raw}.value = _value`))
} else if (type === BindingTypes.SETUP_MAYBE_REF) {
body.push(
createSimpleExpression(
`${helperString(IS_REF)}(${raw}) && (${raw}.value = _value)`
)
)
} else if (type === BindingTypes.SETUP_LET) {
body.push(
createSimpleExpression(
`${helperString(
IS_REF
)}(${raw}) ? ${raw}.value = _value : ${raw} = _value`
)
)
}
return body
}