vize_atelier_core 0.45.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
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
//! Static hoisting transform.
//!
//! Hoists static nodes to reduce runtime overhead.

use vize_carton::{Box, Bump, String, Vec};

use crate::ast::*;
use crate::transform::TransformContext;

/// Check if a node is fully static (can be hoisted)
pub fn is_static_node(node: &TemplateChildNode<'_>) -> bool {
    match node {
        TemplateChildNode::Text(_) => true,
        TemplateChildNode::Comment(_) => true,
        TemplateChildNode::Element(el) => is_static_element(el),
        TemplateChildNode::Interpolation(_) => false,
        TemplateChildNode::If(_) => false,
        TemplateChildNode::For(_) => false,
        _ => false,
    }
}

/// Check if an element is fully static
fn is_static_element(el: &ElementNode<'_>) -> bool {
    // Components are not static
    if el.tag_type != ElementType::Element {
        return false;
    }

    // Check for dynamic props or ref
    for prop in el.props.iter() {
        match prop {
            PropNode::Directive(_) => return false,
            PropNode::Attribute(attr) => {
                // ref attribute prevents hoisting - refs need runtime owner context
                if attr.name == "ref" {
                    return false;
                }
            }
        }
    }

    // Check children recursively
    // Comments are not hoisted because create_children_expression doesn't handle them
    for child in el.children.iter() {
        // Comments prevent hoisting since they can't be serialized to VNodeCall children
        if matches!(child, TemplateChildNode::Comment(_)) {
            return false;
        }
        // Nested elements cannot be fully hoisted yet because create_children_expression
        // doesn't recursively create VNodeCalls for them - this would cause children to be omitted
        if matches!(child, TemplateChildNode::Element(_)) {
            return false;
        }
        if !is_static_node(child) {
            return false;
        }
    }

    true
}

/// Get the static type of a node
pub fn get_static_type(node: &TemplateChildNode<'_>) -> StaticType {
    match node {
        TemplateChildNode::Text(_) => StaticType::FullyStatic,
        TemplateChildNode::Comment(_) => StaticType::FullyStatic,
        TemplateChildNode::Element(el) => get_element_static_type(el),
        TemplateChildNode::Interpolation(_) => StaticType::NotStatic,
        _ => StaticType::NotStatic,
    }
}

fn get_element_static_type(el: &ElementNode<'_>) -> StaticType {
    if el.tag_type != ElementType::Element {
        return StaticType::NotStatic;
    }

    // Check for any dynamic content
    let mut has_dynamic_text = false;

    for prop in el.props.iter() {
        match prop {
            PropNode::Directive(_) => {
                // Any directive makes the element dynamic (non-static)
                // This includes v-bind:class, v-bind:style, v-on:*, etc.
                return StaticType::NotStatic;
            }
            PropNode::Attribute(attr) => {
                // ref attribute prevents hoisting - refs need runtime owner context
                if attr.name == "ref" {
                    return StaticType::NotStatic;
                }
            }
        }
    }

    // Check children
    for child in el.children.iter() {
        match child {
            TemplateChildNode::Interpolation(_) => {
                has_dynamic_text = true;
            }
            // Nested elements cannot be fully hoisted yet because create_children_expression
            // doesn't recursively create VNodeCalls for them - this would cause children to be omitted
            TemplateChildNode::Element(_) => {
                return StaticType::NotStatic;
            }
            TemplateChildNode::If(_) | TemplateChildNode::For(_) => {
                return StaticType::NotStatic;
            }
            // Comments prevent hoisting since they can't be serialized to VNodeCall children
            TemplateChildNode::Comment(_) => {
                return StaticType::NotStatic;
            }
            _ => {}
        }
    }

    if has_dynamic_text {
        StaticType::HasDynamicText
    } else {
        StaticType::FullyStatic
    }
}

/// Static type enumeration
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StaticType {
    NotStatic = 0,
    FullyStatic = 1,
    HasDynamicText = 2,
}

/// Hoist static nodes in the tree
pub fn hoist_static<'a>(
    ctx: &mut TransformContext<'a>,
    children: &mut Vec<'a, TemplateChildNode<'a>>,
) {
    hoist_static_inner(ctx, children, true)
}

/// Inner implementation with is_root flag
fn hoist_static_inner<'a>(
    ctx: &mut TransformContext<'a>,
    children: &mut Vec<'a, TemplateChildNode<'a>>,
    is_root: bool,
) {
    if !ctx.options.hoist_static {
        return;
    }

    let allocator = ctx.allocator;
    let mut i = 0;

    while i < children.len() {
        let static_type = get_static_type(&children[i]);

        match static_type {
            StaticType::FullyStatic => {
                // Root elements should NOT be fully hoisted as VNodes
                // They must use createElementBlock for proper block tracking
                // Only hoist their props instead
                if is_root {
                    if let TemplateChildNode::Element(el) = &mut children[i] {
                        if has_static_props(el) {
                            hoist_element_props(ctx, el, allocator);
                        }
                    }
                } else {
                    // Non-root static elements can be fully hoisted
                    if let TemplateChildNode::Element(el) = &children[i] {
                        let scope_id = ctx.options.scope_id.clone();
                        let vnode_call =
                            create_vnode_call_from_element(allocator, el, scope_id.as_ref());
                        let hoist_index = ctx.hoist(vnode_call);
                        // Replace with hoisted reference
                        children[i] = TemplateChildNode::Hoisted(hoist_index);
                        ctx.helper(RuntimeHelper::CreateElementVNode);
                    }
                }
            }
            StaticType::HasDynamicText => {
                // Element has static props but dynamic text - hoist the props only
                if let TemplateChildNode::Element(el) = &mut children[i] {
                    if has_static_props(el) {
                        hoist_element_props(ctx, el, allocator);
                    }
                }
            }
            StaticType::NotStatic => {
                // Cannot hoist, but check children recursively (not as root)
                match &mut children[i] {
                    TemplateChildNode::Element(el) => {
                        hoist_static_inner(ctx, &mut el.children, false);
                    }
                    TemplateChildNode::If(if_node) => {
                        // For v-if branches, only hoist nested children, not the branch root
                        // The branch root needs a key and must be created inline
                        for branch in if_node.branches.iter_mut() {
                            for child in branch.children.iter_mut() {
                                if let TemplateChildNode::Element(el) = child {
                                    // Only hoist inside the branch root's children
                                    hoist_static_inner(ctx, &mut el.children, false);
                                }
                            }
                        }
                    }
                    TemplateChildNode::For(for_node) => {
                        hoist_static_inner(ctx, &mut for_node.children, false);
                    }
                    _ => {}
                }
            }
        }
        i += 1;
    }
}

/// Create a VNodeCall from an ElementNode for hoisting
fn create_vnode_call_from_element<'a>(
    allocator: &'a Bump,
    el: &ElementNode<'a>,
    scope_id: Option<&vize_carton::String>,
) -> JsChildNode<'a> {
    let tag = VNodeTag::String(el.tag.clone());
    let props = create_props_expression(allocator, &el.props, scope_id);
    let children = create_children_expression(allocator, &el.children);

    let vnode_call = VNodeCall {
        tag,
        props,
        children,
        patch_flag: None,
        dynamic_props: None,
        directives: None,
        is_block: false,
        disable_tracking: false,
        is_component: false,
        loc: el.loc.clone(),
    };

    JsChildNode::VNodeCall(Box::new_in(vnode_call, allocator))
}

/// Create props expression from element props
fn create_props_expression<'a>(
    allocator: &'a Bump,
    props: &[PropNode<'a>],
    scope_id: Option<&vize_carton::String>,
) -> Option<PropsExpression<'a>> {
    // Build object properties from attributes
    let mut obj_props = Vec::new_in(allocator);

    for prop in props {
        if let PropNode::Attribute(attr) = prop {
            let key = ExpressionNode::Simple(Box::new_in(
                SimpleExpressionNode::new(attr.name.clone(), true, attr.loc.clone()),
                allocator,
            ));
            let value_exp = if let Some(v) = &attr.value {
                SimpleExpressionNode::new(v.content.clone(), true, v.loc.clone())
            } else {
                SimpleExpressionNode::new("true", true, attr.loc.clone())
            };
            let value = JsChildNode::SimpleExpression(Box::new_in(value_exp, allocator));

            obj_props.push(Property {
                key,
                value,
                loc: attr.loc.clone(),
            });
        }
    }

    // Add scope_id attribute for scoped CSS if present
    if let Some(scope_id) = scope_id {
        let key = ExpressionNode::Simple(Box::new_in(
            SimpleExpressionNode::new(scope_id.clone(), true, SourceLocation::STUB),
            allocator,
        ));
        let value = JsChildNode::SimpleExpression(Box::new_in(
            SimpleExpressionNode::new("", true, SourceLocation::STUB),
            allocator,
        ));
        obj_props.push(Property {
            key,
            value,
            loc: SourceLocation::STUB,
        });
    }

    if obj_props.is_empty() {
        return None;
    }

    Some(PropsExpression::Object(Box::new_in(
        ObjectExpression {
            properties: obj_props,
            loc: SourceLocation::STUB,
        },
        allocator,
    )))
}

/// Create children expression from template children
fn create_children_expression<'a>(
    allocator: &'a Bump,
    children: &Vec<'a, TemplateChildNode<'a>>,
) -> Option<VNodeChildren<'a>> {
    if children.is_empty() {
        return None;
    }

    // For a single text child, use Single variant with Text
    if children.len() == 1 {
        if let TemplateChildNode::Text(text) = &children[0] {
            let text_node = TextNode::new(text.content.clone(), text.loc.clone());
            return Some(VNodeChildren::Single(TemplateTextChildNode::Text(
                Box::new_in(text_node, allocator),
            )));
        }
    }

    // For multiple text children, combine them
    let mut all_text = true;
    let mut text_content = String::default();

    for child in children.iter() {
        match child {
            TemplateChildNode::Text(text) => {
                text_content.push_str(&text.content);
            }
            _ => {
                all_text = false;
                break;
            }
        }
    }

    if all_text && !text_content.is_empty() {
        let text_node = TextNode::new(text_content, SourceLocation::STUB);
        return Some(VNodeChildren::Single(TemplateTextChildNode::Text(
            Box::new_in(text_node, allocator),
        )));
    }

    // For complex children with nested elements, return as Simple expression for now
    // A full implementation would recursively create VNodeCalls
    None
}

/// Check if an element has static props (all attributes, no dynamic bindings)
fn has_static_props(el: &ElementNode<'_>) -> bool {
    if el.props.is_empty() {
        return false;
    }

    for prop in el.props.iter() {
        match prop {
            PropNode::Directive(_) => {
                return false;
            }
            PropNode::Attribute(attr) => {
                // `ref` attribute must not be hoisted - it needs runtime resolution
                if attr.name == "ref" {
                    return false;
                }
            }
        }
    }

    true
}

/// Hoist the props of an element with static props
fn hoist_element_props<'a>(
    ctx: &mut TransformContext<'a>,
    el: &mut ElementNode<'a>,
    allocator: &'a Bump,
) {
    // Build props object from element attributes
    let mut obj_props = Vec::new_in(allocator);

    for prop in el.props.iter() {
        if let PropNode::Attribute(attr) = prop {
            let key = ExpressionNode::Simple(Box::new_in(
                SimpleExpressionNode::new(attr.name.clone(), true, attr.loc.clone()),
                allocator,
            ));
            let value_exp = if let Some(v) = &attr.value {
                SimpleExpressionNode::new(v.content.clone(), true, v.loc.clone())
            } else {
                SimpleExpressionNode::new("true", true, attr.loc.clone())
            };
            let value = JsChildNode::SimpleExpression(Box::new_in(value_exp, allocator));

            obj_props.push(Property {
                key,
                value,
                loc: attr.loc.clone(),
            });
        }
    }

    // Add scope_id attribute for scoped CSS if present
    if let Some(ref scope_id) = ctx.options.scope_id {
        let key = ExpressionNode::Simple(Box::new_in(
            SimpleExpressionNode::new(scope_id.clone(), true, SourceLocation::STUB),
            allocator,
        ));
        let value = JsChildNode::SimpleExpression(Box::new_in(
            SimpleExpressionNode::new("", true, SourceLocation::STUB),
            allocator,
        ));
        obj_props.push(Property {
            key,
            value,
            loc: SourceLocation::STUB,
        });
    }

    if obj_props.is_empty() {
        return;
    }

    // Create the object expression to hoist
    let obj_expr = ObjectExpression {
        properties: obj_props,
        loc: SourceLocation::STUB,
    };

    let js_node = JsChildNode::Object(Box::new_in(obj_expr, allocator));
    let hoist_index = ctx.hoist(js_node);

    // Mark the element as having hoisted props (1-based index for _hoisted_N)
    el.hoisted_props_index = Some(hoist_index + 1);
}

/// Check if children should use a block
pub fn should_use_block(el: &ElementNode<'_>) -> bool {
    // Use block for elements with v-for, v-if, or components
    for prop in el.props.iter() {
        if let PropNode::Directive(dir) = prop {
            if dir.name == "for" || dir.name == "if" {
                return true;
            }
        }
    }

    el.tag_type == ElementType::Component
}

/// Count dynamic children for optimization hints
pub fn count_dynamic_children(children: &[TemplateChildNode<'_>]) -> usize {
    let mut count = 0;

    for child in children {
        match child {
            TemplateChildNode::Interpolation(_) => count += 1,
            TemplateChildNode::Element(el) => {
                // Check for dynamic props
                for prop in el.props.iter() {
                    if let PropNode::Directive(_) = prop {
                        count += 1;
                        break;
                    }
                }
            }
            TemplateChildNode::If(_) | TemplateChildNode::For(_) => count += 1,
            _ => {}
        }
    }

    count
}

#[cfg(test)]
mod tests {
    use super::{get_static_type, is_static_node};
    use crate::ast::{PropNode, TemplateChildNode};
    use crate::parser::parse;
    use bumpalo::Bump;

    #[test]
    fn test_static_text() {
        let allocator = Bump::new();
        let (root, _) = parse(&allocator, "hello");

        assert!(is_static_node(&root.children[0]));
    }

    #[test]
    fn test_static_element() {
        let allocator = Bump::new();
        let (root, _) = parse(&allocator, "<div>static</div>");

        assert!(is_static_node(&root.children[0]));
    }

    #[test]
    fn test_dynamic_element() {
        let allocator = Bump::new();
        let (root, _) = parse(&allocator, "<div :class=\"cls\">dynamic</div>");

        assert!(!is_static_node(&root.children[0]));
    }

    #[test]
    fn test_interpolation_not_static() {
        let allocator = Bump::new();
        let (root, _) = parse(&allocator, "{{ msg }}");

        assert!(!is_static_node(&root.children[0]));
    }

    #[test]
    fn test_nested_dynamic_class_not_static() {
        let allocator = Bump::new();
        let (root, _) = parse(
            &allocator,
            r#"<div class="checkbox"><span class="icon" :class="{ active: checked }" /></div>"#,
        );

        // The outer div should NOT be static because it contains a child with dynamic :class
        assert!(!is_static_node(&root.children[0]));
    }

    #[test]
    fn test_sibling_with_v_if() {
        let allocator = Bump::new();
        let (root, _) = parse(
            &allocator,
            r#"<div class="wrapper"><div class="checkbox"><span :class="{ active: checked }" /></div><label v-if="label">{{ label }}</label></div>"#,
        );

        // The outer div is not static because it has dynamic content
        if let TemplateChildNode::Element(el) = &root.children[0] {
            eprintln!(
                "Outer div static type: {:?}",
                get_static_type(&root.children[0])
            );

            // Check first child (div.checkbox)
            if let TemplateChildNode::Element(checkbox_div) = &el.children[0] {
                eprintln!("checkbox div props: {:?}", checkbox_div.props.len());
                eprintln!("checkbox div children: {:?}", checkbox_div.children.len());

                // Check nested span
                if let TemplateChildNode::Element(span) = &checkbox_div.children[0] {
                    eprintln!("span props count: {:?}", span.props.len());
                    for prop in span.props.iter() {
                        match prop {
                            PropNode::Attribute(attr) => eprintln!("  attr: {}", attr.name),
                            PropNode::Directive(dir) => {
                                eprintln!("  directive: {} arg: {:?}", dir.name, dir.arg)
                            }
                        }
                    }
                }
            }
        }

        assert!(!is_static_node(&root.children[0]));
    }
}