vize_atelier_core 0.3.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
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
//! v-if generation functions.

use crate::ast::*;

use super::children::generate_children;
use super::context::CodegenContext;
use super::element::is_whitespace_or_comment;
use super::expression::generate_expression;
use super::helpers::{
    camelize, capitalize_first, escape_js_string, is_builtin_component, is_valid_js_identifier,
};
use super::node::generate_node;
use super::props::{generate_directive_prop_with_static, is_supported_directive};
use super::slots::{generate_slots, has_slot_children};
use vize_carton::FxHashSet;

/// Generate if node
pub fn generate_if(ctx: &mut CodegenContext, if_node: &IfNode<'_>) {
    ctx.use_helper(RuntimeHelper::OpenBlock);

    // Vue always imports createCommentVNode for v-if nodes
    ctx.use_helper(RuntimeHelper::CreateComment);

    for (i, branch) in if_node.branches.iter().enumerate() {
        if let Some(condition) = &branch.condition {
            if i == 0 {
                // First branch: output condition with parentheses
                ctx.push("(");
                generate_expression(ctx, condition);
                ctx.push(")");
                ctx.indent();
                ctx.newline();
                ctx.push("? ");
            } else {
                // Subsequent branches (else-if)
                ctx.newline();
                ctx.push(": (");
                generate_expression(ctx, condition);
                ctx.push(")");
                ctx.indent();
                ctx.newline();
                ctx.push("? ");
            }
        } else {
            // Else branch (no condition)
            ctx.newline();
            ctx.push(": ");
        }

        // Generate branch content based on children
        generate_if_branch(ctx, branch, i);

        if branch.condition.is_some() && i > 0 {
            ctx.deindent();
        }
    }

    // Else branch (comment node) - only if all branches have conditions
    if if_node.branches.iter().all(|b| b.condition.is_some()) {
        ctx.newline();
        ctx.push(": ");
        ctx.push(ctx.helper(RuntimeHelper::CreateComment));
        ctx.push("(\"v-if\", true)");
    }

    ctx.deindent();
}

/// Generate a single if branch
pub fn generate_if_branch(
    ctx: &mut CodegenContext,
    branch: &IfBranchNode<'_>,
    branch_index: usize,
) {
    // Single child optimization
    if branch.children.len() == 1 {
        match &branch.children[0] {
            TemplateChildNode::Element(el) => {
                // Check if it's a template element - treat as fragment
                if el.tag_type == ElementType::Template {
                    // Template with single child -> unwrap to single element
                    if el.children.len() == 1 {
                        if let TemplateChildNode::Element(inner) = &el.children[0] {
                            // Check if inner element is a component
                            if inner.tag_type == ElementType::Component {
                                generate_if_branch_component(ctx, inner, branch, branch_index);
                            } else {
                                generate_if_branch_element(ctx, inner, branch, branch_index);
                            }
                            return;
                        }
                    }
                    // Template with multiple children -> fragment
                    generate_if_branch_template_fragment(ctx, &el.children, branch, branch_index);
                } else if el.tag_type == ElementType::Component {
                    // Component
                    generate_if_branch_component(ctx, el, branch, branch_index);
                } else {
                    // Regular element
                    generate_if_branch_element(ctx, el, branch, branch_index);
                }
            }
            _ => {
                // Other node types - wrap in fragment
                generate_if_branch_fragment(ctx, branch, branch_index);
            }
        }
    } else {
        // Multiple children - wrap in fragment
        generate_if_branch_fragment(ctx, branch, branch_index);
    }
}

/// Generate component for if branch
pub fn generate_if_branch_component(
    ctx: &mut CodegenContext,
    el: &ElementNode<'_>,
    branch: &IfBranchNode<'_>,
    branch_index: usize,
) {
    // Components: skip scope_id in props — Vue runtime applies it via __scopeId
    let prev_skip_scope_id = ctx.skip_scope_id;
    ctx.skip_scope_id = true;
    ctx.use_helper(RuntimeHelper::CreateBlock);
    ctx.push("(");
    ctx.push(ctx.helper(RuntimeHelper::OpenBlock));
    ctx.push("(), ");
    ctx.push(ctx.helper(RuntimeHelper::CreateBlock));
    ctx.push("(");
    // Generate component name
    // Handle dynamic component (<component :is="...">)
    if el.tag == "component" {
        let dynamic_is = el.props.iter().find_map(|p| {
            if let PropNode::Directive(dir) = p {
                if dir.name == "bind" {
                    if let Some(ExpressionNode::Simple(arg)) = &dir.arg {
                        if arg.content == "is" {
                            return dir.exp.as_ref();
                        }
                    }
                }
            }
            None
        });
        let static_is = el.props.iter().find_map(|p| {
            if let PropNode::Attribute(attr) = p {
                if attr.name == "is" {
                    return attr.value.as_ref().map(|v| v.content.as_str());
                }
            }
            None
        });
        if let Some(is_exp) = dynamic_is {
            ctx.use_helper(RuntimeHelper::ResolveDynamicComponent);
            ctx.push(ctx.helper(RuntimeHelper::ResolveDynamicComponent));
            ctx.push("(");
            generate_expression(ctx, is_exp);
            ctx.push(")");
        } else if let Some(name) = static_is {
            ctx.use_helper(RuntimeHelper::ResolveDynamicComponent);
            ctx.push(ctx.helper(RuntimeHelper::ResolveDynamicComponent));
            ctx.push("(\"");
            ctx.push(name);
            ctx.push("\")");
        } else {
            ctx.push("_component_component");
        }
    } else if let Some(builtin) = is_builtin_component(&el.tag) {
        ctx.use_helper(builtin);
        ctx.push(ctx.helper(builtin));
    } else if ctx.is_component_in_bindings(&el.tag) {
        // In inline mode, components are directly in scope (imported at module level)
        // In function mode, use $setup.ComponentName to access setup bindings
        if !ctx.options.inline {
            ctx.push("$setup.");
        }
        ctx.push(el.tag.as_str());
    } else {
        ctx.push("_component_");
        ctx.push(&el.tag.replace('-', "_"));
    }

    // Extract static class/style for merging with dynamic bindings
    let (static_class, static_style) = extract_static_class_style(el);
    let has_dyn_class = has_dynamic_class(el);
    let has_dyn_style = has_dynamic_style(el);

    // Check if component has v-bind spread
    let has_vbind_spread = has_vbind_spread(el);
    if has_vbind_spread {
        ctx.use_helper(RuntimeHelper::MergeProps);
        ctx.push(", ");
        ctx.push(ctx.helper(RuntimeHelper::MergeProps));
        ctx.push("(");

        let mut first_merge_arg = true;
        for prop in el.props.iter() {
            if let PropNode::Directive(dir) = prop {
                if dir.name == "bind" && dir.arg.is_none() {
                    if let Some(exp) = &dir.exp {
                        if !first_merge_arg {
                            ctx.push(", ");
                        }
                        generate_expression(ctx, exp);
                        first_merge_arg = false;
                    }
                }
            }
        }

        if !first_merge_arg {
            ctx.push(", ");
        }
        generate_if_branch_props_object(
            ctx,
            el,
            branch,
            branch_index,
            static_class,
            static_style,
            has_dyn_class,
            has_dyn_style,
        );
        ctx.push(")");
    } else {
        ctx.push(", ");
        generate_if_branch_props_object(
            ctx,
            el,
            branch,
            branch_index,
            static_class,
            static_style,
            has_dyn_class,
            has_dyn_style,
        );
    }

    ctx.skip_scope_id = prev_skip_scope_id;

    // Generate children/slots for v-if branch component (same pattern as element.rs)
    if has_slot_children(el) {
        ctx.push(", ");
        generate_slots(ctx, el);
    } else if el.children.iter().any(|c| !is_whitespace_or_comment(c)) {
        // Teleport/KeepAlive: pass children as array, not slot object
        ctx.push(", [");
        for (i, child) in el.children.iter().enumerate() {
            if i > 0 {
                ctx.push(",");
            }
            generate_node(ctx, child);
        }
        ctx.push("]");
    }

    ctx.push("))")
}

/// Check if prop should be skipped for v-if branch element
fn should_skip_prop_for_if(
    p: &PropNode<'_>,
    has_dynamic_class: bool,
    has_dynamic_style: bool,
) -> bool {
    match p {
        PropNode::Attribute(attr) => {
            // Skip static class if there's a dynamic :class (will be merged)
            if attr.name == "class" && has_dynamic_class {
                return true;
            }
            // Skip static style if there's a dynamic :style (will be merged)
            if attr.name == "style" && has_dynamic_style {
                return true;
            }
            false
        }
        PropNode::Directive(dir) => {
            if dir.name == "bind" {
                if let Some(ExpressionNode::Simple(arg)) = &dir.arg {
                    if arg.content == "key" {
                        return true;
                    }
                }
            }
            // Skip v-if/v-else-if/v-else directives
            if matches!(dir.name.as_str(), "if" | "else-if" | "else") {
                return true;
            }
            false
        }
    }
}

/// Extract static class and style values from element props
fn extract_static_class_style<'a>(el: &'a ElementNode<'_>) -> (Option<&'a str>, Option<&'a str>) {
    let mut static_class = None;
    let mut static_style = None;
    for prop in el.props.iter() {
        if let PropNode::Attribute(attr) = prop {
            if attr.name == "class" {
                if let Some(val) = &attr.value {
                    static_class = Some(val.content.as_str());
                }
            } else if attr.name == "style" {
                if let Some(val) = &attr.value {
                    static_style = Some(val.content.as_str());
                }
            }
        }
    }
    (static_class, static_style)
}

/// Check if element has dynamic :class binding
fn has_dynamic_class(el: &ElementNode<'_>) -> bool {
    el.props.iter().any(|p| {
        if let PropNode::Directive(dir) = p {
            if dir.name == "bind" {
                if let Some(ExpressionNode::Simple(arg)) = &dir.arg {
                    return arg.content == "class";
                }
            }
        }
        false
    })
}

/// Check if element has dynamic :style binding
fn has_dynamic_style(el: &ElementNode<'_>) -> bool {
    el.props.iter().any(|p| {
        if let PropNode::Directive(dir) = p {
            if dir.name == "bind" {
                if let Some(ExpressionNode::Simple(arg)) = &dir.arg {
                    return arg.content == "style";
                }
            }
        }
        false
    })
}

/// Generate a single prop for v-if branch element
fn generate_single_prop_for_if(
    ctx: &mut CodegenContext,
    prop: &PropNode<'_>,
    static_class: Option<&str>,
    static_style: Option<&str>,
) {
    match prop {
        PropNode::Attribute(attr) => {
            let needs_quotes = !is_valid_js_identifier(&attr.name);
            if needs_quotes {
                ctx.push("\"");
            }
            ctx.push(&attr.name);
            if needs_quotes {
                ctx.push("\"");
            }
            ctx.push(": ");
            if let Some(value) = &attr.value {
                ctx.push("\"");
                ctx.push(&escape_js_string(value.content.as_str()));
                ctx.push("\"");
            } else {
                ctx.push("\"\"");
            }
        }
        PropNode::Directive(dir) => {
            generate_directive_prop_with_static(ctx, dir, static_class, static_style);
        }
    }
}

/// Generate element for if branch
pub fn generate_if_branch_element(
    ctx: &mut CodegenContext,
    el: &ElementNode<'_>,
    branch: &IfBranchNode<'_>,
    branch_index: usize,
) {
    ctx.use_helper(RuntimeHelper::CreateElementBlock);
    ctx.push("(");
    ctx.push(ctx.helper(RuntimeHelper::OpenBlock));
    ctx.push("(), ");
    ctx.push(ctx.helper(RuntimeHelper::CreateElementBlock));
    ctx.push("(\"");
    ctx.push(el.tag.as_str());
    ctx.push("\"");

    // Extract static class/style for merging with dynamic bindings
    let (static_class, static_style) = extract_static_class_style(el);
    let has_dyn_class = has_dynamic_class(el);
    let has_dyn_style = has_dynamic_style(el);

    // Generate props with key and all other props (handle v-bind spreads)
    let has_vbind_spread = has_vbind_spread(el);
    if has_vbind_spread {
        ctx.use_helper(RuntimeHelper::MergeProps);
        ctx.push(", ");
        ctx.push(ctx.helper(RuntimeHelper::MergeProps));
        ctx.push("(");

        // Add all v-bind spreads
        let mut first_merge_arg = true;
        for prop in el.props.iter() {
            if let PropNode::Directive(dir) = prop {
                if dir.name == "bind" && dir.arg.is_none() {
                    if let Some(exp) = &dir.exp {
                        if !first_merge_arg {
                            ctx.push(", ");
                        }
                        generate_expression(ctx, exp);
                        first_merge_arg = false;
                    }
                }
            }
        }

        if !first_merge_arg {
            ctx.push(", ");
        }
        generate_if_branch_props_object(
            ctx,
            el,
            branch,
            branch_index,
            static_class,
            static_style,
            has_dyn_class,
            has_dyn_style,
        );
        ctx.push(")");
    } else {
        ctx.push(", ");
        generate_if_branch_props_object(
            ctx,
            el,
            branch,
            branch_index,
            static_class,
            static_style,
            has_dyn_class,
            has_dyn_style,
        );
    }

    // Generate children if any
    if !el.children.is_empty() {
        ctx.push(", ");
        if el.children.len() == 1 {
            if let TemplateChildNode::Text(text) = &el.children[0] {
                ctx.push("\"");
                ctx.push(&escape_js_string(text.content.as_str()));
                ctx.push("\"");
            } else {
                generate_if_branch_children(ctx, &el.children);
            }
        } else {
            generate_if_branch_children(ctx, &el.children);
        }
    }

    ctx.push("))");
}

/// Generate props object for v-if branch (with key and other props)
#[allow(clippy::too_many_arguments)]
fn generate_if_branch_props_object(
    ctx: &mut CodegenContext,
    el: &ElementNode<'_>,
    branch: &IfBranchNode<'_>,
    branch_index: usize,
    static_class: Option<&str>,
    static_style: Option<&str>,
    has_dynamic_class: bool,
    has_dynamic_style: bool,
) {
    // Check if there are other props besides key (skip excluded ones)
    let has_other_props = el.props.iter().any(|p| {
        // Skip unsupported directives (v-slot, v-tooltip, custom directives, etc.)
        if let PropNode::Directive(dir) = p {
            if !is_supported_directive(dir) {
                return false;
            }
        }
        !should_skip_prop_for_if(p, has_dynamic_class, has_dynamic_style)
            && !is_vbind_spread_prop(p)
    });
    // For component elements, skip_scope_id suppresses the attribute.
    let scope_id = if ctx.skip_scope_id {
        None
    } else {
        ctx.options.scope_id.clone()
    };
    let has_scope = scope_id.is_some();

    if !has_other_props && !has_scope {
        // Key-only: use inline format { key: N }
        ctx.push("{ key: ");
        generate_if_branch_key(ctx, branch, branch_index);
        ctx.push(" }");
        return;
    }

    // Multiline format for key + other props
    ctx.push("{");
    ctx.indent();
    ctx.newline();
    ctx.push("key: ");
    generate_if_branch_key(ctx, branch, branch_index);

    let mut seen_events: FxHashSet<String> = FxHashSet::default();

    for prop in el.props.iter() {
        // Skip unsupported directives (v-slot, v-tooltip, custom directives, etc.)
        if let PropNode::Directive(dir) = prop {
            if !is_supported_directive(dir) {
                continue;
            }
        }
        if should_skip_prop_for_if(prop, has_dynamic_class, has_dynamic_style) {
            continue;
        }
        if is_vbind_spread_prop(prop) {
            continue;
        }
        if let PropNode::Directive(dir) = prop {
            if dir.name == "on" {
                if let Some(key) = get_static_event_key(dir) {
                    if !seen_events.insert(key) {
                        continue;
                    }
                }
            }
        }
        ctx.push(",");
        ctx.newline();
        generate_single_prop_for_if(ctx, prop, static_class, static_style);
    }

    // Add scope_id for scoped CSS
    if let Some(ref scope_id) = scope_id {
        ctx.push(",");
        ctx.newline();
        ctx.push("\"");
        ctx.push(scope_id);
        ctx.push("\": \"\"");
    }

    ctx.deindent();
    ctx.newline();
    ctx.push("}");
}

/// Check if element has v-bind object spread
fn has_vbind_spread(el: &ElementNode<'_>) -> bool {
    el.props.iter().any(|p| is_vbind_spread_prop(p))
}

/// Check if prop is a v-bind object spread (v-bind="obj")
fn is_vbind_spread_prop(prop: &PropNode<'_>) -> bool {
    if let PropNode::Directive(dir) = prop {
        return dir.name == "bind" && dir.arg.is_none();
    }
    false
}

/// Compute static event prop key for dedupe (e.g., onClick, onUpdate:modelValue)
fn get_static_event_key(dir: &DirectiveNode<'_>) -> Option<String> {
    let arg = dir.arg.as_ref()?;
    let ExpressionNode::Simple(exp) = arg else {
        return None;
    };
    if !exp.is_static {
        return None;
    }

    let mut event_name = exp.content.as_str();
    let is_keyboard_event = matches!(event_name, "keydown" | "keyup" | "keypress");

    let mut event_option_modifiers: Vec<&str> = Vec::new();
    let mut system_modifiers: Vec<&str> = Vec::new();

    for modifier in dir.modifiers.iter() {
        let mod_name = modifier.content.as_str();
        match mod_name {
            "capture" | "once" | "passive" => {
                event_option_modifiers.push(mod_name);
            }
            "left" | "right" => {
                if !is_keyboard_event {
                    system_modifiers.push(mod_name);
                }
            }
            "middle" => {
                system_modifiers.push(mod_name);
            }
            _ => {}
        }
    }

    let has_right_modifier = system_modifiers.contains(&"right");
    let has_middle_modifier = system_modifiers.contains(&"middle");

    if event_name == "click" && has_right_modifier {
        event_name = "contextmenu";
    } else if event_name == "click" && has_middle_modifier {
        event_name = "mouseup";
    }

    let mut key = if event_name.contains(':') {
        let parts: Vec<&str> = event_name.splitn(2, ':').collect();
        if parts.len() == 2 {
            let first_part = camelize(parts[0]);
            let mut name = String::from("on");
            if let Some(first) = first_part.chars().next() {
                name.push_str(&first.to_uppercase().to_string());
                name.push_str(&first_part[first.len_utf8()..]);
            }
            name.push(':');
            name.push_str(parts[1]);
            name
        } else {
            String::from(event_name)
        }
    } else {
        let camelized = camelize(event_name);
        let mut name = String::from("on");
        if let Some(first) = camelized.chars().next() {
            name.push_str(&first.to_uppercase().to_string());
            name.push_str(&camelized[first.len_utf8()..]);
        }
        name
    };

    for opt_mod in &event_option_modifiers {
        key.push_str(&capitalize_first(opt_mod));
    }

    Some(key)
}

/// Generate template fragment for if branch (multiple children from template)
pub fn generate_if_branch_template_fragment(
    ctx: &mut CodegenContext,
    children: &[TemplateChildNode<'_>],
    branch: &IfBranchNode<'_>,
    branch_index: usize,
) {
    ctx.use_helper(RuntimeHelper::CreateElementBlock);
    ctx.use_helper(RuntimeHelper::Fragment);
    ctx.use_helper(RuntimeHelper::CreateElementVNode);
    ctx.push("(");
    ctx.push(ctx.helper(RuntimeHelper::OpenBlock));
    ctx.push("(), ");
    ctx.push(ctx.helper(RuntimeHelper::CreateElementBlock));
    ctx.push("(");
    ctx.push(ctx.helper(RuntimeHelper::Fragment));
    ctx.push(", { key: ");
    generate_if_branch_key(ctx, branch, branch_index);
    ctx.push(" }, [");
    ctx.indent();
    for (i, child) in children.iter().enumerate() {
        if i > 0 {
            ctx.push(",");
        }
        ctx.newline();
        generate_node(ctx, child);
    }
    ctx.deindent();
    ctx.newline();
    ctx.push("], 64 /* STABLE_FRAGMENT */))");
}

/// Generate key for if branch
pub fn generate_if_branch_key(
    ctx: &mut CodegenContext,
    branch: &IfBranchNode<'_>,
    branch_index: usize,
) {
    // Check if branch has a user-provided key
    if let Some(ref user_key) = branch.user_key {
        match user_key {
            PropNode::Attribute(attr) => {
                // Static key attribute
                if let Some(ref value) = attr.value {
                    ctx.push("\"");
                    ctx.push(&escape_js_string(value.content.as_str()));
                    ctx.push("\"");
                } else {
                    ctx.push(&branch_index.to_string());
                }
            }
            PropNode::Directive(dir) => {
                // Dynamic :key binding
                if let Some(ref exp) = dir.exp {
                    generate_expression(ctx, exp);
                } else {
                    ctx.push(&branch_index.to_string());
                }
            }
        }
    } else {
        ctx.push(&branch_index.to_string());
    }
}

// Note: v-if directive behavior is tested via SFC snapshot tests
// in tests/fixtures/sfc/patches.toml. Unit tests for AST-based functions
// require bumpalo allocation which adds complexity without significant benefit.

/// Generate fragment wrapper for if branch with multiple children
pub fn generate_if_branch_fragment(
    ctx: &mut CodegenContext,
    branch: &IfBranchNode<'_>,
    branch_index: usize,
) {
    ctx.use_helper(RuntimeHelper::CreateElementBlock);
    ctx.use_helper(RuntimeHelper::Fragment);
    ctx.push("(");
    ctx.push(ctx.helper(RuntimeHelper::OpenBlock));
    ctx.push("(), ");
    ctx.push(ctx.helper(RuntimeHelper::CreateElementBlock));
    ctx.push("(");
    ctx.push(ctx.helper(RuntimeHelper::Fragment));
    ctx.push(", { key: ");
    generate_if_branch_key(ctx, branch, branch_index);
    ctx.push(" }, ");
    generate_children(ctx, &branch.children);
    ctx.push(", 64 /* STABLE_FRAGMENT */))");
}

/// Generate children for if branch element
pub fn generate_if_branch_children(ctx: &mut CodegenContext, children: &[TemplateChildNode<'_>]) {
    if children.is_empty() {
        return;
    }

    // Check if all children are simple (text or interpolation)
    let has_only_text_or_interpolation = children.iter().all(|c| {
        matches!(
            c,
            TemplateChildNode::Text(_) | TemplateChildNode::Interpolation(_)
        )
    });

    if has_only_text_or_interpolation {
        let has_interpolation = children
            .iter()
            .any(|c| matches!(c, TemplateChildNode::Interpolation(_)));

        // Use string concatenation for text/interpolation mix
        for (i, child) in children.iter().enumerate() {
            if i > 0 {
                ctx.push(" + ");
            }
            match child {
                TemplateChildNode::Interpolation(interp) => {
                    ctx.use_helper(RuntimeHelper::ToDisplayString);
                    ctx.push(ctx.helper(RuntimeHelper::ToDisplayString));
                    ctx.push("(");
                    generate_expression(ctx, &interp.content);
                    ctx.push(")");
                }
                TemplateChildNode::Text(text) => {
                    ctx.push("\"");
                    ctx.push(&escape_js_string(text.content.as_str()));
                    ctx.push("\"");
                }
                _ => {}
            }
        }

        if has_interpolation {
            ctx.push(", 1 /* TEXT */");
        }
    } else {
        // Complex children - use array
        ctx.push("[");
        ctx.indent();
        for (i, child) in children.iter().enumerate() {
            if i > 0 {
                ctx.push(",");
            }
            ctx.newline();
            generate_node(ctx, child);
        }
        ctx.deindent();
        ctx.newline();
        ctx.push("]");
    }
}