vize_atelier_core 0.92.0

Atelier Core - The core workshop for Vize Vue template parsing and transforms
Documentation
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
//! Patch flag calculation and naming functions.

use super::helpers::{camelize, is_constant_simple_expression};
use crate::ast::*;
use crate::options::{BindingMetadata, BindingType};
use vize_carton::is_builtin_directive;
use vize_carton::String;
use vize_carton::ToCompactString;

/// 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).
/// Returns true for object literals, array literals, string literals, numbers
/// that don't reference any runtime variables.
fn is_static_bound_expression(dir: &DirectiveNode<'_>, bindings: Option<&BindingMetadata>) -> bool {
    match &dir.exp {
        Some(ExpressionNode::Simple(simple)) => is_constant_simple_expression(simple, bindings),
        _ => 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 {
            if 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 {
                        if let Some(ExpressionNode::Simple(arg)) = &dir.arg {
                            if 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;
                            } else {
                                let key = exp.content.as_str();
                                match key {
                                    "class" => {
                                        // Only set CLASS flag if the bound expression is dynamic
                                        if !is_static_bound_expression(dir, bindings) {
                                            flag |= 2; // CLASS
                                        }
                                    }
                                    "style" => {
                                        // Only set STYLE flag if the bound expression is dynamic
                                        if !is_static_bound_expression(dir, bindings) {
                                            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") {
                                            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 event name
                                let mut event_name = String::with_capacity(2 + actual_event.len());
                                event_name.push_str("on");
                                // Capitalize first letter inline
                                let mut chars = actual_event.chars();
                                if let Some(c) = chars.next() {
                                    for uc in c.to_uppercase() {
                                        event_name.push(uc);
                                    }
                                    event_name.push_str(chars.as_str());
                                }

                                // Check for event option modifiers that affect the event name
                                for modifier in dir.modifiers.iter() {
                                    let mod_name = modifier.content.as_str();
                                    if mod_name == "capture"
                                        || mod_name == "once"
                                        || mod_name == "passive"
                                    {
                                        let mut cap_mod = String::default();
                                        let mut chars = mod_name.chars();
                                        if let Some(c) = chars.next() {
                                            for uc in c.to_uppercase() {
                                                cap_mod.push(uc);
                                            }
                                            cap_mod.push_str(chars.as_str());
                                        }
                                        event_name.push_str(&cap_mod);
                                    }
                                }

                                // 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
                                // - update:* events (v-model internal events)
                                // - Component events (non-DOM element events)
                                // Note: event name can be "update:modelValue" or "Update:modelValue"
                                let lower_event = base_event.to_lowercase();
                                let is_vmodel_update = lower_event.starts_with("update:");
                                let is_simple_click = matches!(actual_event, "click" | "dblclick")
                                    && !has_option_modifier
                                    && !has_key_modifier
                                    && !has_right_modifier
                                    && !has_middle_modifier;
                                let is_component_event = el.tag_type == ElementType::Component;

                                // 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 {
                                    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 names.is_empty() {
        "UNKNOWN".to_compact_string()
    } else {
        names.join(", ").into()
    }
}