vize_atelier_dom 0.167.0

Atelier DOM - The DOM compiler workshop for Vize
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
//! Vue compiler for DOM platform.
//!
//! This module provides DOM-specific compilation including:
//! - DOM element and attribute validation
//! - v-model transforms for form elements
//! - v-on event modifiers
//! - v-show transform
//! - Style and class binding handling

#![allow(clippy::collapsible_match)]
#![cfg_attr(
    test,
    allow(clippy::disallowed_macros, clippy::field_reassign_with_default)
)]

pub mod options;
pub mod transforms;

pub use options::{DomCompilerOptions, element_checks, event_modifiers};
pub use transforms::{
    EventModifiers, EventOptions, MouseModifiers, PropagationModifiers, SystemModifiers, V_SHOW,
    V_TEXT, VModelModifiers, generate_html_prop, generate_html_warning, generate_key_guard,
    generate_model_props, generate_modifier_guard, generate_show_directive, generate_show_style,
    generate_text_children, generate_text_content, get_model_event, get_model_helper,
    get_model_prop, is_v_html, is_v_show, is_v_text, resolve_key_alias,
};

// Re-export core types
pub use vize_atelier_core::{
    Allocator, CompilerError, Namespace, RootNode, TemplateChildNode, ast, codegen, errors, parser,
    runtime_helpers, tokenizer, transform,
};

use vize_atelier_core::codegen::CodegenResult;
use vize_atelier_core::{
    codegen::generate,
    options::{CodegenOptions, ParserOptions, TransformOptions},
    parser::parse_with_options,
    transform::{
        transform as do_transform, transform_with_hoisted_scope_id,
        transform_with_vue_parser_quirks, transform_with_vue_parser_quirks_and_hoisted_scope_id,
    },
};
use vize_carton::{Bump, String, profile};
use vize_croquis::Croquis;

/// Compile a Vue template for DOM with default options
pub fn compile_template<'a>(
    allocator: &'a Bump,
    source: &'a str,
) -> (RootNode<'a>, Vec<CompilerError>, CodegenResult) {
    compile_template_with_options(allocator, source, DomCompilerOptions::default())
}

/// Compile a Vue template for DOM with custom options
pub fn compile_template_with_options<'a>(
    allocator: &'a Bump,
    source: &'a str,
    options: DomCompilerOptions,
) -> (RootNode<'a>, Vec<CompilerError>, CodegenResult) {
    compile_template_inner(allocator, source, options, false, None)
}

/// Compile a Vue template for DOM with Vue parser quirk compatibility.
pub fn compile_template_with_vue_parser_quirks<'a>(
    allocator: &'a Bump,
    source: &'a str,
    options: DomCompilerOptions,
) -> (RootNode<'a>, Vec<CompilerError>, CodegenResult) {
    compile_template_inner(allocator, source, options, true, None)
}

/// Compile a Vue template for DOM with an explicit scope ID for hoisted static VNodes.
#[doc(hidden)]
pub fn compile_template_with_options_and_hoisted_scope_id<'a>(
    allocator: &'a Bump,
    source: &'a str,
    options: DomCompilerOptions,
    hoisted_scope_id: Option<String>,
) -> (RootNode<'a>, Vec<CompilerError>, CodegenResult) {
    compile_template_inner(allocator, source, options, false, hoisted_scope_id)
}

/// Compile a Vue template for DOM with Vue parser quirks and an explicit hoisted scope ID.
#[doc(hidden)]
pub fn compile_template_with_vue_parser_quirks_and_hoisted_scope_id<'a>(
    allocator: &'a Bump,
    source: &'a str,
    options: DomCompilerOptions,
    hoisted_scope_id: Option<String>,
) -> (RootNode<'a>, Vec<CompilerError>, CodegenResult) {
    compile_template_inner(allocator, source, options, true, hoisted_scope_id)
}

fn compile_template_inner<'a>(
    allocator: &'a Bump,
    source: &'a str,
    options: DomCompilerOptions,
    vue_parser_quirks: bool,
    hoisted_scope_id: Option<String>,
) -> (RootNode<'a>, Vec<CompilerError>, CodegenResult) {
    // Create parser options with DOM-specific settings
    let parser_opts = ParserOptions {
        is_void_tag: vize_carton::is_void_tag,
        is_native_tag: Some(vize_carton::is_native_tag),
        custom_renderer: options.custom_renderer,
        is_pre_tag: |tag| tag == "pre",
        get_namespace,
        comments: options.comments,
        ..ParserOptions::default()
    };

    // Parse
    let (mut root, errors) = profile!(
        "atelier.dom.template.parse",
        parse_with_options(allocator, source, parser_opts)
    );

    // Parser-level diagnostics that are recoverable (e.g. duplicate
    // attribute — Vue keeps the first and continues) must NOT gate
    // codegen, or downstream callers see a 0-byte module reported as a
    // success. (#958) The recoverable diagnostics still ride along in
    // the returned errors vec so the caller can surface them as
    // warnings or test for parity.
    let fatal_count = errors.iter().filter(|e| !e.is_recoverable()).count();
    if fatal_count > 0 {
        let codegen_result = CodegenResult {
            code: String::default(),
            preamble: String::default(),
            map: None,
        };
        return (root, errors.to_vec(), codegen_result);
    }

    // Transform with DOM-specific transforms
    // BindingMetadata is passed directly (no string conversion needed)
    let transform_opts = TransformOptions {
        prefix_identifiers: options.prefix_identifiers,
        hoist_static: options.hoist_static,
        cache_handlers: options.cache_handlers,
        scope_id: options.scope_id.clone(),
        ssr: options.ssr,
        is_ts: options.is_ts,
        inline: options.inline,
        custom_renderer: options.custom_renderer,
        binding_metadata: options.binding_metadata.clone(),
        ..Default::default()
    };
    // Allocate Croquis in the arena so it shares the allocator lifetime
    let analysis: Option<&Croquis> = options.croquis.map(|c| &*allocator.alloc(*c));
    profile!(
        "atelier.dom.template.transform",
        if vue_parser_quirks {
            if hoisted_scope_id.is_some() {
                transform_with_vue_parser_quirks_and_hoisted_scope_id(
                    allocator,
                    &mut root,
                    transform_opts,
                    analysis,
                    hoisted_scope_id,
                )
            } else {
                transform_with_vue_parser_quirks(allocator, &mut root, transform_opts, analysis)
            }
        } else if hoisted_scope_id.is_some() {
            transform_with_hoisted_scope_id(
                allocator,
                &mut root,
                transform_opts,
                analysis,
                hoisted_scope_id,
            )
        } else {
            do_transform(allocator, &mut root, transform_opts, analysis)
        }
    );

    // Codegen
    let codegen_opts = CodegenOptions {
        mode: options.mode,
        source_map: options.source_map,
        component_name: options.component_name,
        scope_id: options.scope_id.clone(),
        ssr: options.ssr,
        is_ts: options.is_ts,
        inline: options.inline,
        cache_handlers: options.cache_handlers,
        binding_metadata: options.binding_metadata,
        ..Default::default()
    };
    let codegen_result = profile!(
        "atelier.dom.template.codegen",
        generate(&root, codegen_opts)
    );

    (root, errors.to_vec(), codegen_result)
}

/// Get the namespace for an element based on its parent
fn get_namespace(tag: &str, parent: Option<&str>) -> Namespace {
    if vize_carton::is_svg_tag(tag) {
        return Namespace::Svg;
    }
    if vize_carton::is_math_ml_tag(tag) {
        return Namespace::MathMl;
    }

    // Inherit namespace from parent
    if let Some(parent_tag) = parent {
        if vize_carton::is_svg_tag(parent_tag) && tag != "foreignObject" {
            return Namespace::Svg;
        }
        if vize_carton::is_math_ml_tag(parent_tag)
            && tag != "annotation-xml"
            && tag != "foreignObject"
        {
            return Namespace::MathMl;
        }
    }

    Namespace::Html
}

#[cfg(test)]
mod tests {
    use super::{
        DomCompilerOptions, Namespace, TemplateChildNode, compile_template,
        compile_template_with_options, compile_template_with_vue_parser_quirks,
    };
    use vize_atelier_core::options::CodegenMode;
    use vize_carton::Bump;

    fn full_output(preamble: &str, code: &str) -> vize_carton::String {
        let mut full = vize_carton::String::with_capacity(preamble.len() + code.len() + 1);
        full.push_str(preamble);
        full.push('\n');
        full.push_str(code);
        full
    }

    #[test]
    fn test_compile_simple_element() {
        let allocator = Bump::new();
        let (root, errors, result) = compile_template(&allocator, "<div>hello</div>");

        assert!(errors.is_empty());
        assert_eq!(root.children.len(), 1);
        let full = full_output(&result.preamble, &result.code);
        insta::assert_snapshot!(full.as_str());
    }

    #[test]
    fn test_compile_svg() {
        let allocator = Bump::new();
        let (root, errors, _) = compile_template(&allocator, "<svg><circle /></svg>");

        assert!(errors.is_empty());
        if let TemplateChildNode::Element(el) = &root.children[0] {
            assert_eq!(el.ns, Namespace::Svg);
        }
    }

    #[test]
    fn test_compile_with_options() {
        let allocator = Bump::new();
        let opts = DomCompilerOptions {
            mode: CodegenMode::Module,
            ..Default::default()
        };
        let (_, errors, result) = compile_template_with_options(&allocator, "<div></div>", opts);

        assert!(errors.is_empty());
        // Empty div generates minimal code
        assert!(!result.code.is_empty());
    }

    #[test]
    fn test_compile_v_for_vue_parser_quirks_accepts_unmatched_alias_paren() {
        let allocator = Bump::new();
        let opts = DomCompilerOptions::default();
        let (_, errors, result) = compile_template_with_vue_parser_quirks(
            &allocator,
            r#"<div v-for="item) in items">{{ item }}</div>"#,
            opts,
        );

        assert!(errors.is_empty(), "Errors: {:?}", errors);
        assert!(result.code.contains("_renderList(items, (item) =>"));
    }

    #[test]
    fn test_event_handler_setup_ref_value() {
        use vize_atelier_core::options::BindingType;
        use vize_carton::FxHashMap;

        let allocator = Bump::new();
        let mut bindings_map = FxHashMap::default();
        bindings_map.insert("quoteId".into(), BindingType::SetupRef);
        bindings_map.insert("renoteTargetNote".into(), BindingType::SetupRef);
        let binding_metadata = vize_atelier_core::options::BindingMetadata {
            bindings: bindings_map,
            props_aliases: FxHashMap::default(),
            is_script_setup: true,
        };

        let opts = DomCompilerOptions {
            mode: CodegenMode::Module,
            prefix_identifiers: true,
            inline: true,
            cache_handlers: true,
            binding_metadata: Some(binding_metadata),
            ..Default::default()
        };
        let template = r#"<button @click="quoteId = null; renoteTargetNote = null;">x</button>"#;
        let (_, errors, result) = compile_template_with_options(&allocator, template, opts);

        eprintln!(
            "=== Template Output ===\npreamble:\n{}\ncode:\n{}",
            result.preamble, result.code
        );
        assert!(errors.is_empty(), "Errors: {:?}", errors);
        let full = full_output(&result.preamble, &result.code);
        insta::assert_snapshot!(full.as_str());
    }

    #[test]
    fn test_inline_ref_class_binding_keeps_class_patch_flag() {
        use vize_atelier_core::options::{BindingMetadata, BindingType};
        use vize_carton::FxHashMap;

        let allocator = Bump::new();
        let mut bindings = FxHashMap::default();
        bindings.insert("currentTab".into(), BindingType::SetupRef);

        let options = DomCompilerOptions {
            mode: CodegenMode::Module,
            prefix_identifiers: true,
            inline: true,
            cache_handlers: true,
            binding_metadata: Some(BindingMetadata {
                bindings,
                props_aliases: FxHashMap::default(),
                is_script_setup: true,
            }),
            ..Default::default()
        };

        let (_, errors, result) = compile_template_with_options(
            &allocator,
            r#"<button :class="['tab', { active: currentTab === 'a' }]" @click="currentTab = 'b'">A</button>"#,
            options,
        );

        assert!(errors.is_empty(), "Errors: {:?}", errors);
        let full = full_output(&result.preamble, &result.code);
        insta::assert_snapshot!(full.as_str());
    }

    #[test]
    fn test_inline_hoisted_bare_static_attrs_are_empty_strings() {
        let allocator = Bump::new();
        let options = DomCompilerOptions {
            mode: CodegenMode::Module,
            prefix_identifiers: true,
            inline: true,
            ..Default::default()
        };

        let (_, errors, result) = compile_template_with_options(
            &allocator,
            r#"<section><h2 sr-only font-bold flex="~ gap-1"><span block /></h2></section>"#,
            options,
        );

        assert!(errors.is_empty(), "Errors: {:?}", errors);
        let full = full_output(&result.preamble, &result.code);
        assert!(full.contains(r#""sr-only": """#), "{full}");
        assert!(full.contains(r#""font-bold": """#), "{full}");
        assert!(full.contains(r#"block: """#), "{full}");
        assert!(!full.contains(r#""sr-only": "true""#), "{full}");
        assert!(!full.contains(r#""font-bold": "true""#), "{full}");
        assert!(!full.contains(r#"block: "true""#), "{full}");
    }

    #[test]
    fn test_inline_component_dynamic_prop_keeps_props_patch_flag() {
        use vize_atelier_core::options::{BindingMetadata, BindingType};
        use vize_carton::FxHashMap;

        let allocator = Bump::new();
        let mut bindings = FxHashMap::default();
        bindings.insert("message".into(), BindingType::SetupRef);
        bindings.insert("activeClass".into(), BindingType::SetupRef);

        let options = DomCompilerOptions {
            mode: CodegenMode::Module,
            prefix_identifiers: true,
            inline: true,
            cache_handlers: true,
            binding_metadata: Some(BindingMetadata {
                bindings,
                props_aliases: FxHashMap::default(),
                is_script_setup: true,
            }),
            ..Default::default()
        };

        let (_, errors, result) = compile_template_with_options(
            &allocator,
            r#"<div><MyComponent :msg="message" :class="activeClass" :full="true" /></div>"#,
            options,
        );

        assert!(errors.is_empty(), "Errors: {:?}", errors);
        let full = full_output(&result.preamble, &result.code);
        insta::assert_snapshot!(full.as_str());
    }

    #[test]
    fn test_v_if_branch_component_dynamic_prop_keeps_props_patch_flag() {
        use vize_atelier_core::options::{BindingMetadata, BindingType};
        use vize_carton::FxHashMap;

        let allocator = Bump::new();
        let mut bindings = FxHashMap::default();
        bindings.insert("show".into(), BindingType::SetupRef);
        bindings.insert("message".into(), BindingType::SetupRef);

        let options = DomCompilerOptions {
            mode: CodegenMode::Module,
            prefix_identifiers: true,
            inline: true,
            cache_handlers: true,
            binding_metadata: Some(BindingMetadata {
                bindings,
                props_aliases: FxHashMap::default(),
                is_script_setup: true,
            }),
            ..Default::default()
        };

        let (_, errors, result) = compile_template_with_options(
            &allocator,
            r#"<div><MyComponent v-if="show" :msg="message" /></div>"#,
            options,
        );

        assert!(errors.is_empty(), "Errors: {:?}", errors);
        let full = full_output(&result.preamble, &result.code);
        insta::assert_snapshot!(full.as_str());
    }
}