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
//! Patch flag calculation and naming functions.
use super::helpers::camelize;
use crate::ast::*;
use crate::options::{BindingMetadata, BindingType};
use oxc_ast::ast as oxc_ast_types;
use oxc_parser::Parser;
use oxc_span::SourceType;
use vize_carton::String;
use vize_carton::ToCompactString;
use vize_carton::is_builtin_directive;
/// Check if an interpolation references only constant bindings (LiteralConst or SetupConst)
/// These bindings never change at runtime, so no TEXT patch flag is needed.
fn is_constant_interpolation(
expr: &ExpressionNode<'_>,
bindings: Option<&BindingMetadata>,
) -> bool {
let bindings = match bindings {
Some(b) => b,
None => return false, // No binding info, assume dynamic
};
match expr {
ExpressionNode::Simple(simple) => {
// Check if the expression is a simple identifier that's a constant
// Both LiteralConst (e.g., const x = 'hello') and SetupConst (e.g., class Foo {})
// are constant at runtime and don't need TEXT patch flag
let name = simple.content.as_str();
matches!(
bindings.bindings.get(name),
Some(BindingType::LiteralConst | BindingType::SetupConst)
)
}
ExpressionNode::Compound(_) => false, // Compound expressions are dynamic
}
}
/// Check if an event handler references a constant binding (SetupConst or LiteralConst)
fn is_const_handler(expr: &ExpressionNode<'_>, bindings: Option<&BindingMetadata>) -> bool {
let bindings = match bindings {
Some(b) => b,
None => return false, // No binding info, assume dynamic
};
match expr {
ExpressionNode::Simple(simple) => {
// Check if the expression is a simple identifier that's a constant
let name = simple.content.as_str();
matches!(
bindings.bindings.get(name),
Some(BindingType::SetupConst | BindingType::LiteralConst)
)
}
ExpressionNode::Compound(_) => false, // Compound expressions are dynamic
}
}
/// Check if a directive's bound expression is a static literal (no runtime identifiers).
fn is_static_bound_expression(dir: &DirectiveNode<'_>) -> bool {
let Some(ExpressionNode::Simple(simple)) = &dir.exp else {
return false;
};
if simple.is_static {
return true;
}
let content = simple.content.trim();
matches!(content, "true" | "false" | "null")
|| is_string_literal(content)
|| content.parse::<f64>().is_ok()
|| is_static_object_or_array_literal(content)
|| (content.starts_with('`') && content.ends_with('`') && !content.contains("${"))
}
fn is_string_literal(content: &str) -> bool {
(content.starts_with('\'') && content.ends_with('\''))
|| (content.starts_with('"') && content.ends_with('"'))
}
fn is_static_object_or_array_literal(content: &str) -> bool {
let mut wrapped = String::with_capacity(content.len() + 2);
wrapped.push('(');
wrapped.push_str(content);
wrapped.push(')');
let allocator = oxc_allocator::Allocator::default();
let parser = Parser::new(
&allocator,
&wrapped,
SourceType::default().with_module(true),
);
let Ok(expr) = parser.parse_expression() else {
return false;
};
is_static_oxc_expression(&expr)
}
fn is_static_oxc_expression(expr: &oxc_ast_types::Expression<'_>) -> bool {
match expr {
oxc_ast_types::Expression::StringLiteral(_)
| oxc_ast_types::Expression::NumericLiteral(_)
| oxc_ast_types::Expression::BooleanLiteral(_)
| oxc_ast_types::Expression::NullLiteral(_)
| oxc_ast_types::Expression::BigIntLiteral(_)
| oxc_ast_types::Expression::RegExpLiteral(_) => true,
oxc_ast_types::Expression::TemplateLiteral(template) => template.expressions.is_empty(),
oxc_ast_types::Expression::UnaryExpression(unary) => {
is_static_oxc_expression(&unary.argument)
}
oxc_ast_types::Expression::ParenthesizedExpression(paren) => {
is_static_oxc_expression(&paren.expression)
}
oxc_ast_types::Expression::CallExpression(call)
if matches!(
&call.callee,
oxc_ast_types::Expression::Identifier(ident)
if matches!(ident.name.as_str(), "_normalizeClass" | "_normalizeStyle")
) =>
{
call.arguments.iter().all(|arg| match arg {
oxc_ast_types::Argument::SpreadElement(_) => false,
_ => arg.as_expression().is_some_and(is_static_oxc_expression),
})
}
oxc_ast_types::Expression::ObjectExpression(obj) => {
obj.properties.iter().all(|prop| match prop {
oxc_ast_types::ObjectPropertyKind::ObjectProperty(prop) => {
is_static_oxc_expression(&prop.value)
}
oxc_ast_types::ObjectPropertyKind::SpreadProperty(_) => false,
})
}
oxc_ast_types::Expression::ArrayExpression(arr) => {
arr.elements.iter().all(|elem| match elem {
oxc_ast_types::ArrayExpressionElement::SpreadElement(_) => false,
oxc_ast_types::ArrayExpressionElement::Elision(_) => true,
_ => elem.as_expression().is_some_and(is_static_oxc_expression),
})
}
_ => false,
}
}
/// Calculate patch flag and dynamic props for an element.
/// `skip_is_prop`: when true, skip `:is` binding (used for `<component :is="...">`)
pub fn calculate_element_patch_info(
el: &ElementNode<'_>,
bindings: Option<&BindingMetadata>,
cache_handlers: bool,
) -> (Option<i32>, Option<Vec<String>>) {
calculate_element_patch_info_inner(el, bindings, cache_handlers, false)
}
/// Same as `calculate_element_patch_info` but allows skipping the `is` prop.
pub fn calculate_element_patch_info_skip_is(
el: &ElementNode<'_>,
bindings: Option<&BindingMetadata>,
cache_handlers: bool,
) -> (Option<i32>, Option<Vec<String>>) {
calculate_element_patch_info_inner(el, bindings, cache_handlers, true)
}
fn calculate_element_patch_info_inner(
el: &ElementNode<'_>,
bindings: Option<&BindingMetadata>,
cache_handlers: bool,
skip_is: bool,
) -> (Option<i32>, Option<Vec<String>>) {
let mut flag: i32 = 0;
// Pre-allocate with small capacity - most elements have few dynamic props
let mut dynamic_props: Vec<String> = Vec::with_capacity(4);
let mut has_vshow = false;
let mut has_vmodel = false;
let mut has_custom_directive = false;
let mut has_ref = false;
for prop in el.props.iter() {
// Check for ref attribute (static)
if let PropNode::Attribute(attr) = prop
&& attr.name == "ref"
{
has_ref = true;
}
if let PropNode::Directive(dir) = prop {
match dir.name.as_str() {
"bind" => {
// Skip `:is` binding for dynamic components
if skip_is
&& let Some(ExpressionNode::Simple(arg)) = &dir.arg
&& arg.content == "is"
{
continue;
}
// Check for modifiers
let has_camel = dir.modifiers.iter().any(|m| m.content == "camel");
let has_prop = dir.modifiers.iter().any(|m| m.content == "prop");
let has_attr = dir.modifiers.iter().any(|m| m.content == "attr");
if let Some(arg) = &dir.arg {
if let ExpressionNode::Simple(exp) = arg {
if !exp.is_static {
// Dynamic key - FULL_PROPS
flag |= 16;
// .prop modifier requires NEED_HYDRATION even with a
// dynamic argument (e.g. :[key].prop).
if has_prop {
flag |= 32; // NEED_HYDRATION
}
} else {
let key = exp.content.as_str();
let bound_is_static = is_static_bound_expression(dir);
match key {
"class" => {
// Component class is a fallthrough prop, not an element-class
// patch target. Vue tracks it through dynamicProps.
if !bound_is_static {
if el.tag_type == ElementType::Component {
flag |= 8; // PROPS
dynamic_props.push("class".to_compact_string());
} else {
flag |= 2; // CLASS
}
}
}
"style" => {
// Component style is a fallthrough prop, not an element-style
// patch target. Vue tracks it through dynamicProps.
if !bound_is_static {
if el.tag_type == ElementType::Component {
flag |= 8; // PROPS
dynamic_props.push("style".to_compact_string());
} else {
flag |= 4; // STYLE
}
}
}
"key" => {}
"ref" => {
// Dynamic ref binding needs NEED_PATCH
flag |= 512; // NEED_PATCH
}
_ => {
// Skip modelModifiers and *Modifiers props (they are static)
if !key.ends_with("Modifiers") && !bound_is_static {
flag |= 8; // PROPS
// Transform key based on modifiers
let prop_name = if has_camel {
camelize(key).to_compact_string()
} else if has_prop {
let mut name = String::with_capacity(1 + key.len());
name.push('.');
name.push_str(key);
name
} else if has_attr {
let mut name = String::with_capacity(1 + key.len());
name.push('^');
name.push_str(key);
name
} else {
key.to_compact_string()
};
dynamic_props.push(prop_name);
// .prop modifier requires NEED_HYDRATION
if has_prop {
flag |= 32; // NEED_HYDRATION
}
}
}
}
}
} else {
// Compound expression as key - FULL_PROPS
flag |= 16;
}
} else {
// No arg (v-bind without argument) - FULL_PROPS
flag |= 16;
}
}
"on" => {
// Event handlers are considered dynamic props
if dir.arg.is_none() {
// v-on without argument (object spread) - FULL_PROPS
flag |= 16;
} else if let Some(arg) = &dir.arg {
if let ExpressionNode::Simple(exp) = arg {
if !exp.is_static {
// Dynamic event name
flag |= 16;
} else {
// Check for mouse button modifiers that transform the event name
let base_event = exp.content.as_str();
let has_right_modifier =
dir.modifiers.iter().any(|m| m.content == "right");
let has_middle_modifier =
dir.modifiers.iter().any(|m| m.content == "middle");
// Transform event name for special mouse button modifiers
let actual_event = if base_event == "click" && has_right_modifier {
"contextmenu"
} else if base_event == "click" && has_middle_modifier {
"mouseup"
} else {
base_event
};
// Build the dynamic-prop event name using the same
// casing rules as v-on prop codegen so the
// dynamicProps array matches the generated keys.
let on_plain_element =
el.tag_type == ElementType::Element && dir.raw_name.is_some();
let event_name = super::props::von_event_key_for(
base_event,
on_plain_element,
dir.modifiers.iter().map(|m| m.content.as_str()),
);
// Check if the handler references a constant binding
// If so, we don't need PROPS flag since the handler won't change
let handler_is_const = if let Some(handler_exp) = &dir.exp {
is_const_handler(handler_exp, bindings)
} else {
false
};
// Check if the handler will be cached.
// Callers pass the effective cache setting for the current
// template scope, so scoped handlers inside v-for / slots
// are treated as dynamic here.
let handler_is_cached = cache_handlers && dir.exp.is_some();
// Only add PROPS flag if handler is neither const nor cached
if !handler_is_const && !handler_is_cached {
flag |= 8; // PROPS
dynamic_props.push(event_name.clone());
}
// Check if this is a custom event (non-standard DOM event)
// Custom events, events with option modifiers, and events with key modifiers need NEED_HYDRATION
let has_option_modifier = dir.modifiers.iter().any(|m| {
let n = m.content.as_str();
n == "capture" || n == "once" || n == "passive"
});
// Check for key modifiers (will use withKeys)
let has_key_modifier = dir.modifiers.iter().any(|m| {
let n = m.content.as_str();
matches!(n, "enter" | "tab" | "delete" | "esc" | "space" | "up" | "down")
|| n.chars().all(|c| c.is_ascii_digit()) // numeric keycodes
|| !matches!(n, "capture" | "once" | "passive" | "stop" | "prevent" | "self" | "ctrl" | "shift" | "alt" | "meta" | "left" | "middle" | "right" | "exact")
});
// Events that don't need NEED_HYDRATION:
// - Basic click/dblclick without special modifiers
// - the v-model `onUpdate:modelValue` handler (Vue
// excludes this exact reserved key only)
// - Component events (non-DOM element events)
let is_vmodel_update = event_name == "onUpdate:modelValue";
// Vue's hydration fast-path covers `onclick` only
// (not dblclick or other mouse events).
let is_simple_click = actual_event == "click"
&& !has_option_modifier
&& !has_key_modifier
&& !has_right_modifier
&& !has_middle_modifier;
let is_component_event = el.tag_type == ElementType::Component;
// onVnodeXXX lifecycle hooks are reserved props and
// never trigger hydration event binding.
let is_vnode_hook = event_name.starts_with("onVnode");
// NEED_HYDRATION is needed for non-click/dblclick events
// This tells Vue to properly hydrate event listeners during SSR
// Note: NEED_HYDRATION is added regardless of caching status
if !is_simple_click
&& !is_vmodel_update
&& !is_component_event
&& !is_vnode_hook
{
flag |= 32; // NEED_HYDRATION
}
}
} else {
flag |= 16;
}
}
}
"model" => {
// v-model on native elements needs NEED_PATCH
has_vmodel = true;
// v-model with dynamic argument → FULL_PROPS
if let Some(arg) = &dir.arg {
match arg {
ExpressionNode::Simple(exp) if !exp.is_static => {
flag |= 16; // FULL_PROPS
}
ExpressionNode::Compound(_) => {
flag |= 16; // FULL_PROPS
}
_ => {}
}
}
}
"show" => {
// v-show requires NEED_PATCH, but only if no other flags are set
has_vshow = true;
}
"html" => {
// v-html sets innerHTML - dynamic prop
flag |= 8; // PROPS
dynamic_props.push("innerHTML".to_compact_string());
}
"text" => {
// v-text sets textContent - dynamic prop
flag |= 8; // PROPS
dynamic_props.push("textContent".to_compact_string());
}
_ => {
// Custom directive - requires NEED_PATCH
if !is_builtin_directive(&dir.name) {
has_custom_directive = true;
}
}
}
}
}
// Check for dynamic text children
// TEXT flag should be set when children contain interpolations and only consist of text/interpolation
// But skip if all interpolations reference only LiteralConst bindings (compile-time constants)
let has_interpolation = el
.children
.iter()
.any(|child| matches!(child, TemplateChildNode::Interpolation(_)));
let all_text_or_interp = el.children.iter().all(|child| {
matches!(
child,
TemplateChildNode::Text(_) | TemplateChildNode::Interpolation(_)
)
});
if has_interpolation && all_text_or_interp {
// Check if all interpolations reference only constant bindings
let all_constant = el.children.iter().all(|child| {
if let TemplateChildNode::Interpolation(interp) = child {
is_constant_interpolation(&interp.content, bindings)
} else {
true // Text nodes are always "constant"
}
});
if !all_constant {
flag |= 1; // TEXT
}
}
// Add NEED_PATCH for v-show, custom directives, or ref only if no other dynamic bindings exist
// Custom directives only need NEED_PATCH when the element has no children
// (children already cause the element to be tracked for patching by the runtime)
// This must come after TEXT flag check so we don't add NEED_PATCH when TEXT is about to be set
let custom_dir_needs_patch = has_custom_directive && el.children.is_empty();
if (has_vshow || has_vmodel || custom_dir_needs_patch || has_ref) && flag == 0 {
flag |= 512; // NEED_PATCH
}
// When FULL_PROPS is set, per-prop flags are redundant (FULL_PROPS covers all prop changes)
if flag & 16 != 0 {
flag &= !(8 | 2 | 4); // Remove PROPS, CLASS, STYLE
}
let patch_flag = if flag > 0 { Some(flag) } else { None };
// Deduplicate dynamic props (e.g., multiple handlers for same event)
dynamic_props.dedup();
let dynamic_props_result = if !dynamic_props.is_empty() {
Some(dynamic_props)
} else {
None
};
(patch_flag, dynamic_props_result)
}
/// Get patch flag name for comment
pub fn patch_flag_name(flag: i32) -> String {
// Single flag matches
match flag {
1 => return "TEXT".to_compact_string(),
2 => return "CLASS".to_compact_string(),
4 => return "STYLE".to_compact_string(),
8 => return "PROPS".to_compact_string(),
16 => return "FULL_PROPS".to_compact_string(),
32 => return "NEED_HYDRATION".to_compact_string(),
64 => return "STABLE_FRAGMENT".to_compact_string(),
128 => return "KEYED_FRAGMENT".to_compact_string(),
256 => return "UNKEYED_FRAGMENT".to_compact_string(),
512 => return "NEED_PATCH".to_compact_string(),
1024 => return "DYNAMIC_SLOTS".to_compact_string(),
_ => {}
}
// Multiple flags - build combined string
let mut names = Vec::new();
if flag & 1 != 0 {
names.push("TEXT");
}
if flag & 2 != 0 {
names.push("CLASS");
}
if flag & 4 != 0 {
names.push("STYLE");
}
if flag & 8 != 0 {
names.push("PROPS");
}
if flag & 16 != 0 {
names.push("FULL_PROPS");
}
if flag & 32 != 0 {
names.push("NEED_HYDRATION");
}
if flag & 64 != 0 {
names.push("STABLE_FRAGMENT");
}
if flag & 128 != 0 {
names.push("KEYED_FRAGMENT");
}
if flag & 256 != 0 {
names.push("UNKEYED_FRAGMENT");
}
if flag & 512 != 0 {
names.push("NEED_PATCH");
}
if flag & 1024 != 0 {
names.push("DYNAMIC_SLOTS");
}
if flag & 2048 != 0 {
names.push("DEV_ROOT_FRAGMENT");
}
if names.is_empty() {
"UNKNOWN".to_compact_string()
} else {
names.join(", ").into()
}
}