vize_atelier_core 0.237.0

Atelier Core - The core workshop for Vize Vue template parsing, transform lanes, and code generation
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
//! Slots object generation for component children.

use crate::steps::v_slot::{collect_slots, get_slot_name, has_v_slot};
use crate::{
    ElementNode, ExpressionNode, ForNode, IfNode, PropNode, RuntimeHelper, TemplateChildNode,
};
use vize_carton::String;
use vize_carton::ToCompactString;

use super::super::context::CodegenContext;
use super::super::expression::generate_expression;
use super::super::helpers::{escape_js_string, is_valid_js_identifier};
use super::super::node::generate_node;
use super::detect::{
    child_is_slot_template, has_conditional_or_loop_slots, has_forwarded_slot_outlet,
    slot_children_have_meaningful_content,
};
use super::params::{extract_slot_params, get_slot_props, prefix_slot_defaults};

/// Generate slots object for component
pub fn generate_slots(ctx: &mut CodegenContext, el: &ElementNode<'_>) {
    // Note: WithCtx helper is registered at each _withCtx() output site,
    // not here, to avoid importing it when slots don't actually use it.

    // Check for v-slot on component root (shorthand for default slot)
    let root_slot = el.props.iter().find_map(|p| {
        if let PropNode::Directive(dir) = p
            && dir.name.as_str() == "slot"
        {
            return Some(dir.as_ref());
        }
        None
    });

    let collected_slots = collect_slots(el);
    let has_forwarded_slots = has_forwarded_slot_outlet(el);
    let has_dynamic_slots =
        ctx.in_v_for || collected_slots.iter().any(|s| s.is_dynamic) || has_forwarded_slots;
    let has_conditional_slots = has_conditional_or_loop_slots(el);

    // If there are conditional (v-if) or looped (v-for) slots, use createSlots
    if has_conditional_slots && root_slot.is_none() {
        generate_create_slots(ctx, el);
        return;
    }

    ctx.push("{");
    ctx.indent();

    if let Some(slot_dir) = root_slot {
        // v-slot on component root - all children go to default slot
        ctx.newline();
        ctx.push("default: ");
        ctx.use_helper(RuntimeHelper::WithCtx);
        ctx.push(ctx.helper(RuntimeHelper::WithCtx));
        ctx.push("(");
        // Slot props (scoped slot params) - use raw source with default value prefix
        let params = if let Some(props_str) = get_slot_props(slot_dir) {
            let processed = prefix_slot_defaults(&props_str);
            ctx.push("(");
            ctx.push(&processed);
            ctx.push(")");
            extract_slot_params(&props_str)
        } else {
            ctx.push("()");
            vec![]
        };

        // Track slot params for stripping _ctx. prefix
        ctx.add_slot_params(&params);

        ctx.push(" => [");
        ctx.indent();
        generate_slot_children(ctx, &el.children);
        ctx.deindent();
        ctx.newline();
        ctx.push("])");

        // Remove slot params
        ctx.remove_slot_params(&params);
    } else {
        // Check for named slots via template#slotName
        let mut has_generated_default = false;
        let mut first_slot = true;

        for child in &el.children {
            if let TemplateChildNode::Element(template_el) = child
                && template_el.tag.as_str() == "template"
                && has_v_slot(template_el)
            {
                // This is a named slot template
                if let Some(slot_dir) = template_el.props.iter().find_map(|p| {
                    if let PropNode::Directive(dir) = p
                        && dir.name.as_str() == "slot"
                    {
                        return Some(dir.as_ref());
                    }
                    None
                }) {
                    if !first_slot {
                        ctx.push(",");
                    }
                    first_slot = false;
                    ctx.newline();

                    let slot_name = get_slot_name(slot_dir);
                    let is_dynamic = slot_dir
                        .arg
                        .as_ref()
                        .map(|arg| match arg {
                            ExpressionNode::Simple(exp) => !exp.is_static,
                            ExpressionNode::Compound(_) => true,
                        })
                        .unwrap_or(false);

                    if is_dynamic {
                        let trimmed_name = slot_name.trim();
                        if trimmed_name.starts_with('`') && trimmed_name.ends_with('`') {
                            // Template literal slot name: `item.name` → ["item.name"]
                            let inner = &trimmed_name[1..trimmed_name.len() - 1];
                            ctx.push("[\"");
                            ctx.push(&escape_js_string(inner));
                            ctx.push("\"]");
                        } else {
                            // Dynamic slot name: [_ctx.slotName]
                            ctx.push("[");
                            ctx.push("_ctx.");
                            ctx.push(&slot_name);
                            ctx.push("]");
                        }
                    } else if is_valid_js_identifier(&slot_name) {
                        ctx.push(&slot_name);
                    } else {
                        ctx.push("\"");
                        ctx.push(&escape_js_string(&slot_name));
                        ctx.push("\"");
                    }

                    if slot_name.as_str() == "default" {
                        has_generated_default = true;
                    }

                    ctx.push(": ");
                    ctx.use_helper(RuntimeHelper::WithCtx);
                    ctx.push(ctx.helper(RuntimeHelper::WithCtx));
                    ctx.push("(");

                    // Slot props - use raw source with default value prefix
                    let params = if let Some(props_str) = get_slot_props(slot_dir) {
                        let processed = prefix_slot_defaults(&props_str);
                        ctx.push("(");
                        ctx.push(&processed);
                        ctx.push(")");
                        extract_slot_params(&props_str)
                    } else {
                        ctx.push("()");
                        vec![]
                    };

                    // Track slot params for stripping _ctx. prefix
                    ctx.add_slot_params(&params);

                    ctx.push(" => [");
                    ctx.indent();
                    generate_slot_children(ctx, &template_el.children);
                    ctx.deindent();
                    ctx.newline();
                    ctx.push("])");

                    // Remove slot params
                    ctx.remove_slot_params(&params);
                }
            }
        }

        // Generate default slot for non-template children
        let default_children: Vec<_> = el
            .children
            .iter()
            .filter(|child| {
                if let TemplateChildNode::Element(template_el) = child {
                    !(template_el.tag.as_str() == "template" && has_v_slot(template_el))
                } else {
                    true
                }
            })
            .collect();

        if !default_children.is_empty() && !has_generated_default {
            if !first_slot {
                ctx.push(",");
            }
            ctx.newline();
            ctx.push("default: ");
            ctx.use_helper(RuntimeHelper::WithCtx);
            ctx.push(ctx.helper(RuntimeHelper::WithCtx));
            ctx.push("(() => [");
            ctx.indent();
            for (i, child) in default_children.iter().enumerate() {
                if i > 0 {
                    ctx.push(",");
                }
                ctx.newline();
                generate_slot_child_node(ctx, child);
            }
            ctx.deindent();
            ctx.newline();
            ctx.push("])");
        }
    }

    // Add slot stability flag
    ctx.push(",");
    ctx.newline();
    if has_forwarded_slots {
        ctx.push("_: 3 /* FORWARDED */");
    } else if has_dynamic_slots {
        ctx.push("_: 2 /* DYNAMIC */");
    } else {
        ctx.push("_: 1 /* STABLE */");
    }

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

/// Generate slots using createSlots for conditional/looped slot templates
fn generate_create_slots(ctx: &mut CodegenContext, el: &ElementNode<'_>) {
    ctx.use_helper(RuntimeHelper::CreateSlots);
    ctx.push(ctx.helper(RuntimeHelper::CreateSlots));
    ctx.push("(");
    generate_create_slots_base(ctx, el);
    ctx.push(", [");
    ctx.indent();

    let mut first = true;
    for child in &el.children {
        match child {
            TemplateChildNode::If(if_node) => {
                // v-if on slot template: generate conditional slot entry
                if !first {
                    ctx.push(",");
                }
                first = false;
                ctx.newline();
                generate_conditional_slot(ctx, if_node);
            }
            TemplateChildNode::For(for_node) => {
                // v-for on slot template: generate looped slot entries
                if !first {
                    ctx.push(",");
                }
                first = false;
                ctx.newline();
                generate_looped_slot(ctx, for_node);
            }
            TemplateChildNode::Element(template_el)
                if template_el.tag.as_str() == "template" && has_v_slot(template_el) =>
            {
                // Regular named slot (no v-if/v-for)
                if !first {
                    ctx.push(",");
                }
                first = false;
                ctx.newline();
                // Generate as static slot entry
                generate_static_slot_entry(ctx, template_el);
            }
            _ => {}
        }
    }

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

fn generate_create_slots_base(ctx: &mut CodegenContext, el: &ElementNode<'_>) {
    let default_children: Vec<_> = el
        .children
        .iter()
        .filter(|child| !child_is_slot_template(child))
        .collect();
    let has_default_children = slot_children_have_meaningful_content(&default_children);

    if !has_default_children {
        ctx.push("{ _: 2 /* DYNAMIC */ }");
        return;
    }

    ctx.push("{");
    ctx.indent();

    ctx.newline();
    ctx.push("default: ");
    ctx.use_helper(RuntimeHelper::WithCtx);
    ctx.push(ctx.helper(RuntimeHelper::WithCtx));
    ctx.push("(() => [");
    ctx.indent();
    for (i, child) in default_children.iter().enumerate() {
        if i > 0 {
            ctx.push(",");
        }
        ctx.newline();
        generate_slot_child_node(ctx, child);
    }
    ctx.deindent();
    ctx.newline();
    ctx.push("]),");

    ctx.newline();
    ctx.push("_: 2 /* DYNAMIC */");

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

/// Generate a conditional slot entry (v-if on slot template)
fn generate_conditional_slot(ctx: &mut CodegenContext, if_node: &IfNode<'_>) {
    // For each branch: condition ? { name, fn, key } : undefined
    for (i, branch) in if_node.branches.iter().enumerate() {
        if i > 0 {
            ctx.newline();
            ctx.push(": ");
        }

        // Generate condition
        if let Some(condition) = &branch.condition {
            ctx.push("(");
            generate_expression(ctx, condition);
            ctx.push(")");
            ctx.indent();
            ctx.newline();
            ctx.push("? ");
        }

        // Find the slot template in this branch
        let slot_template = branch.children.iter().find_map(|child| {
            if let TemplateChildNode::Element(el) = child
                && el.tag.as_str() == "template"
                && has_v_slot(el)
            {
                return Some(el.as_ref());
            }
            None
        });

        if let Some(template_el) = slot_template {
            generate_slot_object_entry(ctx, template_el, Some(i));
        } else {
            ctx.push("undefined");
        }

        if branch.condition.is_some() {
            ctx.deindent();
        }
    }
    if if_node
        .branches
        .last()
        .is_none_or(|branch| branch.condition.is_some())
    {
        ctx.newline();
        ctx.push(": undefined");
    }
}

/// Generate a looped slot entry (v-for on slot template)
fn generate_looped_slot(ctx: &mut CodegenContext, for_node: &ForNode<'_>) {
    ctx.use_helper(RuntimeHelper::RenderList);
    ctx.push(ctx.helper(RuntimeHelper::RenderList));
    ctx.push("(");
    generate_expression(ctx, &for_node.source);
    ctx.push(", (");

    // Collect callback parameter names for scope registration
    let mut callback_params: Vec<String> = Vec::new();

    if let Some(value) = &for_node.value_alias {
        generate_expression(ctx, value);
        super::super::v_for::helpers::extract_for_params(value, &mut callback_params);
    }
    if let Some(key) = &for_node.key_alias {
        ctx.push(", ");
        generate_expression(ctx, key);
        super::super::v_for::helpers::extract_for_params(key, &mut callback_params);
    }
    if let Some(index) = &for_node.object_index_alias {
        ctx.push(", ");
        generate_expression(ctx, index);
        super::super::v_for::helpers::extract_for_params(index, &mut callback_params);
    }

    ctx.add_slot_params(&callback_params);

    ctx.push(") => {");
    ctx.indent();
    ctx.newline();
    ctx.push("return ");

    // Find the slot template in the for body
    let slot_template = for_node.children.iter().find_map(|child| {
        if let TemplateChildNode::Element(el) = child
            && el.tag.as_str() == "template"
            && has_v_slot(el)
        {
            return Some(el.as_ref());
        }
        None
    });

    if let Some(template_el) = slot_template {
        generate_slot_object_entry(ctx, template_el, None);
    }

    ctx.remove_slot_params(&callback_params);

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

/// Generate a slot object entry: { name: "slotName", fn: _withCtx(() => [...]), key: "N" }
fn generate_slot_object_entry(
    ctx: &mut CodegenContext,
    template_el: &ElementNode<'_>,
    key_index: Option<usize>,
) {
    let slot_dir = template_el.props.iter().find_map(|p| {
        if let PropNode::Directive(dir) = p
            && dir.name.as_str() == "slot"
        {
            return Some(dir.as_ref());
        }
        None
    });

    if let Some(dir) = slot_dir {
        let slot_name = get_slot_name(dir);

        ctx.push("{");
        ctx.indent();
        ctx.newline();

        // name
        ctx.push("name: \"");
        ctx.push(&escape_js_string(&slot_name));
        ctx.push("\",");
        ctx.newline();

        // fn
        ctx.push("fn: ");
        ctx.use_helper(RuntimeHelper::WithCtx);
        ctx.push(ctx.helper(RuntimeHelper::WithCtx));
        ctx.push("(");

        // Slot props
        let params = if let Some(props_str) = get_slot_props(dir) {
            let processed = prefix_slot_defaults(&props_str);
            ctx.push("(");
            ctx.push(&processed);
            ctx.push(")");
            extract_slot_params(&props_str)
        } else {
            ctx.push("()");
            vec![]
        };

        ctx.add_slot_params(&params);

        ctx.push(" => [");
        ctx.indent();
        generate_slot_children(ctx, &template_el.children);
        ctx.deindent();
        ctx.newline();
        ctx.push("])");

        ctx.remove_slot_params(&params);

        // key (for v-if branches)
        if let Some(key) = key_index {
            ctx.push(",");
            ctx.newline();
            ctx.push("key: \"");
            ctx.push(&key.to_compact_string());
            ctx.push("\"");
        }

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

/// Generate a static slot entry for createSlots context
fn generate_static_slot_entry(ctx: &mut CodegenContext, template_el: &ElementNode<'_>) {
    generate_slot_object_entry(ctx, template_el, None);
}

/// Generate children for a slot
fn generate_slot_children(ctx: &mut CodegenContext, children: &[TemplateChildNode<'_>]) {
    // Check if all children are text/interpolation - if so, concatenate into single _createTextVNode
    let all_text_or_interp = children.iter().all(|child| {
        matches!(
            child,
            TemplateChildNode::Text(_) | TemplateChildNode::Interpolation(_)
        )
    });

    if all_text_or_interp && !children.is_empty() {
        ctx.newline();
        ctx.use_helper(RuntimeHelper::CreateText);
        ctx.push(ctx.helper(RuntimeHelper::CreateText));
        ctx.push("(");

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

        for (i, child) in children.iter().enumerate() {
            if i > 0 {
                ctx.push(" + ");
            }
            match child {
                TemplateChildNode::Text(text) => {
                    ctx.push("\"");
                    ctx.push(&super::super::helpers::escape_js_string(&text.content));
                    ctx.push("\"");
                }
                TemplateChildNode::Interpolation(interp) => {
                    // Vue 1.x raw-HTML `{{{ … }}}` renders unescaped.
                    #[cfg(feature = "legacy")]
                    let raw = interp.raw;
                    #[cfg(not(feature = "legacy"))]
                    let raw = false;
                    if raw {
                        generate_slot_expression(ctx, &interp.content);
                    } else {
                        ctx.use_helper(RuntimeHelper::ToDisplayString);
                        ctx.push(ctx.helper(RuntimeHelper::ToDisplayString));
                        ctx.push("(");
                        generate_slot_expression(ctx, &interp.content);
                        ctx.push(")");
                    }
                }
                _ => {}
            }
        }

        if has_interpolation {
            ctx.push(", 1 /* TEXT */)");
        } else {
            ctx.push(")");
        }
    } else {
        for (i, child) in children.iter().enumerate() {
            if i > 0 {
                ctx.push(",");
            }
            ctx.newline();
            generate_slot_child_node(ctx, child);
        }
    }
}

/// Generate a single child node for slot content
fn generate_slot_child_node(ctx: &mut CodegenContext, child: &TemplateChildNode<'_>) {
    match child {
        TemplateChildNode::Text(text) => {
            ctx.use_helper(RuntimeHelper::CreateText);
            ctx.push(ctx.helper(RuntimeHelper::CreateText));
            ctx.push("(\"");
            ctx.push(&super::super::helpers::escape_js_string(&text.content));
            ctx.push("\")");
        }
        TemplateChildNode::Interpolation(interp) => {
            ctx.use_helper(RuntimeHelper::CreateText);
            ctx.push(ctx.helper(RuntimeHelper::CreateText));
            ctx.push("(");
            // Vue 1.x raw-HTML `{{{ … }}}` renders unescaped.
            #[cfg(feature = "legacy")]
            let raw = interp.raw;
            #[cfg(not(feature = "legacy"))]
            let raw = false;
            if raw {
                // Generate expression, stripping _ctx. prefix for slot params
                generate_slot_expression(ctx, &interp.content);
            } else {
                ctx.use_helper(RuntimeHelper::ToDisplayString);
                ctx.push(ctx.helper(RuntimeHelper::ToDisplayString));
                ctx.push("(");
                // Generate expression, stripping _ctx. prefix for slot params
                generate_slot_expression(ctx, &interp.content);
                ctx.push(")");
            }
            ctx.push(", 1 /* TEXT */)");
        }
        _ => {
            generate_node(ctx, child);
        }
    }
}

/// Generate expression for slot content, stripping _ctx. prefix for slot parameters
fn generate_slot_expression(ctx: &mut CodegenContext, expr: &ExpressionNode<'_>) {
    match expr {
        ExpressionNode::Simple(exp) => {
            if exp.is_static {
                ctx.push("\"");
                ctx.push(&exp.content);
                ctx.push("\"");
            } else {
                // Strip _ctx. prefix for slot parameters
                let content = strip_ctx_prefix_for_slot_params(ctx, &exp.content);
                ctx.push(&content);
            }
        }
        ExpressionNode::Compound(comp) => {
            for child in comp.children.iter() {
                match child {
                    crate::CompoundExpressionChild::Simple(exp) => {
                        if exp.is_static {
                            ctx.push("\"");
                            ctx.push(&exp.content);
                            ctx.push("\"");
                        } else {
                            let content = strip_ctx_prefix_for_slot_params(ctx, &exp.content);
                            ctx.push(&content);
                        }
                    }
                    crate::CompoundExpressionChild::String(s) => {
                        ctx.push(s);
                    }
                    crate::CompoundExpressionChild::Symbol(helper) => {
                        ctx.push(ctx.helper(*helper));
                    }
                    _ => {}
                }
            }
        }
    }
}

/// Strip _ctx. prefix from identifiers that are slot parameters
fn strip_ctx_prefix_for_slot_params(ctx: &CodegenContext, content: &str) -> String {
    let mut result = String::new(content);
    for param in &ctx.slot_params {
        // Replace _ctx.paramName with paramName
        let mut prefixed = String::with_capacity(5 + param.len());
        prefixed.push_str("_ctx.");
        prefixed.push_str(param);
        let replaced = result.replace(prefixed.as_str(), param.as_str());
        result = String::from(replaced);
    }
    result
}