1
//! XML and XHTML parsing for declarative UI definitions.
2
//!
3
//! This module provides comprehensive XML parsing and manipulation for Azul's XML-based
4
//! UI format (`.azul` files). It supports:
5
//!
6
//! - **XHTML parsing**: Parse HTML-like syntax into DOM structures
7
//! - **CSS extraction**: Extract `<style>` blocks and inline styles
8
//! - **Component system**: Define reusable UI components with arguments
9
//! - **Hot reload**: Track file changes and rebuild UI incrementally
10
//! - **Error reporting**: Detailed syntax error messages with line/column info
11
//!
12
//! # Examples
13
//!
14
//! ```rust,no_run,ignore
15
//! use azul_core::xml::{XmlNode, XmlParseOptions};
16
//!
17
//! let xml = "<div>Hello</div>";
18
//! // let node = XmlNode::parse(xml)?;
19
//! ```
20

            
21
use alloc::{
22
    boxed::Box,
23
    collections::BTreeMap,
24
    string::{String, ToString},
25
    vec::Vec,
26
};
27
use core::{fmt, fmt::Write, hash::Hash};
28

            
29
use azul_css::{
30
    codegen::format::VecContents,
31
    css::{
32
        Css, CssDeclaration, CssPath, CssPathPseudoSelector, CssPathSelector, CssRuleBlock,
33
        NodeTypeTag,
34
    },
35
    parser2::{CssParseErrorOwned, ErrorLocation},
36
    props::{
37
        basic::{ColorU, StyleFontFamilyVec},
38
        property::CssProperty,
39
        style::{
40
            NormalizedLinearColorStopVec, NormalizedRadialColorStopVec, StyleBackgroundContentVec,
41
            StyleBackgroundPositionVec, StyleBackgroundRepeatVec, StyleBackgroundSizeVec,
42
            StyleTransformVec,
43
        },
44
    },
45
    AzString, OptionString, StringVec, U8Vec,
46
};
47

            
48
use crate::{
49
    dom::{Dom, NodeType, OptionNodeType},
50
    styled_dom::StyledDom,
51
    window::{AzStringPair, StringPairVec},
52
};
53

            
54
/// Error that can occur during XML parsing or hot-reload.
55
///
56
/// Stringified for error reporting; not part of the public API.
57
pub type SyntaxError = String;
58

            
59
/// Tag of an XML node, such as the "button" in `<button>Hello</button>`.
60
#[derive(Default, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
61
#[repr(C)]
62
pub struct XmlTagName {
63
    pub inner: AzString,
64
}
65

            
66
impl From<AzString> for XmlTagName {
67
    fn from(s: AzString) -> Self {
68
        Self { inner: s }
69
    }
70
}
71

            
72
impl From<String> for XmlTagName {
73
810293
    fn from(s: String) -> Self {
74
810293
        Self { inner: s.into() }
75
810293
    }
76
}
77

            
78
impl From<&str> for XmlTagName {
79
126501
    fn from(s: &str) -> Self {
80
126501
        Self { inner: s.into() }
81
126501
    }
82
}
83

            
84
impl core::ops::Deref for XmlTagName {
85
    type Target = AzString;
86
1489427
    fn deref(&self) -> &Self::Target {
87
1489427
        &self.inner
88
1489427
    }
89
}
90

            
91
/// (Unparsed) text content of an XML node, such as the "Hello" in `<button>Hello</button>`.
92
pub type XmlTextContent = OptionString;
93

            
94
/// Attributes of an XML node, such as `["color" => "blue"]` in `<button color="blue" />`.
95
#[derive(Default, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
96
#[repr(C)]
97
pub struct XmlAttributeMap {
98
    pub inner: StringPairVec,
99
}
100

            
101
impl From<StringPairVec> for XmlAttributeMap {
102
815334
    fn from(v: StringPairVec) -> Self {
103
815334
        Self { inner: v }
104
815334
    }
105
}
106

            
107
impl core::ops::Deref for XmlAttributeMap {
108
    type Target = StringPairVec;
109
2308670
    fn deref(&self) -> &Self::Target {
110
2308670
        &self.inner
111
2308670
    }
112
}
113

            
114
impl core::ops::DerefMut for XmlAttributeMap {
115
21703
    fn deref_mut(&mut self) -> &mut Self::Target {
116
21703
        &mut self.inner
117
21703
    }
118
}
119

            
120
/// Name of a component argument (e.g. `"text"`, `"href"`).
121
type ComponentArgumentName = String;
122
/// Type of a component argument as a string (e.g. `"String"`, `"bool"`).
123
type ComponentArgumentType = String;
124
/// Zero-based position of an argument in the component's argument list.
125
type ComponentArgumentOrder = usize;
126

            
127
/// FFI-safe replacement for `(ComponentArgumentName, ComponentArgumentType)` tuple.
128
#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
129
#[repr(C)]
130
pub struct ComponentArgument {
131
    pub name: AzString,
132
    pub arg_type: AzString,
133
}
134

            
135
impl_vec!(
136
    ComponentArgument,
137
    ComponentArgumentVec,
138
    ComponentArgumentVecDestructor,
139
    ComponentArgumentVecDestructorType,
140
    ComponentArgumentVecSlice,
141
    OptionComponentArgument
142
);
143
impl_option!(
144
    ComponentArgument,
145
    OptionComponentArgument,
146
    copy = false,
147
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
148
);
149
impl_vec_debug!(ComponentArgument, ComponentArgumentVec);
150
impl_vec_partialeq!(ComponentArgument, ComponentArgumentVec);
151
impl_vec_eq!(ComponentArgument, ComponentArgumentVec);
152
impl_vec_partialord!(ComponentArgument, ComponentArgumentVec);
153
impl_vec_ord!(ComponentArgument, ComponentArgumentVec);
154
impl_vec_hash!(ComponentArgument, ComponentArgumentVec);
155
impl_vec_clone!(
156
    ComponentArgument,
157
    ComponentArgumentVec,
158
    ComponentArgumentVecDestructor
159
);
160
impl_vec_mut!(ComponentArgument, ComponentArgumentVec);
161

            
162
/// Holds the list of arguments and whether the component accepts text content.
163
/// Used by the compile pipeline to generate Rust function signatures.
164
#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
165
pub struct ComponentArguments {
166
    pub args: ComponentArgumentVec,
167
    pub accepts_text: bool,
168
}
169

            
170
/// Name of an XML/HTML component (e.g. `"button"`, `"my-widget"`).
171
type ComponentName = String;
172
/// Compiled source code string for a component.
173
type CompiledComponent = String;
174

            
175
/// Universal HTML attribute names that are handled by the framework
176
/// and should not be passed through to component-specific argument lists.
177
const DEFAULT_ARGS: [&str; 8] = [
178
    "id",
179
    "class",
180
    "tabindex",
181
    "focusable",
182
    "accepts_text",
183
    "name",
184
    "style",
185
    "args",
186
];
187

            
188
/// Opaque void type for FFI pointers. Uses a custom definition instead of
189
/// `core::ffi::c_void` for `#[repr(C)]` compatibility in the generated API.
190
#[allow(non_camel_case_types)]
191
#[derive(Debug, Copy, Clone)]
192
pub enum c_void {}
193

            
194
/// Type of an XML node in the parsed tree.
195
#[repr(C)]
196
#[derive(Debug, Copy, Clone)]
197
pub enum XmlNodeType {
198
    Root,
199
    Element,
200
    PI,
201
    Comment,
202
    Text,
203
}
204

            
205
/// A namespace-qualified XML name (e.g. `svg:rect` has namespace `"svg"` and local name `"rect"`).
206
#[repr(C)]
207
#[derive(Debug)]
208
pub struct XmlQualifiedName {
209
    pub local_name: AzString,
210
    pub namespace: OptionString,
211
}
212

            
213
/// Classification of an external resource referenced in HTML/XML
214
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
215
#[repr(C)]
216
pub enum ExternalResourceKind {
217
    /// Image resource (img src, background-image, etc.)
218
    Image,
219
    /// Font resource (@font-face src, link rel="preload" as="font")
220
    Font,
221
    /// Stylesheet (link rel="stylesheet", @import)
222
    Stylesheet,
223
    /// Script (script src)
224
    Script,
225
    /// Favicon or icon
226
    Icon,
227
    /// Video source
228
    Video,
229
    /// Audio source
230
    Audio,
231
    /// Generic link or unknown resource type
232
    Unknown,
233
}
234

            
235
/// MIME type hint for an external resource
236
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
237
#[repr(C)]
238
pub struct MimeTypeHint {
239
    pub inner: AzString,
240
}
241

            
242
impl MimeTypeHint {
243
    #[must_use]
244
11
    pub fn new(s: &str) -> Self {
245
11
        Self {
246
11
            inner: AzString::from(s),
247
11
        }
248
11
    }
249

            
250
    #[must_use]
251
2022
    pub fn from_extension(ext: &str) -> Self {
252
2022
        let mime = match ext.to_lowercase().as_str() {
253
            // Images
254
2022
            "png" => "image/png",
255
11
            "jpg" | "jpeg" => "image/jpeg",
256
9
            "gif" => "image/gif",
257
8
            "webp" => "image/webp",
258
8
            "svg" => "image/svg+xml",
259
8
            "ico" => "image/x-icon",
260
8
            "bmp" => "image/bmp",
261
8
            "avif" => "image/avif",
262
            // Fonts
263
8
            "ttf" => "font/ttf",
264
8
            "otf" => "font/otf",
265
8
            "woff" => "font/woff",
266
8
            "woff2" => "font/woff2",
267
7
            "eot" => "application/vnd.ms-fontobject",
268
            // Stylesheets
269
7
            "css" => "text/css",
270
            // Scripts
271
5
            "js" | "mjs" => "application/javascript",
272
            // Video
273
5
            "mp4" => "video/mp4",
274
4
            "webm" => "video/webm",
275
4
            "ogg" => "video/ogg",
276
            // Audio
277
4
            "mp3" => "audio/mpeg",
278
3
            "wav" => "audio/wav",
279
3
            "flac" => "audio/flac",
280
            // Default
281
3
            _ => "application/octet-stream",
282
        };
283
2022
        Self {
284
2022
            inner: AzString::from(mime),
285
2022
        }
286
2022
    }
287
}
288

            
289
impl_option!(
290
    MimeTypeHint,
291
    OptionMimeTypeHint,
292
    copy = false,
293
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
294
);
295

            
296
/// An external resource URL found in an XML/HTML document
297
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
298
#[repr(C)]
299
pub struct ExternalResource {
300
    /// The URL as found in the document (may be relative or absolute)
301
    pub url: AzString,
302
    /// Classification of the resource type
303
    pub kind: ExternalResourceKind,
304
    /// MIME type hint (from type attribute, file extension, or heuristics)
305
    pub mime_type: OptionMimeTypeHint,
306
    /// The HTML element that referenced this resource (e.g., "img", "link", "script")
307
    pub source_element: AzString,
308
    /// The attribute that contained the URL (e.g., "src", "href")
309
    pub source_attribute: AzString,
310
}
311

            
312
impl_option!(
313
    ExternalResource,
314
    OptionExternalResource,
315
    copy = false,
316
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
317
);
318

            
319
impl_vec!(
320
    ExternalResource,
321
    ExternalResourceVec,
322
    ExternalResourceVecDestructor,
323
    ExternalResourceVecDestructorType,
324
    ExternalResourceVecSlice,
325
    OptionExternalResource
326
);
327
impl_vec_mut!(ExternalResource, ExternalResourceVec);
328
impl_vec_debug!(ExternalResource, ExternalResourceVec);
329
impl_vec_partialeq!(ExternalResource, ExternalResourceVec);
330
impl_vec_eq!(ExternalResource, ExternalResourceVec);
331
impl_vec_partialord!(ExternalResource, ExternalResourceVec);
332
impl_vec_ord!(ExternalResource, ExternalResourceVec);
333
impl_vec_hash!(ExternalResource, ExternalResourceVec);
334
impl_vec_clone!(
335
    ExternalResource,
336
    ExternalResourceVec,
337
    ExternalResourceVecDestructor
338
);
339

            
340
/// AUDIT 2026-07-08: maximum XML/HTML nesting depth handled by the recursive
341
/// DOM-build (`xml_node_to_dom_fast`, `xml_node_to_fast_dom`), resource-scan
342
/// (iterative worklist in `scan_external_resources`) and `<body>`-lookup
343
/// (`find_body_recursive`) passes. These bound descent per nesting level, so a pathologically deep
344
/// document (e.g. tens of thousands of nested `<div>`s) would overflow the native
345
/// stack. Beyond this depth, deeper children are ignored rather than crashing.
346
/// 512 is far past any realistic hand-authored markup while staying comfortably
347
/// inside the default thread stack.
348
const MAX_XML_NESTING_DEPTH: usize = 512;
349

            
350
/// AUDIT 2026-07-08: maximum recursion depth for [`ComponentFieldType::parse`],
351
/// which recurses through `Option<..>` / `Vec<..>` wrappers. Caps attacker
352
/// strings such as `"Option<".repeat(100_000)` that would otherwise overflow the
353
/// stack. 64 nested type wrappers is far beyond any real field type.
354
const MAX_TYPE_PARSE_DEPTH: usize = 64;
355

            
356
#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
357
#[repr(C)]
358
pub struct Xml {
359
    pub root: XmlNodeChildVec,
360
}
361

            
362
impl Xml {
363
    /// Scan the XML/HTML document for external resource URLs.
364
    ///
365
    /// This function traverses the entire document tree and extracts URLs from:
366
    /// - `<img src="...">` - Images
367
    /// - `<link href="...">` - Stylesheets, icons, fonts
368
    /// - `<script src="...">` - Scripts
369
    /// - `<video src="...">`, `<source src="...">` - Video
370
    /// - `<audio src="...">` - Audio
371
    /// - `<a href="...">` - Links (classified as Unknown)
372
    /// - CSS `url()` in style attributes
373
    /// - `<style>` blocks with @import or `url()`
374
    #[must_use]
375
3
    pub fn scan_external_resources(&self) -> ExternalResourceVec {
376
3
        let mut resources = Vec::new();
377

            
378
        // AUDIT 2026-07-08: iterative DFS with an explicit worklist. The old
379
        // per-node recursion overflowed the stack on pathologically deep markup
380
        // (a single-purpose scan frame is large: string lowercasing + closure +
381
        // wide match). An explicit stack keeps memory on the heap; `depth` still
382
        // bounds how deep we descend so unbounded input can't grow the worklist
383
        // without limit.
384
3
        let mut stack: Vec<(&XmlNodeChild, usize)> = Vec::new();
385
8
        for child in self.root.as_ref() {
386
8
            stack.push((child, 0));
387
8
        }
388
524
        while let Some((child, depth)) = stack.pop() {
389
521
            match child {
390
                XmlNodeChild::Text(text) => {
391
                    // CSS @import / url() in text content (inside <style> tags).
392
                    Self::extract_css_urls(text.as_str(), &mut resources);
393
                }
394
521
                XmlNodeChild::Element(node) => {
395
521
                    if depth > MAX_XML_NESTING_DEPTH {
396
                        // Deeper subtrees are simply not scanned.
397
1
                        continue;
398
520
                    }
399
520
                    Self::scan_node(node, &mut resources);
400
520
                    for c in node.children.as_ref() {
401
513
                        stack.push((c, depth + 1));
402
513
                    }
403
                }
404
            }
405
        }
406

            
407
3
        resources.into()
408
3
    }
409

            
410
    #[allow(clippy::too_many_lines, clippy::cognitive_complexity)] // large but cohesive:
411
                                                                   // single-purpose
412
                                                                   // parser/builder/dispatch (one
413
                                                                   // branch per input variant)
414
524
    fn scan_node(node: &XmlNode, resources: &mut Vec<ExternalResource>) {
415
524
        let tag_name = node.node_type.inner.as_str().to_lowercase();
416

            
417
        // Get attribute lookup helper
418
1063
        let get_attr = |name: &str| -> Option<String> {
419
1063
            node.attributes
420
1063
                .inner
421
1063
                .as_ref()
422
1063
                .iter()
423
1063
                .find(|pair| pair.key.as_str().eq_ignore_ascii_case(name))
424
1063
                .map(|pair| pair.value.as_str().to_string())
425
1063
        };
426

            
427
524
        match tag_name.as_str() {
428
524
            "img" => {
429
2
                if let Some(src) = get_attr("src") {
430
2
                    let mime = Self::guess_mime_from_url(&src, "image");
431
2
                    resources.push(ExternalResource {
432
2
                        url: AzString::from(src),
433
2
                        kind: ExternalResourceKind::Image,
434
2
                        mime_type: mime.into(),
435
2
                        source_element: AzString::from("img"),
436
2
                        source_attribute: AzString::from("src"),
437
2
                    });
438
2
                }
439
                // Also check srcset
440
2
                if let Some(srcset) = get_attr("srcset") {
441
2
                    for src in Self::parse_srcset(&srcset) {
442
2
                        let mime = Self::guess_mime_from_url(&src, "image");
443
2
                        resources.push(ExternalResource {
444
2
                            url: AzString::from(src),
445
2
                            kind: ExternalResourceKind::Image,
446
2
                            mime_type: mime.into(),
447
2
                            source_element: AzString::from("img"),
448
2
                            source_attribute: AzString::from("srcset"),
449
2
                        });
450
2
                    }
451
1
                }
452
            }
453
522
            "link" => {
454
1
                if let Some(href) = get_attr("href") {
455
1
                    let rel = get_attr("rel").unwrap_or_default().to_lowercase();
456
1
                    let type_attr = get_attr("type");
457
1
                    let as_attr = get_attr("as").unwrap_or_default().to_lowercase();
458

            
459
1
                    let (kind, category) = if rel.contains("stylesheet") {
460
1
                        (ExternalResourceKind::Stylesheet, "stylesheet")
461
                    } else if rel.contains("icon") || rel.contains("apple-touch-icon") {
462
                        (ExternalResourceKind::Icon, "image")
463
                    } else if as_attr == "font" {
464
                        (ExternalResourceKind::Font, "font")
465
                    } else if as_attr == "script" {
466
                        (ExternalResourceKind::Script, "script")
467
                    } else if as_attr == "image" {
468
                        (ExternalResourceKind::Image, "image")
469
                    } else {
470
                        (ExternalResourceKind::Unknown, "")
471
                    };
472

            
473
1
                    let mime = type_attr
474
1
                        .map(|t| MimeTypeHint::new(&t))
475
1
                        .or_else(|| Self::guess_mime_from_url(&href, category));
476

            
477
1
                    resources.push(ExternalResource {
478
1
                        url: AzString::from(href),
479
1
                        kind,
480
1
                        mime_type: mime.into(),
481
1
                        source_element: AzString::from("link"),
482
1
                        source_attribute: AzString::from("href"),
483
1
                    });
484
                }
485
            }
486
521
            "script" => {
487
1
                if let Some(src) = get_attr("src") {
488
1
                    let type_attr = get_attr("type");
489
1
                    let mime = type_attr
490
1
                        .map(|t| MimeTypeHint::new(&t))
491
1
                        .or_else(|| Some(MimeTypeHint::new("application/javascript")));
492

            
493
1
                    resources.push(ExternalResource {
494
1
                        url: AzString::from(src),
495
1
                        kind: ExternalResourceKind::Script,
496
1
                        mime_type: mime.into(),
497
1
                        source_element: AzString::from("script"),
498
1
                        source_attribute: AzString::from("src"),
499
1
                    });
500
                }
501
            }
502
520
            "video" => {
503
1
                if let Some(src) = get_attr("src") {
504
1
                    let mime = Self::guess_mime_from_url(&src, "video");
505
1
                    resources.push(ExternalResource {
506
1
                        url: AzString::from(src),
507
1
                        kind: ExternalResourceKind::Video,
508
1
                        mime_type: mime.into(),
509
1
                        source_element: AzString::from("video"),
510
1
                        source_attribute: AzString::from("src"),
511
1
                    });
512
1
                }
513
1
                if let Some(poster) = get_attr("poster") {
514
1
                    let mime = Self::guess_mime_from_url(&poster, "image");
515
1
                    resources.push(ExternalResource {
516
1
                        url: AzString::from(poster),
517
1
                        kind: ExternalResourceKind::Image,
518
1
                        mime_type: mime.into(),
519
1
                        source_element: AzString::from("video"),
520
1
                        source_attribute: AzString::from("poster"),
521
1
                    });
522
1
                }
523
            }
524
519
            "audio" => {
525
1
                if let Some(src) = get_attr("src") {
526
1
                    let mime = Self::guess_mime_from_url(&src, "audio");
527
1
                    resources.push(ExternalResource {
528
1
                        url: AzString::from(src),
529
1
                        kind: ExternalResourceKind::Audio,
530
1
                        mime_type: mime.into(),
531
1
                        source_element: AzString::from("audio"),
532
1
                        source_attribute: AzString::from("src"),
533
1
                    });
534
1
                }
535
            }
536
518
            "source" => {
537
                if let Some(src) = get_attr("src") {
538
                    let type_attr = get_attr("type");
539
                    // Determine kind based on type or parent (heuristic: assume video)
540
                    let kind = if type_attr.as_ref().is_some_and(|t| t.starts_with("audio")) {
541
                        ExternalResourceKind::Audio
542
                    } else {
543
                        ExternalResourceKind::Video
544
                    };
545
                    let mime = type_attr.map(|t| MimeTypeHint::new(&t)).or_else(|| {
546
                        Self::guess_mime_from_url(
547
                            &src,
548
                            if kind == ExternalResourceKind::Audio {
549
                                "audio"
550
                            } else {
551
                                "video"
552
                            },
553
                        )
554
                    });
555

            
556
                    resources.push(ExternalResource {
557
                        url: AzString::from(src),
558
                        kind,
559
                        mime_type: mime.into(),
560
                        source_element: AzString::from("source"),
561
                        source_attribute: AzString::from("src"),
562
                    });
563
                }
564
                // Also handle srcset for picture elements
565
                if let Some(srcset) = get_attr("srcset") {
566
                    for src in Self::parse_srcset(&srcset) {
567
                        let mime = Self::guess_mime_from_url(&src, "image");
568
                        resources.push(ExternalResource {
569
                            url: AzString::from(src),
570
                            kind: ExternalResourceKind::Image,
571
                            mime_type: mime.into(),
572
                            source_element: AzString::from("source"),
573
                            source_attribute: AzString::from("srcset"),
574
                        });
575
                    }
576
                }
577
            }
578
518
            "a" => {
579
2
                if let Some(href) = get_attr("href") {
580
                    // Only include if it looks like a resource, not a page link
581
2
                    if Self::looks_like_resource(&href) {
582
1
                        let mime = Self::guess_mime_from_url(&href, "");
583
1
                        resources.push(ExternalResource {
584
1
                            url: AzString::from(href),
585
1
                            kind: ExternalResourceKind::Unknown,
586
1
                            mime_type: mime.into(),
587
1
                            source_element: AzString::from("a"),
588
1
                            source_attribute: AzString::from("href"),
589
1
                        });
590
1
                    }
591
                }
592
            }
593
516
            "virtualized-view" | "embed" | "object" => {
594
                let src_attr = if tag_name == "object" { "data" } else { "src" };
595
                if let Some(src) = get_attr(src_attr) {
596
                    resources.push(ExternalResource {
597
                        url: AzString::from(src),
598
                        kind: ExternalResourceKind::Unknown,
599
                        mime_type: OptionMimeTypeHint::None,
600
                        source_element: AzString::from(tag_name.clone()),
601
                        source_attribute: AzString::from(src_attr),
602
                    });
603
                }
604
            }
605
516
            "style" => {
606
                // Scan text content for CSS URLs
607
                for child in node.children.as_ref() {
608
                    if let XmlNodeChild::Text(text) = child {
609
                        Self::extract_css_urls(text.as_str(), resources);
610
                    }
611
                }
612
            }
613
516
            _ => {}
614
        }
615

            
616
        // Check inline style attribute for url()
617
524
        if let Some(style) = get_attr("style") {
618
1
            Self::extract_css_urls(&style, resources);
619
523
        }
620

            
621
        // Check for background attribute (deprecated but still used)
622
524
        if let Some(bg) = get_attr("background") {
623
1
            let mime = Self::guess_mime_from_url(&bg, "image");
624
1
            resources.push(ExternalResource {
625
1
                url: AzString::from(bg),
626
1
                kind: ExternalResourceKind::Image,
627
1
                mime_type: mime.into(),
628
1
                source_element: AzString::from(tag_name),
629
1
                source_attribute: AzString::from("background"),
630
1
            });
631
523
        }
632

            
633
        // Children are walked by the iterative driver in `scan_external_resources`.
634
524
    }
635

            
636
    /// Extract URLs from CSS content (handles `url()` and @import)
637
15
    fn extract_css_urls(css: &str, resources: &mut Vec<ExternalResource>) {
638
        // AUDIT 2026-07-08: fold to lowercase ONCE using ASCII-only folding.
639
        // `to_ascii_lowercase` never changes a string's byte length (only A-Z are
640
        // touched, multi-byte code points are left verbatim), so every byte offset
641
        // into `lower` maps 1:1 onto `css`. The old code called `to_lowercase()`
642
        // every iteration (O(n^2)) and then sliced the ORIGINAL `css` with an
643
        // offset computed in the lowercased temporary -- for characters whose
644
        // lowercase changes byte length (e.g. 'İ' U+0130, 2 bytes -> 3 bytes) that
645
        // offset landed off a char boundary and panicked. Searching in `lower` and
646
        // slicing `css` at the same offset also makes the `url(` / `@import` scans
647
        // case-insensitive for free.
648
15
        let lower = css.to_ascii_lowercase();
649

            
650
        // url(...) scan (case-insensitive)
651
15
        let mut search_from = 0;
652
4022
        while let Some(rel) = lower[search_from..].find("url(") {
653
4007
            let url_start = search_from + rel;
654
4007
            let after = url_start + 4;
655
            // Skip a `url(` that is the argument of an `@import` — the @import scan
656
            // below emits it, correctly tagged as a Stylesheet. Without this guard the
657
            // same URL is pushed twice (once here, mistagged "url()").
658
4007
            if lower[..url_start].trim_end().ends_with("@import") {
659
2
                search_from = after;
660
2
                continue;
661
4005
            }
662
4005
            let after_url = &css[after..];
663
4005
            if let Some(url) = Self::extract_url_value(after_url) {
664
2004
                let mime = Self::guess_mime_from_url(&url, "");
665
2004
                let kind = Self::guess_kind_from_url(&url);
666
2004
                resources.push(ExternalResource {
667
2004
                    url: AzString::from(url),
668
2004
                    kind,
669
2004
                    mime_type: mime.into(),
670
2004
                    source_element: AzString::from("style"),
671
2004
                    source_attribute: AzString::from("url()"),
672
2004
                });
673
2004
            }
674
4005
            search_from = after;
675
        }
676

            
677
        // Handle @import "url" or @import url(...) (case-insensitive)
678
15
        let mut search_from = 0;
679
20
        while let Some(rel) = lower[search_from..].find("@import") {
680
5
            let after = search_from + rel + 7;
681
5
            let after_import = &css[after..];
682
5
            let trimmed = after_import.trim_start();
683

            
684
            // Match `url(` case-insensitively without allocating. `get(..4)`
685
            // returns `None` if byte 4 is not a char boundary, so the slice below
686
            // can never panic on multi-byte input.
687
5
            let import_url = if trimmed
688
5
                .get(..4)
689
5
                .is_some_and(|p| p.eq_ignore_ascii_case("url("))
690
            {
691
2
                Self::extract_url_value(&trimmed[4..])
692
            } else {
693
3
                Self::extract_quoted_string(trimmed)
694
            };
695

            
696
5
            if let Some(url) = import_url {
697
3
                resources.push(ExternalResource {
698
3
                    url: AzString::from(url),
699
3
                    kind: ExternalResourceKind::Stylesheet,
700
3
                    mime_type: Some(MimeTypeHint::new("text/css")).into(),
701
3
                    source_element: AzString::from("style"),
702
3
                    source_attribute: AzString::from("@import"),
703
3
                });
704
3
            }
705

            
706
5
            search_from = after;
707
        }
708
15
    }
709

            
710
    /// Extract value from url(...) - handles quoted and unquoted URLs
711
4033
    fn extract_url_value(s: &str) -> Option<String> {
712
4033
        let trimmed = s.trim_start();
713
4033
        if trimmed.starts_with('"') {
714
4
            Self::extract_quoted_string(trimmed)
715
4029
        } else if let Some(rest) = trimmed.strip_prefix('\'') {
716
3
            let end = rest.find('\'')?;
717
2
            Some(rest[..end].to_string())
718
        } else {
719
4026
            let end = trimmed.find(')')?;
720
2016
            Some(trimmed[..end].trim().to_string())
721
        }
722
4033
    }
723

            
724
    /// Extract a quoted string value
725
25
    fn extract_quoted_string(s: &str) -> Option<String> {
726
25
        if let Some(rest) = s.strip_prefix('"') {
727
15
            let end = rest.find('"')?;
728
11
            Some(rest[..end].to_string())
729
10
        } else if let Some(rest) = s.strip_prefix('\'') {
730
4
            let end = rest.find('\'')?;
731
3
            Some(rest[..end].to_string())
732
        } else {
733
6
            None
734
        }
735
25
    }
736

            
737
    /// Parse srcset attribute into individual URLs
738
12
    fn parse_srcset(srcset: &str) -> Vec<String> {
739
12
        srcset
740
12
            .split(',')
741
20020
            .filter_map(|entry| {
742
20020
                let trimmed = entry.trim();
743
                // srcset format: "url 1x" or "url 100w"
744
20020
                trimmed
745
20020
                    .split_whitespace()
746
20020
                    .next()
747
20020
                    .map(alloc::string::ToString::to_string)
748
20020
            })
749
20012
            .filter(|url| !url.is_empty())
750
12
            .collect()
751
12
    }
752

            
753
    /// Check if a URL looks like a downloadable resource (not a page)
754
9
    fn looks_like_resource(url: &str) -> bool {
755
9
        let lower = url.to_lowercase();
756
        // Check for common resource extensions
757
9
        let resource_exts = [
758
9
            ".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".ico", ".bmp", ".ttf", ".otf",
759
9
            ".woff", ".woff2", ".eot", ".css", ".js", ".mp4", ".webm", ".ogg", ".mp3", ".wav",
760
9
            ".pdf", ".zip", ".tar", ".gz",
761
9
        ];
762
187
        resource_exts.iter().any(|ext| lower.ends_with(ext))
763
9
    }
764

            
765
    /// Guess the resource kind from URL based on file extension.
766
    // `url` is lowercased into `path` below, so these literal `.ext` checks are
767
    // already case-insensitive — the lint can't see the runtime lowercasing.
768
    #[allow(clippy::case_sensitive_file_extension_comparisons)]
769
2014
    fn guess_kind_from_url(url: &str) -> ExternalResourceKind {
770
2014
        let lower = url.to_lowercase();
771
        // Strip query string before checking extension
772
2014
        let path = lower.split('?').next().unwrap_or(&lower);
773
2014
        if path.ends_with(".png")
774
9
            || path.ends_with(".jpg")
775
9
            || path.ends_with(".jpeg")
776
9
            || path.ends_with(".gif")
777
9
            || path.ends_with(".webp")
778
9
            || path.ends_with(".svg")
779
9
            || path.ends_with(".bmp")
780
9
            || path.ends_with(".avif")
781
        {
782
2005
            ExternalResourceKind::Image
783
9
        } else if path.ends_with(".ttf")
784
9
            || path.ends_with(".otf")
785
9
            || path.ends_with(".woff")
786
9
            || path.ends_with(".woff2")
787
8
            || path.ends_with(".eot")
788
        {
789
1
            ExternalResourceKind::Font
790
8
        } else if path.ends_with(".css") {
791
2
            ExternalResourceKind::Stylesheet
792
6
        } else if path.ends_with(".js") || path.ends_with(".mjs") {
793
1
            ExternalResourceKind::Script
794
5
        } else if path.ends_with(".mp4") || path.ends_with(".webm") || path.ends_with(".ogg") {
795
1
            ExternalResourceKind::Video
796
4
        } else if path.ends_with(".mp3") || path.ends_with(".wav") || path.ends_with(".flac") {
797
1
            ExternalResourceKind::Audio
798
3
        } else if path.ends_with(".ico") {
799
1
            ExternalResourceKind::Icon
800
        } else {
801
2
            ExternalResourceKind::Unknown
802
        }
803
2014
    }
804

            
805
    /// Guess MIME type from URL based on extension
806
2027
    fn guess_mime_from_url(url: &str, category: &str) -> Option<MimeTypeHint> {
807
2027
        let lower = url.to_lowercase();
808
        // Find extension
809
2027
        let ext = lower.rsplit('.').next()?;
810
        // Remove query string if present
811
2027
        let ext = ext.split('?').next()?;
812

            
813
        // Check if it's a valid extension
814
2027
        let valid_exts = [
815
2027
            "png", "jpg", "jpeg", "gif", "webp", "svg", "ico", "bmp", "avif", "ttf", "otf", "woff",
816
2027
            "woff2", "eot", "css", "js", "mjs", "mp4", "webm", "ogg", "mp3", "wav", "flac",
817
2027
        ];
818

            
819
2027
        if valid_exts.contains(&ext) {
820
2016
            Some(MimeTypeHint::from_extension(ext))
821
11
        } else if !category.is_empty() {
822
            // Use category hint for default
823
2
            match category {
824
2
                "image" => Some(MimeTypeHint::new("image/*")),
825
1
                "font" => Some(MimeTypeHint::new("font/*")),
826
1
                "stylesheet" => Some(MimeTypeHint::new("text/css")),
827
1
                "script" => Some(MimeTypeHint::new("application/javascript")),
828
1
                "video" => Some(MimeTypeHint::new("video/*")),
829
1
                "audio" => Some(MimeTypeHint::new("audio/*")),
830
1
                _ => None,
831
            }
832
        } else {
833
9
            None
834
        }
835
2027
    }
836
}
837

            
838
#[derive(Debug, PartialEq, Eq, PartialOrd, Clone, Copy)]
839
#[repr(C)]
840
pub struct NonXmlCharError {
841
    pub ch: u32, /* u32 = char, but ABI stable */
842
    pub pos: XmlTextPos,
843
}
844

            
845
#[derive(Debug, PartialEq, Eq, PartialOrd, Clone, Copy)]
846
#[repr(C)]
847
pub struct InvalidCharError {
848
    pub expected: u8,
849
    pub got: u8,
850
    pub pos: XmlTextPos,
851
}
852

            
853
#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
854
#[repr(C)]
855
pub struct InvalidCharMultipleError {
856
    pub expected: u8,
857
    pub got: U8Vec,
858
    pub pos: XmlTextPos,
859
}
860

            
861
#[derive(Debug, PartialEq, Eq, PartialOrd, Clone, Copy)]
862
#[repr(C)]
863
pub struct InvalidQuoteError {
864
    pub got: u8,
865
    pub pos: XmlTextPos,
866
}
867

            
868
#[derive(Debug, PartialEq, Eq, PartialOrd, Clone, Copy)]
869
#[repr(C)]
870
pub struct InvalidSpaceError {
871
    pub got: u8,
872
    pub pos: XmlTextPos,
873
}
874

            
875
#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
876
#[repr(C)]
877
pub struct InvalidStringError {
878
    pub got: AzString,
879
    pub pos: XmlTextPos,
880
}
881

            
882
#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
883
#[repr(C, u8)]
884
pub enum XmlStreamError {
885
    UnexpectedEndOfStream,
886
    InvalidName,
887
    NonXmlChar(NonXmlCharError),
888
    InvalidChar(InvalidCharError),
889
    InvalidCharMultiple(InvalidCharMultipleError),
890
    InvalidQuote(InvalidQuoteError),
891
    InvalidSpace(InvalidSpaceError),
892
    InvalidString(InvalidStringError),
893
    InvalidReference,
894
    InvalidExternalID,
895
    InvalidCommentData,
896
    InvalidCommentEnd,
897
    InvalidCharacterData,
898
}
899

            
900
impl fmt::Display for XmlStreamError {
901
287
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
902
        use self::XmlStreamError::{
903
            InvalidChar, InvalidCharMultiple, InvalidCharacterData, InvalidCommentData,
904
            InvalidCommentEnd, InvalidExternalID, InvalidName, InvalidQuote, InvalidReference,
905
            InvalidSpace, InvalidString, NonXmlChar, UnexpectedEndOfStream,
906
        };
907
287
        match self {
908
13
            UnexpectedEndOfStream => write!(f, "Unexpected end of stream"),
909
178
            InvalidName => write!(f, "Invalid name"),
910
38
            NonXmlChar(nx) => write!(
911
38
                f,
912
38
                "Non-XML character: {:?} at {}",
913
38
                core::char::from_u32(nx.ch),
914
                nx.pos
915
            ),
916
1
            InvalidChar(ic) => write!(
917
1
                f,
918
1
                "Invalid character: expected: {}, got: {} at {}",
919
1
                ic.expected as char, ic.got as char, ic.pos
920
            ),
921
1
            InvalidCharMultiple(imc) => write!(
922
1
                f,
923
1
                "Multiple invalid characters: expected: {}, got: {:?} at {}",
924
                imc.expected,
925
1
                imc.got.as_ref(),
926
                imc.pos
927
            ),
928
13
            InvalidQuote(iq) => write!(f, "Invalid quote: got {} at {}", iq.got as char, iq.pos),
929
1
            InvalidSpace(is) => write!(f, "Invalid space: got {} at {}", is.got as char, is.pos),
930
25
            InvalidString(ise) => write!(
931
25
                f,
932
25
                "Invalid string: got \"{}\" at {}",
933
25
                ise.got.as_str(),
934
                ise.pos
935
            ),
936
1
            InvalidReference => write!(f, "Invalid reference"),
937
1
            InvalidExternalID => write!(f, "Invalid external ID"),
938
1
            InvalidCommentData => write!(f, "Invalid comment data"),
939
1
            InvalidCommentEnd => write!(f, "Invalid comment end"),
940
13
            InvalidCharacterData => write!(f, "Invalid character data"),
941
        }
942
287
    }
943
}
944

            
945
#[derive(Debug, PartialEq, PartialOrd, Clone, Copy, Ord, Hash, Eq)]
946
#[repr(C)]
947
pub struct XmlTextPos {
948
    pub row: u32,
949
    pub col: u32,
950
}
951

            
952
impl fmt::Display for XmlTextPos {
953
382
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
954
382
        write!(f, "line {}:{}", self.row, self.col)
955
382
    }
956
}
957

            
958
#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
959
#[repr(C)]
960
pub struct XmlTextError {
961
    pub stream_error: XmlStreamError,
962
    pub pos: XmlTextPos,
963
}
964

            
965
#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
966
#[repr(C, u8)]
967
pub enum XmlParseError {
968
    InvalidDeclaration(XmlTextError),
969
    InvalidComment(XmlTextError),
970
    InvalidPI(XmlTextError),
971
    InvalidDoctype(XmlTextError),
972
    InvalidEntity(XmlTextError),
973
    InvalidElement(XmlTextError),
974
    InvalidAttribute(XmlTextError),
975
    InvalidCdata(XmlTextError),
976
    InvalidCharData(XmlTextError),
977
    UnknownToken(XmlTextPos),
978
}
979

            
980
impl fmt::Display for XmlParseError {
981
287
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
982
        use self::XmlParseError::{
983
            InvalidAttribute, InvalidCdata, InvalidCharData, InvalidComment, InvalidDeclaration,
984
            InvalidDoctype, InvalidElement, InvalidEntity, InvalidPI, UnknownToken,
985
        };
986
287
        match self {
987
1
            InvalidDeclaration(e) => {
988
1
                write!(f, "Invalid declaration: {} at {}", e.stream_error, e.pos)
989
            }
990
13
            InvalidComment(e) => write!(f, "Invalid comment: {} at {}", e.stream_error, e.pos),
991
1
            InvalidPI(e) => write!(
992
1
                f,
993
1
                "Invalid processing instruction: {} at {}",
994
                e.stream_error, e.pos
995
            ),
996
1
            InvalidDoctype(e) => write!(f, "Invalid doctype: {} at {}", e.stream_error, e.pos),
997
1
            InvalidEntity(e) => write!(f, "Invalid entity: {} at {}", e.stream_error, e.pos),
998
181
            InvalidElement(e) => write!(f, "Invalid element: {} at {}", e.stream_error, e.pos),
999
13
            InvalidAttribute(e) => write!(f, "Invalid attribute: {} at {}", e.stream_error, e.pos),
13
            InvalidCdata(e) => write!(f, "Invalid CDATA: {} at {}", e.stream_error, e.pos),
49
            InvalidCharData(e) => write!(f, "Invalid char data: {} at {}", e.stream_error, e.pos),
14
            UnknownToken(e) => write!(f, "Unknown token at {e}"),
        }
287
    }
}
impl_result!(
    Xml,
    XmlError,
    ResultXmlXmlError,
    copy = false,
    [Debug, PartialEq, Eq, PartialOrd, Clone]
);
#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
#[repr(C)]
pub struct DuplicatedNamespaceError {
    pub ns: AzString,
    pub pos: XmlTextPos,
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
#[repr(C)]
pub struct UnknownNamespaceError {
    pub ns: AzString,
    pub pos: XmlTextPos,
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
#[repr(C)]
pub struct UnexpectedCloseTagError {
    pub expected: AzString,
    pub actual: AzString,
    pub pos: XmlTextPos,
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
#[repr(C)]
pub struct UnknownEntityReferenceError {
    pub entity: AzString,
    pub pos: XmlTextPos,
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
#[repr(C)]
pub struct DuplicatedAttributeError {
    pub attribute: AzString,
    pub pos: XmlTextPos,
}
/// Error for mismatched open/close tags in XML hierarchy
#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
#[repr(C)]
pub struct MalformedHierarchyError {
    /// The tag that was expected (from the opening tag)
    pub expected: AzString,
    /// The tag that was actually found (the closing tag)
    pub got: AzString,
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
#[repr(C, u8)]
pub enum XmlError {
    NoParserAvailable,
    InvalidXmlPrefixUri(XmlTextPos),
    UnexpectedXmlUri(XmlTextPos),
    UnexpectedXmlnsUri(XmlTextPos),
    InvalidElementNamePrefix(XmlTextPos),
    DuplicatedNamespace(DuplicatedNamespaceError),
    UnknownNamespace(UnknownNamespaceError),
    UnexpectedCloseTag(UnexpectedCloseTagError),
    UnexpectedEntityCloseTag(XmlTextPos),
    UnknownEntityReference(UnknownEntityReferenceError),
    MalformedEntityReference(XmlTextPos),
    EntityReferenceLoop(XmlTextPos),
    InvalidAttributeValue(XmlTextPos),
    DuplicatedAttribute(DuplicatedAttributeError),
    NoRootNode,
    SizeLimit,
    DtdDetected,
    /// Invalid hierarchy close tags, i.e `<app></p></app>`
    MalformedHierarchy(MalformedHierarchyError),
    ParserError(XmlParseError),
    UnclosedRootNode,
    UnexpectedDeclaration(XmlTextPos),
    NodesLimitReached,
    AttributesLimitReached,
    NamespacesLimitReached,
    InvalidName(XmlTextPos),
    NonXmlChar(XmlTextPos),
    InvalidChar(XmlTextPos),
    InvalidChar2(XmlTextPos),
    InvalidString(XmlTextPos),
    InvalidExternalID(XmlTextPos),
    InvalidComment(XmlTextPos),
    InvalidCharacterData(XmlTextPos),
    UnknownToken(XmlTextPos),
    UnexpectedEndOfStream,
}
impl fmt::Display for XmlError {
    #[allow(clippy::too_many_lines)] // large but cohesive: one arm per variant
398
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use self::XmlError::{
            AttributesLimitReached, DtdDetected, DuplicatedAttribute, DuplicatedNamespace,
            EntityReferenceLoop, InvalidAttributeValue, InvalidChar, InvalidChar2,
            InvalidCharacterData, InvalidComment, InvalidElementNamePrefix, InvalidExternalID,
            InvalidName, InvalidString, InvalidXmlPrefixUri, MalformedEntityReference,
            MalformedHierarchy, NamespacesLimitReached, NoParserAvailable, NoRootNode,
            NodesLimitReached, NonXmlChar, ParserError, SizeLimit, UnclosedRootNode,
            UnexpectedCloseTag, UnexpectedDeclaration, UnexpectedEndOfStream,
            UnexpectedEntityCloseTag, UnexpectedXmlUri, UnexpectedXmlnsUri, UnknownEntityReference,
            UnknownNamespace, UnknownToken,
        };
398
        match self {
1
            NoParserAvailable => write!(
1
                f,
1
                "Library was compiled without XML parser (XML parser not available)"
            ),
1
            InvalidXmlPrefixUri(pos) => {
1
                write!(f, "Invalid XML Prefix URI at line {}:{}", pos.row, pos.col)
            }
1
            UnexpectedXmlUri(pos) => {
1
                write!(f, "Unexpected XML URI at line {}:{}", pos.row, pos.col)
            }
1
            UnexpectedXmlnsUri(pos) => write!(
1
                f,
1
                "Unexpected XML namespace URI at line {}:{}",
                pos.row, pos.col
            ),
1
            InvalidElementNamePrefix(pos) => write!(
1
                f,
1
                "Invalid element name prefix at line {}:{}",
                pos.row, pos.col
            ),
1
            DuplicatedNamespace(ns) => write!(
1
                f,
1
                "Duplicated namespace: \"{}\" at {}",
1
                ns.ns.as_str(),
                ns.pos
            ),
1
            UnknownNamespace(uns) => write!(
1
                f,
1
                "Unknown namespace: \"{}\" at {}",
1
                uns.ns.as_str(),
                uns.pos
            ),
1
            UnexpectedCloseTag(ct) => write!(
1
                f,
1
                "Unexpected close tag: expected \"{}\", got \"{}\" at {}",
1
                ct.expected.as_str(),
1
                ct.actual.as_str(),
                ct.pos
            ),
1
            UnexpectedEntityCloseTag(pos) => write!(
1
                f,
1
                "Unexpected entity close tag at line {}:{}",
                pos.row, pos.col
            ),
1
            UnknownEntityReference(uer) => write!(
1
                f,
1
                "Unexpected entity reference: \"{}\" at {}",
                uer.entity, uer.pos
            ),
1
            MalformedEntityReference(pos) => write!(
1
                f,
1
                "Malformed entity reference at line {}:{}",
                pos.row, pos.col
            ),
1
            EntityReferenceLoop(pos) => write!(
1
                f,
1
                "Entity reference loop (recursive entity reference) at line {}:{}",
                pos.row, pos.col
            ),
1
            InvalidAttributeValue(pos) => {
1
                write!(f, "Invalid attribute value at line {}:{}", pos.row, pos.col)
            }
1
            DuplicatedAttribute(ae) => write!(
1
                f,
1
                "Duplicated attribute \"{}\" at line {}:{}",
1
                ae.attribute.as_str(),
                ae.pos.row,
                ae.pos.col
            ),
5
            NoRootNode => write!(f, "No root node found"),
1
            SizeLimit => write!(f, "XML file too large (size limit reached)"),
1
            DtdDetected => write!(f, "Document type descriptor detected"),
25
            MalformedHierarchy(e) => write!(
25
                f,
25
                "Malformed hierarchy: expected <{}/> closing tag, got <{}/>",
25
                e.expected.as_str(),
25
                e.got.as_str()
            ),
277
            ParserError(p) => write!(f, "{p}"),
61
            UnclosedRootNode => write!(f, "unclosed root node"),
1
            UnexpectedDeclaration(tp) => write!(f, "unexpected declaration at {tp}"),
1
            NodesLimitReached => write!(f, "nodes limit reached"),
1
            AttributesLimitReached => write!(f, "attributes limit reached"),
1
            NamespacesLimitReached => write!(f, "namespaces limit reached"),
1
            InvalidName(tp) => write!(f, "invalid name at {tp}"),
1
            NonXmlChar(tp) => write!(f, "non xml char at {tp}"),
1
            InvalidChar(tp) => write!(f, "invalid char at {tp}"),
1
            InvalidChar2(tp) => write!(f, "invalid char2 at {tp}"),
1
            InvalidString(tp) => write!(f, "invalid string at {tp}"),
1
            InvalidExternalID(tp) => write!(f, "invalid externalid at {tp}"),
1
            InvalidComment(tp) => write!(f, "invalid comment at {tp}"),
1
            InvalidCharacterData(tp) => write!(f, "invalid character data at {tp}"),
1
            UnknownToken(tp) => write!(f, "unknown token at {tp}"),
1
            UnexpectedEndOfStream => write!(f, "unexpected end of stream"),
        }
398
    }
}
// ============================================================================
// New repr(C) component system
// ============================================================================
/// Identifies a component within a library collection.
/// e.g. collection="builtin", name="div" for the `<div>` element,
/// or collection="shadcn", name="avatar" for a custom component.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct ComponentId {
    /// Library / collection name: "builtin", "shadcn", "myproject"
    pub collection: AzString,
    /// Component name within the collection: "div", "avatar", "card"
    pub name: AzString,
}
impl ComponentId {
    #[must_use]
409149
    pub fn builtin(name: &str) -> Self {
409149
        Self {
409149
            collection: AzString::from_const_str("builtin"),
409149
            name: AzString::from(name),
409149
        }
409149
    }
    #[must_use]
12
    pub fn new(collection: &str, name: &str) -> Self {
12
        Self {
12
            collection: AzString::from(collection),
12
            name: AzString::from(name),
12
        }
12
    }
    /// Returns "collection:name" format string
    #[must_use]
5
    pub fn qualified_name(&self) -> String {
5
        format!("{}:{}", self.collection.as_str(), self.name.as_str())
5
    }
}
// ============================================================================
// Component type system — rich type descriptors for component fields
// ============================================================================
/// A single argument in a callback signature.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct ComponentCallbackArg {
    /// Argument name, e.g. "`button_id`"
    pub name: AzString,
    /// Argument type
    pub arg_type: ComponentFieldType,
}
impl_vec!(
    ComponentCallbackArg,
    ComponentCallbackArgVec,
    ComponentCallbackArgVecDestructor,
    ComponentCallbackArgVecDestructorType,
    ComponentCallbackArgVecSlice,
    OptionComponentCallbackArg
);
impl_option!(
    ComponentCallbackArg,
    OptionComponentCallbackArg,
    copy = false,
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);
impl_vec_debug!(ComponentCallbackArg, ComponentCallbackArgVec);
impl_vec_partialeq!(ComponentCallbackArg, ComponentCallbackArgVec);
impl_vec_eq!(ComponentCallbackArg, ComponentCallbackArgVec);
impl_vec_partialord!(ComponentCallbackArg, ComponentCallbackArgVec);
impl_vec_ord!(ComponentCallbackArg, ComponentCallbackArgVec);
impl_vec_hash!(ComponentCallbackArg, ComponentCallbackArgVec);
impl_vec_clone!(
    ComponentCallbackArg,
    ComponentCallbackArgVec,
    ComponentCallbackArgVecDestructor
);
/// Callback signature: return type + argument list.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct ComponentCallbackSignature {
    /// Return type name, e.g. "Update"
    pub return_type: AzString,
    /// Callback arguments (excluding the implicit `&mut RefAny` and `&mut CallbackInfo`)
    pub args: ComponentCallbackArgVec,
}
/// Heap-allocated box for recursive `ComponentFieldType` (e.g. `Option<String>`).
/// Uses raw pointer indirection to break the infinite size.
#[repr(C)]
pub struct ComponentFieldTypeBox {
    pub ptr: *mut ComponentFieldType,
}
impl ComponentFieldTypeBox {
    #[must_use]
151
    pub fn new(t: ComponentFieldType) -> Self {
151
        Self {
151
            ptr: Box::into_raw(Box::new(t)),
151
        }
151
    }
    #[must_use]
74
    pub fn as_ref(&self) -> &ComponentFieldType {
74
        unsafe { &*self.ptr }
74
    }
}
impl Clone for ComponentFieldTypeBox {
5
    fn clone(&self) -> Self {
5
        Self::new(unsafe { (*self.ptr).clone() })
5
    }
}
impl Drop for ComponentFieldTypeBox {
151
    fn drop(&mut self) {
        // Null the pointer as we free it, so a *second* drop is a no-op instead
        // of a double free. This type is a by-value payload of the
        // `ComponentFieldType` enum, whose codegen FFI mirror gets
        // `impl Drop { _delete }` (= drop_in_place of the real type) AND Rust
        // field drop-glue — dropping each by-value field twice. Without this
        // take-and-null the second drop would `Box::from_raw` a dangling pointer.
151
        let ptr = core::mem::replace(&mut self.ptr, core::ptr::null_mut());
151
        if !ptr.is_null() {
151
            unsafe {
151
                drop(Box::from_raw(ptr));
151
            }
        }
151
    }
}
impl fmt::Debug for ComponentFieldTypeBox {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.ptr.is_null() {
            write!(f, "ComponentFieldTypeBox(null)")
        } else {
            write!(f, "ComponentFieldTypeBox({:?})", unsafe { &*self.ptr })
        }
    }
}
impl PartialEq for ComponentFieldTypeBox {
5
    fn eq(&self, other: &Self) -> bool {
5
        if self.ptr.is_null() && other.ptr.is_null() {
            return true;
5
        }
5
        if self.ptr.is_null() || other.ptr.is_null() {
            return false;
5
        }
5
        unsafe { *self.ptr == *other.ptr }
5
    }
}
impl Eq for ComponentFieldTypeBox {}
impl PartialOrd for ComponentFieldTypeBox {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl Ord for ComponentFieldTypeBox {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        match (self.ptr.is_null(), other.ptr.is_null()) {
            (true, true) => core::cmp::Ordering::Equal,
            (true, false) => core::cmp::Ordering::Less,
            (false, true) => core::cmp::Ordering::Greater,
            (false, false) => unsafe { (*self.ptr).cmp(&*other.ptr) },
        }
    }
}
impl Hash for ComponentFieldTypeBox {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        if !self.ptr.is_null() {
            unsafe {
                (*self.ptr).hash(state);
            }
        }
    }
}
/// Heap-allocated box for recursive `ComponentFieldValue` (e.g. `Some(value)`).
/// Uses raw pointer indirection to break the infinite size.
#[repr(C)]
pub struct ComponentFieldValueBox {
    pub ptr: *mut ComponentFieldValue,
}
impl ComponentFieldValueBox {
    #[must_use]
2
    pub fn new(v: ComponentFieldValue) -> Self {
2
        Self {
2
            ptr: Box::into_raw(Box::new(v)),
2
        }
2
    }
    #[must_use]
1
    pub fn as_ref(&self) -> &ComponentFieldValue {
1
        unsafe { &*self.ptr }
1
    }
}
impl Clone for ComponentFieldValueBox {
1
    fn clone(&self) -> Self {
1
        Self::new(unsafe { (*self.ptr).clone() })
1
    }
}
impl Drop for ComponentFieldValueBox {
2
    fn drop(&mut self) {
        // Take-and-null so a second drop (codegen FFI double-drop of a by-value
        // field, see `ComponentFieldTypeBox`) is a no-op, not a double free.
2
        let ptr = core::mem::replace(&mut self.ptr, core::ptr::null_mut());
2
        if !ptr.is_null() {
2
            unsafe {
2
                drop(Box::from_raw(ptr));
2
            }
        }
2
    }
}
impl fmt::Debug for ComponentFieldValueBox {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.ptr.is_null() {
            write!(f, "ComponentFieldValueBox(null)")
        } else {
            write!(f, "ComponentFieldValueBox({:?})", unsafe { &*self.ptr })
        }
    }
}
impl PartialEq for ComponentFieldValueBox {
1
    fn eq(&self, other: &Self) -> bool {
1
        if self.ptr.is_null() && other.ptr.is_null() {
            return true;
1
        }
1
        if self.ptr.is_null() || other.ptr.is_null() {
            return false;
1
        }
1
        unsafe { *self.ptr == *other.ptr }
1
    }
}
/// Rich type descriptor for a component field.
/// Replaces the old `AzString` type names ("String", "bool", etc.) with
/// a structured enum that the debugger can use for type-aware editing.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C, u8)]
pub enum ComponentFieldType {
    String,
    Bool,
    I32,
    I64,
    U32,
    U64,
    Usize,
    F32,
    F64,
    ColorU,
    CssProperty,
    ImageRef,
    FontRef,
    /// `StyledDom` slot — field name = slot name
    StyledDom,
    /// Callback with typed signature
    Callback(ComponentCallbackSignature),
    /// `RefAny` data binding with type hint
    RefAny(AzString),
    /// Optional value (recursive via Box)
    OptionType(ComponentFieldTypeBox),
    /// Vec of values (recursive via Box)
    VecType(ComponentFieldTypeBox),
    /// Reference to a struct defined in the same library
    StructRef(AzString),
    /// Reference to an enum defined in the same library
    EnumRef(AzString),
}
impl ComponentFieldType {
    /// Parse a field type string like "String", "Option<Bool>", "Vec<I32>",
    /// "Callback(fn(LayoutCallbackInfo) -> Dom)", "StructRef(MyStruct)" etc.
    /// Returns `None` if the string cannot be parsed.
    #[must_use]
56
    pub fn parse(s: &str) -> Option<Self> {
56
        Self::parse_depth(s, 0)
56
    }
    /// Depth-bounded implementation of [`parse`](Self::parse).
    ///
    /// AUDIT 2026-07-08: `Option<..>` / `Vec<..>` wrappers recurse once per level,
    /// so an attacker string like `"Option<".repeat(100_000)` (with matching `>`)
    /// overflowed the stack. Recursion is capped at [`MAX_TYPE_PARSE_DEPTH`];
    /// beyond it, parsing fails (`None`) instead of crashing.
333
    fn parse_depth(s: &str, depth: usize) -> Option<Self> {
333
        if depth > MAX_TYPE_PARSE_DEPTH {
5
            return None;
328
        }
328
        let s = s.trim();
328
        match s {
328
            "String" | "string" => return Some(Self::String),
325
            "Bool" | "bool" => return Some(Self::Bool),
319
            "I32" | "i32" => return Some(Self::I32),
317
            "I64" | "i64" => return Some(Self::I64),
316
            "U32" | "u32" => return Some(Self::U32),
315
            "U64" | "u64" => return Some(Self::U64),
314
            "Usize" | "usize" => return Some(Self::Usize),
312
            "F32" | "f32" => return Some(Self::F32),
311
            "F64" | "f64" => return Some(Self::F64),
310
            "ColorU" => return Some(Self::ColorU),
309
            "CssProperty" => return Some(Self::CssProperty),
308
            "ImageRef" => return Some(Self::ImageRef),
307
            "FontRef" => return Some(Self::FontRef),
306
            "StyledDom" => return Some(Self::StyledDom),
305
            "RefAny" => return Some(Self::RefAny(AzString::from(""))),
303
            _ => {}
        }
        // Option<T>
303
        if let Some(inner) = s.strip_prefix("Option<").and_then(|r| r.strip_suffix('>')) {
206
            let inner_type = Self::parse_depth(inner, depth + 1)?;
74
            return Some(Self::OptionType(ComponentFieldTypeBox::new(inner_type)));
97
        }
        // Vec<T>
97
        if let Some(inner) = s.strip_prefix("Vec<").and_then(|r| r.strip_suffix('>')) {
68
            let inner_type = Self::parse_depth(inner, depth + 1)?;
2
            return Some(Self::VecType(ComponentFieldTypeBox::new(inner_type)));
29
        }
        // Callback(signature)
29
        if let Some(sig) = s
29
            .strip_prefix("Callback(")
29
            .and_then(|r| r.strip_suffix(')'))
        {
2
            return Some(Self::Callback(ComponentCallbackSignature {
2
                return_type: AzString::from(sig),
2
                args: Vec::new().into(),
2
            }));
27
        }
        // RefAny(TypeHint)
27
        if let Some(hint) = s.strip_prefix("RefAny(").and_then(|r| r.strip_suffix(')')) {
1
            return Some(Self::RefAny(AzString::from(hint)));
26
        }
        // EnumRef(Name) — explicit
26
        if let Some(name) = s.strip_prefix("EnumRef(").and_then(|r| r.strip_suffix(')')) {
1
            return Some(Self::EnumRef(AzString::from(name)));
25
        }
        // StructRef(Name) — explicit
25
        if let Some(name) = s
25
            .strip_prefix("StructRef(")
25
            .and_then(|r| r.strip_suffix(')'))
        {
1
            return Some(Self::StructRef(AzString::from(name)));
24
        }
        // If starts with uppercase, treat as StructRef
24
        if s.chars().next().is_some_and(char::is_uppercase) {
8
            return Some(Self::StructRef(AzString::from(s)));
16
        }
16
        None
333
    }
    /// Format this field type to its canonical string representation.
    /// This is the inverse of `parse`.
    #[must_use]
100
    pub fn format(&self) -> String {
100
        match self {
1
            Self::String => "String".to_string(),
3
            Self::Bool => "Bool".to_string(),
2
            Self::I32 => "I32".to_string(),
1
            Self::I64 => "I64".to_string(),
1
            Self::U32 => "U32".to_string(),
1
            Self::U64 => "U64".to_string(),
1
            Self::Usize => "Usize".to_string(),
1
            Self::F32 => "F32".to_string(),
4
            Self::F64 => "F64".to_string(),
1
            Self::ColorU => "ColorU".to_string(),
1
            Self::CssProperty => "CssProperty".to_string(),
1
            Self::ImageRef => "ImageRef".to_string(),
1
            Self::FontRef => "FontRef".to_string(),
1
            Self::StyledDom => "StyledDom".to_string(),
2
            Self::Callback(sig) => format!("Callback({})", sig.return_type.as_str()),
2
            Self::RefAny(hint) => {
2
                if hint.as_str().is_empty() {
1
                    "RefAny".to_string()
                } else {
1
                    format!("RefAny({})", hint.as_str())
                }
            }
69
            Self::OptionType(inner) => format!("Option<{}>", inner.as_ref().format()),
2
            Self::VecType(inner) => format!("Vec<{}>", inner.as_ref().format()),
5
            Self::StructRef(name) | Self::EnumRef(name) => name.as_str().to_string(),
        }
100
    }
}
impl fmt::Display for ComponentFieldType {
2
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2
        f.write_str(&self.format())
2
    }
}
/// A single variant in a component enum model.
#[derive(Debug, Clone, PartialEq)]
#[repr(C)]
pub struct ComponentEnumVariant {
    /// Variant name, e.g. "Admin", "Editor", "Viewer"
    pub name: AzString,
    /// Human-readable description for this variant
    pub description: AzString,
    /// Optional associated fields for this variant
    pub fields: ComponentDataFieldVec,
}
impl_vec!(
    ComponentEnumVariant,
    ComponentEnumVariantVec,
    ComponentEnumVariantVecDestructor,
    ComponentEnumVariantVecDestructorType,
    ComponentEnumVariantVecSlice,
    OptionComponentEnumVariant
);
impl_option!(
    ComponentEnumVariant,
    OptionComponentEnumVariant,
    copy = false,
    [Debug, Clone, PartialEq]
);
impl_vec_debug!(ComponentEnumVariant, ComponentEnumVariantVec);
impl_vec_partialeq!(ComponentEnumVariant, ComponentEnumVariantVec);
impl_vec_clone!(
    ComponentEnumVariant,
    ComponentEnumVariantVec,
    ComponentEnumVariantVecDestructor
);
/// A named enum model for code generation.
/// Stored in `ComponentLibrary::enum_models`.
#[derive(Debug, Clone, PartialEq)]
#[repr(C)]
pub struct ComponentEnumModel {
    /// Enum name, e.g. "`UserRole`"
    pub name: AzString,
    /// Human-readable description
    pub description: AzString,
    /// Variants
    pub variants: ComponentEnumVariantVec,
}
impl_vec!(
    ComponentEnumModel,
    ComponentEnumModelVec,
    ComponentEnumModelVecDestructor,
    ComponentEnumModelVecDestructorType,
    ComponentEnumModelVecSlice,
    OptionComponentEnumModel
);
impl_option!(
    ComponentEnumModel,
    OptionComponentEnumModel,
    copy = false,
    [Debug, Clone, PartialEq]
);
impl_vec_debug!(ComponentEnumModel, ComponentEnumModelVec);
impl_vec_partialeq!(ComponentEnumModel, ComponentEnumModelVec);
impl_vec_clone!(
    ComponentEnumModel,
    ComponentEnumModelVec,
    ComponentEnumModelVecDestructor
);
/// Default value for a component field.
#[derive(Debug, Clone, PartialEq)]
#[repr(C, u8)]
pub enum ComponentDefaultValue {
    /// No default value (field is required)
    None,
    /// String literal default
    String(AzString),
    /// Boolean default
    Bool(bool),
    /// i32 default
    I32(i32),
    /// i64 default
    I64(i64),
    /// u32 default
    U32(u32),
    /// u64 default
    U64(u64),
    /// usize default
    Usize(usize),
    /// f32 default
    F32(f32),
    /// f64 default
    F64(f64),
    /// `ColorU` default
    ColorU(ColorU),
    /// Default is an instance of another component
    ComponentInstance(ComponentInstanceDefault),
    /// Default callback function pointer name
    CallbackFnPointer(AzString),
    /// JSON string representing a complex default value
    Json(AzString),
}
impl_option!(
    ComponentDefaultValue,
    OptionComponentDefaultValue,
    copy = false,
    [Debug, Clone, PartialEq]
);
/// Default component instance for a `StyledDom` slot.
#[derive(Debug, Clone, PartialEq)]
#[repr(C)]
pub struct ComponentInstanceDefault {
    /// Library name, e.g. "builtin"
    pub library: AzString,
    /// Component tag, e.g. "a"
    pub component: AzString,
    /// Field overrides for this instance
    pub field_overrides: ComponentFieldOverrideVec,
}
/// An override for a single field in a component instance.
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct ComponentFieldOverride {
    /// Field name to override
    pub field_name: AzString,
    /// Value source for this override
    pub source: ComponentFieldValueSource,
}
impl_vec!(
    ComponentFieldOverride,
    ComponentFieldOverrideVec,
    ComponentFieldOverrideVecDestructor,
    ComponentFieldOverrideVecDestructorType,
    ComponentFieldOverrideVecSlice,
    OptionComponentFieldOverride
);
impl_option!(
    ComponentFieldOverride,
    OptionComponentFieldOverride,
    copy = false,
    [Debug, Clone, PartialEq, Eq]
);
impl_vec_debug!(ComponentFieldOverride, ComponentFieldOverrideVec);
impl_vec_partialeq!(ComponentFieldOverride, ComponentFieldOverrideVec);
impl_vec_clone!(
    ComponentFieldOverride,
    ComponentFieldOverrideVec,
    ComponentFieldOverrideVecDestructor
);
/// How a field value is sourced at the instance level.
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C, u8)]
pub enum ComponentFieldValueSource {
    /// Use the component's default value
    Default,
    /// Hardcoded literal value (as string, parsed at runtime)
    Literal(AzString),
    /// Bound to an app state path (e.g. "`app_state.user.name`")
    Binding(AzString),
}
#[allow(variant_size_differences)]
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
// disparity accepted
/// Runtime value for a component field — the "instance" counterpart
/// to `ComponentFieldType` (which is the "class" / type descriptor).
#[derive(Debug, Clone, PartialEq)]
#[repr(C, u8)]
#[allow(clippy::large_enum_variant)] // #[repr(C,u8)] FFI enum: boxing a variant changes the C
                                     // ABI/api.json
pub enum ComponentFieldValue {
    String(AzString),
    Bool(bool),
    I32(i32),
    I64(i64),
    U32(u32),
    U64(u64),
    Usize(usize),
    F32(f32),
    F64(f64),
    ColorU(ColorU),
    /// Option<T> with no value
    None,
    /// Option<T> with a value
    Some(ComponentFieldValueBox),
    /// Vec of values
    Vec(ComponentFieldValueVec),
    /// `StyledDom` slot content
    StyledDom(StyledDom),
    /// Struct fields, in order
    Struct(ComponentFieldNamedValueVec),
    /// Enum variant
    Enum {
        variant: AzString,
        fields: ComponentFieldNamedValueVec,
    },
    /// Callback function reference (function name as string)
    Callback(AzString),
    /// Opaque reference-counted data
    RefAny(crate::refany::RefAny),
}
/// Named field value: (`field_name`, value) pair.
#[derive(Debug, Clone, PartialEq)]
#[repr(C)]
pub struct ComponentFieldNamedValue {
    pub name: AzString,
    pub value: ComponentFieldValue,
}
impl_vec!(
    ComponentFieldNamedValue,
    ComponentFieldNamedValueVec,
    ComponentFieldNamedValueVecDestructor,
    ComponentFieldNamedValueVecDestructorType,
    ComponentFieldNamedValueVecSlice,
    OptionComponentFieldNamedValue
);
impl_option!(
    ComponentFieldNamedValue,
    OptionComponentFieldNamedValue,
    copy = false,
    [Debug, Clone, PartialEq]
);
impl_vec_debug!(ComponentFieldNamedValue, ComponentFieldNamedValueVec);
impl_vec_partialeq!(ComponentFieldNamedValue, ComponentFieldNamedValueVec);
impl_vec_clone!(
    ComponentFieldNamedValue,
    ComponentFieldNamedValueVec,
    ComponentFieldNamedValueVecDestructor
);
impl ComponentFieldNamedValueVec {
    /// Look up a field by name, return a reference to its value.
    #[must_use]
20
    pub fn get_field(&self, name: &str) -> Option<&ComponentFieldValue> {
54
        self.as_ref().iter().find_map(|v| {
54
            if v.name.as_str() == name {
11
                Some(&v.value)
            } else {
43
                None
            }
54
        })
20
    }
    /// Convenience: get a field as `&str` if it is `ComponentFieldValue::String`.
    #[must_use]
5
    pub fn get_string(&self, name: &str) -> Option<&AzString> {
5
        match self.get_field(name) {
1
            Some(ComponentFieldValue::String(s)) => Some(s),
4
            _ => None,
        }
5
    }
}
impl_vec!(
    ComponentFieldValue,
    ComponentFieldValueVec,
    ComponentFieldValueVecDestructor,
    ComponentFieldValueVecDestructorType,
    ComponentFieldValueVecSlice,
    OptionComponentFieldValue
);
impl_option!(
    ComponentFieldValue,
    OptionComponentFieldValue,
    copy = false,
    [Debug, Clone, PartialEq]
);
impl_vec_debug!(ComponentFieldValue, ComponentFieldValueVec);
impl_vec_partialeq!(ComponentFieldValue, ComponentFieldValueVec);
impl_vec_clone!(
    ComponentFieldValue,
    ComponentFieldValueVec,
    ComponentFieldValueVecDestructor
);
/// A field in the component's internal data model.
#[derive(Debug, Clone, PartialEq)]
#[repr(C)]
pub struct ComponentDataField {
    /// Field name, e.g. "counter", "text", "number"
    pub name: AzString,
    /// Rich type descriptor for this field
    pub field_type: ComponentFieldType,
    /// Typed default value, or None if the field is required
    pub default_value: OptionComponentDefaultValue,
    /// Whether this field is required (must be provided by the parent)
    pub required: bool,
    /// Human-readable description
    pub description: AzString,
}
impl_vec!(
    ComponentDataField,
    ComponentDataFieldVec,
    ComponentDataFieldVecDestructor,
    ComponentDataFieldVecDestructorType,
    ComponentDataFieldVecSlice,
    OptionComponentDataField
);
impl_option!(
    ComponentDataField,
    OptionComponentDataField,
    copy = false,
    [Debug, Clone, PartialEq]
);
impl_vec_debug!(ComponentDataField, ComponentDataFieldVec);
impl_vec_partialeq!(ComponentDataField, ComponentDataFieldVec);
impl_vec_clone!(
    ComponentDataField,
    ComponentDataFieldVec,
    ComponentDataFieldVecDestructor
);
/// A named data model (struct definition) for code generation.
///
/// Stored in `ComponentLibrary::data_models`. Components reference these
/// by name in `ComponentDataField::field_type`, enabling nested/structured
/// data models. For example, a `UserCard` component might have a field
/// `user: UserProfile` where `UserProfile` is a `ComponentDataModel`.
#[derive(Debug, Clone)]
#[repr(C)]
pub struct ComponentDataModel {
    /// Type name, e.g. "`UserProfile`", "`TodoItem`"
    pub name: AzString,
    /// Human-readable description
    pub description: AzString,
    /// Fields in this struct
    pub fields: ComponentDataFieldVec,
}
impl ComponentDataModel {
    /// Look up a field by name.
    #[must_use]
44
    pub fn get_field(&self, name: &str) -> Option<&ComponentDataField> {
44
        self.fields
44
            .as_ref()
44
            .iter()
64
            .find(|f| f.name.as_str() == name)
44
    }
    /// Look up a field's default value as a string, if it exists and is a String variant.
    #[must_use]
26
    pub fn get_default_string(&self, name: &str) -> Option<&AzString> {
26
        self.get_field(name).and_then(|f| match &f.default_value {
12
            OptionComponentDefaultValue::Some(ComponentDefaultValue::String(s)) => Some(s),
3
            _ => None,
15
        })
26
    }
    /// Clone this data model, overriding the default value for a field by name.
    /// If the field is not found, the data model is returned unchanged.
    #[must_use]
13
    pub fn with_default(mut self, name: &str, value: ComponentDefaultValue) -> Self {
13
        let mut fields_vec = core::mem::replace(
13
            &mut self.fields,
13
            ComponentDataFieldVec::from_const_slice(&[]),
        )
13
        .into_library_owned_vec();
26
        for f in &mut fields_vec {
23
            if f.name.as_str() == name {
10
                f.default_value = OptionComponentDefaultValue::Some(value);
10
                break;
13
            }
        }
13
        self.fields = ComponentDataFieldVec::from_vec(fields_vec);
13
        self
13
    }
}
impl_vec!(
    ComponentDataModel,
    ComponentDataModelVec,
    ComponentDataModelVecDestructor,
    ComponentDataModelVecDestructorType,
    ComponentDataModelVecSlice,
    OptionComponentDataModel
);
impl_option!(
    ComponentDataModel,
    OptionComponentDataModel,
    copy = false,
    [Debug, Clone]
);
impl_vec_debug!(ComponentDataModel, ComponentDataModelVec);
impl_vec_clone!(
    ComponentDataModel,
    ComponentDataModelVec,
    ComponentDataModelVecDestructor
);
impl_vec_mut!(ComponentDataModel, ComponentDataModelVec);
// ============================================================================
// Serde support for ComponentDataModel (feature-gated)
// ============================================================================
#[cfg(feature = "serde-json")]
mod serde_impl {
    use serde::{ser::SerializeStruct, Deserialize, Deserializer, Serialize, Serializer};
    #[allow(clippy::wildcard_imports)] // serde impl module mirrors the parent surface
    use super::*;
    // --- AzString helpers ---
    fn ser_azstring<S: Serializer>(s: &AzString, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(s.as_str())
    }
    fn de_azstring<'de, D: Deserializer<'de>>(deserializer: D) -> Result<AzString, D::Error> {
        let s = String::deserialize(deserializer)?;
        Ok(AzString::from(s.as_str()))
    }
    // --- ComponentFieldType ---
    impl Serialize for ComponentFieldType {
3
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
3
            serializer.serialize_str(&field_type_to_string(self))
3
        }
    }
    impl<'de> Deserialize<'de> for ComponentFieldType {
3
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
3
            let s = String::deserialize(deserializer)?;
3
            Ok(string_to_field_type(&s))
3
        }
    }
3
    fn field_type_to_string(ft: &ComponentFieldType) -> String {
3
        match ft {
2
            ComponentFieldType::String => "String".into(),
            ComponentFieldType::Bool => "bool".into(),
            ComponentFieldType::I32 => "i32".into(),
            ComponentFieldType::I64 => "i64".into(),
1
            ComponentFieldType::U32 => "u32".into(),
            ComponentFieldType::U64 => "u64".into(),
            ComponentFieldType::Usize => "usize".into(),
            ComponentFieldType::F32 => "f32".into(),
            ComponentFieldType::F64 => "f64".into(),
            ComponentFieldType::ColorU => "ColorU".into(),
            ComponentFieldType::CssProperty => "CssProperty".into(),
            ComponentFieldType::ImageRef => "ImageRef".into(),
            ComponentFieldType::FontRef => "FontRef".into(),
            ComponentFieldType::StyledDom => "Dom".into(),
            ComponentFieldType::Callback(sig) => {
                alloc::format!("Callback({})", sig.return_type.as_str())
            }
            ComponentFieldType::RefAny(hint) => alloc::format!("RefAny({})", hint.as_str()),
            ComponentFieldType::OptionType(inner) => {
                alloc::format!("Option<{}>", field_type_to_string(inner.as_ref()))
            }
            ComponentFieldType::VecType(inner) => {
                alloc::format!("Vec<{}>", field_type_to_string(inner.as_ref()))
            }
            ComponentFieldType::StructRef(name) => alloc::format!("struct:{}", name.as_str()),
            ComponentFieldType::EnumRef(name) => alloc::format!("enum:{}", name.as_str()),
        }
3
    }
    // A 5-arm strip_prefix dispatch ladder. `option_if_let_else` (nursery)
    // wants `map_or_else` here, which would nest five closures inside each
    // other's else-branch — strictly less readable than the ladder.
    #[allow(clippy::option_if_let_else)]
3
    fn string_to_field_type(s: &str) -> ComponentFieldType {
3
        match s {
3
            "String" | "string" => ComponentFieldType::String,
1
            "bool" | "Bool" => ComponentFieldType::Bool,
1
            "i32" | "I32" => ComponentFieldType::I32,
1
            "i64" | "I64" => ComponentFieldType::I64,
1
            "u32" | "U32" => ComponentFieldType::U32,
            "u64" | "U64" => ComponentFieldType::U64,
            "usize" | "Usize" => ComponentFieldType::Usize,
            "f32" | "F32" => ComponentFieldType::F32,
            "f64" | "F64" => ComponentFieldType::F64,
            "ColorU" | "Color" | "color" => ComponentFieldType::ColorU,
            "CssProperty" => ComponentFieldType::CssProperty,
            "ImageRef" | "Image" => ComponentFieldType::ImageRef,
            "FontRef" | "Font" => ComponentFieldType::FontRef,
            "Dom" | "StyledDom" | "Children" => ComponentFieldType::StyledDom,
            other => {
                if let Some(inner) = other
                    .strip_prefix("Option<")
                    .and_then(|s| s.strip_suffix('>'))
                {
                    ComponentFieldType::OptionType(ComponentFieldTypeBox::new(
                        string_to_field_type(inner),
                    ))
                } else if let Some(inner) =
                    other.strip_prefix("Vec<").and_then(|s| s.strip_suffix('>'))
                {
                    ComponentFieldType::VecType(ComponentFieldTypeBox::new(string_to_field_type(
                        inner,
                    )))
                } else if let Some(name) = other.strip_prefix("struct:") {
                    ComponentFieldType::StructRef(AzString::from(name))
                } else if let Some(name) = other.strip_prefix("enum:") {
                    ComponentFieldType::EnumRef(AzString::from(name))
                } else if other.starts_with("Callback") {
                    let ret = other
                        .strip_prefix("Callback(")
                        .and_then(|s| s.strip_suffix(')'))
                        .unwrap_or("()");
                    ComponentFieldType::Callback(ComponentCallbackSignature {
                        return_type: AzString::from(ret),
                        args: ComponentCallbackArgVec::from_const_slice(&[]),
                    })
                } else if other.starts_with("RefAny") {
                    let hint = other
                        .strip_prefix("RefAny(")
                        .and_then(|s| s.strip_suffix(')'))
                        .unwrap_or("");
                    ComponentFieldType::RefAny(AzString::from(hint))
                } else {
                    ComponentFieldType::String // fallback
                }
            }
        }
3
    }
    // --- ComponentDefaultValue ---
    impl Serialize for ComponentDefaultValue {
2
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            use serde::ser::SerializeMap;
2
            match self {
                Self::None => serializer.serialize_none(),
1
                Self::String(s) => serializer.serialize_str(s.as_str()),
                Self::Bool(b) => serializer.serialize_bool(*b),
                Self::I32(v) => serializer.serialize_i32(*v),
                Self::I64(v) => serializer.serialize_i64(*v),
1
                Self::U32(v) => serializer.serialize_u32(*v),
                Self::U64(v) => serializer.serialize_u64(*v),
                Self::Usize(v) => serializer.serialize_u64(*v as u64),
                Self::F32(v) => serializer.serialize_f32(*v),
                Self::F64(v) => serializer.serialize_f64(*v),
                Self::ColorU(c) => serializer.serialize_str(&alloc::format!(
                    "#{:02x}{:02x}{:02x}{:02x}",
                    c.r,
                    c.g,
                    c.b,
                    c.a
                )),
                Self::ComponentInstance(ci) => {
                    let mut map = serializer.serialize_map(Some(2))?;
                    map.serialize_entry("library", ci.library.as_str())?;
                    map.serialize_entry("component", ci.component.as_str())?;
                    map.end()
                }
                Self::CallbackFnPointer(name) => serializer.serialize_str(name.as_str()),
                Self::Json(json_str) => {
                    // Serialize raw JSON string as-is by parsing and re-emitting
                    match serde_json::from_str::<serde_json::Value>(json_str.as_str()) {
                        Ok(v) => v.serialize(serializer),
                        Err(_) => serializer.serialize_str(json_str.as_str()),
                    }
                }
            }
2
        }
    }
    impl<'de> Deserialize<'de> for ComponentDefaultValue {
2
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2
            let val = serde_json::Value::deserialize(deserializer)?;
            // NOTE: `Value::Null` is deliberately NOT its own arm — it maps to
            // `Self::None`, which is exactly what the catch-all below produces.
2
            Ok(match val {
                serde_json::Value::Bool(b) => Self::Bool(b),
1
                serde_json::Value::Number(n) => n.as_i64().map_or_else(
                    || n.as_f64().map_or(Self::None, Self::F64),
1
                    |i| i32::try_from(i).map_or(Self::I64(i), Self::I32),
                ),
1
                serde_json::Value::String(s) => Self::String(AzString::from(s.as_str())),
                _ => Self::None,
            })
2
        }
    }
    // --- OptionComponentDefaultValue ---
    impl Serialize for OptionComponentDefaultValue {
3
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
3
            match self {
2
                Self::Some(v) => v.serialize(serializer),
1
                Self::None => serializer.serialize_none(),
            }
3
        }
    }
    impl<'de> Deserialize<'de> for OptionComponentDefaultValue {
3
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
3
            let val = Option::<ComponentDefaultValue>::deserialize(deserializer)?;
3
            Ok(val.map_or(Self::None, Self::Some))
3
        }
    }
    // --- ComponentDataField ---
    impl Serialize for ComponentDataField {
3
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
3
            let mut s = serializer.serialize_struct("ComponentDataField", 5)?;
3
            s.serialize_field("name", self.name.as_str())?;
3
            s.serialize_field("type", &self.field_type)?;
3
            s.serialize_field("default", &self.default_value)?;
3
            s.serialize_field("required", &self.required)?;
3
            s.serialize_field("description", self.description.as_str())?;
3
            s.end()
3
        }
    }
    impl<'de> Deserialize<'de> for ComponentDataField {
3
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            #[derive(Deserialize)]
            struct Helper {
                name: String,
                #[serde(rename = "type", default = "default_type")]
                field_type: ComponentFieldType,
                #[serde(default)]
                default: OptionComponentDefaultValue,
                #[serde(default)]
                required: bool,
                #[serde(default)]
                description: String,
            }
            const fn default_type() -> ComponentFieldType {
                ComponentFieldType::String
            }
3
            let h = Helper::deserialize(deserializer)?;
3
            Ok(Self {
3
                name: AzString::from(h.name.as_str()),
3
                field_type: h.field_type,
3
                default_value: h.default,
3
                required: h.required,
3
                description: AzString::from(h.description.as_str()),
3
            })
3
        }
    }
    // --- ComponentDataModel ---
    impl Serialize for ComponentDataModel {
2
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2
            let mut s = serializer.serialize_struct("ComponentDataModel", 3)?;
2
            s.serialize_field("name", self.name.as_str())?;
2
            s.serialize_field("description", self.description.as_str())?;
2
            let fields: Vec<&ComponentDataField> = self.fields.as_ref().iter().collect();
2
            s.serialize_field("fields", &fields)?;
2
            s.end()
2
        }
    }
    impl<'de> Deserialize<'de> for ComponentDataModel {
        /// A data model is a JSON **object**. This deliberately drives the
        /// deserializer with `deserialize_map` instead of `deserialize_struct`:
        /// the struct hint makes serde accept a *sequence* as well (the
        /// positional encoding used by compact formats), so `from_json("[]")`
        /// used to succeed and hand back a nameless, field-less model instead of
        /// reporting that the input is not a data model at all. Every key stays
        /// optional, so `{}` still deserializes to the empty model.
15
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            use serde::de::{IgnoredAny, MapAccess, Visitor};
            struct ModelVisitor;
            impl<'de> Visitor<'de> for ModelVisitor {
                type Value = ComponentDataModel;
6
                fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6
                    f.write_str("a data model object with `name`, `description` and `fields`")
6
                }
3
                fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
3
                    let mut name: Option<String> = None;
3
                    let mut description: Option<String> = None;
3
                    let mut fields: Option<Vec<ComponentDataField>> = None;
9
                    while let Some(key) = map.next_key::<String>()? {
6
                        match key.as_str() {
6
                            "name" => name = Some(map.next_value()?),
4
                            "description" => description = Some(map.next_value()?),
2
                            "fields" => fields = Some(map.next_value()?),
                            // Unknown keys are ignored (forward compatibility),
                            // but their values must still be consumed.
                            _ => {
                                map.next_value::<IgnoredAny>()?;
                            }
                        }
                    }
2
                    Ok(ComponentDataModel {
2
                        name: AzString::from(name.unwrap_or_default().as_str()),
2
                        description: AzString::from(description.unwrap_or_default().as_str()),
2
                        fields: ComponentDataFieldVec::from_vec(fields.unwrap_or_default()),
2
                    })
3
                }
            }
15
            deserializer.deserialize_map(ModelVisitor)
15
        }
    }
}
// NOTE: no `pub use serde_impl::*` — the module holds only private helpers and
// trait impls, and trait impls are in scope crate-wide (and for downstream
// users) regardless of the defining module's visibility.
#[cfg(feature = "serde-json")]
impl ComponentDataModel {
    /// Serialize this data model to a JSON string.
    ///
    /// # Errors
    ///
    /// Returns the serializer's error message if the model cannot be
    /// represented as JSON.
2
    pub fn to_json(&self) -> Result<String, String> {
2
        serde_json::to_string_pretty(self).map_err(|e| alloc::format!("{e}"))
2
    }
    /// Deserialize a data model from a JSON string.
    ///
    /// # Errors
    ///
    /// Returns the parser's error message if `json` is malformed or does not
    /// match the data-model shape.
15
    pub fn from_json(json: &str) -> Result<Self, String> {
15
        serde_json::from_str(json).map_err(|e| alloc::format!("{e}"))
15
    }
}
/// Source of a component definition — determines whether it can be exported
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
#[derive(Default)]
pub enum ComponentSource {
    /// Built into the DLL (HTML elements). Never exported.
    Builtin,
    /// Compiled Rust widget (Button, `TextInput`, etc.). Never exported.
    Compiled,
    /// Defined via JSON/XML at runtime. Can be exported.
    #[default]
    UserDefined,
}
impl ComponentSource {
    #[must_use]
1
    pub fn create() -> Self {
1
        Self::default()
1
    }
}
/// The target language for code compilation
// Threaded by reference through the codegen call graph; kept non-Copy so
// deriving Copy doesn't force trivially_copy_pass_by_ref churn across the many
// &CompileTarget codegen callers for a perf-neutral change.
#[allow(missing_copy_implementations)]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub enum CompileTarget {
    Rust,
    C,
    Cpp,
    Python,
}
impl_result!(
    StyledDom,
    RenderDomError,
    ResultStyledDomRenderDomError,
    copy = false,
    [Debug, Clone, PartialEq]
);
impl_result!(
    AzString,
    CompileError,
    ResultStringCompileError,
    copy = false,
    [Debug, Clone, PartialEq]
);
/// Render function type: takes component definition + data model (with current values
/// in `default_value` fields) + component map for recursive sub-component instantiation,
/// returns `StyledDom`.
///
/// The `data` parameter is typically `def.data_model` cloned and with caller-provided
/// values substituted into the `default_value` fields.
pub type ComponentRenderFn =
    fn(&ComponentDef, &ComponentDataModel, &ComponentMap) -> ResultStyledDomRenderDomError;
/// Compile function type: takes component definition + target language + data model, returns source
/// code.
pub type ComponentCompileFn = fn(
    &ComponentDef,
    &CompileTarget,
    &ComponentDataModel,
    indent: usize,
) -> ResultStringCompileError;
/// Raw function pointer type that returns a single `ComponentDef` when called.
/// Used as the `cb` field in `RegisterComponentFn`.
pub type RegisterComponentFnType = extern "C" fn() -> ComponentDef;
/// Callback struct for registering individual components at startup.
///
/// In C: pass a bare `extern "C" fn() -> ComponentDef` function pointer —
/// it converts automatically via `From<RegisterComponentFnType>`.
///
/// In Python: construct this struct with `cb` set to a trampoline and
/// `ctx` set to `Some(RefAny(...))` wrapping the Python callable.
#[repr(C)]
pub struct RegisterComponentFn {
    pub cb: RegisterComponentFnType,
    /// For FFI: stores the foreign callable (e.g., `PyFunction`).
    /// Native Rust/C code sets this to None.
    pub ctx: crate::refany::OptionRefAny,
}
impl_callback!(RegisterComponentFn, RegisterComponentFnType);
/// Raw function pointer type that returns a complete `ComponentLibrary` when called.
/// Used as the `cb` field in `RegisterComponentLibraryFn`.
pub type RegisterComponentLibraryFnType = extern "C" fn() -> ComponentLibrary;
/// Callback struct for registering entire component libraries at startup.
///
/// In C: pass a bare `extern "C" fn() -> ComponentLibrary` function pointer —
/// it converts automatically via `From<RegisterComponentLibraryFnType>`.
///
/// In Python: construct this struct with `cb` set to a trampoline and
/// `ctx` set to `Some(RefAny(...))` wrapping the Python callable.
#[repr(C)]
pub struct RegisterComponentLibraryFn {
    pub cb: RegisterComponentLibraryFnType,
    /// For FFI: stores the foreign callable (e.g., `PyFunction`).
    /// Native Rust/C code sets this to None.
    pub ctx: crate::refany::OptionRefAny,
}
impl_callback!(RegisterComponentLibraryFn, RegisterComponentLibraryFnType);
/// A component definition — the "class" / "template" of a component.
/// Can come from Rust builtins, compiled widgets, JSON, or user creation in debugger.
#[derive(Clone)]
#[repr(C)]
pub struct ComponentDef {
    /// Collection + name, e.g. builtin:div, shadcn:avatar
    pub id: ComponentId,
    /// Human-readable display name, e.g. "Link" for builtin:a, "Avatar" for shadcn:avatar
    pub display_name: AzString,
    /// Markdown documentation for the component
    pub description: AzString,
    /// The component's CSS
    pub css: AzString,
    /// Where this component was defined (determines exportability)
    pub source: ComponentSource,
    /// Unified data model: all value fields, callback slots, and child slots
    /// in a single named struct. Code gen uses `data_model.name` as the
    /// input struct type name (e.g. "`ButtonData`").
    /// The `default_value` on each field doubles as the "current value" for
    /// preview rendering — callers override defaults before calling `render_fn`.
    pub data_model: ComponentDataModel,
    /// Render to live DOM
    pub render_fn: ComponentRenderFn,
    /// Compile to source code in target language
    pub compile_fn: ComponentCompileFn,
    /// Source code for `render_fn` (user-defined components only)
    pub render_fn_source: OptionString,
    /// Source code for `compile_fn` (user-defined components only)
    pub compile_fn_source: OptionString,
}
impl fmt::Debug for ComponentDef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ComponentDef")
            .field("id", &self.id)
            .field("display_name", &self.display_name)
            .field("source", &self.source)
            .field("data_model", &self.data_model.name)
            .finish_non_exhaustive()
    }
}
impl_vec!(
    ComponentDef,
    ComponentDefVec,
    ComponentDefVecDestructor,
    ComponentDefVecDestructorType,
    ComponentDefVecSlice,
    OptionComponentDef
);
impl_option!(ComponentDef, OptionComponentDef, copy = false, [Clone]);
impl_vec_debug!(ComponentDef, ComponentDefVec);
impl_vec_clone!(ComponentDef, ComponentDefVec, ComponentDefVecDestructor);
impl_vec_mut!(ComponentDef, ComponentDefVec);
/// A named collection of component definitions
#[derive(Debug, Clone)]
#[repr(C)]
pub struct ComponentLibrary {
    /// Library identifier, e.g. "builtin", "shadcn", "myproject"
    pub name: AzString,
    /// Version string
    pub version: AzString,
    /// Human-readable description
    pub description: AzString,
    /// The components in this library
    pub components: ComponentDefVec,
    /// Whether this library can be exported (false for builtin/compiled)
    pub exportable: bool,
    /// Whether this library can be modified by the user (add/remove/edit components).
    /// False for builtin and compiled libraries. True for user-created libraries.
    pub modifiable: bool,
    /// Named data model types defined by this library.
    /// Components reference these by name in their `field_type`.
    pub data_models: ComponentDataModelVec,
    /// Named enum types defined by this library.
    /// Components reference these via `ComponentFieldType::EnumRef(name)`.
    pub enum_models: ComponentEnumModelVec,
}
impl_vec!(
    ComponentLibrary,
    ComponentLibraryVec,
    ComponentLibraryVecDestructor,
    ComponentLibraryVecDestructorType,
    ComponentLibraryVecSlice,
    OptionComponentLibrary
);
impl_option!(
    ComponentLibrary,
    OptionComponentLibrary,
    copy = false,
    [Debug, Clone]
);
impl_vec_debug!(ComponentLibrary, ComponentLibraryVec);
impl_vec_clone!(
    ComponentLibrary,
    ComponentLibraryVec,
    ComponentLibraryVecDestructor
);
impl_vec_mut!(ComponentLibrary, ComponentLibraryVec);
/// The component map — holds libraries with namespaced components.
#[derive(Debug, Clone)]
#[repr(C)]
pub struct ComponentMap {
    /// Libraries indexed by name. "builtin" is always present.
    pub libraries: ComponentLibraryVec,
}
impl ComponentMap {
    /// Qualified lookup: "shadcn:avatar" -> finds library "shadcn", component "avatar"
    #[must_use]
38
    pub fn get(&self, collection: &str, name: &str) -> Option<&ComponentDef> {
38
        self.libraries
38
            .iter()
38
            .find(|lib| lib.name.as_str() == collection)
1935
            .and_then(|lib| lib.components.iter().find(|c| c.id.name.as_str() == name))
38
    }
    /// Unqualified lookup: "div" -> searches ONLY the "builtin" library.
    #[must_use]
13
    pub fn get_unqualified(&self, name: &str) -> Option<&ComponentDef> {
13
        self.get("builtin", name)
13
    }
    /// Parse a "collection:name" string into a lookup
    #[must_use]
11
    pub fn get_by_qualified_name(&self, qualified: &str) -> Option<&ComponentDef> {
11
        if let Some((collection, name)) = qualified.split_once(':') {
7
            self.get(collection, name)
        } else {
4
            self.get_unqualified(qualified)
        }
11
    }
    /// Get all libraries that can be exported (user-defined only)
    #[must_use]
3
    pub fn get_exportable_libraries(&self) -> Vec<&ComponentLibrary> {
3
        self.libraries.iter().filter(|lib| lib.exportable).collect()
3
    }
    /// Get all component definitions across all libraries
    #[must_use]
5
    pub fn all_components(&self) -> Vec<&ComponentDef> {
5
        self.libraries
5
            .iter()
5
            .flat_map(|lib| lib.components.iter())
5
            .collect()
5
    }
}
// ============================================================================
// Builtin component bridge — wraps existing render/compile into ComponentDef
// ============================================================================
/// Single source of truth mapping HTML/SVG tag names to node variants.
///
/// Each `"tag" => Variant` entry expands to **both** a `NodeType::Variant` arm in
/// [`tag_to_node_type`] and a `NodeTypeTag::Variant` arm in [`tag_to_node_type_tag`],
/// so the two lookups can never drift apart. Tags whose two enums diverge —
/// `img`, `image`, `icon` — are handled as explicit special cases inside each
/// generated function and are intentionally absent from this table.
macro_rules! html_tag_node_types {
    ($($tag:literal => $variant:ident),* $(,)?) => {
        /// Map a builtin tag name to its corresponding `NodeType`.
        /// Falls back to `NodeType::Div` for unknown tags.
170249
        #[must_use] pub fn tag_to_node_type(tag: &str) -> NodeType {
170249
            match tag {
                // `<img>` becomes a replaced `NodeType::Image`. The `src` attribute is not
                // available here, so a placeholder `NullImage` (0x0, empty tag) is created;
                // `xml_node_to_dom_fast` overrides it with a `NullImage` whose `tag` carries
                // the `src` bytes so a renderer (e.g. printpdf) can resolve the actual image.
170249
                "img" => NodeType::Image(azul_css::css::BoxOrStatic::heap(
5
                    crate::resources::ImageRef::null_image(
5
                        0,
5
                        0,
5
                        crate::resources::RawImageFormat::RGBA8,
5
                        alloc::vec::Vec::new(),
5
                    ),
5
                )),
                // `<icon>content_copy</icon>` becomes an un-named `NodeType::Icon`;
                // the icon SPEC is its text content, consumed by the icon
                // resolution pass (`resolve_icons_in_styled_dom`) against the
                // registered icon packs — exactly like a ligature icon font
                // turns glyph text into an icon. The builders stay generic.
170244
                "icon" => NodeType::Icon(azul_css::css::BoxOrStatic::heap(
49
                    azul_css::AzString::from_const_str(""),
49
                )),
                // `<transient-window>` starts CLOSED with every default; the
                // parser applies `open=` / `anchor=` / `dismiss=` / `size=` /
                // `tearoff=` onto this config afterwards (see
                // `apply_transient_window_attrs`). Carrying the config inline is
                // what lets a closed popup cost nothing.
170195
                "transient-window" => NodeType::TransientWindow(
24
                    crate::transient::TransientWindowConfig::closed(),
24
                ),
                $($tag => NodeType::$variant,)*
                _ => NodeType::Div,
            }
170249
        }
        /// Map a tag name to its CSS `NodeTypeTag` for CSS matching in the compile pipeline.
        /// Falls back to `NodeTypeTag::Div` for unknown tags.
6
        fn tag_to_node_type_tag(tag: &str) -> NodeTypeTag {
6
            match tag {
                // `img`/`image`/`icon` have no 1:1 `NodeType` equivalent (see
                // `tag_to_node_type`), so they map to dedicated `NodeTypeTag` variants.
6
                "img" | "image" => NodeTypeTag::Img,
6
                "icon" => NodeTypeTag::Icon,
6
                "transient-window" => NodeTypeTag::TransientWindow,
                $($tag => NodeTypeTag::$variant,)*
                _ => NodeTypeTag::Div,
            }
6
        }
    };
}
html_tag_node_types! {
    // Document structure
    "html" => Html,
    "head" => Head,
    "title" => Title,
    "body" => Body,
    // Block-level
    "div" => Div,
    "header" => Header,
    "footer" => Footer,
    "section" => Section,
    "article" => Article,
    "aside" => Aside,
    "nav" => Nav,
    "main" => Main,
    "figure" => Figure,
    "figcaption" => FigCaption,
    "address" => Address,
    "details" => Details,
    "summary" => Summary,
    "dialog" => Dialog,
    // Headings
    "h1" => H1,
    "h2" => H2,
    "h3" => H3,
    "h4" => H4,
    "h5" => H5,
    "h6" => H6,
    // Text content
    "p" => P,
    "span" => Span,
    "pre" => Pre,
    "code" => Code,
    "blockquote" => BlockQuote,
    "br" => Br,
    "hr" => Hr,
    "pagebreak" => PageBreak,
    // Lists
    "ul" => Ul,
    "ol" => Ol,
    "li" => Li,
    "dl" => Dl,
    "dt" => Dt,
    "dd" => Dd,
    "menu" => Menu,
    "menuitem" => MenuItem,
    "dir" => Dir,
    // Tables
    "table" => Table,
    "caption" => Caption,
    "thead" => THead,
    "tbody" => TBody,
    "tfoot" => TFoot,
    "tr" => Tr,
    "th" => Th,
    "td" => Td,
    "colgroup" => ColGroup,
    "col" => Col,
    // Forms
    "form" => Form,
    "fieldset" => FieldSet,
    "legend" => Legend,
    "label" => Label,
    "input" => Input,
    "button" => Button,
    "select" => Select,
    "optgroup" => OptGroup,
    "option" => SelectOption,
    "textarea" => TextArea,
    "output" => Output,
    "progress" => Progress,
    "meter" => Meter,
    "datalist" => DataList,
    // Inline
    "a" => A,
    "strong" => Strong,
    "em" => Em,
    "b" => B,
    "i" => I,
    "u" => U,
    "s" => S,
    "small" => Small,
    "mark" => Mark,
    "del" => Del,
    "ins" => Ins,
    "samp" => Samp,
    "kbd" => Kbd,
    "var" => Var,
    "cite" => Cite,
    "dfn" => Dfn,
    "abbr" => Abbr,
    "acronym" => Acronym,
    "q" => Q,
    "time" => Time,
    "sub" => Sub,
    "sup" => Sup,
    "big" => Big,
    "bdo" => Bdo,
    "bdi" => Bdi,
    "wbr" => Wbr,
    "ruby" => Ruby,
    "rt" => Rt,
    "rtc" => Rtc,
    "rp" => Rp,
    "data" => Data,
    // Embedded content (`img` is a special case in the generated fns)
    "canvas" => Canvas,
    "object" => Object,
    "param" => Param,
    "embed" => Embed,
    "audio" => Audio,
    "video" => Video,
    "source" => Source,
    "track" => Track,
    "map" => Map,
    "area" => Area,
    // SVG elements
    "svg" => Svg,
    "g" => SvgG,
    "defs" => SvgDefs,
    "symbol" => SvgSymbol,
    "use" => SvgUse,
    "switch" => SvgSwitch,
    "path" => SvgPath,
    "circle" => SvgCircle,
    "rect" => SvgRect,
    "ellipse" => SvgEllipse,
    "line" => SvgLine,
    "polygon" => SvgPolygon,
    "polyline" => SvgPolyline,
    "tspan" => SvgTspan,
    "textpath" => SvgTextPath,
    "lineargradient" => SvgLinearGradient,
    "radialgradient" => SvgRadialGradient,
    "stop" => SvgStop,
    "pattern" => SvgPattern,
    "clippath" => SvgClipPathElement,
    "mask" => SvgMask,
    "filter" => SvgFilter,
    "feblend" => SvgFeBlend,
    "fecolormatrix" => SvgFeColorMatrix,
    "fecomponenttransfer" => SvgFeComponentTransfer,
    "fecomposite" => SvgFeComposite,
    "feconvolvematrix" => SvgFeConvolveMatrix,
    "fediffuselighting" => SvgFeDiffuseLighting,
    "fedisplacementmap" => SvgFeDisplacementMap,
    "fedistantlight" => SvgFeDistantLight,
    "fedropshadow" => SvgFeDropShadow,
    "feflood" => SvgFeFlood,
    "fefuncr" => SvgFeFuncR,
    "fefuncg" => SvgFeFuncG,
    "fefuncb" => SvgFeFuncB,
    "fefunca" => SvgFeFuncA,
    "fegaussianblur" => SvgFeGaussianBlur,
    "feimage" => SvgFeImage,
    "femerge" => SvgFeMerge,
    "femergenode" => SvgFeMergeNode,
    "femorphology" => SvgFeMorphology,
    "feoffset" => SvgFeOffset,
    "fepointlight" => SvgFePointLight,
    "fespecularlighting" => SvgFeSpecularLighting,
    "fespotlight" => SvgFeSpotLight,
    "fetile" => SvgFeTile,
    "feturbulence" => SvgFeTurbulence,
    "foreignobject" => SvgForeignObject,
    "desc" => SvgDesc,
    "view" => SvgView,
    "animate" => SvgAnimate,
    "animatemotion" => SvgAnimateMotion,
    "animatetransform" => SvgAnimateTransform,
    "set" => SvgSet,
    "mpath" => SvgMpath,
    // Metadata
    "meta" => Meta,
    "link" => Link,
    "script" => Script,
    "style" => Style,
    "base" => Base,
}
/// Default render function for builtin HTML elements.
/// Delegates to creating a DOM node of the appropriate `NodeType`.
2
fn builtin_render_fn(
2
    def: &ComponentDef,
2
    data: &ComponentDataModel,
2
    _component_map: &ComponentMap,
2
) -> ResultStyledDomRenderDomError {
2
    let node_type = tag_to_node_type(def.id.name.as_str());
2
    let mut dom = Dom::create_node(node_type);
2
    if let Some(text_str) = data.get_default_string("text") {
1
        let prepared = prepare_string(text_str);
1
        if !prepared.is_empty() {
1
            dom = dom.with_children(
1
                alloc::vec![Dom::create_text_do_not_use_without_block_level_wrapper(
1
                    prepared
1
                )]
1
                .into(),
1
            );
1
        }
1
    }
2
    let r: Result<StyledDom, RenderDomError> = Ok(StyledDom::create(&mut dom, Css::empty()));
2
    r.into()
2
}
/// Default compile function for builtin HTML elements.
/// Generates `Dom::create_node(NodeType::Div)` style code for the target language.
9
fn builtin_compile_fn(
9
    def: &ComponentDef,
9
    target: &CompileTarget,
9
    data: &ComponentDataModel,
9
    indent: usize,
9
) -> ResultStringCompileError {
9
    let node_type = tag_to_node_type(def.id.name.as_str());
9
    let type_name = format!("{node_type:?}"); // "Div", "Body", "P", etc.
9
    let text = data.get_default_string("text");
9
    let r: Result<AzString, CompileError> = match target {
6
        CompileTarget::Rust => text.map_or_else(
5
            || Ok(format!("Dom::create_node(NodeType::{type_name})").into()),
1
            |text_str| {
1
                Ok(format!(
1
                    "Dom::create_node(NodeType::{}).with_children(vec!\
1
                     [Dom::create_text_do_not_use_without_block_level_wrapper(\"{}\")])",
1
                    type_name,
1
                    text_str.as_str().replace('\\', "\\\\").replace('"', "\\\"")
1
                )
1
                .into())
1
            },
        ),
1
        CompileTarget::C => text.map_or_else(
1
            || Ok(format!("AzDom_create{type_name}()").into()),
            |text_str| {
                Ok(format!(
                    "AzDom_createTextDoNotUseWithoutBlockLevelWrapper(AZ_STR(\"{}\"))",
                    text_str.as_str().replace('\\', "\\\\").replace('"', "\\\"")
                )
                .into())
            },
        ),
1
        CompileTarget::Cpp => Ok(format!("Dom::create_{}()", type_name.to_lowercase()).into()),
1
        CompileTarget::Python => Ok(format!("Dom.create_{}()", type_name.to_lowercase()).into()),
    };
9
    r.into()
9
}
/// Pushes a `<div>` containing `"field_name: value"` text into the children list.
11
fn push_scalar_field(children: &mut Vec<Dom>, field_name: &str, value: &dyn fmt::Display) {
    use crate::dom::{Dom, NodeType};
11
    let text = alloc::format!("{field_name}: {value}");
11
    children.push(
11
        Dom::create_node(NodeType::Div).with_children(
11
            alloc::vec![Dom::create_text_do_not_use_without_block_level_wrapper(
11
                text
            )]
11
            .into(),
        ),
    );
11
}
/// Default render function for user-defined (JSON-imported) components.
///
/// Interprets the `ComponentDef` structure generically:
/// 1. Creates a wrapper `<div>` with the component's CSS class
/// 2. For each data field, renders content based on type:
///    - String fields → text node with current value
///    - Bool fields → conditional display
///    - `StyledDom` fields → embeds the child DOM subtree
///    - StructRef/EnumRef → recursively renders sub-components if found in `ComponentMap`
///    - Other scalar fields → text display of the value
/// 3. Applies the component's scoped CSS
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch (one branch per input variant)
#[must_use]
4
pub fn user_defined_render_fn(
4
    def: &ComponentDef,
4
    data: &ComponentDataModel,
4
    component_map: &ComponentMap,
4
) -> ResultStyledDomRenderDomError {
    use azul_css::css::Css;
    use crate::dom::{Dom, NodeType};
4
    let mut children: Vec<Dom> = Vec::new();
15
    for field in data.fields.as_ref() {
15
        let field_name = field.name.as_str();
        // Get the current value from default_value
15
        match &field.default_value {
1
            OptionComponentDefaultValue::None => {
1
                // Required field with no value — skip in preview
1
            }
14
            OptionComponentDefaultValue::Some(default_val) => {
14
                match default_val {
1
                    ComponentDefaultValue::String(s) => {
1
                        let text = s.as_str().trim();
1
                        if !text.is_empty() {
1
                            let label_dom = Dom::create_node(NodeType::Div).with_children(
1
                                alloc::vec![
1
                                    Dom::create_text_do_not_use_without_block_level_wrapper(
1
                                        text.to_string()
1
                                    )
1
                                ]
1
                                .into(),
1
                            );
1
                            children.push(label_dom);
1
                        }
                    }
1
                    ComponentDefaultValue::Bool(v) => {
1
                        push_scalar_field(&mut children, field_name, v);
1
                    }
1
                    ComponentDefaultValue::I32(v) => {
1
                        push_scalar_field(&mut children, field_name, v);
1
                    }
1
                    ComponentDefaultValue::I64(v) => {
1
                        push_scalar_field(&mut children, field_name, v);
1
                    }
1
                    ComponentDefaultValue::U32(v) => {
1
                        push_scalar_field(&mut children, field_name, v);
1
                    }
1
                    ComponentDefaultValue::U64(v) => {
1
                        push_scalar_field(&mut children, field_name, v);
1
                    }
1
                    ComponentDefaultValue::Usize(v) => {
1
                        push_scalar_field(&mut children, field_name, v);
1
                    }
1
                    ComponentDefaultValue::F32(v) => {
1
                        push_scalar_field(&mut children, field_name, v);
1
                    }
1
                    ComponentDefaultValue::F64(v) => {
1
                        push_scalar_field(&mut children, field_name, v);
1
                    }
1
                    ComponentDefaultValue::ColorU(c) => {
1
                        let text = alloc::format!(
1
                            "{}: #{:02x}{:02x}{:02x}{:02x}",
1
                            field_name,
1
                            c.r,
1
                            c.g,
1
                            c.b,
1
                            c.a
1
                        );
1
                        children.push(
1
                            Dom::create_node(NodeType::Div).with_children(
1
                                alloc::vec![
1
                                    Dom::create_text_do_not_use_without_block_level_wrapper(text)
1
                                ]
1
                                .into(),
1
                            ),
1
                        );
1
                    }
1
                    ComponentDefaultValue::ComponentInstance(ci) => {
                        // Recursively instantiate sub-component from ComponentMap
                        if let Some(sub_comp) =
1
                            component_map.get(ci.library.as_str(), ci.component.as_str())
                        {
                            let sub_data = sub_comp.data_model.clone();
                            match (sub_comp.render_fn)(sub_comp, &sub_data, component_map) {
                                ResultStyledDomRenderDomError::Ok(_styled_dom) => {
                                    // Sub-component rendered successfully — add a placeholder
                                    // (StyledDom cannot be directly converted back to Dom)
                                    let text = alloc::format!(
                                        "[{}:{}]",
                                        ci.library.as_str(),
                                        ci.component.as_str()
                                    );
                                    children.push(
                                        Dom::create_node(NodeType::Div).with_children(
                                            alloc::vec![Dom::create_text_do_not_use_without_block_level_wrapper(text)].into(),
                                        ),
                                    );
                                }
                                ResultStyledDomRenderDomError::Err(_) => {
                                    // On error, show a placeholder
                                    let text = alloc::format!(
                                        "[Error rendering {}:{}]",
                                        ci.library.as_str(),
                                        ci.component.as_str()
                                    );
                                    children.push(
                                        Dom::create_node(NodeType::Div).with_children(
                                            alloc::vec![Dom::create_text_do_not_use_without_block_level_wrapper(text)].into(),
                                        ),
                                    );
                                }
                            }
1
                        } else {
1
                            let text = alloc::format!(
1
                                "[Unknown component {}:{}]",
1
                                ci.library.as_str(),
1
                                ci.component.as_str()
1
                            );
1
                            children.push(
1
                                Dom::create_node(NodeType::Div).with_children(
1
                                    alloc::vec![
1
                                        Dom::create_text_do_not_use_without_block_level_wrapper(
1
                                            text
1
                                        )
1
                                    ]
1
                                    .into(),
1
                                ),
1
                            );
1
                        }
                    }
1
                    ComponentDefaultValue::CallbackFnPointer(name) => {
1
                        // Callbacks are not rendered, just acknowledged
1
                        let text = alloc::format!("{}: fn({})", field_name, name.as_str());
1
                        children.push(
1
                            Dom::create_node(NodeType::Div).with_children(
1
                                alloc::vec![
1
                                    Dom::create_text_do_not_use_without_block_level_wrapper(text)
1
                                ]
1
                                .into(),
1
                            ),
1
                        );
1
                    }
1
                    ComponentDefaultValue::Json(json_str) => {
1
                        let text = alloc::format!("{}: {}", field_name, json_str.as_str());
1
                        children.push(
1
                            Dom::create_node(NodeType::Div).with_children(
1
                                alloc::vec![
1
                                    Dom::create_text_do_not_use_without_block_level_wrapper(text)
1
                                ]
1
                                .into(),
1
                            ),
1
                        );
1
                    }
1
                    ComponentDefaultValue::None => {
1
                        // No default, skip
1
                    }
                }
            }
        }
    }
4
    let mut wrapper = Dom::create_node(NodeType::Div);
4
    if !children.is_empty() {
2
        wrapper = wrapper.with_children(children.into());
2
    }
    // Apply component CSS
4
    let css = if def.css.as_str().is_empty() {
3
        Css::empty()
    } else {
1
        Css::from_string(def.css.clone())
    };
4
    let r: Result<StyledDom, RenderDomError> = Ok(StyledDom::create(&mut wrapper, css));
4
    r.into()
4
}
/// Default compile function for user-defined (JSON-imported) components.
///
/// Generates source code that creates the component's DOM structure for the
/// target language. For each data field, emits the appropriate code:
/// - String fields → text node creation
/// - Scalar fields → formatted display
/// - `ComponentInstance` → function call to sub-component's render function
/// - `StyledDom` slots → child parameter pass-through
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch (one branch per input variant)
#[must_use]
9
pub fn user_defined_compile_fn(
9
    def: &ComponentDef,
9
    target: &CompileTarget,
9
    data: &ComponentDataModel,
9
    indent: usize,
9
) -> ResultStringCompileError {
9
    let tag = def.id.name.as_str();
9
    let indent_str = " ".repeat(indent * 4);
9
    let inner_indent = " ".repeat((indent + 1) * 4);
9
    let r: Result<AzString, CompileError> = match target {
        CompileTarget::Rust => {
6
            let mut lines = Vec::new();
6
            lines.push(alloc::format!("{indent_str}// Component: {tag}"));
6
            lines.push(alloc::format!(
6
                "{indent_str}let mut children: Vec<Dom> = Vec::new();"
            ));
15
            for field in data.fields.as_ref() {
15
                let fname = field.name.as_str();
14
                match &field.default_value {
2
                    OptionComponentDefaultValue::Some(ComponentDefaultValue::String(s)) => {
2
                        let escaped = s.as_str().replace('\\', "\\\\").replace('"', "\\\"");
2
                        lines.push(alloc::format!(
2
                            "{inner_indent}children.\
2
                             push(Dom::create_text_do_not_use_without_block_level_wrapper(\"\
2
                             {escaped}\"));"
2
                        ));
2
                    }
1
                    OptionComponentDefaultValue::Some(ComponentDefaultValue::Bool(b)) => {
1
                        lines.push(alloc::format!(
1
                            "{inner_indent}children.\
1
                             push(Dom::create_text_do_not_use_without_block_level_wrapper(format!\
1
                             (\"{{}}: {{}}\", \"{fname}\", {b}).as_str()));"
1
                        ));
1
                    }
                    OptionComponentDefaultValue::Some(
                        ComponentDefaultValue::ComponentInstance(ci),
                    ) => {
                        let fn_name =
                            alloc::format!("render_{}", ci.component.as_str().replace('-', "_"));
                        lines.push(alloc::format!(
                            "{}children.push({}()); // sub-component {}:{}",
                            inner_indent,
                            fn_name,
                            ci.library.as_str(),
                            ci.component.as_str()
                        ));
                    }
12
                    _ => {
12
                        // For other types, generate a placeholder comment
12
                        lines.push(alloc::format!(
12
                            "{}// field '{}': {:?}",
12
                            inner_indent,
12
                            fname,
12
                            field.field_type
12
                        ));
12
                    }
                }
            }
6
            lines.push(alloc::format!(
6
                "{indent_str}Dom::create_node(NodeType::Div).with_children(children.into())"
            ));
6
            Ok(lines.join("\n").into())
        }
        CompileTarget::C => {
1
            let mut lines = Vec::new();
1
            lines.push(alloc::format!("{indent_str}/* Component: {tag} */"));
1
            lines.push(alloc::format!(
1
                "{indent_str}AzDom root = AzDom_createDiv();"
            ));
14
            for field in data.fields.as_ref() {
14
                let fname = field.name.as_str();
13
                match &field.default_value {
1
                    OptionComponentDefaultValue::Some(ComponentDefaultValue::String(s)) => {
1
                        let escaped = s.as_str().replace('\\', "\\\\").replace('"', "\\\"");
1
                        lines.push(alloc::format!(
1
                            "{inner_indent}AzDom_addChild(&root, \
1
                             AzDom_createTextDoNotUseWithoutBlockLevelWrapper(AZ_STR(\"{escaped}\"\
1
                             )));"
1
                        ));
1
                    }
                    OptionComponentDefaultValue::Some(
                        ComponentDefaultValue::ComponentInstance(ci),
                    ) => {
                        let fn_name =
                            alloc::format!("render_{}", ci.component.as_str().replace('-', "_"));
                        lines.push(alloc::format!(
                            "{inner_indent}AzDom_addChild(&root, {fn_name}());"
                        ));
                    }
13
                    _ => {
13
                        lines.push(alloc::format!("{inner_indent}/* field '{fname}' */"));
13
                    }
                }
            }
1
            lines.push(alloc::format!("{indent_str}return root;"));
1
            Ok(lines.join("\n").into())
        }
        CompileTarget::Cpp => {
1
            let mut lines = Vec::new();
1
            lines.push(alloc::format!("{indent_str}// Component: {tag}"));
1
            lines.push(alloc::format!("{indent_str}auto root = Dom::create_div();"));
14
            for field in data.fields.as_ref() {
14
                let fname = field.name.as_str();
13
                match &field.default_value {
1
                    OptionComponentDefaultValue::Some(ComponentDefaultValue::String(s)) => {
1
                        let escaped = s.as_str().replace('\\', "\\\\").replace('"', "\\\"");
1
                        lines.push(alloc::format!(
1
                            "{inner_indent}root.add_child(Dom::create_text_do_not_use_without_block_level_wrapper(String(\"{escaped}\")));"
1
                        ));
1
                    }
                    OptionComponentDefaultValue::Some(
                        ComponentDefaultValue::ComponentInstance(ci),
                    ) => {
                        let fn_name =
                            alloc::format!("render_{}", ci.component.as_str().replace('-', "_"));
                        lines.push(alloc::format!("{inner_indent}root.add_child({fn_name}());"));
                    }
13
                    _ => {
13
                        lines.push(alloc::format!("{inner_indent}// field '{fname}'"));
13
                    }
                }
            }
1
            lines.push(alloc::format!("{indent_str}return root;"));
1
            Ok(lines.join("\n").into())
        }
        CompileTarget::Python => {
1
            let mut lines = Vec::new();
1
            lines.push(alloc::format!("{indent_str}# Component: {tag}"));
1
            lines.push(alloc::format!("{indent_str}root = Dom.create_div()"));
14
            for field in data.fields.as_ref() {
14
                let fname = field.name.as_str();
13
                match &field.default_value {
1
                    OptionComponentDefaultValue::Some(ComponentDefaultValue::String(s)) => {
1
                        let escaped = s
1
                            .as_str()
1
                            .replace('\\', "\\\\")
1
                            .replace('"', "\\\"")
1
                            .replace('\'', "\\'");
1
                        lines.push(alloc::format!(
1
                            "{inner_indent}root = \
1
                             root.with_child(Dom.\
1
                             create_text_do_not_use_without_block_level_wrapper(\"{escaped}\"))"
1
                        ));
1
                    }
                    OptionComponentDefaultValue::Some(
                        ComponentDefaultValue::ComponentInstance(ci),
                    ) => {
                        let fn_name =
                            alloc::format!("render_{}", ci.component.as_str().replace('-', "_"));
                        lines.push(alloc::format!(
                            "{inner_indent}root = root.with_child({fn_name}())"
                        ));
                    }
13
                    _ => {
13
                        lines.push(alloc::format!("{inner_indent}# field '{fname}'"));
13
                    }
                }
            }
1
            lines.push(alloc::format!("{indent_str}return root"));
1
            Ok(lines.join("\n").into())
        }
    };
9
    r.into()
9
}
/// Create a `ComponentDef` for a builtin HTML element.
///
/// # Arguments
/// * `tag` - HTML tag name (e.g. "button", "div")
/// * `display_name` - Human-readable name (e.g. "Button", "Div")
/// * `default_text` - Default text content for the preview, or `None` if the element has no text.
///   Pass `Some("Button text")` for `<button>`, `Some("")` for text elements like `<span>` that
///   accept text but have no meaningful default.
/// * `css` - Component-level CSS string. For most builtin elements this is `""` because styling
///   comes from `ua_css.rs` and the `SystemStyle`. Components that need extra styling (e.g. a
///   future high-level button widget) can pass CSS here.
398557
fn builtin_component_def(
398557
    tag: &str,
398557
    display_name: &str,
398557
    default_text: Option<&str>,
398557
    css: &str,
398557
) -> ComponentDef {
398557
    let mut fields = builtin_data_model(tag);
    // If a default_text is provided, this element accepts text content
398557
    if let Some(text) = default_text {
208098
        fields.push(data_field(
208098
            "text",
208098
            ComponentFieldType::String,
208098
            Some(ComponentDefaultValue::String(AzString::from(text))),
208098
            "Text content of the element",
208098
        ));
208098
    }
398557
    let model_name = format!("{display_name}Data");
398557
    ComponentDef {
398557
        id: ComponentId::builtin(tag),
398557
        display_name: AzString::from(display_name),
398557
        description: AzString::from(format!("HTML <{tag}> element").as_str()),
398557
        css: AzString::from(css),
398557
        source: ComponentSource::Builtin,
398557
        data_model: ComponentDataModel {
398557
            name: AzString::from(model_name.as_str()),
398557
            description: AzString::from(format!("Data model for <{tag}>").as_str()),
398557
            fields: fields.into(),
398557
        },
398557
        render_fn: builtin_render_fn,
398557
        compile_fn: builtin_compile_fn,
398557
        render_fn_source: None.into(),
398557
        compile_fn_source: None.into(),
398557
    }
398557
}
/// Helper to create a `ComponentDataField` with a rich type
656111
fn data_field(
656111
    name: &str,
656111
    ft: ComponentFieldType,
656111
    default: Option<ComponentDefaultValue>,
656111
    description: &str,
656111
) -> ComponentDataField {
656111
    let required = default.is_none();
    ComponentDataField {
656111
        name: AzString::from(name),
656111
        field_type: ft,
656111
        default_value: default.map_or_else(
            || OptionComponentDefaultValue::None,
            OptionComponentDefaultValue::Some,
        ),
656111
        required,
656111
        description: AzString::from(description),
    }
656111
}
/// Returns the tag-specific data model fields for builtin HTML elements.
/// These are the component's "main data model" — the attributes that define
/// what the component needs as configuration (e.g., `href` for `<a>`,
/// `src` for `<img>`). Universal HTML attributes (id, class, style, etc.)
/// are NOT included here — they are added separately by the debug server.
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch (one
                                 // branch per input variant)
398564
fn builtin_data_model(tag: &str) -> Vec<ComponentDataField> {
    use ComponentDefaultValue as D;
    use ComponentFieldType::{Bool, String, I32};
398564
    match tag {
398564
        "a" => alloc::vec![
3531
            data_field(
3531
                "href",
3531
                String,
3531
                Some(D::String(AzString::from_const_str(""))),
3531
                "URL the link points to"
            ),
3531
            data_field(
3531
                "target",
3531
                String,
3531
                Some(D::String(AzString::from_const_str(""))),
3531
                "Where to open the linked document (_blank, _self, _parent, _top)"
            ),
3531
            data_field(
3531
                "rel",
3531
                String,
3531
                Some(D::String(AzString::from_const_str(""))),
3531
                "Relationship between current and linked document"
            ),
        ],
395033
        "img" | "image" => alloc::vec![
2
            data_field("src", String, None, "URL of the image"),
2
            data_field(
2
                "alt",
2
                String,
2
                Some(D::String(AzString::from_const_str(""))),
2
                "Alternative text for the image"
            ),
2
            data_field(
2
                "width",
2
                String,
2
                Some(D::String(AzString::from_const_str(""))),
2
                "Width of the image"
            ),
2
            data_field(
2
                "height",
2
                String,
2
                Some(D::String(AzString::from_const_str(""))),
2
                "Height of the image"
            ),
        ],
395031
        "form" => alloc::vec![
3527
            data_field(
3527
                "action",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "URL where form data is submitted"
            ),
3527
            data_field(
3527
                "method",
3527
                String,
3527
                Some(D::String(AzString::from_const_str("GET"))),
3527
                "HTTP method for form submission (GET or POST)"
            ),
        ],
391504
        "label" => alloc::vec![data_field(
3527
            "for",
3527
            String,
3527
            Some(D::String(AzString::from_const_str(""))),
3527
            "ID of the form element this label is for"
        ),],
387977
        "button" => alloc::vec![
3527
            data_field(
3527
                "type",
3527
                String,
3527
                Some(D::String(AzString::from_const_str("button"))),
3527
                "Button type (button, submit, reset)"
            ),
3527
            data_field(
3527
                "disabled",
3527
                Bool,
3527
                Some(D::Bool(false)),
3527
                "Whether the button is disabled"
            ),
        ],
384450
        "td" | "th" => alloc::vec![
7054
            data_field(
7054
                "colspan",
7054
                I32,
7054
                Some(D::I32(1)),
7054
                "Number of columns the cell spans"
            ),
7054
            data_field(
7054
                "rowspan",
7054
                I32,
7054
                Some(D::I32(1)),
7054
                "Number of rows the cell spans"
            ),
        ],
377396
        "icon" => alloc::vec![data_field(
3527
            "name",
3527
            String,
3527
            Some(D::String(AzString::from_const_str(""))),
3527
            "Icon name"
        ),],
373869
        "ol" => alloc::vec![
3527
            data_field(
3527
                "start",
3527
                I32,
3527
                Some(D::I32(1)),
3527
                "Start value for the ordered list"
            ),
3527
            data_field(
3527
                "type",
3527
                String,
3527
                Some(D::String(AzString::from_const_str("1"))),
3527
                "Numbering type (1, A, a, I, i)"
            ),
        ],
        // Form controls
370342
        "input" => alloc::vec![
3527
            data_field(
3527
                "type",
3527
                String,
3527
                Some(D::String(AzString::from_const_str("text"))),
3527
                "Input type (text, password, email, number, checkbox, radio, etc.)"
            ),
3527
            data_field(
3527
                "name",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Name of the input for form submission"
            ),
3527
            data_field(
3527
                "value",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Current value of the input"
            ),
3527
            data_field(
3527
                "placeholder",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Placeholder text"
            ),
3527
            data_field(
3527
                "disabled",
3527
                Bool,
3527
                Some(D::Bool(false)),
3527
                "Whether the input is disabled"
            ),
3527
            data_field(
3527
                "required",
3527
                Bool,
3527
                Some(D::Bool(false)),
3527
                "Whether the input is required"
            ),
3527
            data_field(
3527
                "readonly",
3527
                Bool,
3527
                Some(D::Bool(false)),
3527
                "Whether the input is read-only"
            ),
3527
            data_field(
3527
                "checked",
3527
                Bool,
3527
                Some(D::Bool(false)),
3527
                "Whether the checkbox/radio is checked"
            ),
3527
            data_field(
3527
                "min",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Minimum value (for number, range, date)"
            ),
3527
            data_field(
3527
                "max",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Maximum value (for number, range, date)"
            ),
3527
            data_field(
3527
                "step",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Step increment (for number, range)"
            ),
3527
            data_field(
3527
                "pattern",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Regex pattern for validation"
            ),
3527
            data_field(
3527
                "maxlength",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Maximum number of characters"
            ),
        ],
366815
        "select" => alloc::vec![
3527
            data_field(
3527
                "name",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Name for form submission"
            ),
3527
            data_field(
3527
                "multiple",
3527
                Bool,
3527
                Some(D::Bool(false)),
3527
                "Whether multiple options can be selected"
            ),
3527
            data_field(
3527
                "disabled",
3527
                Bool,
3527
                Some(D::Bool(false)),
3527
                "Whether the select is disabled"
            ),
3527
            data_field(
3527
                "required",
3527
                Bool,
3527
                Some(D::Bool(false)),
3527
                "Whether selection is required"
            ),
3527
            data_field(
3527
                "size",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Number of visible options"
            ),
        ],
363288
        "option" => alloc::vec![
3527
            data_field(
3527
                "value",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Value submitted with the form"
            ),
3527
            data_field(
3527
                "selected",
3527
                Bool,
3527
                Some(D::Bool(false)),
3527
                "Whether this option is selected"
            ),
3527
            data_field(
3527
                "disabled",
3527
                Bool,
3527
                Some(D::Bool(false)),
3527
                "Whether this option is disabled"
            ),
        ],
359761
        "optgroup" => alloc::vec![
3527
            data_field(
3527
                "label",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Label for the option group"
            ),
3527
            data_field(
3527
                "disabled",
3527
                Bool,
3527
                Some(D::Bool(false)),
3527
                "Whether the group is disabled"
            ),
        ],
356234
        "textarea" => alloc::vec![
3527
            data_field(
3527
                "name",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Name for form submission"
            ),
3527
            data_field(
3527
                "placeholder",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Placeholder text"
            ),
3527
            data_field("rows", I32, Some(D::I32(2)), "Number of visible text lines"),
3527
            data_field(
3527
                "cols",
3527
                I32,
3527
                Some(D::I32(20)),
3527
                "Visible width in average character widths"
            ),
3527
            data_field(
3527
                "disabled",
3527
                Bool,
3527
                Some(D::Bool(false)),
3527
                "Whether the textarea is disabled"
            ),
3527
            data_field(
3527
                "required",
3527
                Bool,
3527
                Some(D::Bool(false)),
3527
                "Whether content is required"
            ),
3527
            data_field(
3527
                "readonly",
3527
                Bool,
3527
                Some(D::Bool(false)),
3527
                "Whether the textarea is read-only"
            ),
3527
            data_field(
3527
                "maxlength",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Maximum number of characters"
            ),
        ],
352707
        "fieldset" => alloc::vec![data_field(
3527
            "disabled",
3527
            Bool,
3527
            Some(D::Bool(false)),
3527
            "Whether all controls in the fieldset are disabled"
        ),],
349180
        "output" => alloc::vec![
3527
            data_field(
3527
                "for",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "IDs of elements that contributed to the output"
            ),
3527
            data_field(
3527
                "name",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Name for form submission"
            ),
        ],
345653
        "progress" => alloc::vec![
3527
            data_field(
3527
                "value",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Current progress value"
            ),
3527
            data_field(
3527
                "max",
3527
                String,
3527
                Some(D::String(AzString::from_const_str("1"))),
3527
                "Maximum value"
            ),
        ],
342126
        "meter" => alloc::vec![
3527
            data_field(
3527
                "value",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Current value"
            ),
3527
            data_field(
3527
                "min",
3527
                String,
3527
                Some(D::String(AzString::from_const_str("0"))),
3527
                "Minimum value"
            ),
3527
            data_field(
3527
                "max",
3527
                String,
3527
                Some(D::String(AzString::from_const_str("1"))),
3527
                "Maximum value"
            ),
3527
            data_field(
3527
                "low",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Low threshold"
            ),
3527
            data_field(
3527
                "high",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "High threshold"
            ),
3527
            data_field(
3527
                "optimum",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Optimum value"
            ),
        ],
        // Interactive
338599
        "details" => alloc::vec![data_field(
3527
            "open",
3527
            Bool,
3527
            Some(D::Bool(false)),
3527
            "Whether the details are visible"
        ),],
335072
        "dialog" => alloc::vec![data_field(
3527
            "open",
3527
            Bool,
3527
            Some(D::Bool(false)),
3527
            "Whether the dialog is active and can be interacted with"
        ),],
        // Embedded content
331545
        "audio" | "video" => alloc::vec![
7054
            data_field(
7054
                "src",
7054
                String,
7054
                Some(D::String(AzString::from_const_str(""))),
7054
                "URL of the media resource"
            ),
7054
            data_field(
7054
                "controls",
7054
                Bool,
7054
                Some(D::Bool(false)),
7054
                "Whether to show playback controls"
            ),
7054
            data_field(
7054
                "autoplay",
7054
                Bool,
7054
                Some(D::Bool(false)),
7054
                "Whether to start playing automatically"
            ),
7054
            data_field(
7054
                "loop",
7054
                Bool,
7054
                Some(D::Bool(false)),
7054
                "Whether to loop playback"
            ),
7054
            data_field(
7054
                "muted",
7054
                Bool,
7054
                Some(D::Bool(false)),
7054
                "Whether audio is muted"
            ),
7054
            data_field(
7054
                "preload",
7054
                String,
7054
                Some(D::String(AzString::from_const_str("auto"))),
7054
                "Preload hint (none, metadata, auto)"
            ),
        ],
324491
        "source" => alloc::vec![
3527
            data_field("src", String, None, "URL of the media resource"),
3527
            data_field(
3527
                "type",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "MIME type of the resource"
            ),
        ],
320964
        "track" => alloc::vec![
3527
            data_field("src", String, None, "URL of the track file"),
3527
            data_field(
3527
                "kind",
3527
                String,
3527
                Some(D::String(AzString::from_const_str("subtitles"))),
3527
                "Kind of text track (subtitles, captions, descriptions, chapters, metadata)"
            ),
3527
            data_field(
3527
                "srclang",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Language of the track text"
            ),
3527
            data_field(
3527
                "label",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "User-readable title for the track"
            ),
3527
            data_field(
3527
                "default",
3527
                Bool,
3527
                Some(D::Bool(false)),
3527
                "Whether this is the default track"
            ),
        ],
317437
        "canvas" => alloc::vec![
3527
            data_field(
3527
                "width",
3527
                String,
3527
                Some(D::String(AzString::from_const_str("300"))),
3527
                "Width of the canvas in pixels"
            ),
3527
            data_field(
3527
                "height",
3527
                String,
3527
                Some(D::String(AzString::from_const_str("150"))),
3527
                "Height of the canvas in pixels"
            ),
        ],
313910
        "embed" => alloc::vec![
3527
            data_field("src", String, None, "URL of the resource to embed"),
3527
            data_field(
3527
                "type",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "MIME type of the embedded content"
            ),
3527
            data_field(
3527
                "width",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Width"
            ),
3527
            data_field(
3527
                "height",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Height"
            ),
        ],
310383
        "object" => alloc::vec![
3527
            data_field(
3527
                "data",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "URL of the resource"
            ),
3527
            data_field(
3527
                "type",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "MIME type of the resource"
            ),
3527
            data_field(
3527
                "width",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Width"
            ),
3527
            data_field(
3527
                "height",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Height"
            ),
        ],
306856
        "param" => alloc::vec![
3527
            data_field("name", String, None, "Name of the parameter"),
3527
            data_field(
3527
                "value",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Value of the parameter"
            ),
        ],
303329
        "area" => alloc::vec![
3527
            data_field(
3527
                "shape",
3527
                String,
3527
                Some(D::String(AzString::from_const_str("default"))),
3527
                "Shape of the area (default, rect, circle, poly)"
            ),
3527
            data_field(
3527
                "coords",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Coordinates of the area"
            ),
3527
            data_field(
3527
                "href",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "URL for the area link"
            ),
3527
            data_field(
3527
                "alt",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Alternative text"
            ),
3527
            data_field(
3527
                "target",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Where to open the linked document"
            ),
        ],
299802
        "map" => alloc::vec![data_field(
3527
            "name",
3527
            String,
3527
            None,
3527
            "Name of the image map (referenced by usemap)"
        ),],
        // Inline semantics with special attributes
296275
        "time" => alloc::vec![data_field(
3527
            "datetime",
3527
            String,
3527
            Some(D::String(AzString::from_const_str(""))),
3527
            "Machine-readable date/time value"
        ),],
292748
        "data" => alloc::vec![data_field(
3527
            "value",
3527
            String,
3527
            Some(D::String(AzString::from_const_str(""))),
3527
            "Machine-readable value"
        ),],
289221
        "abbr" | "acronym" | "dfn" => alloc::vec![data_field(
10581
            "title",
10581
            String,
10581
            Some(D::String(AzString::from_const_str(""))),
10581
            "Full expansion or definition"
        ),],
278640
        "q" | "blockquote" => alloc::vec![data_field(
7054
            "cite",
7054
            String,
7054
            Some(D::String(AzString::from_const_str(""))),
7054
            "URL of the source of the quotation"
        ),],
271586
        "del" | "ins" => alloc::vec![
7054
            data_field(
7054
                "cite",
7054
                String,
7054
                Some(D::String(AzString::from_const_str(""))),
7054
                "URL explaining the change"
            ),
7054
            data_field(
7054
                "datetime",
7054
                String,
7054
                Some(D::String(AzString::from_const_str(""))),
7054
                "Date/time of the change"
            ),
        ],
264532
        "bdo" => alloc::vec![data_field(
3527
            "dir",
3527
            String,
3527
            Some(D::String(AzString::from_const_str("ltr"))),
3527
            "Text direction (ltr, rtl)"
        ),],
261005
        "col" | "colgroup" => alloc::vec![data_field(
7054
            "span",
7054
            I32,
7054
            Some(D::I32(1)),
7054
            "Number of columns the element spans"
        ),],
        // Metadata
253951
        "meta" => alloc::vec![
3527
            data_field(
3527
                "name",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Metadata name"
            ),
3527
            data_field(
3527
                "content",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Metadata value"
            ),
3527
            data_field(
3527
                "charset",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Character encoding"
            ),
3527
            data_field(
3527
                "http-equiv",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "HTTP header equivalent"
            ),
        ],
250424
        "link" => alloc::vec![
3527
            data_field("rel", String, None, "Relationship type"),
3527
            data_field(
3527
                "href",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "URL of the linked resource"
            ),
3527
            data_field(
3527
                "type",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "MIME type of the linked resource"
            ),
        ],
246897
        "script" => alloc::vec![
3527
            data_field(
3527
                "src",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "URL of external script"
            ),
3527
            data_field(
3527
                "type",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "MIME type or module"
            ),
3527
            data_field(
3527
                "async",
3527
                Bool,
3527
                Some(D::Bool(false)),
3527
                "Execute asynchronously"
            ),
3527
            data_field(
3527
                "defer",
3527
                Bool,
3527
                Some(D::Bool(false)),
3527
                "Defer execution until page load"
            ),
        ],
243370
        "style" => alloc::vec![data_field(
3527
            "type",
3527
            String,
3527
            Some(D::String(AzString::from_const_str("text/css"))),
3527
            "MIME type of the style sheet"
        ),],
239843
        "base" => alloc::vec![
3527
            data_field(
3527
                "href",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Base URL for relative URLs"
            ),
3527
            data_field(
3527
                "target",
3527
                String,
3527
                Some(D::String(AzString::from_const_str(""))),
3527
                "Default target for hyperlinks"
            ),
        ],
236316
        _ => alloc::vec![],
    }
398564
}
impl Default for ComponentMap {
    /// Returns an empty `ComponentMap` with no libraries.
    ///
    /// Use `AppConfig::create()` (which registers the 52 builtins via
    /// `register_builtin_components`) followed by `ComponentMap::from_libraries()`
    /// to get a fully-populated map.
82
    fn default() -> Self {
82
        Self {
82
            libraries: ComponentLibraryVec::from_const_slice(&[]),
82
        }
82
    }
}
impl ComponentMap {
    #[must_use]
5
    pub fn create() -> Self {
5
        Self::default()
5
    }
    /// Create a `ComponentMap` with the 52 built-in HTML element components pre-registered.
    #[must_use]
3491
    pub fn with_builtin() -> Self {
3491
        Self {
3491
            libraries: alloc::vec![register_builtin_components()].into(),
3491
        }
3491
    }
    /// Build a `ComponentMap` from the libraries stored in an `AppConfig`.
    ///
    /// The `component_libraries` field already contains builtins (registered in
    /// `AppConfig::create()`) plus any user-added libraries.  No merging needed —
    /// `add_component_library` / `add_component` handle insertion at registration time.
    #[must_use]
2
    pub fn from_libraries(libs: &ComponentLibraryVec) -> Self {
2
        Self {
2
            libraries: libs.clone(),
2
        }
2
    }
}
/// Convert XML attributes to a `ComponentDataModel` by cloning the component's
/// base data model and overriding field defaults with values from the XML attributes.
///
/// This is the bridge between the XML parsing layer (key-value string pairs)
/// and the typed component data model. For each field in the base model,
/// if a matching XML attribute exists, its string value is set as the new default.
///
/// # Arguments
/// * `base_model` - The component's data model template (from `ComponentDef::data_model`)
/// * `xml_attributes` - The XML node's attribute map
/// * `text_content` - Optional text content from child text nodes
///
/// # Returns
/// A cloned `ComponentDataModel` with overridden defaults
4
fn xml_attrs_to_data_model(
4
    base_model: &ComponentDataModel,
4
    xml_attributes: &XmlAttributeMap,
4
    text_content: Option<&str>,
4
) -> ComponentDataModel {
4
    let mut model = base_model.clone();
    // Override defaults from XML attributes
4
    let mut fields_vec = core::mem::replace(
4
        &mut model.fields,
4
        ComponentDataFieldVec::from_const_slice(&[]),
    )
4
    .into_library_owned_vec();
20
    for field in &mut fields_vec {
16
        if let Some(attr_value) = xml_attributes.get_key(field.name.as_str()) {
1
            // Override the default_value with the XML attribute's string value
1
            field.default_value = OptionComponentDefaultValue::Some(ComponentDefaultValue::String(
1
                attr_value.clone(),
1
            ));
15
        }
    }
4
    model.fields = ComponentDataFieldVec::from_vec(fields_vec);
    // Handle text content — set the "text" field if present
4
    if let Some(text) = text_content {
2
        let prepared = prepare_string(text);
2
        if !prepared.is_empty() {
1
            model = model.with_default(
1
                "text",
1
                ComponentDefaultValue::String(AzString::from(prepared.as_str())),
1
            );
1
        }
2
    }
4
    model
4
}
// ============================================================================
// Structural builtin components: if, for, map
// ============================================================================
/// `builtin:if` — conditional rendering.
/// Takes `condition: Bool`, `then: StyledDom`, and optionally `else: StyledDom`.
3530
fn builtin_if_component() -> ComponentDef {
3530
    ComponentDef {
3530
        id: ComponentId::builtin("if"),
3530
        display_name: AzString::from_const_str("If"),
3530
        description: AzString::from_const_str(
3530
            "Conditional rendering: shows 'then' if condition is true, else shows 'else' (if \
3530
             provided).",
3530
        ),
3530
        css: AzString::from_const_str(""),
3530
        source: ComponentSource::Builtin,
3530
        data_model: ComponentDataModel {
3530
            name: AzString::from_const_str("IfData"),
3530
            description: AzString::from_const_str("Data for conditional rendering"),
3530
            fields: alloc::vec![data_field(
3530
                "condition",
3530
                ComponentFieldType::Bool,
3530
                Some(ComponentDefaultValue::Bool(false)),
3530
                "The boolean condition to evaluate"
3530
            ),]
3530
            .into(),
3530
        },
3530
        render_fn: builtin_if_render_fn,
3530
        compile_fn: builtin_if_compile_fn,
3530
        render_fn_source: None.into(),
3530
        compile_fn_source: None.into(),
3530
    }
3530
}
2
fn builtin_if_render_fn(
2
    _comp: &ComponentDef,
2
    data_model: &ComponentDataModel,
2
    _component_map: &ComponentMap,
2
) -> ResultStyledDomRenderDomError {
    // Evaluate the condition field
2
    let condition = data_model
2
        .fields
2
        .iter()
2
        .find(|f| f.name.as_str() == "condition")
2
        .and_then(|f| match &f.default_value {
1
            OptionComponentDefaultValue::Some(ComponentDefaultValue::Bool(b)) => Some(*b),
            _ => None,
1
        })
2
        .unwrap_or(false);
2
    let label = if condition {
1
        "if: true (then branch)"
    } else {
1
        "if: false (else branch)"
    };
2
    let mut dom = Dom::create_node(NodeType::Div).with_children(
2
        alloc::vec![Dom::create_text_do_not_use_without_block_level_wrapper(
2
            label
        )]
2
        .into(),
    );
2
    let css = Css::empty();
2
    ResultStyledDomRenderDomError::Ok(StyledDom::create(&mut dom, css))
2
}
8
fn builtin_if_compile_fn(
8
    _comp: &ComponentDef,
8
    target: &CompileTarget,
8
    _data: &ComponentDataModel,
8
    _indent: usize,
8
) -> ResultStringCompileError {
8
    match target {
2
        CompileTarget::Rust => ResultStringCompileError::Ok(AzString::from(
2
            "if data.condition {\n    // then branch\n    Dom::create_div()\n} else {\n    // \
2
             else branch\n    Dom::create_div()\n}",
2
        )),
2
        CompileTarget::C => ResultStringCompileError::Ok(AzString::from(
2
            "if (data.condition) {\n    // then branch\n    AzDom_createDiv();\n} else {\n    // \
2
             else branch\n    AzDom_createDiv();\n}",
2
        )),
2
        CompileTarget::Cpp => ResultStringCompileError::Ok(AzString::from(
2
            "if (data.condition) {\n    // then branch\n    Dom::create_div();\n} else {\n    // \
2
             else branch\n    Dom::create_div();\n}",
2
        )),
2
        CompileTarget::Python => ResultStringCompileError::Ok(AzString::from(
2
            "if data.condition:\n    # then branch\n    Dom.create_div()\nelse:\n    # else \
2
             branch\n    Dom.create_div()",
2
        )),
    }
8
}
/// `builtin:for` — iterative rendering.
/// Takes `count: U32` (number of iterations), renders children N times.
3530
fn builtin_for_component() -> ComponentDef {
3530
    ComponentDef {
3530
        id: ComponentId::builtin("for"),
3530
        display_name: AzString::from_const_str("For Loop"),
3530
        description: AzString::from_const_str(
3530
            "Iterative rendering: repeats children 'count' times.",
3530
        ),
3530
        css: AzString::from_const_str(""),
3530
        source: ComponentSource::Builtin,
3530
        data_model: ComponentDataModel {
3530
            name: AzString::from_const_str("ForData"),
3530
            description: AzString::from_const_str("Data for iterative rendering"),
3530
            fields: alloc::vec![data_field(
3530
                "count",
3530
                ComponentFieldType::U32,
3530
                Some(ComponentDefaultValue::U32(3)),
3530
                "Number of iterations"
3530
            ),]
3530
            .into(),
3530
        },
3530
        render_fn: builtin_for_render_fn,
3530
        compile_fn: builtin_for_compile_fn,
3530
        render_fn_source: None.into(),
3530
        compile_fn_source: None.into(),
3530
    }
3530
}
2
fn builtin_for_render_fn(
2
    _comp: &ComponentDef,
2
    data_model: &ComponentDataModel,
2
    _component_map: &ComponentMap,
2
) -> ResultStyledDomRenderDomError {
2
    let count = data_model
2
        .fields
2
        .iter()
2
        .find(|f| f.name.as_str() == "count")
2
        .and_then(|f| match &f.default_value {
1
            OptionComponentDefaultValue::Some(ComponentDefaultValue::U32(n)) => Some(*n),
1
            _ => None,
2
        })
2
        .unwrap_or(3);
2
    let mut items: Vec<Dom> = Vec::new();
3
    for i in 0..count {
3
        items.push(
3
            Dom::create_node(NodeType::Div).with_children(
3
                alloc::vec![Dom::create_text_do_not_use_without_block_level_wrapper(
3
                    alloc::format!("Item {i}")
3
                )]
3
                .into(),
3
            ),
3
        );
3
    }
2
    let mut dom = Dom::create_node(NodeType::Div).with_children(items.into());
2
    let css = Css::empty();
2
    ResultStyledDomRenderDomError::Ok(StyledDom::create(&mut dom, css))
2
}
8
fn builtin_for_compile_fn(
8
    _comp: &ComponentDef,
8
    target: &CompileTarget,
8
    _data: &ComponentDataModel,
8
    _indent: usize,
8
) -> ResultStringCompileError {
8
    match target {
2
        CompileTarget::Rust => ResultStringCompileError::Ok(AzString::from(
2
            "let mut children = Vec::new();\nfor i in 0..data.count {\n    \
2
             children.push(Dom::create_div());\n}\nDom::create_div().with_children(children)",
2
        )),
        CompileTarget::C => {
2
            ResultStringCompileError::Ok(AzString::from(
2
                "AzDom container = AzDom_createDiv();\nfor (uint32_t i = 0; i < data.count; i++) \
2
                 {\n    AzDom_addChild(&container, AzDom_createDiv());\n}",
2
            ))
        }
        CompileTarget::Cpp => {
2
            ResultStringCompileError::Ok(AzString::from(
2
                "auto container = Dom::create_div();\nfor (uint32_t i = 0; i < data.count; i++) \
2
                 {\n    container.add_child(Dom::create_div());\n}",
2
            ))
        }
2
        CompileTarget::Python => ResultStringCompileError::Ok(AzString::from(
2
            "container = Dom.create_div()\nfor i in range(data.count):\n    container = \
2
             container.with_child(Dom.create_div())",
2
        )),
    }
8
}
/// `builtin:map` — map data to DOM.
/// Takes `data_json: String` (JSON array) + maps each element.
3530
fn builtin_map_component() -> ComponentDef {
3530
    ComponentDef {
3530
        id: ComponentId::builtin("map"),
3530
        display_name: AzString::from_const_str("Map"),
3530
        description: AzString::from_const_str(
3530
            "Map data to DOM: applies a template to each item in a collection.",
3530
        ),
3530
        css: AzString::from_const_str(""),
3530
        source: ComponentSource::Builtin,
3530
        data_model: ComponentDataModel {
3530
            name: AzString::from_const_str("MapData"),
3530
            description: AzString::from_const_str("Data for map rendering"),
3530
            fields: alloc::vec![data_field(
3530
                "data_json",
3530
                ComponentFieldType::String,
3530
                Some(ComponentDefaultValue::String(AzString::from_const_str(
3530
                    "[]"
3530
                ))),
3530
                "JSON array of items to map over"
3530
            ),]
3530
            .into(),
3530
        },
3530
        render_fn: builtin_map_render_fn,
3530
        compile_fn: builtin_map_compile_fn,
3530
        render_fn_source: None.into(),
3530
        compile_fn_source: None.into(),
3530
    }
3530
}
2
fn builtin_map_render_fn(
2
    _comp: &ComponentDef,
2
    data_model: &ComponentDataModel,
2
    _component_map: &ComponentMap,
2
) -> ResultStyledDomRenderDomError {
    // For now, render a placeholder — actual mapping requires callback support
2
    let data_str = data_model
2
        .fields
2
        .iter()
2
        .find(|f| f.name.as_str() == "data_json")
2
        .and_then(|f| match &f.default_value {
1
            OptionComponentDefaultValue::Some(ComponentDefaultValue::String(s)) => {
1
                Some(s.as_str().to_string())
            }
            _ => None,
1
        })
2
        .unwrap_or_else(|| "[]".to_string());
2
    let label = alloc::format!("map: data_json={data_str}");
2
    let mut dom = Dom::create_node(NodeType::Div).with_children(
2
        alloc::vec![Dom::create_text_do_not_use_without_block_level_wrapper(
2
            label
        )]
2
        .into(),
    );
2
    let css = Css::empty();
2
    ResultStyledDomRenderDomError::Ok(StyledDom::create(&mut dom, css))
2
}
8
fn builtin_map_compile_fn(
8
    _comp: &ComponentDef,
8
    target: &CompileTarget,
8
    _data: &ComponentDataModel,
8
    _indent: usize,
8
) -> ResultStringCompileError {
8
    match target {
2
        CompileTarget::Rust => ResultStringCompileError::Ok(AzString::from(
2
            "let items: Vec<serde_json::Value> = \
2
             serde_json::from_str(&data.data_json).unwrap_or_default();\nlet children: Vec<Dom> = \
2
             items.iter().map(|item| {\n    Dom::create_div() // map \
2
             template\n}).collect();\nDom::create_div().with_children(children)",
2
        )),
2
        CompileTarget::C => ResultStringCompileError::Ok(AzString::from(
2
            "// Parse data.data_json and map each item\nAzDom container = AzDom_createDiv();\n// \
2
             TODO: iterate parsed JSON array",
2
        )),
2
        CompileTarget::Cpp => ResultStringCompileError::Ok(AzString::from(
2
            "// Parse data.data_json and map each item\nauto container = Dom::create_div();\n// \
2
             TODO: iterate parsed JSON array",
2
        )),
2
        CompileTarget::Python => ResultStringCompileError::Ok(AzString::from(
2
            "import json\nitems = json.loads(data.data_json)\ncontainer = Dom.create_div()\nfor \
2
             item in items:\n    container = container.with_child(Dom.create_div())",
2
        )),
    }
8
}
/// Register the 52 built-in HTML element components.
///
/// This is an `extern "C"` function pointer compatible with
/// `RegisterComponentLibraryFnType`, so it can be passed directly to
/// `AppConfig::add_component_library()`.
///
/// Called once during `AppConfig::create()` — the framework dogfoods
/// its own component registration system for builtins.
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch (one branch per input variant)
#[must_use]
3527
pub extern "C" fn register_builtin_components() -> ComponentLibrary {
3527
    ComponentLibrary {
3527
        name: AzString::from_const_str("builtin"),
3527
        version: AzString::from_const_str("1.0.0"),
3527
        description: AzString::from_const_str("Built-in HTML elements"),
3527
        exportable: false,
3527
        modifiable: false,
3527
        data_models: Vec::new().into(),
3527
        enum_models: Vec::new().into(),
3527
        components: alloc::vec![
3527
            // Structural
3527
            builtin_component_def("html", "HTML", None, ""),
3527
            builtin_component_def("head", "Head", None, ""),
3527
            builtin_component_def("title", "Title", Some(""), ""),
3527
            builtin_component_def("body", "Body", None, ""),
3527
            // Block-level
3527
            builtin_component_def("div", "Div", None, ""),
3527
            builtin_component_def("header", "Header", None, ""),
3527
            builtin_component_def("footer", "Footer", None, ""),
3527
            builtin_component_def("section", "Section", None, ""),
3527
            builtin_component_def("article", "Article", None, ""),
3527
            builtin_component_def("aside", "Aside", None, ""),
3527
            builtin_component_def("nav", "Nav", None, ""),
3527
            builtin_component_def("main", "Main", None, ""),
3527
            builtin_component_def("figure", "Figure", None, ""),
3527
            builtin_component_def("figcaption", "Figure Caption", Some(""), ""),
3527
            builtin_component_def("address", "Address", Some(""), ""),
3527
            builtin_component_def("details", "Details", None, ""),
3527
            builtin_component_def("summary", "Summary", Some("Details"), ""),
3527
            builtin_component_def("dialog", "Dialog", None, ""),
3527
            // Headings — default text is the heading level name so preview is visible
3527
            builtin_component_def("h1", "Heading 1", Some("Heading 1"), ""),
3527
            builtin_component_def("h2", "Heading 2", Some("Heading 2"), ""),
3527
            builtin_component_def("h3", "Heading 3", Some("Heading 3"), ""),
3527
            builtin_component_def("h4", "Heading 4", Some("Heading 4"), ""),
3527
            builtin_component_def("h5", "Heading 5", Some("Heading 5"), ""),
3527
            builtin_component_def("h6", "Heading 6", Some("Heading 6"), ""),
3527
            // Text content
3527
            builtin_component_def("p", "Paragraph", Some("Paragraph text"), ""),
3527
            builtin_component_def("span", "Span", Some(""), ""),
3527
            builtin_component_def("pre", "Preformatted", Some(""), ""),
3527
            builtin_component_def("code", "Code", Some(""), ""),
3527
            builtin_component_def("blockquote", "Blockquote", Some(""), ""),
3527
            builtin_component_def("br", "Line Break", None, ""),
3527
            builtin_component_def("hr", "Horizontal Rule", None, ""),
3527
            builtin_component_def("pagebreak", "Page Break", None, ""),
3527
            builtin_component_def("icon", "Icon", Some(""), ""),
3527
            // Lists
3527
            builtin_component_def("ul", "Unordered List", None, ""),
3527
            builtin_component_def("ol", "Ordered List", None, ""),
3527
            builtin_component_def("li", "List Item", Some("List item"), ""),
3527
            builtin_component_def("dl", "Description List", None, ""),
3527
            builtin_component_def("dt", "Description Term", Some(""), ""),
3527
            builtin_component_def("dd", "Description Details", Some(""), ""),
3527
            builtin_component_def("menu", "Menu", None, ""),
3527
            builtin_component_def("menuitem", "Menu Item", Some(""), ""),
3527
            builtin_component_def("dir", "Directory List", None, ""),
3527
            // Tables
3527
            builtin_component_def("table", "Table", None, ""),
3527
            builtin_component_def("caption", "Table Caption", Some(""), ""),
3527
            builtin_component_def("thead", "Table Head", None, ""),
3527
            builtin_component_def("tbody", "Table Body", None, ""),
3527
            builtin_component_def("tfoot", "Table Foot", None, ""),
3527
            builtin_component_def("tr", "Table Row", None, ""),
3527
            builtin_component_def("th", "Table Header Cell", Some("Header"), ""),
3527
            builtin_component_def("td", "Table Data Cell", Some(""), ""),
3527
            builtin_component_def("colgroup", "Column Group", None, ""),
3527
            builtin_component_def("col", "Column", None, ""),
3527
            // Inline
3527
            builtin_component_def("a", "Link", Some("Link text"), ""),
3527
            builtin_component_def("strong", "Strong", Some(""), ""),
3527
            builtin_component_def("em", "Emphasis", Some(""), ""),
3527
            builtin_component_def("b", "Bold", Some(""), ""),
3527
            builtin_component_def("i", "Italic", Some(""), ""),
3527
            builtin_component_def("u", "Underline", Some(""), ""),
3527
            builtin_component_def("s", "Strikethrough", Some(""), ""),
3527
            builtin_component_def("small", "Small", Some(""), ""),
3527
            builtin_component_def("mark", "Mark", Some(""), ""),
3527
            builtin_component_def("del", "Deleted Text", Some(""), ""),
3527
            builtin_component_def("ins", "Inserted Text", Some(""), ""),
3527
            builtin_component_def("sub", "Subscript", Some(""), ""),
3527
            builtin_component_def("sup", "Superscript", Some(""), ""),
3527
            builtin_component_def("samp", "Sample Output", Some(""), ""),
3527
            builtin_component_def("kbd", "Keyboard Input", Some(""), ""),
3527
            builtin_component_def("var", "Variable", Some(""), ""),
3527
            builtin_component_def("cite", "Citation", Some(""), ""),
3527
            builtin_component_def("dfn", "Definition", Some(""), ""),
3527
            builtin_component_def("abbr", "Abbreviation", Some(""), ""),
3527
            builtin_component_def("acronym", "Acronym", Some(""), ""),
3527
            builtin_component_def("q", "Inline Quote", Some(""), ""),
3527
            builtin_component_def("time", "Time", Some(""), ""),
3527
            builtin_component_def("big", "Big", Some(""), ""),
3527
            builtin_component_def("bdo", "BiDi Override", Some(""), ""),
3527
            builtin_component_def("bdi", "BiDi Isolate", Some(""), ""),
3527
            builtin_component_def("wbr", "Word Break Opportunity", None, ""),
3527
            builtin_component_def("ruby", "Ruby Annotation", None, ""),
3527
            builtin_component_def("rt", "Ruby Text", Some(""), ""),
3527
            builtin_component_def("rtc", "Ruby Text Container", None, ""),
3527
            builtin_component_def("rp", "Ruby Parenthesis", Some(""), ""),
3527
            builtin_component_def("data", "Data", Some(""), ""),
3527
            // Forms
3527
            builtin_component_def("form", "Form", None, ""),
3527
            builtin_component_def("fieldset", "Field Set", None, ""),
3527
            builtin_component_def("legend", "Legend", Some("Legend"), ""),
3527
            builtin_component_def("label", "Label", Some("Label"), ""),
3527
            builtin_component_def("input", "Input", None, ""),
3527
            builtin_component_def("button", "Button", Some("Button text"), ""),
3527
            builtin_component_def("select", "Select", None, ""),
3527
            builtin_component_def("optgroup", "Option Group", None, ""),
3527
            builtin_component_def("option", "Option", Some(""), ""),
3527
            builtin_component_def("textarea", "Text Area", Some(""), ""),
3527
            builtin_component_def("output", "Output", Some(""), ""),
3527
            builtin_component_def("progress", "Progress", None, ""),
3527
            builtin_component_def("meter", "Meter", None, ""),
3527
            builtin_component_def("datalist", "Data List", None, ""),
3527
            // Embedded content
3527
            builtin_component_def("canvas", "Canvas", None, ""),
3527
            builtin_component_def("object", "Object", None, ""),
3527
            builtin_component_def("param", "Parameter", None, ""),
3527
            builtin_component_def("embed", "Embed", None, ""),
3527
            builtin_component_def("audio", "Audio", None, ""),
3527
            builtin_component_def("video", "Video", None, ""),
3527
            builtin_component_def("source", "Source", None, ""),
3527
            builtin_component_def("track", "Track", None, ""),
3527
            builtin_component_def("map", "Image Map", None, ""),
3527
            builtin_component_def("area", "Map Area", None, ""),
3527
            builtin_component_def("svg", "SVG", None, ""),
3527
            // Metadata
3527
            builtin_component_def("meta", "Meta", None, ""),
3527
            builtin_component_def("link", "Link (Resource)", None, ""),
3527
            builtin_component_def("script", "Script", Some(""), ""),
3527
            builtin_component_def("style", "Style", Some(""), ""),
3527
            builtin_component_def("base", "Base URL", None, ""),
3527
            // Structural control-flow builtins (F1-F3)
3527
            builtin_if_component(),
3527
            builtin_for_component(),
3527
            builtin_map_component(),
3527
        ]
3527
        .into(),
3527
    }
3527
}
// ============================================================================
// End new component system types
// ============================================================================
/// Wrapper for the XML parser - necessary to easily create a Dom from
/// XML without putting an XML solver into `azul-core`.
#[derive(Debug, Default)]
pub struct DomXml {
    pub parsed_dom: StyledDom,
}
impl DomXml {
    /// Convenience function, only available in tests, useful for quickly writing UI tests.
    /// Wraps the XML string in the required `<app></app>` braces, panics if the XML couldn't be
    /// parsed.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// # use azul::dom::Dom;
    /// # use azul::xml::DomXml;
    /// let dom = DomXml::mock("<div id='test' />");
    /// dom.assert_eq(Dom::create_div().with_id("test"));
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the rendered DOM does not equal `other` (this is a test-only
    /// assertion helper).
    #[cfg(test)]
    pub fn assert_eq(self, other: StyledDom) {
        let mut body = Dom::create_body();
        let mut fixed = StyledDom::create(&mut body, Css::empty());
        fixed.append_child(other);
        assert!(
            !(self.parsed_dom != fixed),
            "\r\nExpected DOM did not match:\r\n\r\nexpected: ----------\r\n{}\r\ngot: \
             ----------\r\n{}\r\n",
            self.parsed_dom.get_html_string("", "", true),
            fixed.get_html_string("", "", true)
        );
    }
    #[must_use]
1
    pub fn into_styled_dom(self) -> StyledDom {
1
        self.into()
1
    }
}
impl From<DomXml> for StyledDom {
2
    fn from(val: DomXml) -> Self {
2
        val.parsed_dom
2
    }
}
/// Represents a child of an XML node - either an element or text
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C, u8)]
pub enum XmlNodeChild {
    /// A text node
    Text(AzString),
    /// An element node
    Element(XmlNode),
}
impl_option!(
    XmlNodeChild,
    OptionXmlNodeChild,
    copy = false,
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);
impl XmlNodeChild {
    /// Get the text content if this is a text node
    #[must_use]
3107
    pub fn as_text(&self) -> Option<&str> {
3107
        match self {
3093
            Self::Text(s) => Some(s.as_str()),
14
            Self::Element(_) => None,
        }
3107
    }
    /// Get the element if this is an element node
    #[must_use]
3036
    pub const fn as_element(&self) -> Option<&XmlNode> {
3036
        match self {
2
            Self::Text(_) => None,
3034
            Self::Element(node) => Some(node),
        }
3036
    }
    /// Get the element mutably if this is an element node
2
    pub const fn as_element_mut(&mut self) -> Option<&mut XmlNode> {
2
        match self {
1
            Self::Text(_) => None,
1
            Self::Element(node) => Some(node),
        }
2
    }
}
impl_vec!(
    XmlNodeChild,
    XmlNodeChildVec,
    XmlNodeChildVecDestructor,
    XmlNodeChildVecDestructorType,
    XmlNodeChildVecSlice,
    OptionXmlNodeChild
);
impl_vec_mut!(XmlNodeChild, XmlNodeChildVec);
impl_vec_debug!(XmlNodeChild, XmlNodeChildVec);
impl_vec_partialeq!(XmlNodeChild, XmlNodeChildVec);
impl_vec_eq!(XmlNodeChild, XmlNodeChildVec);
impl_vec_partialord!(XmlNodeChild, XmlNodeChildVec);
impl_vec_ord!(XmlNodeChild, XmlNodeChildVec);
impl_vec_hash!(XmlNodeChild, XmlNodeChildVec);
impl_vec_clone!(XmlNodeChild, XmlNodeChildVec, XmlNodeChildVecDestructor);
/// Represents one XML node tag
#[derive(Default, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct XmlNode {
    /// Type of the node
    pub node_type: XmlTagName,
    /// Attributes of an XML node (note: not yet filtered and / or broken into function arguments!)
    pub attributes: XmlAttributeMap,
    /// Direct children of this node (can be text or element nodes)
    pub children: XmlNodeChildVec,
}
impl_option!(
    XmlNode,
    OptionXmlNode,
    copy = false,
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);
impl XmlNode {
1378
    pub fn create<I: Into<XmlTagName>>(node_type: I) -> Self {
1378
        Self {
1378
            node_type: node_type.into(),
1378
            ..Default::default()
1378
        }
1378
    }
    #[must_use]
7438
    pub fn with_children(mut self, v: Vec<XmlNodeChild>) -> Self {
7438
        Self {
7438
            children: v.into(),
7438
            ..self
7438
        }
7438
    }
    /// Get all text content concatenated from direct children
    #[must_use]
2977
    pub fn get_text_content(&self) -> String {
2977
        self.children
2977
            .as_ref()
2977
            .iter()
2978
            .filter_map(|child| child.as_text())
2977
            .collect::<Vec<_>>()
2977
            .join("")
2977
    }
    /// Check if this node has only text children (no element children)
    #[must_use]
29
    pub fn has_only_text_children(&self) -> bool {
29
        self.children
29
            .as_ref()
29
            .iter()
29
            .all(|child| matches!(child, XmlNodeChild::Text(_)))
29
    }
}
impl_vec!(
    XmlNode,
    XmlNodeVec,
    XmlNodeVecDestructor,
    XmlNodeVecDestructorType,
    XmlNodeVecSlice,
    OptionXmlNode
);
impl_vec_mut!(XmlNode, XmlNodeVec);
impl_vec_debug!(XmlNode, XmlNodeVec);
impl_vec_partialeq!(XmlNode, XmlNodeVec);
impl_vec_eq!(XmlNode, XmlNodeVec);
impl_vec_partialord!(XmlNode, XmlNodeVec);
impl_vec_ord!(XmlNode, XmlNodeVec);
impl_vec_hash!(XmlNode, XmlNodeVec);
impl_vec_clone!(XmlNode, XmlNodeVec, XmlNodeVecDestructor);
#[derive(Debug, Clone, PartialEq)]
#[repr(C, u8)]
pub enum DomXmlParseError {
    /// No `<html></html>` node component present
    NoHtmlNode,
    /// Multiple `<html>` nodes
    MultipleHtmlRootNodes,
    /// No ´<body></body>´ node in the root HTML
    NoBodyInHtml,
    /// The DOM can only have one <body> node, not multiple.
    MultipleBodyNodes,
    /// Note: Sadly, the error type can only be a string because xmlparser
    /// returns all errors as strings. There is an open PR to fix
    /// this deficiency, but since the XML parsing is only needed for
    /// hot-reloading and compiling, it doesn't matter that much.
    Xml(XmlError),
    /// Invalid hierarchy close tags, i.e `<app></p></app>`
    MalformedHierarchy(MalformedHierarchyError),
    /// A component raised an error while rendering the DOM - holds the component name + error
    /// string
    RenderDom(RenderDomError),
    /// Something went wrong while parsing an XML component
    Component(ComponentParseError),
    /// Error parsing global CSS in head node
    Css(CssParseErrorOwned),
}
impl From<XmlError> for DomXmlParseError {
    fn from(e: XmlError) -> Self {
        Self::Xml(e)
    }
}
impl From<ComponentParseError> for DomXmlParseError {
    fn from(e: ComponentParseError) -> Self {
        Self::Component(e)
    }
}
impl From<RenderDomError> for DomXmlParseError {
1
    fn from(e: RenderDomError) -> Self {
1
        Self::RenderDom(e)
1
    }
}
impl From<CssParseErrorOwned> for DomXmlParseError {
    fn from(e: CssParseErrorOwned) -> Self {
        Self::Css(e)
    }
}
/// Error that can happen from the translation from XML code to Rust code -
/// stringified, since it is only used for printing and is not exposed in the public API
#[derive(Debug, Clone, PartialEq)]
#[repr(C, u8)]
pub enum CompileError {
    Dom(RenderDomError),
    Xml(DomXmlParseError),
    Css(CssParseErrorOwned),
}
impl From<ComponentError> for CompileError {
    fn from(e: ComponentError) -> Self {
        Self::Dom(RenderDomError::Component(e))
    }
}
impl From<CssParseErrorOwned> for CompileError {
    fn from(e: CssParseErrorOwned) -> Self {
        Self::Css(e)
    }
}
impl fmt::Display for CompileError {
2
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use self::CompileError::{Css, Dom, Xml};
2
        match self {
1
            Dom(d) => write!(f, "{d}"),
1
            Xml(s) => write!(f, "{s}"),
            Css(s) => write!(f, "{}", s.to_shared()),
        }
2
    }
}
impl From<RenderDomError> for CompileError {
1
    fn from(e: RenderDomError) -> Self {
1
        Self::Dom(e)
1
    }
}
impl From<DomXmlParseError> for CompileError {
1
    fn from(e: DomXmlParseError) -> Self {
1
        Self::Xml(e)
1
    }
}
/// Wrapper for `UselessFunctionArgument` error data.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct UselessFunctionArgumentError {
    pub component_name: AzString,
    pub argument_name: AzString,
    pub valid_args: StringVec,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C, u8)]
pub enum ComponentError {
    /// While instantiating a component, a function argument
    /// was encountered that the component won't use or react to.
    UselessFunctionArgument(UselessFunctionArgumentError),
    /// A certain node type can't be rendered, because the
    /// renderer for this node is not available isn't available
    ///
    /// `UnknownComponent(component_name)`
    UnknownComponent(AzString),
}
#[derive(Debug, Clone, PartialEq)]
#[repr(C, u8)]
pub enum RenderDomError {
    Component(ComponentError),
    /// Error parsing the CSS on the component style
    CssError(CssParseErrorOwned),
}
impl From<ComponentError> for RenderDomError {
1
    fn from(e: ComponentError) -> Self {
1
        Self::Component(e)
1
    }
}
impl From<CssParseErrorOwned> for RenderDomError {
    fn from(e: CssParseErrorOwned) -> Self {
        Self::CssError(e)
    }
}
/// Wrapper for `MissingType` error data.
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct MissingTypeError {
    pub arg_pos: usize,
    pub arg_name: AzString,
}
/// Wrapper for `WhiteSpaceInComponentName` error data.
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct WhiteSpaceInComponentNameError {
    pub arg_pos: usize,
    pub arg_name: AzString,
}
/// Wrapper for `WhiteSpaceInComponentType` error data.
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct WhiteSpaceInComponentTypeError {
    pub arg_pos: usize,
    pub arg_name: AzString,
    pub arg_type: AzString,
}
#[derive(Debug, Clone, PartialEq)]
#[repr(C, u8)]
pub enum ComponentParseError {
    /// Given `XmlNode` is not a `<component />` node.
    NotAComponent,
    /// A `<component>` node does not have a `name` attribute.
    UnnamedComponent,
    /// Argument at position `usize` is either empty or has no name
    MissingName(usize),
    /// Argument at position `usize` with the name
    /// `String` doesn't have a `: type`
    MissingType(MissingTypeError),
    /// Component name may not contain a whitespace
    /// (probably missing a `:` between the name and the type)
    WhiteSpaceInComponentName(WhiteSpaceInComponentNameError),
    /// Component type may not contain a whitespace
    /// (probably missing a `,` between the type and the next name)
    WhiteSpaceInComponentType(WhiteSpaceInComponentTypeError),
    /// Error parsing the <style> tag / CSS
    CssError(CssParseErrorOwned),
}
impl fmt::Display for DomXmlParseError {
22
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use self::DomXmlParseError::{
            Component, Css, MalformedHierarchy, MultipleBodyNodes, MultipleHtmlRootNodes,
            NoBodyInHtml, NoHtmlNode, RenderDom, Xml,
        };
22
        match self {
1
            NoHtmlNode => write!(
1
                f,
1
                "No <html> node found as the root of the file - empty file?"
            ),
1
            MultipleHtmlRootNodes => write!(
1
                f,
1
                "Multiple <html> nodes found as the root of the file - only one root node allowed"
            ),
13
            NoBodyInHtml => write!(
13
                f,
13
                "No <body> node found as a direct child of an <html> node - malformed DOM \
13
                 hierarchy?"
            ),
1
            MultipleBodyNodes => write!(
1
                f,
1
                "Multiple <body> nodes present, only one <body> node is allowed"
            ),
1
            Xml(e) => write!(f, "Error parsing XML: {e}"),
1
            MalformedHierarchy(e) => write!(
1
                f,
1
                "Invalid </{}> tag: expected </{}>",
1
                e.got.as_str(),
1
                e.expected.as_str()
            ),
3
            RenderDom(e) => write!(f, "Error rendering DOM: {e}"),
1
            Component(c) => write!(f, "Error parsing component in <head> node:\r\n{c}"),
            Css(c) => write!(f, "Error parsing CSS in <head> node:\r\n{}", c.to_shared()),
        }
22
    }
}
impl fmt::Display for ComponentParseError {
7
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use self::ComponentParseError::{
            CssError, MissingName, MissingType, NotAComponent, UnnamedComponent,
            WhiteSpaceInComponentName, WhiteSpaceInComponentType,
        };
7
        match self {
2
            NotAComponent => write!(f, "Expected <component/> node, found no such node"),
1
            UnnamedComponent => write!(
1
                f,
1
                "Found <component/> tag with out a \"name\" attribute, component must have a name"
            ),
1
            MissingName(arg_pos) => write!(
1
                f,
1
                "Argument at position {arg_pos} is either empty or has no name"
            ),
1
            MissingType(e) => write!(
1
                f,
1
                "Argument \"{}\" at position {} doesn't have a `: type`",
                e.arg_name, e.arg_pos
            ),
1
            WhiteSpaceInComponentName(e) => {
1
                write!(
1
                    f,
1
                    "Missing `:` between the name and the type in argument {} (around \"{}\")",
                    e.arg_pos, e.arg_name
                )
            }
1
            WhiteSpaceInComponentType(e) => {
1
                write!(
1
                    f,
1
                    "Missing `,` between two arguments (in argument {}, position {}, around \
1
                     \"{}\")",
                    e.arg_name, e.arg_pos, e.arg_type
                )
            }
            CssError(lsf) => write!(f, "Error parsing <style> tag: {}", lsf.to_shared()),
        }
7
    }
}
impl fmt::Display for ComponentError {
7
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use self::ComponentError::{UnknownComponent, UselessFunctionArgument};
7
        match self {
1
            UselessFunctionArgument(e) => {
1
                write!(
1
                    f,
1
                    "Useless component argument \"{}\": \"{}\" - available args are: {:#?}",
                    e.component_name, e.argument_name, e.valid_args
                )
            }
6
            UnknownComponent(name) => write!(f, "Unknown component: \"{name}\""),
        }
7
    }
}
impl fmt::Display for RenderDomError {
5
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use self::RenderDomError::{Component, CssError};
5
        match self {
5
            Component(c) => write!(f, "{c}"),
            CssError(e) => write!(f, "Error parsing CSS in component: {}", e.to_shared()),
        }
5
    }
}
/// Find the one and only `<body>` node, return error if
/// there is no app node or there are multiple app nodes
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
/// # Errors
///
/// Returns an error if the document has no `<html>` root node.
/// Every `<head><style>` block's text, concatenated in document order.
///
/// ALL of them, not the first: a document may state its stylesheet in several
/// blocks (a reset, then the page's own rules), and browsers apply each in
/// turn. Reading only the first silently dropped everything after it - and it
/// is silent in the worst way, because the page still renders, just with some
/// rules missing and nothing to say which.
3573
fn head_style_text(html_node: &XmlNode) -> String {
3573
    let Some(head) = find_node_by_type(html_node.children.as_ref(), "head") else {
643
        return String::new();
    };
2930
    let mut out = String::new();
3542
    for child in head.children.as_ref() {
3542
        let XmlNodeChild::Element(element) = child else {
624
            continue;
        };
2918
        if !element.node_type.as_str().eq_ignore_ascii_case("style") {
            continue;
2918
        }
2918
        let text = element.get_text_content();
2918
        if !text.is_empty() {
2906
            if !out.is_empty() {
12
                out.push('\n');
2894
            }
2906
            out.push_str(&text);
12
        }
    }
2930
    out
3573
}
/// The document's single root `<html>` node.
///
/// # Errors
///
/// Returns [`DomXmlParseError::NoHtmlNode`] when the document has no root
/// `<html>` node, and [`DomXmlParseError::MultipleHtmlRootNodes`] when it has
/// more than one.
// `DomXmlParseError` is the crate's public XML error type, shared with the C
// ABI; boxing it to shrink the Err variant would change that surface.
#[allow(clippy::result_large_err)]
3603
pub fn get_html_node(
3603
    root_nodes: &[XmlNodeChild],
3603
) -> Result<alloc::borrow::Cow<'_, XmlNode>, DomXmlParseError> {
    use alloc::borrow::Cow;
3771
    let mut html_node_iterator = root_nodes.iter().filter_map(|child| {
3767
        if let XmlNodeChild::Element(node) = child {
            // HTML element names are case-insensitive (ASCII). NOT normalize_casing:
            // that inserts '_' before each uppercase letter for component-name
            // canonicalisation, so "HTML" would become "h_t_m_l" and never match.
3667
            if node.node_type.as_str().eq_ignore_ascii_case("html") {
3288
                Some(node)
            } else {
379
                None
            }
        } else {
100
            None
        }
3767
    });
3603
    if let Some(html_node) = html_node_iterator.next() {
3287
        return if html_node_iterator.next().is_some() {
1
            Err(DomXmlParseError::MultipleHtmlRootNodes)
        } else {
3286
            Ok(Cow::Borrowed(html_node))
        };
316
    }
    // NO <html> ROOT: synthesise one, the way a browser does.
    //
    // Requiring the wrapper made a perfectly good fragment - `<svg>…</svg>`,
    // `<div>hi</div>`, an icon file straight off the disk - parse into the
    // TEXT "No <html> node found as the root of the file", which then lays
    // out and paints like any other text. The failure was silent and looked
    // exactly like a rendering bug: a caller measuring pixels saw an error
    // message it never asked for and no sign of what happened.
    //
    // A root `<body>`/`<head>` is ADOPTED rather than nested (again like a
    // browser): wrapping `<body>` inside a fresh `<body>` would give the
    // document two, which is its own error.
472
    let has_structural_root = root_nodes.iter().any(|child| match child {
367
        XmlNodeChild::Element(node) => {
367
            let tag = node.node_type.as_str();
367
            tag.eq_ignore_ascii_case("body") || tag.eq_ignore_ascii_case("head")
        }
100
        XmlNodeChild::Text(_) => false,
467
    });
316
    if has_structural_root {
1
        return Ok(Cow::Owned(
1
            XmlNode::create("html").with_children(root_nodes.to_vec()),
1
        ));
315
    }
    // METADATA GOES TO THE HEAD, content to the body - the same split a
    // browser makes. A `<style>` left in the body is not looked at by
    // `str_to_dom_unstyled` (it reads `<head><style>`), so a fragment that
    // brought its own stylesheet would render unstyled and give no hint why.
315
    let (head_children, body_children): (Vec<_>, Vec<_>) =
471
        root_nodes.iter().cloned().partition(|child| match child {
366
            XmlNodeChild::Element(node) => {
366
                let tag = node.node_type.as_str();
366
                tag.eq_ignore_ascii_case("style")
197
                    || tag.eq_ignore_ascii_case("link")
197
                    || tag.eq_ignore_ascii_case("meta")
197
                    || tag.eq_ignore_ascii_case("title")
196
                    || tag.eq_ignore_ascii_case("base")
            }
100
            XmlNodeChild::Text(_) => false,
466
        });
315
    let mut html_children = Vec::new();
315
    if !head_children.is_empty() {
157
        html_children.push(XmlNodeChild::Element(
157
            XmlNode::create("head").with_children(head_children),
157
        ));
170
    }
315
    html_children.push(XmlNodeChild::Element(
315
        XmlNode::create("body").with_children(body_children),
315
    ));
315
    Ok(Cow::Owned(
315
        XmlNode::create("html").with_children(html_children),
315
    ))
3603
}
/// Find the one and only `<body>` node, return error if
/// there is no app node or there are multiple app nodes
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
/// # Errors
///
/// Returns an error if the document has no `<body>` node.
3601
pub fn get_body_node(root_nodes: &[XmlNodeChild]) -> Result<&XmlNode, DomXmlParseError> {
1044
    fn find_body_recursive(nodes: &[XmlNodeChild], depth: usize) -> Option<&XmlNode> {
        // AUDIT 2026-07-08: bound recursion depth to avoid a stack overflow on
        // pathologically deep markup while hunting for the <body> element.
1044
        if depth > MAX_XML_NESTING_DEPTH {
1
            return None;
1043
        }
1557
        for child in nodes {
1028
            if let XmlNodeChild::Element(node) = child {
                // case-insensitive ASCII tag match; see get_html_node.
1028
                if node.node_type.as_str().eq_ignore_ascii_case("body") {
2
                    return Some(node);
1026
                }
                // Recurse into children
1026
                if let Some(found) = find_body_recursive(node.children.as_ref(), depth + 1) {
512
                    return Some(found);
514
                }
            }
        }
529
        None
1044
    }
    // First try to find body as a direct child (proper HTML structure)
8515
    let direct_body = root_nodes.iter().find_map(|child| {
8515
        if let XmlNodeChild::Element(node) = child {
            // case-insensitive ASCII tag match; see get_html_node.
6523
            if node.node_type.as_str().eq_ignore_ascii_case("body") {
3583
                Some(node)
            } else {
2940
                None
            }
        } else {
1992
            None
        }
8515
    });
3601
    if let Some(body) = direct_body {
3583
        return Ok(body);
18
    }
    // If not found as direct child, search recursively (for malformed HTML like example.com)
    // where <body> might be nested inside <head> due to missing </head> tag
18
    find_body_recursive(root_nodes, 0).ok_or(DomXmlParseError::NoBodyInHtml)
3601
}
/// Searches in the the `root_nodes` for a `node_type`, convenience function in order to
/// for example find the first <blah /> node in all these nodes.
/// This function searches recursively through the entire tree.
11719
fn find_node_by_type<'a>(root_nodes: &'a [XmlNodeChild], node_type: &str) -> Option<&'a XmlNode> {
    // First check direct children
20900
    for child in root_nodes {
12126
        if let XmlNodeChild::Element(node) = child {
            // case-insensitive ASCII tag match; see get_html_node.
11066
            if node.node_type.as_str().eq_ignore_ascii_case(node_type) {
2945
                return Some(node);
8121
            }
1060
        }
    }
    // If not found, search recursively (for malformed HTML)
17376
    for child in root_nodes {
8604
        if let XmlNodeChild::Element(node) = child {
8120
            if let Some(found) = find_node_by_type(node.children.as_ref(), node_type) {
2
                return Some(found);
8118
            }
484
        }
    }
8772
    None
11719
}
#[must_use]
11
pub fn find_attribute<'a>(node: &'a XmlNode, attribute: &str) -> Option<&'a AzString> {
11
    node.attributes
11
        .iter()
17
        .find(|n| normalize_casing(n.key.as_str()).as_str() == attribute)
11
        .map(|s| &s.value)
11
}
/// Normalizes input such as `abcDef`, `AbcDef`, `abc-def` to the normalized form of `abc_def`
#[must_use]
53287
pub fn normalize_casing(input: &str) -> String {
53287
    let mut words: Vec<String> = Vec::new();
53287
    let mut cur_str = Vec::new();
220424
    for ch in input.chars() {
220424
        if ch.is_uppercase() || ch == '_' || ch == '-' {
50025
            if !cur_str.is_empty() {
50011
                words.push(cur_str.iter().collect());
50011
                cur_str.clear();
50011
            }
50025
            if ch.is_uppercase() {
50013
                cur_str.extend(ch.to_lowercase());
50013
            }
170399
        } else {
170399
            cur_str.extend(ch.to_lowercase());
170399
        }
    }
53287
    if !cur_str.is_empty() {
53283
        words.push(cur_str.iter().collect());
53283
        cur_str.clear();
53283
    }
53287
    words.join("_")
53287
}
/// Given a root node, traverses along the hierarchy, and returns a
/// mutable reference to the last child node of the root node
#[allow(trivial_casts)]
8
pub fn get_item<'a>(hierarchy: &[usize], root_node: &'a mut XmlNode) -> Option<&'a mut XmlNode> {
8
    let mut hierarchy = hierarchy.to_vec();
8
    hierarchy.reverse();
8
    let Some(item) = hierarchy.pop() else {
1
        return Some(root_node);
    };
7
    let child = root_node.children.as_mut().get_mut(item)?;
5
    match child {
4
        XmlNodeChild::Element(node) => get_item_internal(&mut hierarchy, node),
1
        XmlNodeChild::Text(_) => None, // Can't traverse into text nodes
    }
8
}
404
fn get_item_internal<'a>(
404
    hierarchy: &mut Vec<usize>,
404
    root_node: &'a mut XmlNode,
404
) -> Option<&'a mut XmlNode> {
404
    if hierarchy.is_empty() {
3
        return Some(root_node);
401
    }
401
    let Some(cur_item) = hierarchy.pop() else {
        return Some(root_node);
    };
401
    let child = root_node.children.as_mut().get_mut(cur_item)?;
400
    match child {
400
        XmlNodeChild::Element(node) => get_item_internal(hierarchy, node),
        XmlNodeChild::Text(_) => None, // Can't traverse into text nodes
    }
404
}
/// Parses an XML string and returns a `StyledDom` with the components instantiated in the
/// `<app></app>`
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
/// # Errors
///
/// Returns an error if the XML cannot be parsed into a DOM (malformed markup or an unknown
/// component).
3241
pub fn str_to_dom<'a>(
3241
    root_nodes: &'a [XmlNodeChild],
3241
    component_map: &'a ComponentMap,
3241
    max_width: Option<f32>,
3241
) -> Result<StyledDom, DomXmlParseError> {
    // Delegate to the fast path (Dom::Fast / CompactDom arena).
3241
    str_to_dom_fast(root_nodes, component_map, max_width)
3241
}
/// Parse XML to `StyledDom` via arena-based `FastDom` (no tree intermediary).
///
/// **Note**: `str_to_dom()` now delegates to this function, so you can use
/// either one. This function is kept for backward compatibility.
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would
                                   // break the C ABI/api.json
3241
fn str_to_dom_fast<'a>(
3241
    root_nodes: &'a [XmlNodeChild],
3241
    component_map: &'a ComponentMap,
3241
    max_width: Option<f32>,
3241
) -> Result<StyledDom, DomXmlParseError> {
3241
    let html_node = get_html_node(root_nodes)?;
3241
    let body_node = get_body_node(html_node.children.as_ref())?;
3240
    let style_text = head_style_text(&html_node);
3240
    let global_style = if style_text.is_empty() {
563
        None
    } else {
2677
        Some(Css::from_string(style_text.into()))
    };
3240
    render_dom_from_body_node_fast(body_node, global_style, component_map, max_width)
3240
        .map_err(Into::into)
3241
}
/// Parses XML nodes and returns a `Dom` with CSS stylesheets attached (but not applied).
///
/// Unlike `str_to_dom` which returns a fully styled `StyledDom`, this function
/// returns an unstyled `Dom` whose `css` field carries the parsed `<style>` rules.
/// The layout framework will apply the CSS during the cascade pass.
///
/// This is the correct function for building a `Dom` from XML in layout callbacks
/// (which must return `Dom`, not `StyledDom`).
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
/// # Errors
///
/// Returns an error if the XML cannot be parsed into a DOM (malformed markup or an unknown
/// component).
339
pub fn str_to_dom_unstyled<'a>(
339
    root_nodes: &'a [XmlNodeChild],
339
    component_map: &'a ComponentMap,
339
) -> Result<Dom, DomXmlParseError> {
339
    let html_node = get_html_node(root_nodes)?;
339
    let body_node = get_body_node(html_node.children.as_ref())?;
327
    let style_text = head_style_text(&html_node);
327
    let global_style = if style_text.is_empty() {
110
        None
    } else {
217
        Some(Css::from_string(style_text.into()))
    };
    // Build the DOM tree from the body node
327
    let body_dom =
327
        xml_node_to_dom_fast(body_node, component_map, false, 0).map_err(DomXmlParseError::from)?;
    // Wrap in proper HTML structure (NodeType is imported at module top)
327
    let root_node_type = body_dom.root.node_type.clone();
327
    let mut full_dom = match root_node_type {
        NodeType::Html => body_dom,
327
        NodeType::Body => Dom::create_html().with_child(body_dom),
        _ => {
            let body_wrapper = Dom::create_body().with_child(body_dom);
            Dom::create_html().with_child(body_wrapper)
        }
    };
    // Attach CSS to the Dom's css field instead of applying it immediately
327
    if let Some(css) = global_style {
217
        full_dom.css = alloc::vec![css].into();
218
    }
327
    Ok(full_dom)
339
}
/// Parses an XML string and returns a `String`, which contains the Rust source code
/// (i.e. it compiles the XML to valid Rust)
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
/// # Errors
///
/// Returns an error if the XML cannot be parsed or compiled to Rust code.
6
pub fn str_to_rust_code<'a>(
6
    root_nodes: &'a [XmlNodeChild],
6
    imports: &str,
6
    component_map: &'a ComponentMap,
6
) -> Result<String, CompileError> {
6
    let html_node = get_html_node(root_nodes)?;
6
    let body_node = get_body_node(html_node.children.as_ref())?;
6
    let style_text = head_style_text(&html_node);
6
    let mut global_style = if style_text.is_empty() {
6
        Css::empty()
    } else {
        azul_css::parser2::new_from_str(&style_text).0
    };
6
    global_style.sort_by_specificity();
6
    let mut css_blocks = BTreeMap::new();
6
    let mut extra_blocks = VecContents::default();
6
    let app_source = compile_body_node_to_rust_code(
6
        body_node,
6
        component_map,
6
        &mut extra_blocks,
6
        &mut css_blocks,
6
        &global_style,
6
        CssMatcher {
6
            path: Vec::new(),
6
            indices_in_parent: vec![0],
6
            children_length: vec![body_node.children.as_ref().len()],
6
        },
    )?;
6
    let app_source = app_source
6
        .lines()
27
        .map(|l| format!("        {l}"))
6
        .collect::<Vec<String>>()
6
        .join("\r\n");
    // NOTE: `css_blocks` / `extra_blocks` are no longer emitted — per-node styles
    // are now inlined as `.with_css("..")` strings (public API) rather than as
    // `const CSS_MATCH_*: NodeDataInlineCssPropertyVec` blocks (that API was
    // removed in 32d44ed8a). The maps stay in the signatures for compatibility.
6
    let _ = (&css_blocks, &extra_blocks);
6
    let main_func = "
6

            
6
use azul::{
6
    app::{App, AppConfig},
6
    dom::Dom,
6
    callbacks::{RefAny, LayoutCallbackInfo},
6
    window::WindowCreateOptions,
6
};
6

            
6
struct Data { }
6

            
6
extern \"C\" fn render(_: RefAny, _: LayoutCallbackInfo) -> Dom {
6
    crate::ui::render()
6
}
6

            
6
fn main() {
6
    let config = AppConfig::create();
6
    let app = App::create(RefAny::new(Data { }), config);
6
    let window = WindowCreateOptions::create(render);
6
    app.run(window);
6
}";
6
    let ui_module = format!(
6
        "#[allow(unused_imports)]\r\npub mod ui {{
6

            
6
    use azul::prelude::*;
6
    use azul::dom::{{NodeType, TabIndex, SmallAriaInfo}};
6
    use azul::str::String as AzString;
6

            
6
    pub fn render() -> Dom {{\r\n{app_source}\r\n    }}\r\n}}"
    );
6
    let source_code = format!(
6
        "#![windows_subsystem = \"windows\"]\r\n//! Auto-generated UI source \
6
         code\r\n{}\r\n{}\r\n\r\n{}{}",
        imports,
6
        compile_components(Vec::new()), // no user-defined components to compile
        ui_module,
        main_func,
    );
6
    Ok(source_code)
6
}
// Compile all components to source code
#[allow(clippy::needless_pass_by_value)] // owned azul value taken by value (public API /
                                         // ownership-transfer convention)
7
fn compile_components(
7
    components: Vec<(
7
        ComponentName,
7
        CompiledComponent,
7
        ComponentArguments,
7
        BTreeMap<String, String>,
7
    )>,
7
) -> String {
7
    let cs = components
7
        .iter()
7
        .map(|(name, function_body, function_args, css_blocks)| {
            let name = &normalize_casing(name);
            let f = compile_component(name, function_args, function_body)
                .lines()
                .map(|l| format!("    {l}"))
                .collect::<Vec<String>>()
                .join("\r\n");
            // let css_blocks = ...
            format!(
                "#[allow(unused_imports)]\r\npub mod {name} {{\r\n    use azul::dom::Dom;\r\n    \
                 use azul::str::String as AzString;\r\n{f}\r\n}}"
            )
        })
7
        .collect::<Vec<String>>()
7
        .join("\r\n\r\n");
7
    let cs = cs
7
        .lines()
7
        .map(|l| format!("    {l}"))
7
        .collect::<Vec<String>>()
7
        .join("\r\n");
7
    if cs.is_empty() {
7
        cs
    } else {
        format!("pub mod components {{\r\n{cs}\r\n}}")
    }
7
}
7
fn format_component_args(component_args: &ComponentArgumentVec) -> String {
7
    let mut args = component_args
7
        .iter()
7
        .map(|a| format!("{}: {}", a.name, a.arg_type))
7
        .collect::<Vec<String>>();
7
    args.sort_by(|a, b| b.cmp(a));
7
    args.join(", ")
7
}
#[must_use]
4
pub fn compile_component(
4
    component_name: &str,
4
    component_args: &ComponentArguments,
4
    component_function_body: &str,
4
) -> String {
4
    let component_name = &normalize_casing(component_name);
4
    let function_args = format_component_args(&component_args.args);
4
    let component_function_body = component_function_body
4
        .lines()
4
        .map(|l| format!("    {l}"))
4
        .collect::<Vec<String>>()
4
        .join("\r\n");
4
    let should_inline = component_function_body.lines().count() == 1;
4
    format!(
4
        "{}pub fn render({}{}{}) -> Dom {{\r\n{}\r\n}}",
4
        if should_inline { "#[inline]\r\n" } else { "" },
        // pass the text content as the first
4
        if component_args.accepts_text {
2
            "text: AzString"
        } else {
2
            ""
        },
4
        if function_args.is_empty() || !component_args.accepts_text {
3
            ""
        } else {
1
            ", "
        },
        function_args,
        component_function_body,
    )
4
}
/// Parse an SVG numeric attribute value to f32.
///
/// STRICT: a geometry attribute (`cx`, `r`, `x1`, ...) is a USER UNIT, and
/// `cx="10px"` is not valid SVG. The `<svg>` element's own `width`/`height`
/// are CSS lengths and a different thing entirely - see [`parse_svg_length`].
1775
fn parse_svg_float(attr: Option<&AzString>) -> Option<f32> {
1775
    attr?.as_str().trim().parse::<f32>().ok()
1775
}
/// Parse the `<svg>` element's own `width`/`height`, which - unlike the
/// geometry attributes - are CSS LENGTHS.
///
/// A bare `px` is accepted because `width="16px"` is as common in the wild as
/// `width="16"`. A relative unit (`%`, `em`) is REJECTED rather than guessed
/// at: the caller then falls back to the viewBox, which is a real answer,
/// instead of resolving a percentage against nothing.
1058
fn parse_svg_length(attr: Option<&AzString>) -> Option<f32> {
1058
    let raw = attr?.as_str().trim();
384
    let number = raw.strip_suffix("px").unwrap_or(raw).trim();
384
    number.parse::<f32>().ok()
1058
}
/// Parse an SVG `viewBox` into `(min_x, min_y, width, height)`.
///
/// Space- or comma-separated, per the spec; exactly four numbers, because
/// three or five is a malformed viewBox and silently taking the first four
/// would place the art somewhere nobody asked for.
276
fn parse_svg_view_box(value: &str) -> Option<(f32, f32, f32, f32)> {
276
    let nums: Vec<f32> = value
2124
        .split(|c: char| c == ',' || c.is_ascii_whitespace())
1032
        .filter(|s| !s.is_empty())
276
        .map(str::parse::<f32>)
276
        .collect::<Result<Vec<_>, _>>()
276
        .ok()?;
264
    match nums[..] {
228
        [min_x, min_y, width, height] if width > 0.0 && height > 0.0 => {
216
            Some((min_x, min_y, width, height))
        }
48
        _ => None,
    }
276
}
/// Parse an SVG `points` attribute (used by `<polygon>` and `<polyline>`).
48
fn parse_svg_points(pts: &str, close: bool) -> Option<crate::svg::SvgMultiPolygon> {
48
    let nums: Vec<f32> = pts
80723
        .split(|c: char| c == ',' || c.is_ascii_whitespace())
40278
        .filter(|s| !s.is_empty())
40272
        .filter_map(|s| s.parse::<f32>().ok())
48
        .collect();
48
    if nums.len() < 4 || !nums.len().is_multiple_of(2) {
6
        return None;
42
    }
42
    let mut elements = Vec::new();
42
    let points: Vec<azul_css::props::basic::SvgPoint> = nums
42
        .chunks_exact(2)
20132
        .map(|c| azul_css::props::basic::SvgPoint { x: c[0], y: c[1] })
42
        .collect();
20090
    for w in points.windows(2) {
20090
        elements.push(crate::svg::SvgPathElement::Line(crate::svg::SvgLine::new(
20090
            w[0], w[1],
20090
        )));
20090
    }
42
    if close && points.len() >= 2 {
26
        let first = points[0];
26
        let last = *points.last().unwrap();
26
        if (first.x - last.x).abs() > 0.001 || (first.y - last.y).abs() > 0.001 {
25
            elements.push(crate::svg::SvgPathElement::Line(crate::svg::SvgLine::new(
25
                last, first,
25
            )));
25
        }
16
    }
42
    Some(crate::svg::SvgMultiPolygon {
42
        rings: crate::svg::SvgPathVec::from_vec(vec![crate::svg::SvgPath {
42
            items: crate::svg::SvgPathElementVec::from_vec(elements),
42
        }]),
42
    })
48
}
/// Fast XML to Dom conversion that builds Dom tree directly without intermediate `StyledDom`
/// This is O(n) instead of O(n²) for large documents
/// Apply the shared set of XML attributes onto a single [`NodeData`] node.
///
/// Handles `<img src>` rebuild, `id`/`class`, `focusable`, `tabindex`, inline
/// `style`, and SVG-shape geometry — the block that was previously duplicated
/// verbatim between [`xml_node_to_dom_fast`] (operating on `dom.root`) and
/// [`xml_node_to_fast_dom`] (operating on the arena `NodeData`). `component_name`
/// must already be normalized (lowercased); the caller computes `child_inside_svg`.
// Large but cohesive: one branch per input variant. Splitting the dispatch
// would scatter the attribute table it exists to keep in one place.
#[allow(clippy::too_many_lines, clippy::cognitive_complexity)]
45156
fn apply_xml_node_attributes(
45156
    node: &mut crate::dom::NodeData,
45156
    xml_node: &XmlNode,
45156
    component_name: &str,
45156
    inside_svg: bool,
45156
) {
    use crate::dom::{IdOrClass, NodeType, TabIndex};
    // `<img src="...">`: rebuild the placeholder Image node so its `NullImage`
    // carries the `src` string (as UTF-8 bytes in `tag`). The bytes are NOT
    // resolved here — a downstream renderer (printpdf, the compositor, ...) uses
    // the tag to look up and embed the actual image. Optional `width`/`height`
    // attributes set the intrinsic size used for layout (CSS still overrides).
45156
    if component_name == "img" {
2
        if let Some(src) = xml_node.attributes.get_key("src") {
2
            let width = xml_node
2
                .attributes
2
                .get_key("width")
2
                .and_then(|w| {
2
                    w.as_str()
2
                        .trim()
2
                        .trim_end_matches("px")
2
                        .trim()
2
                        .parse::<usize>()
2
                        .ok()
2
                })
2
                .unwrap_or(0);
2
            let height = xml_node
2
                .attributes
2
                .get_key("height")
2
                .and_then(|h| {
2
                    h.as_str()
2
                        .trim()
2
                        .trim_end_matches("px")
2
                        .trim()
2
                        .parse::<usize>()
2
                        .ok()
2
                })
2
                .unwrap_or(0);
2
            let image_ref = crate::resources::ImageRef::null_image(
2
                width,
2
                height,
2
                crate::resources::RawImageFormat::RGBA8,
2
                src.as_str().as_bytes().to_vec(),
            );
2
            node.set_node_type(NodeType::Image(azul_css::css::BoxOrStatic::heap(image_ref)));
        }
45154
    }
    // Set id and class attributes
45156
    let mut ids_and_classes = Vec::new();
45156
    if let Some(id_str) = xml_node.attributes.get_key("id") {
302
        for id in id_str.split_whitespace() {
302
            ids_and_classes.push(IdOrClass::Id(id.into()));
302
        }
44854
    }
45156
    if let Some(class_str) = xml_node.attributes.get_key("class") {
3792
        for class in class_str.split_whitespace() {
3792
            ids_and_classes.push(IdOrClass::Class(class.into()));
3792
        }
41364
    }
45156
    if !ids_and_classes.is_empty() {
4094
        node.set_ids_and_classes(ids_and_classes.into());
41062
    }
    // Handle focusable attribute
45156
    if let Some(focusable) = xml_node
45156
        .attributes
45156
        .get_key("focusable")
45156
        .and_then(|f| parse_bool(f.as_str()))
    {
9
        if focusable {
9
            node.set_tab_index(TabIndex::Auto);
9
        } else {
            node.set_tab_index(TabIndex::NoKeyboardFocus);
        }
45147
    }
    // Handle tabindex attribute
45156
    if let Some(tab_index) = xml_node
45156
        .attributes
45156
        .get_key("tabindex")
45156
        .and_then(|val| val.parse::<isize>().ok())
    {
4
        match tab_index {
1
            0 => node.set_tab_index(TabIndex::Auto),
4
            i if i > 0 => node.set_tab_index(TabIndex::OverrideInParent(
2
                u32::try_from(i).unwrap_or(u32::MAX),
2
            )),
2
            _ => node.set_tab_index(TabIndex::NoKeyboardFocus),
        }
45151
    }
    // Table cell span attributes (`colspan` / `rowspan`).
45156
    apply_cell_span_attributes(node, xml_node);
    // HTML `dir` attribute → the `direction` CSS property (dir="rtl"/"ltr"). Without
    // this, dir="rtl" (the common way to set RTL in HTML) had no effect. Appended
    // BEFORE the inline `style` below so author style still wins on equal specificity.
45156
    let dir_prop = xml_node.attributes.get_key("dir").and_then(|d| {
        let v = d.as_str().trim();
        if v.eq_ignore_ascii_case("rtl") {
            Some(azul_css::props::style::StyleDirection::Rtl)
        } else if v.eq_ignore_ascii_case("ltr") {
            Some(azul_css::props::style::StyleDirection::Ltr)
        } else {
            None
        }
    });
    // `<svg>`: its own viewport. Two things have to come off the element, and
    // both were being dropped.
    //
    //   * the `viewBox`, which is the element's USER-SPACE coordinate system.
    //     `SvgNodeData::ViewBox` existed as a variant but nothing ever produced one, so a parsed
    //     `<svg>` had no record of what coordinate space its children were drawn in.
    //   * an INTRINSIC SIZE. An `<svg>` is a replaced element: it is as big as `width`/`height`
    //     say, and failing that as big as its viewBox (SVG's own default sizing rule). Without one
    //     the element lays out 0x0 and takes no space at all - which is what an icon parsed
    //     straight from a theme file did, and why it came out blank.
    //
    // These are INTRINSIC dimensions, not a demand: they are pushed ahead of
    // the inline `style` below, so a call site that says how big it wants the
    // thing still wins.
45156
    let mut intrinsic_props: Vec<azul_css::dynamic_selector::CssPropertyWithConditions> =
45156
        Vec::new();
45156
    if component_name == "svg" {
529
        let view_box = xml_node
529
            .attributes
529
            .get_key("viewBox")
529
            .or_else(|| xml_node.attributes.get_key("viewbox"))
529
            .and_then(|v| parse_svg_view_box(v.as_str()));
529
        if let Some((min_x, min_y, width, height)) = view_box {
216
            node.set_svg_data(crate::dom::SvgNodeData::ViewBox {
216
                min_x,
216
                min_y,
216
                width,
216
                height,
216
            });
313
        }
1058
        let stated = |key: &str| parse_svg_length(xml_node.attributes.get_key(key));
529
        let usable = |v: f32| v.is_finite() && v > 0.0;
529
        if let Some(w) = stated("width")
529
            .or_else(|| view_box.map(|(_, _, w, _)| w))
529
            .filter(|w| usable(*w))
216
        {
216
            intrinsic_props.push(
216
                azul_css::dynamic_selector::CssPropertyWithConditions::simple(
216
                    azul_css::props::property::CssProperty::width(
216
                        azul_css::props::layout::LayoutWidth::px(w),
216
                    ),
216
                ),
216
            );
313
        }
529
        if let Some(h) = stated("height")
529
            .or_else(|| view_box.map(|(_, _, _, h)| h))
529
            .filter(|h| usable(*h))
216
        {
216
            intrinsic_props.push(
216
                azul_css::dynamic_selector::CssPropertyWithConditions::simple(
216
                    azul_css::props::property::CssProperty::height(
216
                        azul_css::props::layout::LayoutHeight::px(h),
216
                    ),
216
                ),
216
            );
313
        }
44627
    }
    // An SVG SHAPE is painted by filling its own box and clipping that box to
    // its geometry (`SvgNodeData::*`, pushed as a clip mask by the display
    // list). Two things make that work, and both are ordinary CSS:
    //
    //   * the box has to BE the `<svg>`'s viewport - the clip mask is rasterised into the node's
    //     paint rect, so a shape that laid out as an ordinary in-flow block would be clipped
    //     against the wrong rectangle (and, being empty, would be 0-high anyway);
    //   * `fill` has to reach the cascade. The presentation ATTRIBUTE is translated here;
    //     `style="fill:…"` and a stylesheet rule need nothing, because `fill` is an accepted
    //     spelling of `background-color` (`COMBINED_CSS_PROPERTIES_KEY_MAP`).
    //
    // `fill="none"` deliberately emits NOTHING rather than a transparent
    // background: it must not shadow a stylesheet rule that does set a fill.
45156
    if inside_svg
432
        && matches!(
480
            component_name,
480
            "path" | "circle" | "rect" | "ellipse" | "line" | "polygon" | "polyline"
        )
    {
        use azul_css::props::{
            layout::{LayoutInsetBottom, LayoutLeft, LayoutPosition, LayoutRight, LayoutTop},
            property::CssProperty,
        };
432
        let simple = azul_css::dynamic_selector::CssPropertyWithConditions::simple;
432
        intrinsic_props.push(simple(CssProperty::const_position(
432
            LayoutPosition::Absolute,
432
        )));
432
        intrinsic_props.push(simple(CssProperty::const_left(LayoutLeft::const_px(0))));
432
        intrinsic_props.push(simple(CssProperty::const_top(LayoutTop::const_px(0))));
432
        intrinsic_props.push(simple(CssProperty::const_right(LayoutRight::const_px(0))));
432
        intrinsic_props.push(simple(CssProperty::const_bottom(
432
            LayoutInsetBottom::const_px(0),
432
        )));
432
        if let Some(fill) = xml_node.attributes.get_key("fill") {
108
            let fill = fill.as_str().trim();
108
            if fill != "none" {
72
                if let Ok(color) = azul_css::props::basic::color::parse_css_color(fill) {
72
                    intrinsic_props.push(simple(CssProperty::const_background_content(
72
                        azul_css::props::style::StyleBackgroundContentVec::from_vec(vec![
72
                            azul_css::props::style::StyleBackgroundContent::Color(color),
72
                        ]),
72
                    )));
72
                }
36
            }
324
        }
        // The STROKE, as the box's border - the display list turns it into a
        // stroked path rather than a rectangle. Both halves are translated
        // here only for the presentation ATTRIBUTE; `style="stroke:…"` and a
        // stylesheet rule need nothing, because `stroke`/`stroke-width` are
        // accepted spellings of `border-color`/`border-width`.
432
        if let Some(stroke) = xml_node.attributes.get_key("stroke") {
24
            let stroke = stroke.as_str().trim();
24
            if stroke != "none" {
24
                if let Ok(color) = azul_css::props::basic::color::parse_css_color(stroke) {
                    use azul_css::props::style::{
                        StyleBorderBottomColor, StyleBorderLeftColor, StyleBorderRightColor,
                        StyleBorderTopColor,
                    };
24
                    intrinsic_props.push(simple(CssProperty::const_border_top_color(
24
                        StyleBorderTopColor { inner: color },
24
                    )));
24
                    intrinsic_props.push(simple(CssProperty::const_border_right_color(
24
                        StyleBorderRightColor { inner: color },
24
                    )));
24
                    intrinsic_props.push(simple(CssProperty::const_border_bottom_color(
24
                        StyleBorderBottomColor { inner: color },
24
                    )));
24
                    intrinsic_props.push(simple(CssProperty::const_border_left_color(
24
                        StyleBorderLeftColor { inner: color },
24
                    )));
                }
            }
408
        }
        // `stroke-width` is in USER UNITS, like every other geometry
        // attribute - not a CSS length.
432
        if let Some(width) = parse_svg_float(xml_node.attributes.get_key("stroke-width")) {
24
            if width.is_finite() && width > 0.0 {
                use azul_css::props::style::{
                    LayoutBorderBottomWidth, LayoutBorderLeftWidth, LayoutBorderRightWidth,
                    LayoutBorderTopWidth,
                };
24
                let px = azul_css::props::basic::PixelValue::px(width);
24
                intrinsic_props.push(simple(CssProperty::const_border_top_width(
24
                    LayoutBorderTopWidth { inner: px },
24
                )));
24
                intrinsic_props.push(simple(CssProperty::const_border_right_width(
24
                    LayoutBorderRightWidth { inner: px },
24
                )));
24
                intrinsic_props.push(simple(CssProperty::const_border_bottom_width(
24
                    LayoutBorderBottomWidth { inner: px },
24
                )));
24
                intrinsic_props.push(simple(CssProperty::const_border_left_width(
24
                    LayoutBorderLeftWidth { inner: px },
24
                )));
            }
408
        }
44724
    }
    // `<svg>` is the positioning context its shapes resolve against.
45156
    if component_name == "svg" {
529
        intrinsic_props.push(
529
            azul_css::dynamic_selector::CssPropertyWithConditions::simple(
529
                azul_css::props::property::CssProperty::const_position(
529
                    azul_css::props::layout::LayoutPosition::Relative,
529
                ),
529
            ),
529
        );
44627
    }
    // Handle inline style attribute (and the mapped `dir` attribute above)
45156
    let style_attr = xml_node.attributes.get_key("style");
45156
    if style_attr.is_some() || dir_prop.is_some() || !intrinsic_props.is_empty() {
        use azul_css::dynamic_selector::CssPropertyWithConditions;
985
        let css_key_map = azul_css::props::property::get_css_key_map();
985
        let mut props: Vec<CssPropertyWithConditions> = intrinsic_props;
985
        if let Some(dir) = dir_prop {
            props.push(CssPropertyWithConditions::simple(
                azul_css::props::property::CssProperty::Direction(
                    azul_css::css::CssPropertyValue::Exact(dir),
                ),
            ));
985
        }
985
        if let Some(style) = style_attr {
36
            let mut attributes = Vec::new();
72
            for s in style.as_str().split(';') {
72
                let mut s = s.split(':');
72
                let Some(key) = s.next() else {
                    continue;
                };
72
                let Some(value) = s.next() else {
24
                    continue;
                };
                // Called for its side effect (writes parsed props into `attributes`);
                // the returned value is intentionally discarded.
48
                drop(azul_css::parser2::parse_css_declaration(
48
                    key.trim(),
48
                    value.trim(),
48
                    azul_css::parser2::ErrorLocationRange::default(),
48
                    &css_key_map,
48
                    &mut Vec::new(),
48
                    &mut attributes,
                ));
            }
48
            props.extend(attributes.into_iter().filter_map(|s| match s {
48
                CssDeclaration::Static(s) => Some(CssPropertyWithConditions::simple(s)),
                CssDeclaration::Dynamic(_) => None,
48
            }));
949
        }
985
        if !props.is_empty() {
985
            node.set_css_props(props.into());
985
        }
44171
    }
    // Handle SVG shape elements when inside an <svg> context
45156
    let tag = component_name;
45156
    let is_svg_shape = inside_svg
432
        && matches!(
480
            tag,
480
            "path" | "circle" | "rect" | "ellipse" | "line" | "polygon" | "polyline"
        );
45156
    if is_svg_shape {
432
        let clip = match tag {
432
            "path" => xml_node
132
                .attributes
132
                .get_key("d")
132
                .and_then(|d| crate::path_parser::parse_svg_path_d(d.as_str()).ok()),
300
            "circle" => {
60
                let cx = parse_svg_float(xml_node.attributes.get_key("cx")).unwrap_or(0.0);
60
                let cy = parse_svg_float(xml_node.attributes.get_key("cy")).unwrap_or(0.0);
60
                let r = parse_svg_float(xml_node.attributes.get_key("r")).unwrap_or(0.0);
60
                if r > 0.0 {
48
                    Some(crate::svg::SvgMultiPolygon {
48
                        rings: crate::svg::SvgPathVec::from_vec(vec![
48
                            crate::path_parser::svg_circle_to_paths(cx, cy, r),
48
                        ]),
48
                    })
                } else {
12
                    None
                }
            }
240
            "rect" => {
168
                let x = parse_svg_float(xml_node.attributes.get_key("x")).unwrap_or(0.0);
168
                let y = parse_svg_float(xml_node.attributes.get_key("y")).unwrap_or(0.0);
168
                let w = parse_svg_float(xml_node.attributes.get_key("width")).unwrap_or(0.0);
168
                let h = parse_svg_float(xml_node.attributes.get_key("height")).unwrap_or(0.0);
168
                let rx = parse_svg_float(xml_node.attributes.get_key("rx")).unwrap_or(0.0);
168
                let ry = parse_svg_float(xml_node.attributes.get_key("ry")).unwrap_or(rx);
168
                if w > 0.0 && h > 0.0 {
156
                    Some(crate::svg::SvgMultiPolygon {
156
                        rings: crate::svg::SvgPathVec::from_vec(vec![
156
                            crate::path_parser::svg_rect_to_path(x, y, w, h, rx, ry),
156
                        ]),
156
                    })
                } else {
12
                    None
                }
            }
72
            "ellipse" => {
24
                let cx = parse_svg_float(xml_node.attributes.get_key("cx")).unwrap_or(0.0);
24
                let cy = parse_svg_float(xml_node.attributes.get_key("cy")).unwrap_or(0.0);
24
                let rx = parse_svg_float(xml_node.attributes.get_key("rx")).unwrap_or(0.0);
24
                let ry = parse_svg_float(xml_node.attributes.get_key("ry")).unwrap_or(0.0);
24
                if rx > 0.0 && ry > 0.0 {
                    // Approximate ellipse with 4 cubic beziers (using rx for x-kappa, ry for
                    // y-kappa)
                    use azul_css::props::basic::{SvgCubicCurve, SvgPoint};
                    const KAPPA: f32 = 0.552_284_8;
24
                    let kx = rx * KAPPA;
24
                    let ky = ry * KAPPA;
24
                    let elements = vec![
24
                        crate::svg::SvgPathElement::CubicCurve(SvgCubicCurve {
24
                            start: SvgPoint { x: cx, y: cy - ry },
24
                            ctrl_1: SvgPoint {
24
                                x: cx + kx,
24
                                y: cy - ry,
24
                            },
24
                            ctrl_2: SvgPoint {
24
                                x: cx + rx,
24
                                y: cy - ky,
24
                            },
24
                            end: SvgPoint { x: cx + rx, y: cy },
24
                        }),
24
                        crate::svg::SvgPathElement::CubicCurve(SvgCubicCurve {
24
                            start: SvgPoint { x: cx + rx, y: cy },
24
                            ctrl_1: SvgPoint {
24
                                x: cx + rx,
24
                                y: cy + ky,
24
                            },
24
                            ctrl_2: SvgPoint {
24
                                x: cx + kx,
24
                                y: cy + ry,
24
                            },
24
                            end: SvgPoint { x: cx, y: cy + ry },
24
                        }),
24
                        crate::svg::SvgPathElement::CubicCurve(SvgCubicCurve {
24
                            start: SvgPoint { x: cx, y: cy + ry },
24
                            ctrl_1: SvgPoint {
24
                                x: cx - kx,
24
                                y: cy + ry,
24
                            },
24
                            ctrl_2: SvgPoint {
24
                                x: cx - rx,
24
                                y: cy + ky,
24
                            },
24
                            end: SvgPoint { x: cx - rx, y: cy },
24
                        }),
24
                        crate::svg::SvgPathElement::CubicCurve(SvgCubicCurve {
24
                            start: SvgPoint { x: cx - rx, y: cy },
24
                            ctrl_1: SvgPoint {
24
                                x: cx - rx,
24
                                y: cy - ky,
24
                            },
24
                            ctrl_2: SvgPoint {
24
                                x: cx - kx,
24
                                y: cy - ry,
24
                            },
24
                            end: SvgPoint { x: cx, y: cy - ry },
24
                        }),
                    ];
24
                    Some(crate::svg::SvgMultiPolygon {
24
                        rings: crate::svg::SvgPathVec::from_vec(vec![crate::svg::SvgPath {
24
                            items: crate::svg::SvgPathElementVec::from_vec(elements),
24
                        }]),
24
                    })
                } else {
                    None
                }
            }
48
            "line" => {
12
                let x1 = parse_svg_float(xml_node.attributes.get_key("x1")).unwrap_or(0.0);
12
                let y1 = parse_svg_float(xml_node.attributes.get_key("y1")).unwrap_or(0.0);
12
                let x2 = parse_svg_float(xml_node.attributes.get_key("x2")).unwrap_or(0.0);
12
                let y2 = parse_svg_float(xml_node.attributes.get_key("y2")).unwrap_or(0.0);
12
                Some(crate::svg::SvgMultiPolygon {
12
                    rings: crate::svg::SvgPathVec::from_vec(vec![crate::svg::SvgPath {
12
                        items: crate::svg::SvgPathElementVec::from_vec(vec![
12
                            crate::svg::SvgPathElement::Line(crate::svg::SvgLine::new(
12
                                azul_css::props::basic::SvgPoint { x: x1, y: y1 },
12
                                azul_css::props::basic::SvgPoint { x: x2, y: y2 },
12
                            )),
12
                        ]),
12
                    }]),
12
                })
            }
36
            "polygon" | "polyline" => xml_node
36
                .attributes
36
                .get_key("points")
36
                .and_then(|pts| parse_svg_points(pts.as_str(), tag == "polygon")),
            _ => None,
        };
432
        if let Some(mp) = clip {
408
            node.set_svg_data(crate::dom::SvgNodeData::Path(mp));
408
        }
44724
    }
45156
}
/// Parse the HTML `colspan` / `rowspan` presentational attributes into
/// `AttributeType`s on the node. The table layout reads them back via
/// `get_cell_spans`. Without this the XML→DOM conversion dropped them and every
/// cell defaulted to span 1, so `<th colspan="2">` only covered one column.
/// Parsed unconditionally — non-cell elements simply don't carry these attributes.
45156
fn apply_cell_span_attributes(node: &mut crate::dom::NodeData, xml_node: &XmlNode) {
45156
    let mut spans = Vec::new();
45156
    if let Some(n) = xml_node
45156
        .attributes
45156
        .get_key("colspan")
45156
        .and_then(|v| v.as_str().trim().parse::<i32>().ok())
    {
        spans.push(crate::dom::AttributeType::ColSpan(n));
45156
    }
45156
    if let Some(n) = xml_node
45156
        .attributes
45156
        .get_key("rowspan")
45156
        .and_then(|v| v.as_str().trim().parse::<i32>().ok())
    {
        spans.push(crate::dom::AttributeType::RowSpan(n));
45156
    }
45156
    if !spans.is_empty() {
        let mut v = node.attributes().clone().into_library_owned_vec();
        v.extend(spans);
        node.set_attributes(v.into());
45156
    }
45156
}
#[allow(clippy::result_large_err)]
// returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
// component_map is threaded through the whole fast-DOM pipeline for parity with the
// component-expanding interpreter path (see ~xml.rs:2845); this fast path never expands
// components, so it only forwards the map into recursive calls. Removing it here would
// cascade unused-param removals up the entire pipeline.
#[allow(clippy::only_used_in_recursion)]
/// Every `<style>` element's text in this subtree, in document order.
///
/// Depth-bounded for the same reason the DOM conversion is: this reads files
/// nothing in this build produced.
373
fn collect_style_text(node: &XmlNode, out: &mut Vec<String>, depth: usize) {
373
    if depth >= MAX_XML_NESTING_DEPTH {
        return;
373
    }
577
    for child in node.children.as_ref() {
576
        let XmlNodeChild::Element(element) = child else {
360
            continue;
        };
216
        if normalize_casing(&element.node_type) == "style" {
24
            let text = element.get_text_content();
24
            if !text.is_empty() {
24
                out.push(text);
24
            }
192
        } else {
192
            collect_style_text(element, out, depth + 1);
192
        }
    }
373
}
// `component_map` is threaded through purely to reach the recursive calls; it
// stays in the signature because the sibling `xml_node_to_fast_dom` reads it and
// the two must keep the same shape. `RenderDomError` is large but is the crate's
// public XML error type, shared with the C ABI, so it is not boxed here.
#[allow(clippy::only_used_in_recursion, clippy::result_large_err)]
8179
fn xml_node_to_dom_fast<'a>(
8179
    xml_node: &'a XmlNode,
8179
    component_map: &'a ComponentMap,
8179
    inside_svg: bool,
8179
    depth: usize,
8179
) -> Result<Dom, RenderDomError> {
    use crate::dom::Dom;
8179
    let component_name = normalize_casing(&xml_node.node_type);
    // Look up the component definition
8179
    let node_type = tag_to_node_type(&component_name);
8179
    let mut dom = Dom::create_node(node_type);
8179
    apply_xml_node_attributes(&mut dom.root, xml_node, &component_name, inside_svg);
8179
    let child_inside_svg = inside_svg || component_name == "svg";
    // AUDIT 2026-07-08: bound recursion depth to avoid a native stack overflow on
    // pathologically deep markup. At the cap, this node is emitted without its
    // children (truncation) rather than crashing the process.
    // AUDIT-TODO: a worklist-based iterative builder would preserve deep subtrees.
8179
    if depth >= MAX_XML_NESTING_DEPTH {
15
        return Ok(dom);
8164
    }
    // Recursively convert children
8164
    let mut children = Vec::new();
    // A `<style>` found INSIDE the tree - an SVG's own `<defs><style>`, above
    // all - is a stylesheet, not content. In azul a stylesheet is an ATTRIBUTE
    // of a node (`Dom.css`, scoped to that subtree by `scope_inline_css`)
    // rather than a node of its own, so it has to be recognised HERE, at the
    // input, and hung on the element that contains it. Leaving it as a node
    // rendered the CSS source as visible text.
    //
    // Scoping to the subtree is exactly right for the case that motivates it:
    // an icon's `.ColorScheme-Text { color:… }` is meant for that icon, and
    // must not reach the rest of the document.
8164
    let mut scoped_css: Vec<Css> = Vec::new();
    // An `<svg>`'s stylesheet is SVG-GLOBAL: it is nearly always written in
    // `<defs><style>`, and `<defs>` is a definition container that draws
    // nothing - attaching the sheet there would scope it to a subtree with no
    // shapes in it. Collected from the whole subtree and hung on the `<svg>`,
    // which is as global as it should ever get.
8164
    if component_name == "svg" {
181
        let mut texts = Vec::new();
181
        collect_style_text(xml_node, &mut texts, 0);
205
        for text in texts {
24
            scoped_css.push(Css::from_string(text.into()));
24
        }
7983
    }
9712
    for child in xml_node.children.as_ref() {
7859
        match child {
7859
            XmlNodeChild::Element(child_node)
7859
                if normalize_casing(&child_node.node_type) == "style" =>
            {
                // Never a rendered node. Inside an `<svg>` it was already
                // hoisted above; elsewhere it scopes to THIS element.
24
                if component_name != "svg" {
24
                    let text = child_node.get_text_content();
24
                    if !text.is_empty() {
24
                        scoped_css.push(Css::from_string(text.into()));
24
                    }
                }
            }
7835
            XmlNodeChild::Element(child_node) => {
7835
                let child_dom =
7835
                    xml_node_to_dom_fast(child_node, component_map, child_inside_svg, depth + 1)?;
7835
                children.push(child_dom);
            }
1839
            XmlNodeChild::Text(text) => {
1839
                let text_dom = Dom::create_text_do_not_use_without_block_level_wrapper(
1839
                    AzString::from(text.as_str()),
1839
                );
1839
                children.push(text_dom);
1839
            }
        }
    }
8164
    if !children.is_empty() {
7897
        dom = dom.with_children(children.into());
7897
    }
8212
    for css in scoped_css {
48
        dom.add_component_css(css);
48
    }
8164
    Ok(dom)
8179
}
/// Builder for arena-based DOM construction (`FastDom`).
/// Builds two parallel Vecs (hierarchy + `node_data`) in a single DFS pass.
#[derive(Debug)]
pub struct CompactDomBuilder {
    hierarchy: Vec<crate::styled_dom::NodeHierarchyItem>,
    node_data: Vec<crate::dom::NodeData>,
    css: Vec<crate::dom::CssWithNodeId>,
    /// Stack of (`node_index`, `previous_child_index`) for open elements
    stack: Vec<(usize, Option<usize>)>,
}
impl Default for CompactDomBuilder {
1
    fn default() -> Self {
1
        Self::new()
1
    }
}
impl CompactDomBuilder {
    #[must_use]
3249
    pub const fn new() -> Self {
3249
        Self {
3249
            hierarchy: Vec::new(),
3249
            node_data: Vec::new(),
3249
            css: Vec::new(),
3249
            stack: Vec::new(),
3249
        }
3249
    }
    #[must_use]
2275
    pub fn with_capacity(cap: usize) -> Self {
2275
        Self {
2275
            hierarchy: Vec::with_capacity(cap),
2275
            node_data: Vec::with_capacity(cap),
2275
            css: Vec::new(),
2275
            stack: Vec::new(),
2275
        }
2275
    }
    /// Open a new element node. Must be paired with `close_node()`.
221790
    pub fn open_node(&mut self, node_data: crate::dom::NodeData) {
        use crate::{id::NodeId, styled_dom::NodeHierarchyItem};
221790
        let idx = self.hierarchy.len();
        // Determine parent from stack
221790
        let parent_raw = if let Some(&(parent_idx, _)) = self.stack.last() {
216921
            NodeId::into_raw(&Some(NodeId::new(parent_idx)))
        } else {
4869
            0 // No parent (root)
        };
        // Determine previous sibling from parent's last child tracking
221790
        let prev_sibling_raw = if let Some(&(_, prev_child)) = self.stack.last() {
216921
            prev_child.map_or(0, |pi| NodeId::into_raw(&Some(NodeId::new(pi))))
        } else {
4869
            0
        };
        // If there's a previous sibling, set its next_sibling to us
221790
        if let Some(&(_, Some(prev_idx))) = self.stack.last() {
54901
            self.hierarchy[prev_idx].next_sibling = NodeId::into_raw(&Some(NodeId::new(idx)));
167241
        }
        // Update parent's "last seen child" to us
221790
        if let Some(parent) = self.stack.last_mut() {
216921
            parent.1 = Some(idx);
216921
        }
        // Push the hierarchy item (last_child will be set in close_node)
221790
        self.hierarchy.push(NodeHierarchyItem {
221790
            parent: parent_raw,
221790
            previous_sibling: prev_sibling_raw,
221790
            next_sibling: 0, // Will be set by next sibling's open_node
221790
            last_child: 0,   // Will be set in close_node
221790
        });
221790
        self.node_data.push(node_data);
        // Push onto stack: this node is now the "open" element, no children yet
221790
        self.stack.push((idx, None));
221790
    }
    /// Close the current element. Sets the `last_child` pointer.
221791
    pub fn close_node(&mut self) {
        use crate::id::NodeId;
221791
        if let Some((idx, last_child_idx)) = self.stack.pop() {
            // Set last_child on this node's hierarchy item
221693
            self.hierarchy[idx].last_child =
221693
                last_child_idx.map_or(0, |lc| NodeId::into_raw(&Some(NodeId::new(lc))));
98
        }
221791
    }
    /// Add a leaf node (text, br, hr, etc.) that has no children.
57173
    pub fn add_leaf(&mut self, node_data: crate::dom::NodeData) {
57173
        self.open_node(node_data);
57173
        self.close_node();
57173
    }
    /// Add a CSS stylesheet scoped to a node ID.
2
    pub fn add_css(&mut self, node_id: usize, css: Css) {
2
        self.css.push(crate::dom::CssWithNodeId { node_id, css });
2
    }
    /// Finish building and produce a `FastDom`.
    #[must_use]
4995
    pub fn finish(self) -> crate::dom::FastDom {
4995
        crate::dom::FastDom {
4995
            node_hierarchy: self.hierarchy.into(),
4995
            node_data: self.node_data.into(),
4995
            css: self.css.into(),
4995
        }
4995
    }
}
/// Convert an XML node tree into a `FastDom` (arena-based) in a single DFS pass.
/// This is the fast path equivalent of `xml_node_to_dom_fast`.
#[allow(clippy::result_large_err)]
// returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
// See xml_node_to_dom_fast: component_map is forwarded for pipeline parity, not read here.
#[allow(clippy::only_used_in_recursion)]
36977
fn xml_node_to_fast_dom<'a>(
36977
    xml_node: &'a XmlNode,
36977
    component_map: &'a ComponentMap,
36977
    inside_svg: bool,
36977
    builder: &mut CompactDomBuilder,
36977
    depth: usize,
36977
) -> Result<(), RenderDomError> {
    use crate::dom::NodeData;
36977
    let component_name = normalize_casing(&xml_node.node_type);
36977
    let node_type = tag_to_node_type(&component_name);
36977
    let mut node_data = NodeData::create_node(node_type);
36977
    apply_xml_node_attributes(&mut node_data, xml_node, &component_name, inside_svg);
36977
    let child_inside_svg = inside_svg || component_name == "svg";
    // Open this node in the builder
36977
    builder.open_node(node_data);
    // AUDIT 2026-07-08: bound recursion depth to avoid a native stack overflow on
    // pathologically deep markup. At the cap, children are dropped (the node is
    // still opened+closed) rather than crashing the process.
    // AUDIT-TODO: a worklist-based iterative builder would preserve deep subtrees.
36977
    if depth < MAX_XML_NESTING_DEPTH {
        // Recursively convert children
89222
        for child in xml_node.children.as_ref() {
89211
            match child {
33734
                XmlNodeChild::Element(child_node) => {
33734
                    xml_node_to_fast_dom(
33734
                        child_node,
33734
                        component_map,
33734
                        child_inside_svg,
33734
                        builder,
33734
                        depth + 1,
                    )?;
                }
55477
                XmlNodeChild::Text(text) => {
55477
                    builder.add_leaf(
55477
                        NodeData::create_text_do_not_use_without_block_level_wrapper(
55477
                            AzString::from(text.as_str()),
55477
                        ),
55477
                    );
55477
                }
            }
        }
3
    }
    // Close this node
36977
    builder.close_node();
36977
    Ok(())
36977
}
/// Render a DOM from an XML body node using the fast arena-based path.
/// Builds a `FastDom` directly (no tree intermediary), then creates `StyledDom`.
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would
                                   // break the C ABI/api.json
3240
fn render_dom_from_body_node_fast<'a>(
3240
    body_node: &'a XmlNode,
3240
    mut global_css: Option<Css>,
3240
    component_map: &'a ComponentMap,
3240
    max_width: Option<f32>,
3240
) -> Result<StyledDom, RenderDomError> {
    use crate::dom::{NodeData, NodeType};
3240
    let mut builder = CompactDomBuilder::new();
    // Build the HTML > Body wrapper + body content in one pass
    // Open <html>
3240
    builder.open_node(NodeData::create_node(NodeType::Html));
    // Open <body> (the body_node content goes inside)
3240
    xml_node_to_fast_dom(body_node, component_map, false, &mut builder, 0)?;
    // Close <html>
3240
    builder.close_node();
    // Collect CSS rules from each source.
3240
    let mut combined_rules: Vec<CssRuleBlock> = Vec::new();
3240
    if let Some(max_width) = max_width {
8
        let max_width_css =
8
            Css::from_string(format!("html {{ max-width: {max_width}px; }}").into());
8
        combined_rules.extend(max_width_css.rules.into_library_owned_vec());
3236
    }
3240
    let mut combined_keyframes = Vec::new();
3240
    if let Some(css) = global_css.take() {
2677
        combined_rules.extend(css.rules.into_library_owned_vec());
2677
        combined_keyframes.extend(css.keyframes.into_library_owned_vec());
2687
    }
3240
    let mut combined_css = Css::new(combined_rules);
3240
    combined_css.keyframes = combined_keyframes.into();
    // Add CSS to the FastDom
3240
    let mut fast_dom = builder.finish();
3240
    fast_dom.css = vec![crate::dom::CssWithNodeId {
3240
        node_id: 0, // Global scope (root)
3240
        css: combined_css,
3240
    }]
3240
    .into();
    // Create StyledDom via the fast path (no tree→arena conversion)
3240
    let styled = StyledDom::create_from_fast_dom(fast_dom);
3240
    Ok(styled)
3240
}
// render_dom_from_body_node() removed — use render_dom_from_body_node_fast() or str_to_dom()
15
fn set_stringified_attributes(
15
    dom_string: &mut String,
15
    xml_attributes: &XmlAttributeMap,
15
    filtered_xml_attributes: &ComponentArgumentVec,
15
    tabs: usize,
15
) {
15
    let t0 = String::from("    ").repeat(tabs);
15
    let t = String::from("    ").repeat(tabs + 1);
    // push ids and classes as chained `.with_id("..")` / `.with_class("..")`
    // calls (public builder API; both take `Into<AzString>`, so bare &str works).
15
    let _ = &t;
15
    for id in xml_attributes
15
        .get_key("id")
15
        .map(|s| s.split_whitespace().collect::<Vec<_>>())
15
        .unwrap_or_default()
3
    {
3
        let _ = write!(
3
            dom_string,
3
            "\r\n{}.with_id(\"{}\")",
3
            t0,
3
            format_args_dynamic(id, filtered_xml_attributes)
3
        );
3
    }
15
    for class in xml_attributes
15
        .get_key("class")
15
        .map(|s| s.split_whitespace().collect::<Vec<_>>())
15
        .unwrap_or_default()
2
    {
2
        let _ = write!(
2
            dom_string,
2
            "\r\n{}.with_class(\"{}\")",
2
            t0,
2
            format_args_dynamic(class, filtered_xml_attributes)
2
        );
2
    }
15
    if let Some(focusable) = xml_attributes
15
        .get_key("focusable")
15
        .map(|f| format_args_dynamic(f, filtered_xml_attributes))
15
        .and_then(|f| parse_bool(&f))
    {
2
        if focusable {
1
            let _ = write!(dom_string, "\r\n{t}.with_tab_index(TabIndex::Auto)");
1
        } else {
1
            let _ = write!(
1
                dom_string,
1
                "\r\n{t}.with_tab_index(TabIndex::NoKeyboardFocus)"
1
            );
1
        }
13
    }
15
    if let Some(tab_index) = xml_attributes
15
        .get_key("tabindex")
15
        .map(|val| format_args_dynamic(val, filtered_xml_attributes))
15
        .and_then(|val| val.parse::<isize>().ok())
    {
2
        match tab_index {
1
            0 => {
1
                let _ = write!(dom_string, "\r\n{t}.with_tab_index(TabIndex::Auto)");
1
            }
2
            i if i > 0 => {
1
                let _ = write!(
1
                    dom_string,
1
                    "\r\n{}.with_tab_index(TabIndex::OverrideInParent({}))",
1
                    t,
1
                    usize::try_from(i).unwrap_or(0)
1
                );
1
            }
1
            _ => {
1
                let _ = write!(
1
                    dom_string,
1
                    "\r\n{t}.with_tab_index(TabIndex::NoKeyboardFocus)"
1
                );
1
            }
        }
12
    }
15
}
/// Item of a split string - either a variable name (with optional format spec) or a string
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub enum DynamicItem {
    /// A variable reference, e.g. {counter} or {counter:?} or {price:.2}
    Var {
        name: String,
        /// Optional format specifier after the colon: "?" for debug, ".2" for precision, etc.
        format_spec: Option<String>,
    },
    Str(String),
}
/// Splits a string into formatting arguments, supporting format specifiers like `{var:?}`
/// ```rust
/// # use azul_core::xml::DynamicItem::*;
/// # use azul_core::xml::split_dynamic_string;
/// let s = "hello {a}, {b}{{ {c} }}";
/// let split = split_dynamic_string(s);
/// let output = vec![
///     Str("hello ".to_string()),
///     Var {
///         name: "a".to_string(),
///         format_spec: None,
///     },
///     Str(", ".to_string()),
///     Var {
///         name: "b".to_string(),
///         format_spec: None,
///     },
///     Str("{ ".to_string()),
///     Var {
///         name: "c".to_string(),
///         format_spec: None,
///     },
///     Str(" }".to_string()),
/// ];
/// assert_eq!(output, split);
/// ```
#[must_use]
41
pub fn split_dynamic_string(input: &str) -> Vec<DynamicItem> {
    use self::DynamicItem::{Str, Var};
41
    let input: Vec<char> = input.chars().collect();
41
    let input_chars_len = input.len();
41
    let mut items = Vec::new();
41
    let mut current_idx = 0;
41
    let mut last_idx = 0;
150173
    while current_idx < input_chars_len {
150132
        let c = input[current_idx];
100023
        match c {
100023
            '{' if input.get(current_idx + 1).copied() != Some('{') => {
                // variable start, search until next closing brace or whitespace or end of string
22
                let mut start_offset = 1;
22
                let mut has_found_variable = false;
100069
                while let Some(c) = input.get(current_idx + start_offset) {
100066
                    if c.is_whitespace() {
3
                        break;
100063
                    }
100063
                    if *c == '}' && input.get(current_idx + start_offset + 1).copied() != Some('}')
                    {
16
                        start_offset += 1;
16
                        has_found_variable = true;
16
                        break;
100047
                    }
100047
                    start_offset += 1;
                }
                // advance current_idx accordingly
                // on fail, set cursor to end
                // set last_idx accordingly
22
                if has_found_variable {
16
                    if last_idx != current_idx {
8
                        items.push(Str(input[last_idx..current_idx].iter().collect()));
8
                    }
                    // subtract 1 from start for opening brace, one from end for closing brace
16
                    let var_content: String = input
16
                        [(current_idx + 1)..(current_idx + start_offset - 1)]
16
                        .iter()
16
                        .collect();
                    // Split on first ':' to separate variable name from format specifier
16
                    let (var_name, format_spec) = if let Some(colon_pos) = var_content.find(':') {
4
                        let name = var_content[..colon_pos].to_string();
4
                        let spec = var_content[(colon_pos + 1)..].to_string();
4
                        (name, Some(spec))
                    } else {
12
                        (var_content, None)
                    };
16
                    items.push(Var {
16
                        name: var_name,
16
                        format_spec,
16
                    });
16
                    current_idx += start_offset;
16
                    last_idx = current_idx;
6
                } else {
6
                    current_idx += start_offset;
6
                }
            }
150110
            _ => {
150110
                current_idx += 1;
150110
            }
        }
    }
41
    if current_idx != last_idx {
26
        items.push(Str(input[last_idx..].iter().collect()));
26
    }
91
    for item in &mut items {
        // replace {{ with { in strings
50
        if let Str(s) = item {
34
            *s = s.replace("{{", "{").replace("}}", "}");
34
        }
    }
41
    items
41
}
/// Combines the split string back into its original form while replacing the variables with their
/// values
///
/// let variables = btreemap!{ "a" => "value1", "b" => "value2" };
/// [Str("hello "), Var("a"), Str(", "), Var("b"), Str("{ "), Var("c"), Str(" }}")]
/// => "hello value1, valuec{ {c} }"
27
fn combine_and_replace_dynamic_items(
27
    input: &[DynamicItem],
27
    variables: &ComponentArgumentVec,
27
) -> String {
27
    let mut s = String::new();
58
    for item in input {
31
        match item {
8
            DynamicItem::Var { name, format_spec } => {
8
                let variable_name = normalize_casing(name.trim());
8
                if let Some(resolved_var) = variables
8
                    .iter()
8
                    .find(|s| s.name.as_str() == variable_name)
8
                    .map(|q| &q.arg_type)
4
                {
4
                    // Format specifiers are applied at compile time, not at runtime replacement
4
                    s.push_str(resolved_var);
4
                } else {
4
                    s.push('{');
4
                    s.push_str(name);
4
                    if let Some(spec) = format_spec {
1
                        s.push(':');
1
                        s.push_str(spec);
3
                    }
4
                    s.push('}');
                }
            }
23
            DynamicItem::Str(dynamic_str) => {
23
                s.push_str(dynamic_str);
23
            }
        }
    }
27
    s
27
}
/// Given a string and a key => value mapping, replaces parts of the string with the value, i.e.:
///
/// ```rust
/// # use azul_core::xml::{format_args_dynamic, ComponentArgument, ComponentArgumentVec};
/// # use azul_css::AzString;
/// let variables: ComponentArgumentVec = vec![
///     ComponentArgument {
///         name: AzString::from("a"),
///         arg_type: AzString::from("value1"),
///     },
///     ComponentArgument {
///         name: AzString::from("b"),
///         arg_type: AzString::from("value2"),
///     },
/// ]
/// .into();
///
/// let initial = "hello {a}, {b}{{ {c} }}";
/// let expected = "hello value1, value2{ {c} }".to_string();
/// assert_eq!(format_args_dynamic(initial, &variables), expected);
/// ```
///
/// Note: the number (0, 1, etc.) is the order of the argument, it is irrelevant for
/// runtime formatting, only important for keeping the component / function arguments
/// in order when compiling the arguments to Rust code
#[must_use]
26
pub fn format_args_dynamic(input: &str, variables: &ComponentArgumentVec) -> String {
26
    let dynamic_str_items = split_dynamic_string(input);
26
    combine_and_replace_dynamic_items(&dynamic_str_items, variables)
26
}
/// Decode a numeric character reference body (the part between `&` and `;`),
/// e.g. `"#65"` -> `'A'`, `"#x41"` -> `'A'`. Returns `None` if it is not a valid
/// numeric reference.
28
fn decode_numeric_entity(entity: &str) -> Option<char> {
28
    let num = entity.strip_prefix('#')?;
21
    let code = if let Some(hex) = num.strip_prefix(['x', 'X']) {
9
        u32::from_str_radix(hex, 16).ok()?
    } else {
12
        num.parse::<u32>().ok()?
    };
12
    char::from_u32(code)
28
}
/// Decode the common HTML/XML entities in a single left-to-right pass.
///
/// Handles `&lt;` `&gt;` `&amp;` `&quot;` `&apos;` and numeric references
/// (`&#NN;` / `&#xHH;`). `&nbsp;` and any unrecognized `&...;` sequence are left
/// verbatim. The single pass guarantees `&amp;` never double-decodes a following
/// entity. See [`prepare_string`] for why `&nbsp;` is deliberately preserved.
27
fn decode_entities(input: &str) -> String {
    // Longest handled entity body is a hex numeric ref like `#x10FFFF` (8 bytes);
    // cap the `;` search window so a stray `&` far from a `;` stays cheap.
    const MAX_ENTITY_BODY: usize = 12;
27
    let mut out = String::with_capacity(input.len());
27
    let bytes = input.as_bytes();
27
    let mut i = 0;
220152
    while i < input.len() {
220125
        if bytes[i] == b'&' {
20023
            if let Some(semi_rel) = input[i + 1..].find(';') {
22
                if semi_rel <= MAX_ENTITY_BODY {
21
                    let body = &input[i + 1..i + 1 + semi_rel];
21
                    let end = i + 1 + semi_rel; // index of ';'
                                                // Leave &nbsp; for the per-line pass in
                                                // prepare_string.
21
                    if body.eq_ignore_ascii_case("nbsp") {
3
                        out.push_str(&input[i..=end]);
3
                        i = end + 1;
3
                        continue;
18
                    }
18
                    let decoded = match body {
18
                        "lt" => Some('<'),
16
                        "gt" => Some('>'),
14
                        "amp" => Some('&'),
9
                        "quot" => Some('"'),
6
                        "apos" => Some('\''),
5
                        _ => decode_numeric_entity(body),
                    };
18
                    if let Some(c) = decoded {
16
                        out.push(c);
16
                        i = end + 1;
16
                        continue;
2
                    }
1
                }
20001
            }
            // Not a recognized entity: emit the '&' literally.
20004
            out.push('&');
20004
            i += 1;
200102
        } else {
200102
            // Copy one whole UTF-8 char (i is always on a char boundary here).
200102
            let ch = input[i..].chars().next().unwrap_or('\u{FFFD}');
200102
            out.push(ch);
200102
            i += ch.len_utf8();
200102
        }
    }
27
    out
27
}
// NOTE: Two sequential returns count as a single return, while single returns get ignored.
#[must_use]
21
pub fn prepare_string(input: &str) -> String {
    const SPACE: &str = " ";
    const RETURN: &str = "\n";
21
    let input = input.trim();
21
    if input.is_empty() {
4
        return String::new();
17
    }
    // AUDIT 2026-07-08: previously only `&lt;`/`&gt;` were decoded. Decode the full
    // common named-entity set (`&lt;` `&gt;` `&amp;` `&quot;` `&apos;`) plus numeric
    // references (`&#NN;` decimal and `&#xHH;` hex) in a single left-to-right pass.
    // A single pass is used deliberately so `&amp;` cannot double-decode a following
    // entity (e.g. "&amp;lt;" -> literal "&lt;", not "<"). `&nbsp;` is intentionally
    // left untouched here so the per-line pass below (which runs AFTER trimming) can
    // still turn it into a space that survives leading/trailing trim.
17
    let input = decode_entities(input);
17
    let input_len = input.len();
17
    let mut final_lines: Vec<String> = Vec::new();
17
    let mut last_line_was_empty = false;
26
    for line in input.lines() {
26
        let line = line.trim();
26
        let line = line.replace("&nbsp;", " ");
26
        let current_line_is_empty = line.is_empty();
26
        if !current_line_is_empty {
22
            if last_line_was_empty {
2
                final_lines.push(format!("{RETURN}{line}"));
20
            } else {
20
                final_lines.push(line);
20
            }
4
        }
26
        last_line_was_empty = current_line_is_empty;
    }
17
    let mut target = String::with_capacity(input_len);
22
    for (line_idx, line) in final_lines.iter().enumerate() {
        // A joining space goes before every line EXCEPT the first (idx 0) and a
        // paragraph break (RETURN-prefixed). The old code also skipped the LAST line,
        // which dropped the word boundary for a soft-wrapped final line
        // ("Hello\nworld" -> "Helloworld").
22
        if !(line.starts_with(RETURN) || line_idx == 0) {
3
            target.push_str(SPACE);
19
        }
22
        target.push_str(line);
    }
17
    target
21
}
/// Parses a string ("true" or "false")
#[must_use]
229
pub fn parse_bool(input: &str) -> Option<bool> {
229
    match input {
229
        "true" => Some(true),
154
        "false" => Some(false),
116
        _ => None,
    }
229
}
#[derive(Debug, Clone)]
pub struct CssMatcher {
    path: Vec<CssPathSelector>,
    indices_in_parent: Vec<usize>,
    children_length: Vec<usize>,
}
impl CssMatcher {
17
    fn get_hash(&self) -> u64 {
        use core::hash::{Hash, Hasher};
17
        let mut hasher = crate::hash::DefaultHasher::new();
37
        for p in &self.path {
20
            p.hash(&mut hasher);
20
        }
17
        hasher.finish()
17
    }
}
impl CssMatcher {
3
    fn matches(&self, path: &CssPath) -> bool {
        use azul_css::css::CssPathSelector::*;
        use crate::style::{CssGroupIterator, CssGroupSplitReason};
3
        if self.path.is_empty() {
1
            return false;
2
        }
2
        if path.selectors.as_ref().is_empty() {
1
            return false;
1
        }
        // self_matcher is only ever going to contain "Children" selectors, never "DirectChildren"
1
        let mut path_groups = CssGroupIterator::new(path.selectors.as_ref()).collect::<Vec<_>>();
1
        path_groups.reverse();
1
        if path_groups.is_empty() {
            return false;
1
        }
1
        let mut self_groups = CssGroupIterator::new(self.path.as_ref()).collect::<Vec<_>>();
1
        self_groups.reverse();
1
        if self_groups.is_empty() {
            return false;
1
        }
1
        if self.indices_in_parent.len() != self_groups.len() {
1
            return false;
        }
        if self.children_length.len() != self_groups.len() {
            return false;
        }
        // self_groups = [ // HTML
        //     "body",
        //     "div.__azul_native-ribbon-container"
        //     "div.__azul_native-ribbon-tabs"
        //     "p.home"
        // ]
        //
        // path_groups = [ // CSS
        //     ".__azul_native-ribbon-tabs"
        //     "div.after-tabs"
        // ]
        // get the first path group and see if it matches anywhere in the self group
        let mut cur_selfgroup_scan = 0;
        let mut cur_pathgroup_scan = 0;
        let mut valid = false;
        let mut path_group = path_groups[cur_pathgroup_scan].clone();
        while cur_selfgroup_scan < self_groups.len() {
            let mut advance = None;
            // scan all remaining path groups
            for (id, cg) in self_groups[cur_selfgroup_scan..].iter().enumerate() {
                let gm = group_matches(
                    &path_group.0,
                    &self_groups[cur_selfgroup_scan + id].0,
                    self.indices_in_parent[cur_selfgroup_scan + id],
                    self.children_length[cur_selfgroup_scan + id],
                );
                if gm {
                    // ok: ".__azul_native-ribbon-tabs" was found within self_groups
                    // advance the self_groups by n
                    advance = Some(id);
                    break;
                }
            }
            match advance {
                Some(n) => {
                    // group was found in remaining items
                    // advance cur_pathgroup_scan by 1 and cur_selfgroup_scan by n
                    if cur_pathgroup_scan == path_groups.len() - 1 {
                        // last path group
                        return cur_selfgroup_scan + n == self_groups.len() - 1;
                    }
                    cur_pathgroup_scan += 1;
                    cur_selfgroup_scan += n;
                    path_group = path_groups[cur_pathgroup_scan].clone();
                }
                None => return false, // group was not found in remaining items
            }
        }
        // only return true if all path_groups matched
        cur_pathgroup_scan == path_groups.len() - 1
3
    }
}
// does p.home match div.after-tabs?
// a: div.after-tabs
26
fn group_matches(
26
    a: &[&CssPathSelector],
26
    b: &[&CssPathSelector],
26
    idx_in_parent: usize,
26
    parent_children: usize,
26
) -> bool {
    use azul_css::css::{
        CssNthChildSelector, CssPathPseudoSelector,
        CssPathSelector::{Class, Global, Id, PseudoSelector, Type},
    };
38
    for selector in a {
10
        match selector {
            // always matches
            Global
            | PseudoSelector(
                CssPathPseudoSelector::Hover
                | CssPathPseudoSelector::Active
                | CssPathPseudoSelector::Focus
                | CssPathPseudoSelector::SeatFocus,
2
            ) => {}
3
            Type(tag) => {
3
                if !b.iter().any(|t| **t == Type(*tag)) {
2
                    return false;
1
                }
            }
1
            Class(class) => {
1
                if !b.iter().any(|t| **t == Class(class.clone())) {
                    return false;
1
                }
            }
1
            Id(id) => {
1
                if !b.iter().any(|t| **t == Id(id.clone())) {
1
                    return false;
                }
            }
            PseudoSelector(CssPathPseudoSelector::First) => {
2
                if idx_in_parent != 0 {
1
                    return false;
1
                }
            }
            PseudoSelector(CssPathPseudoSelector::Last) => {
3
                if idx_in_parent != parent_children.saturating_sub(1) {
1
                    return false;
2
                }
            }
2
            PseudoSelector(CssPathPseudoSelector::NthChild(CssNthChildSelector::Number(i))) => {
2
                if idx_in_parent != *i as usize {
1
                    return false;
1
                }
            }
            PseudoSelector(CssPathPseudoSelector::NthChild(CssNthChildSelector::Even)) => {
3
                if !idx_in_parent.is_multiple_of(2) {
2
                    return false;
1
                }
            }
            PseudoSelector(CssPathPseudoSelector::NthChild(CssNthChildSelector::Odd)) => {
2
                if idx_in_parent.is_multiple_of(2) {
1
                    return false;
1
                }
            }
3
            PseudoSelector(CssPathPseudoSelector::NthChild(CssNthChildSelector::Pattern(p))) => {
3
                if !idx_in_parent
3
                    .saturating_sub(p.offset as usize)
3
                    .is_multiple_of(p.pattern_repeat as usize)
                {
1
                    return false;
2
                }
            }
4
            _ => return false, // can't happen
        }
    }
12
    true
26
}
struct CssBlock {
    ending: Option<CssPathPseudoSelector>,
    block: CssRuleBlock,
}
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
/// # Errors
///
/// Returns an error if the body node cannot be compiled to Rust code.
8
pub fn compile_body_node_to_rust_code<'a>(
8
    body_node: &'a XmlNode,
8
    component_map: &'a ComponentMap,
8
    extra_blocks: &mut VecContents,
8
    css_blocks: &mut BTreeMap<String, String>,
8
    css: &Css,
8
    mut matcher: CssMatcher,
8
) -> Result<String, CompileError> {
    use azul_css::css::CssDeclaration;
8
    let t = "";
8
    let t2 = "    ";
8
    let mut dom_string = String::from("Dom::create_body()");
8
    let node_type = CssPathSelector::Type(NodeTypeTag::Body);
8
    matcher.path.push(node_type);
8
    let ids = body_node
8
        .attributes
8
        .get_key("id")
8
        .map(|s| s.split_whitespace().collect::<Vec<_>>())
8
        .unwrap_or_default();
8
    matcher.path.extend(
8
        ids.into_iter()
8
            .map(|id| CssPathSelector::Id(id.to_string().into())),
    );
8
    let classes = body_node
8
        .attributes
8
        .get_key("class")
8
        .map(|s| s.split_whitespace().collect::<Vec<_>>())
8
        .unwrap_or_default();
8
    matcher.path.extend(
8
        classes
8
            .into_iter()
8
            .map(|class| CssPathSelector::Class(class.to_string().into())),
    );
8
    let matcher_hash = matcher.get_hash();
8
    let css_blocks_for_this_node = get_css_blocks(css, &matcher);
8
    if !css_blocks_for_this_node.is_empty() {
        // Track property types for the helper-const machinery, then emit the
        // matched declarations as an inline CSS string. (The old path emitted a
        // `const CSS_MATCH_*: NodeDataInlineCssPropertyVec` + `.with_inline_css_props`,
        // but that API was removed in 32d44ed8a; `.with_css(<str>)` is the
        // current equivalent and parses pseudo blocks too.)
        for css_block in &css_blocks_for_this_node {
            for declaration in css_block.block.declarations.as_ref() {
                let prop = match declaration {
                    CssDeclaration::Static(s) => s,
                    CssDeclaration::Dynamic(d) => &d.default_value,
                };
                extra_blocks.insert_from_css_property(prop);
            }
        }
        let inline_css = css_blocks_to_inline_string(&css_blocks_for_this_node);
        if !inline_css.is_empty() {
            let escaped = inline_css.replace('\\', "\\\\").replace('"', "\\\"");
            let _ = write!(dom_string, "\r\n{t2}.with_css(\"{escaped}\")");
        }
        let _ = (&mut *css_blocks, matcher_hash); // retained for signature compat
8
    }
8
    if !body_node.children.as_ref().is_empty() {
        use azul_css::codegen::format::GetHash;
6
        let children_hash = body_node.children.as_ref().get_hash();
6
        dom_string.push_str("\r\n.with_children(vec![\r\n");
6
        for (child_idx, child) in body_node.children.as_ref().iter().enumerate() {
6
            match child {
2
                XmlNodeChild::Element(child_node) => {
2
                    let mut matcher = matcher.clone();
2
                    matcher.path.push(CssPathSelector::Children);
2
                    matcher.indices_in_parent.push(child_idx);
2
                    matcher.children_length.push(body_node.children.len());
2
                    let _ = write!(
2
                        dom_string,
2
                        "{}{},\r\n",
                        t,
2
                        compile_node_to_rust_code_inner(
2
                            child_node,
2
                            component_map,
                            1,
2
                            extra_blocks,
2
                            css_blocks,
2
                            css,
2
                            matcher,
                        )?
                    );
                }
4
                XmlNodeChild::Text(text) => {
4
                    let text = text.trim();
4
                    if !text.is_empty() {
1
                        let escaped = text.replace('\\', "\\\\").replace('"', "\\\"");
1
                        let _ = write!(
1
                            dom_string,
1
                            "{t}Dom::create_text_do_not_use_without_block_level_wrapper(\"\
1
                             {escaped}\"),\r\n"
1
                        );
3
                    }
                }
            }
        }
6
        let _ = write!(dom_string, "\r\n{t}])");
2
    }
8
    let dom_string = dom_string.trim();
8
    Ok(dom_string.to_string())
8
}
/// Serialize the CSS blocks matched for a node into one inline CSS string for
/// `Dom::with_css(...)`. `with_css` parses via `Css::parse_inline`, which runs
/// the full selector+nesting machinery, so `:hover`/`:active`/`:focus` are
/// emitted as nested pseudo blocks and round-trip faithfully; plain rules are
/// emitted flat as `key: value;` (via `CssProperty::key()` / `value()`).
1
fn css_blocks_to_inline_string(blocks: &[CssBlock]) -> String {
    fn decls_of(block: &CssBlock) -> Vec<String> {
        block
            .block
            .declarations
            .as_ref()
            .iter()
            .map(|d| {
                let prop = match d {
                    CssDeclaration::Static(s) => s,
                    CssDeclaration::Dynamic(dy) => &dy.default_value,
                };
                format!("{}: {};", prop.key(), prop.value())
            })
            .collect()
    }
1
    let mut normal: Vec<String> = Vec::new();
1
    let mut pseudo: Vec<String> = Vec::new();
1
    for block in blocks {
        let pseudo_sel = match block.ending {
            Some(CssPathPseudoSelector::Hover) => Some(":hover"),
            Some(CssPathPseudoSelector::Active) => Some(":active"),
            Some(CssPathPseudoSelector::Focus) => Some(":focus"),
            Some(CssPathPseudoSelector::SeatFocus) => Some(":seat-focus"),
            _ => None,
        };
        match pseudo_sel {
            None => normal.extend(decls_of(block)),
            Some(sel) => pseudo.push(format!("{} {{ {} }}", sel, decls_of(block).join(" "))),
        }
    }
1
    let mut parts = normal;
1
    parts.extend(pseudo);
1
    parts.join(" ")
1
}
22
fn get_css_blocks(css: &Css, matcher: &CssMatcher) -> Vec<CssBlock> {
22
    let mut blocks = Vec::new();
22
    for css_block in css.rules.as_ref() {
        if matcher.matches(&css_block.path) {
            let ending = match css_block.path.selectors.as_ref().last() {
                Some(CssPathSelector::PseudoSelector(p)) => Some(p.clone()),
                _ => None,
            };
            blocks.push(CssBlock {
                ending,
                block: css_block.clone(),
            });
        }
    }
22
    blocks
22
}
9
fn compile_and_format_dynamic_items(input: &[DynamicItem]) -> String {
    use self::DynamicItem::{Str, Var};
9
    if input.is_empty() {
2
        String::from("AzString::from_const_str(\"\")")
7
    } else if input.len() == 1 {
        // common: there is only one "dynamic item" - skip the "format!()" macro
5
        match &input[0] {
3
            Var { name, format_spec } => {
3
                let var_name = normalize_casing(name.trim());
3
                if let Some(spec) = format_spec {
1
                    format!("format!(\"{{:{spec}}}\", {var_name}).into()")
                } else {
2
                    var_name
                }
            }
2
            Str(s) => format!("AzString::from_const_str(\"{s}\")"),
        }
    } else {
        // build a "format!("{var}, blah", var)" string
2
        let mut formatted_str = String::from("format!(\"");
2
        let mut variables = Vec::new();
8
        for item in input {
6
            match item {
3
                Var { name, format_spec } => {
3
                    let variable_name = normalize_casing(name.trim());
3
                    if let Some(spec) = format_spec {
                        let _ = write!(formatted_str, "{{{variable_name}:{spec}}}");
3
                    } else {
3
                        let _ = write!(formatted_str, "{{{variable_name}}}");
3
                    }
3
                    variables.push(variable_name.clone());
                }
3
                Str(s) => {
3
                    let s = s.replace('"', "\\\"");
3
                    formatted_str.push_str(&s);
3
                }
            }
        }
2
        formatted_str.push('\"');
2
        if !variables.is_empty() {
2
            formatted_str.push_str(", ");
2
        }
2
        formatted_str.push_str(&variables.join(", "));
2
        formatted_str.push_str(").into()");
2
        formatted_str
    }
9
}
6
fn format_args_for_rust_code(input: &str) -> String {
6
    let dynamic_str_items = split_dynamic_string(input);
6
    compile_and_format_dynamic_items(&dynamic_str_items)
6
}
#[allow(clippy::result_large_err)]
// returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
// component_map is forwarded through the codegen recursion for parity with the
// component-expanding path; this Rust-codegen path only threads it into recursive calls.
#[allow(clippy::only_used_in_recursion)]
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch (one
                                 // branch per input variant)
2
fn compile_node_to_rust_code_inner(
2
    node: &XmlNode,
2
    component_map: &ComponentMap,
2
    tabs: usize,
2
    extra_blocks: &mut VecContents,
2
    css_blocks: &mut BTreeMap<String, String>,
2
    css: &Css,
2
    mut matcher: CssMatcher,
2
) -> Result<String, CompileError> {
    use azul_css::css::CssDeclaration;
2
    let t = String::from("    ").repeat(tabs - 1);
2
    let t2 = String::from("    ").repeat(tabs);
2
    let component_name = normalize_casing(&node.node_type);
    // Look up the CSS NodeTypeTag
2
    let node_type_tag = tag_to_node_type_tag(&component_name);
2
    let node_type = CssPathSelector::Type(node_type_tag);
    // Emit a plain `create_node(<Tag>)` for the base node. Do NOT route through
    // the component `compile_fn`: its Rust arm bakes inline text into a
    // `.with_children(..)`, which the child-walk below would then OVERWRITE with
    // a second `.with_children(..)` — silently dropping the text on any node
    // that has BOTH text and element children. The child-walk handles ALL
    // children (text + elements) in order, so the base node must stay childless.
    // Interactive/data tags (Button/Input/…) whose NodeType carries data fall
    // back to `div`, matching the C/C++/Python walkers (`safe_container_tag`).
2
    let ctor = analyze_node_ctor(&component_name, node);
2
    let mut dom_string = ctor.render_rust().map_or_else(
1
        || {
1
            let tag = safe_container_tag(&format!("{:?}", tag_to_node_type(&component_name)));
1
            format!("{t2}Dom::create_node(NodeType::{tag})")
1
        },
1
        |expr| format!("{t2}{expr}"),
    );
2
    matcher.path.push(node_type);
2
    let ids = node
2
        .attributes
2
        .get_key("id")
2
        .map(|s| s.split_whitespace().collect::<Vec<_>>())
2
        .unwrap_or_default();
2
    matcher.path.extend(
2
        ids.into_iter()
2
            .map(|id| CssPathSelector::Id(id.to_string().into())),
    );
2
    let classes = node
2
        .attributes
2
        .get_key("class")
2
        .map(|s| s.split_whitespace().collect::<Vec<_>>())
2
        .unwrap_or_default();
2
    matcher.path.extend(
2
        classes
2
            .into_iter()
2
            .map(|class| CssPathSelector::Class(class.to_string().into())),
    );
2
    let matcher_hash = matcher.get_hash();
2
    let css_blocks_for_this_node = get_css_blocks(css, &matcher);
2
    if !css_blocks_for_this_node.is_empty() {
        // Track property types for the helper-const machinery, then emit the
        // matched declarations as an inline CSS string. (The old path emitted a
        // `const CSS_MATCH_*: NodeDataInlineCssPropertyVec` + `.with_inline_css_props`,
        // but that API was removed in 32d44ed8a; `.with_css(<str>)` is the
        // current equivalent and parses pseudo blocks too.)
        for css_block in &css_blocks_for_this_node {
            for declaration in css_block.block.declarations.as_ref() {
                let prop = match declaration {
                    CssDeclaration::Static(s) => s,
                    CssDeclaration::Dynamic(d) => &d.default_value,
                };
                extra_blocks.insert_from_css_property(prop);
            }
        }
        let inline_css = css_blocks_to_inline_string(&css_blocks_for_this_node);
        if !inline_css.is_empty() {
            let escaped = inline_css.replace('\\', "\\\\").replace('"', "\\\"");
            let _ = write!(dom_string, "\r\n{t2}.with_css(\"{escaped}\")");
        }
        let _ = (&mut *css_blocks, matcher_hash); // retained for signature compat
2
    }
2
    set_stringified_attributes(
2
        &mut dom_string,
2
        &node.attributes,
2
        &ComponentArgumentVec::new(),
2
        tabs,
    );
    // Text folded into the ctor (Tier A/C) is skipped, as is a `<caption>`
    // already injected by `create_table`.
2
    let mut caption_skipped = false;
2
    let mut children_string = node
2
        .children
2
        .as_ref()
2
        .iter()
2
        .enumerate()
2
        .filter_map(|(child_idx, c)| match c {
            XmlNodeChild::Element(child_node) => {
                if ctor.skip_caption()
                    && !caption_skipped
                    && child_node
                        .node_type
                        .as_str()
                        .eq_ignore_ascii_case("caption")
                {
                    caption_skipped = true;
                    return None;
                }
                let mut matcher = matcher.clone();
                matcher.path.push(CssPathSelector::Children);
                matcher.indices_in_parent.push(child_idx);
                matcher.children_length.push(node.children.len());
                Some(compile_node_to_rust_code_inner(
                    child_node,
                    component_map,
                    tabs + 1,
                    extra_blocks,
                    css_blocks,
                    css,
                    matcher,
                ))
            }
2
            XmlNodeChild::Text(text) => {
2
                if ctor.consumes_text() {
1
                    return None;
1
                }
1
                let text = text.trim();
1
                if text.is_empty() {
                    None
                } else {
1
                    let t2 = String::from("    ").repeat(tabs);
1
                    let escaped = text.replace('\\', "\\\\").replace('"', "\\\"");
1
                    Some(Ok(format!(
1
                        "{t2}Dom::create_text_do_not_use_without_block_level_wrapper(\"{escaped}\"\
1
                         )"
1
                    )))
                }
            }
2
        })
2
        .collect::<Result<Vec<_>, _>>()?
2
        .join(",\r\n");
2
    if !children_string.is_empty() {
1
        let _ = write!(
1
            dom_string,
1
            "\r\n{t2}.with_children(vec![\r\n{children_string}\r\n{t2}])"
1
        );
1
    }
2
    Ok(dom_string)
2
}
// ───────────────────────────────────────────────────────────────────────────
// Generic FLUENT DOM-builder emitter (C++ / Python).
//
// Rust has its own dedicated walker above (`compile_*_to_rust_code`). C++ and
// Python share this generic walker because their builder APIs are also fluent
// (`Dom::create_*().with_css(..).with_child(..)`); only the surface tokens
// differ, captured in `FluentSyntax`. Plain C is imperative and has its own
// walker (`compile_*_to_c_code`).
// ───────────────────────────────────────────────────────────────────────────
/// Tags with a zero-arg per-tag creator (`create_<tag>()` / `AzDom_create<Tag>()`
/// / `create_node(NodeType::<Tag>)`). Interactive / data elements (Button, Input,
/// Img, Select, Textarea, Label, A, Table, …) take constructor arguments, so an
/// exported page maps them to a plain `div` container (structure preserved; the
/// user re-wires behavior). Keep these CamelCase to match `NodeTypeTag` debug names.
const SAFE_CONTAINER_TAGS: &[&str] = &[
    // These must match the real `NodeType` Debug names exactly (the lookup below is a
    // string compare against `{:?}`). Six used to be mis-cased — "Blockquote",
    // "Colgroup", "Figcaption", "Tbody", "Tfoot", "Thead" — so those tags silently
    // degraded to "Div".
    "Abbr",
    "Acronym",
    "Address",
    "Article",
    "Aside",
    "B",
    "Bdi",
    "Bdo",
    "Big",
    "BlockQuote",
    "Body",
    "Br",
    "Caption",
    "Cite",
    "Code",
    "ColGroup",
    "Dd",
    "Del",
    "Dfn",
    "Dir",
    "Div",
    "Dl",
    "Dt",
    "Em",
    "Embed",
    "FigCaption",
    "Figure",
    "Footer",
    "H1",
    "H2",
    "H3",
    "H4",
    "H5",
    "H6",
    "Head",
    "Header",
    "Hr",
    "Html",
    "I",
    "Ins",
    "Kbd",
    "Li",
    "Link",
    "Main",
    "Map",
    "Mark",
    "Meta",
    "Nav",
    "Object",
    "Ol",
    "P",
    "Pre",
    "Q",
    "Rp",
    "Rt",
    "Rtc",
    "Ruby",
    "S",
    "Samp",
    "Script",
    "Section",
    "Small",
    "Span",
    "Strong",
    "Style",
    "Sub",
    "Sup",
    "Svg",
    "TBody",
    "Td",
    "TFoot",
    "Th",
    "THead",
    "Title",
    "Tr",
    "U",
    "Ul",
    "Var",
    "Wbr",
];
/// The CamelCase tag to actually emit a creator for: the tag itself if it has a
/// zero-arg creator, else `"Div"`.
17
fn safe_container_tag(tag_dbg: &str) -> &'static str {
17
    SAFE_CONTAINER_TAGS
17
        .iter()
17
        .copied()
894
        .find(|t| *t == tag_dbg)
17
        .unwrap_or("Div")
17
}
// ───────────────────────────────────────────────────────────────────────────
// Semantic / accessibility-aware constructor selection.
//
// Instead of mapping every element to a plain `div`, an exported live page
// picks the *most specific* Azul constructor so the generated app keeps the
// page's semantics + accessibility tree:
//
//   • Tier A  `create_<tag>_with_text(text)` — a tag with a single text child
//             and no element children (P, Span, H1-H6, Li, Td, Code, …).
//   • Tier B  aria-only / void widgets (Details, Summary, Form, Canvas, Area,
//             …) — `create_<tag>(SmallAriaInfo::label(..))` when `aria-label`
//             is present, else `create_<tag>_no_a11y()`.
//   • Tier C  multi-arg widgets (Button, A, Label, Input, Select, Option,
//             Optgroup, Textarea, Table) — args pulled from HTML attributes.
//   • Tier D  scalar-driven widgets (Progress, Meter, Dialog) — the `*_no_a11y`
//             form with extracted numeric args (the full aria structs are
//             complex; the NoA11y form is simplest + correct).
//
// Every symbol emitted here is verified to exist in `target/codegen/azul.h` (C)
// and `azul20.hpp` (C++); anything else falls back to `safe_container_tag`
// (`div`). The four walkers share `analyze_node_ctor` and each renders the
// result with its own surface tokens.
// ───────────────────────────────────────────────────────────────────────────
/// A single positional argument of a semantic constructor. String payloads are
/// RAW — escaping happens at render time (matching the walkers).
#[derive(Debug, Clone)]
enum CtorArg {
    /// Plain string literal (`AzString` / `String` / `"…"`).
    Str(String),
    /// `SmallAriaInfo` built from an accessible label.
    Aria(String),
    /// `f32` numeric literal.
    Float(f32),
    /// `OptionString::Some(text)`.
    OptSome(String),
    /// `OptionString::None`.
    OptNone,
}
/// The constructor chosen for an element node.
enum NodeCtor {
    /// Plain container — keep each walker's existing `create_<tag>()` path.
    Plain,
    /// A specific semantic constructor.
    Semantic {
        /// Canonical CamelCase suffix after `create` / `AzDom_create`
        /// (e.g. `Button`, `ButtonNoA11y`, `PWithText`, `A`, `ANoA11y`).
        suffix: String,
        args: Vec<CtorArg>,
        /// The node's direct text is folded into the ctor — skip text children
        /// in the walk so it isn't emitted twice.
        consumes_text: bool,
        /// The table aria form injects its own `<caption>` child — drop the
        /// first literal `<caption>` element so it isn't duplicated.
        skip_caption: bool,
    },
}
/// Uppercase the first character (`button` → `Button`, `h1` → `H1`). HTML tags
/// are single lowercase tokens, so this yields the exact `AzDom_create<Suffix>`
/// spelling.
32
fn cap_first(tag: &str) -> String {
32
    let mut c = tag.chars();
32
    c.next().map_or_else(String::new, |f| {
30
        f.to_uppercase().collect::<String>() + c.as_str()
30
    })
32
}
/// CamelCase → `snake_case` for the C++/Python/Rust method names
/// (`ButtonNoA11y` → `button_no_a11y`, `PWithText` → `p_with_text`,
/// `ANoA11y` → `a_no_a11y`, `H1WithText` → `h1_with_text`).
29
fn camel_to_snake(s: &str) -> String {
29
    let chars: Vec<char> = s.chars().collect();
29
    let mut out = String::new();
10217
    for (i, &ch) in chars.iter().enumerate() {
10217
        if ch.is_ascii_uppercase() && i > 0 {
42
            let prev = chars[i - 1];
42
            let next_lower = chars.get(i + 1).is_some_and(char::is_ascii_lowercase);
42
            if prev.is_ascii_lowercase()
16
                || prev.is_ascii_digit()
15
                || (prev.is_ascii_uppercase() && next_lower)
41
            {
41
                out.push('_');
41
            }
10175
        }
10217
        out.extend(ch.to_lowercase());
    }
29
    out
29
}
/// Escape `\` and `"` for a double-quoted string literal.
30
fn esc_lit(s: &str) -> String {
30
    s.replace('\\', "\\\\").replace('"', "\\\"")
30
}
/// Format an `f32` as a valid float literal with a decimal point (`1` → `1.0`).
22
fn fmt_f32_lit(f: f32) -> String {
22
    let s = format!("{f}");
22
    if s.contains('.') || s.contains('e') || s.contains("inf") || s.contains("NaN") {
10
        s
    } else {
12
        format!("{s}.0")
    }
22
}
/// Joined, trimmed text of a node's *direct* text children (`"  Go  "` → `"Go"`).
29
fn node_direct_text(node: &XmlNode) -> String {
29
    node.children
29
        .as_ref()
29
        .iter()
29
        .filter_map(|c| match c {
19
            XmlNodeChild::Text(t) => {
19
                let t = t.trim();
19
                if t.is_empty() {
2
                    None
                } else {
17
                    Some(t.to_string())
                }
            }
3
            XmlNodeChild::Element(_) => None,
22
        })
29
        .collect::<Vec<_>>()
29
        .join(" ")
29
}
/// Non-empty `aria-label` attribute value, if present.
29
fn node_aria_label(node: &XmlNode) -> Option<String> {
29
    node.attributes.get_key("aria-label").and_then(|v| {
5
        let v = v.as_str().trim();
5
        if v.is_empty() {
2
            None
        } else {
3
            Some(v.to_string())
        }
5
    })
29
}
/// Attribute value, or `default` when absent.
7
fn node_attr_or(node: &XmlNode, key: &str, default: &str) -> String {
7
    node.attributes
7
        .get_key(key)
7
        .map_or_else(|| default.to_string(), |v| v.as_str().to_string())
7
}
/// Attribute parsed as `f32`, or `default` when absent / unparsable.
21
fn node_attr_f32(node: &XmlNode, key: &str, default: f32) -> f32 {
21
    node.attributes
21
        .get_key(key)
21
        .and_then(|v| v.as_str().trim().parse::<f32>().ok())
21
        .unwrap_or(default)
21
}
/// Text of the node's first `<caption>` element child, if any (non-empty).
4
fn first_caption_text(node: &XmlNode) -> Option<String> {
4
    node.children.as_ref().iter().find_map(|c| match c {
3
        XmlNodeChild::Element(e) if e.node_type.as_str().eq_ignore_ascii_case("caption") => {
3
            let t = e.get_text_content();
3
            let t = t.trim();
3
            if t.is_empty() {
1
                None
            } else {
2
                Some(t.to_string())
            }
        }
        _ => None,
3
    })
4
}
/// Tags with a single-arg `create_<tag>_with_text(text)` constructor (Tier A).
const WITH_TEXT_TAGS: &[&str] = &[
    "acronym",
    "b",
    "bdi",
    "bdo",
    "big",
    "blockquote",
    "cite",
    "code",
    "del",
    "dfn",
    "em",
    "h1",
    "h2",
    "h3",
    "h4",
    "h5",
    "h6",
    "i",
    "ins",
    "kbd",
    "li",
    "mark",
    "p",
    "pre",
    "rp",
    "rt",
    "s",
    "samp",
    "small",
    "span",
    "strong",
    "style",
    "sub",
    "sup",
    "td",
    "th",
    "title",
    "u",
    "var",
];
/// Pick the semantic constructor for `tag` (lowercase HTML tag) + `node`.
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch (one
                                 // branch per input variant)
25
fn analyze_node_ctor(tag: &str, node: &XmlNode) -> NodeCtor {
    // Helper for the common "no caption skip" case.
16
    fn sem(suffix: impl Into<String>, args: Vec<CtorArg>, consumes_text: bool) -> NodeCtor {
16
        NodeCtor::Semantic {
16
            suffix: suffix.into(),
16
            args,
16
            consumes_text,
16
            skip_caption: false,
16
        }
16
    }
25
    let aria = node_aria_label(node);
25
    let has_aria = aria.is_some();
25
    let label = aria.unwrap_or_default();
    // `has_only_text_children()` is also true for childless nodes; pair it with
    // `has_text` so empty elements stay plain containers.
25
    let pure_text = node.has_only_text_children();
25
    let text = node_direct_text(node);
25
    let has_text = !text.is_empty();
25
    let cap = cap_first(tag);
    // Tier A — *_with_text (single text child, no element children).
25
    if WITH_TEXT_TAGS.contains(&tag) {
8
        if pure_text && has_text {
6
            return sem(format!("{cap}WithText"), vec![CtorArg::Str(text)], true);
2
        }
2
        return NodeCtor::Plain;
17
    }
17
    match tag {
        // Tier B — aria-only / void widgets.
17
        "details" | "form" | "fieldset" | "legend" | "menu" | "output" | "datalist" | "canvas"
17
        | "audio" | "video" | "area" => {
            if has_aria {
                sem(cap, vec![CtorArg::Aria(label)], false)
            } else {
                sem(format!("{cap}NoA11y"), vec![], false)
            }
        }
        // Summary is Tier B but also has a WithText form for a single text child.
17
        "summary" => {
            if pure_text && has_text {
                if has_aria {
                    sem(
                        "SummaryWithText",
                        vec![CtorArg::Str(text), CtorArg::Aria(label)],
                        true,
                    )
                } else {
                    sem("SummaryWithTextNoA11y", vec![CtorArg::Str(text)], true)
                }
            } else if has_aria {
                sem("Summary", vec![CtorArg::Aria(label)], false)
            } else {
                sem("SummaryNoA11y", vec![], false)
            }
        }
        // Tier C — multi-arg widgets (args from HTML attributes).
17
        "button" => {
3
            if has_aria {
1
                sem(
                    "Button",
1
                    vec![CtorArg::Str(text), CtorArg::Aria(label)],
                    true,
                )
            } else {
2
                sem("ButtonNoA11y", vec![CtorArg::Str(text)], true)
            }
        }
14
        "a" => {
3
            let href = node_attr_or(node, "href", "");
3
            if has_aria {
                sem(
                    "A",
                    vec![CtorArg::Str(href), CtorArg::Str(text), CtorArg::Aria(label)],
                    true,
                )
            } else {
3
                let lbl = if has_text {
2
                    CtorArg::OptSome(text)
                } else {
1
                    CtorArg::OptNone
                };
3
                sem("ANoA11y", vec![CtorArg::Str(href), lbl], true)
            }
        }
11
        "label" => {
            let for_id = node_attr_or(node, "for", "");
            if has_aria {
                sem(
                    "Label",
                    vec![
                        CtorArg::Str(for_id),
                        CtorArg::Str(text),
                        CtorArg::Aria(label),
                    ],
                    true,
                )
            } else {
                sem(
                    "LabelNoA11y",
                    vec![CtorArg::Str(for_id), CtorArg::Str(text)],
                    true,
                )
            }
        }
11
        "input" => {
            let ty = node_attr_or(node, "type", "text");
            let name = node_attr_or(node, "name", "");
            if has_aria {
                sem(
                    "Input",
                    vec![
                        CtorArg::Str(ty),
                        CtorArg::Str(name),
                        CtorArg::Str(label.clone()),
                        CtorArg::Aria(label),
                    ],
                    false,
                )
            } else {
                sem(
                    "InputNoA11y",
                    vec![CtorArg::Str(ty), CtorArg::Str(name), CtorArg::Str(label)],
                    false,
                )
            }
        }
11
        "textarea" => {
            let name = node_attr_or(node, "name", "");
            if has_aria {
                sem(
                    "Textarea",
                    vec![
                        CtorArg::Str(name),
                        CtorArg::Str(label.clone()),
                        CtorArg::Aria(label),
                    ],
                    false,
                )
            } else {
                sem(
                    "TextareaNoA11y",
                    vec![CtorArg::Str(name), CtorArg::Str(label)],
                    false,
                )
            }
        }
11
        "select" => {
            let name = node_attr_or(node, "name", "");
            if has_aria {
                sem(
                    "Select",
                    vec![
                        CtorArg::Str(name),
                        CtorArg::Str(label.clone()),
                        CtorArg::Aria(label),
                    ],
                    false,
                )
            } else {
                sem(
                    "SelectNoA11y",
                    vec![CtorArg::Str(name), CtorArg::Str(label)],
                    false,
                )
            }
        }
11
        "option" => {
            let value = node_attr_or(node, "value", "");
            if has_aria {
                sem(
                    "Option",
                    vec![
                        CtorArg::Str(value),
                        CtorArg::Str(text),
                        CtorArg::Aria(label),
                    ],
                    true,
                )
            } else {
                sem(
                    "OptionNoA11y",
                    vec![CtorArg::Str(value), CtorArg::Str(text)],
                    true,
                )
            }
        }
11
        "optgroup" => {
            let lbl = node_attr_or(node, "label", "");
            if has_aria {
                sem(
                    "Optgroup",
                    vec![CtorArg::Str(lbl), CtorArg::Aria(label)],
                    false,
                )
            } else {
                sem("OptgroupNoA11y", vec![CtorArg::Str(lbl)], false)
            }
        }
11
        "table" => {
2
            if has_aria {
                // The aria form injects a caption child, so take the caption from
                // the literal <caption> (or the aria label) and drop the literal.
1
                let caption = first_caption_text(node).unwrap_or_else(|| label.clone());
1
                NodeCtor::Semantic {
1
                    suffix: "Table".to_string(),
1
                    args: vec![CtorArg::Str(caption), CtorArg::Aria(label)],
1
                    consumes_text: false,
1
                    skip_caption: true,
1
                }
            } else {
1
                sem("TableNoA11y", vec![], false)
            }
        }
        // Tier D — scalar-driven widgets (NoA11y form with extracted numbers).
9
        "progress" => sem(
            "ProgressNoA11y",
2
            vec![
2
                CtorArg::Float(node_attr_f32(node, "value", 0.0)),
2
                CtorArg::Float(node_attr_f32(node, "max", 1.0)),
            ],
            false,
        ),
7
        "meter" => sem(
            "MeterNoA11y",
1
            vec![
1
                CtorArg::Float(node_attr_f32(node, "value", 0.0)),
1
                CtorArg::Float(node_attr_f32(node, "min", 0.0)),
1
                CtorArg::Float(node_attr_f32(node, "max", 1.0)),
            ],
            false,
        ),
6
        "dialog" => sem("DialogNoA11y", vec![], false),
6
        _ => NodeCtor::Plain,
    }
25
}
impl CtorArg {
    /// Rust expression for this argument (`AzString::from(..)` works for both the
    /// `Into<AzString>` and the concrete `AzString` parameter forms).
19
    fn render_rust(&self) -> String {
19
        match self {
9
            Self::Str(s) => format!("AzString::from(\"{}\")", esc_lit(s)),
2
            Self::Aria(s) => format!("SmallAriaInfo::label(AzString::from(\"{}\"))", esc_lit(s)),
5
            Self::Float(f) => fmt_f32_lit(*f),
1
            Self::OptSome(s) => format!("OptionString::Some(AzString::from(\"{}\"))", esc_lit(s)),
2
            Self::OptNone => "OptionString::None".to_string(),
        }
19
    }
11
    fn render_c(&self) -> String {
11
        match self {
4
            Self::Str(s) => format!("AZ_STR(\"{}\")", esc_lit(s)),
            Self::Aria(s) => format!("AzSmallAriaInfo_label(AZ_STR(\"{}\"))", esc_lit(s)),
5
            Self::Float(f) => format!("{}f", fmt_f32_lit(*f)),
1
            Self::OptSome(s) => format!("AzOptionString_some(AZ_STR(\"{}\"))", esc_lit(s)),
1
            Self::OptNone => "AzOptionString_none()".to_string(),
        }
11
    }
4
    fn render_cpp(&self) -> String {
4
        match self {
3
            Self::Str(s) => format!("String(\"{}\")", esc_lit(s)),
            Self::Aria(s) => format!("SmallAriaInfo::label(String(\"{}\"))", esc_lit(s)),
            Self::Float(f) => format!("{}f", fmt_f32_lit(*f)),
            Self::OptSome(s) => format!("OptionString::some(String(\"{}\"))", esc_lit(s)),
1
            Self::OptNone => "OptionString::none()".to_string(),
        }
4
    }
5
    fn render_python(&self) -> String {
5
        match self {
4
            Self::Str(s) => format!("\"{}\"", esc_lit(s)),
            Self::Aria(s) => format!("azul.SmallAriaInfo.label(\"{}\")", esc_lit(s)),
            Self::Float(f) => fmt_f32_lit(*f),
            Self::OptSome(s) => format!("azul.OptionString.some(\"{}\")", esc_lit(s)),
1
            Self::OptNone => "azul.OptionString.none()".to_string(),
        }
5
    }
}
impl NodeCtor {
8
    const fn consumes_text(&self) -> bool {
5
        matches!(
8
            self,
            Self::Semantic {
                consumes_text: true,
                ..
            }
        )
8
    }
3
    const fn skip_caption(&self) -> bool {
1
        matches!(
3
            self,
            Self::Semantic {
                skip_caption: true,
                ..
            }
        )
3
    }
    /// `Dom::create_…(args)` for Rust, or `None` for a plain container.
13
    fn render_rust(&self) -> Option<String> {
13
        match self {
2
            Self::Plain => None,
11
            Self::Semantic { suffix, args, .. } => Some(format!(
11
                "Dom::create_{}({})",
11
                camel_to_snake(suffix),
11
                args.iter()
11
                    .map(CtorArg::render_rust)
11
                    .collect::<Vec<_>>()
11
                    .join(", ")
11
            )),
        }
13
    }
    /// `AzDom_create…(args)` for C, or `None` for a plain container.
6
    fn render_c(&self) -> Option<String> {
6
        match self {
2
            Self::Plain => None,
4
            Self::Semantic { suffix, args, .. } => Some(format!(
4
                "AzDom_create{}({})",
4
                suffix,
4
                args.iter()
4
                    .map(CtorArg::render_c)
4
                    .collect::<Vec<_>>()
4
                    .join(", ")
4
            )),
        }
6
    }
    /// Fluent `Dom::create_…` (C++) / `azul.Dom.create_…` (Python), or `None`.
8
    fn render_fluent(&self, target: &CompileTarget) -> Option<String> {
8
        match self {
1
            Self::Plain => None,
7
            Self::Semantic { suffix, args, .. } => {
7
                let snake = camel_to_snake(suffix);
7
                let (prefix, rendered) = match target {
2
                    CompileTarget::Cpp => (
2
                        format!("Dom::create_{snake}"),
2
                        args.iter().map(CtorArg::render_cpp).collect::<Vec<_>>(),
2
                    ),
3
                    CompileTarget::Python => (
3
                        format!("azul.Dom.create_{snake}"),
3
                        args.iter().map(CtorArg::render_python).collect::<Vec<_>>(),
3
                    ),
2
                    _ => return None,
                };
5
                Some(format!("{}({})", prefix, rendered.join(", ")))
            }
        }
8
    }
}
/// Per-language token hooks for the fluent walker. The `&str` args are already
/// escaped for a double-quoted string literal.
struct FluentSyntax {
    target: CompileTarget,
    /// tag debug-name (e.g. "Div") -> full create expression
    create_node: fn(&str) -> String,
    /// escaped text -> create-text expression
    create_text: fn(&str) -> String,
    /// escaped css -> `.with_css(..)` call
    with_css: fn(&str) -> String,
    /// escaped class -> `.with_class(..)` call
    with_class: fn(&str) -> String,
    /// escaped id -> `.with_id(..)` call
    with_id: fn(&str) -> String,
    /// escaped child expression -> `.with_child(..)` call (children are chained)
    with_child: fn(&str) -> String,
}
const CPP_SYNTAX: FluentSyntax = FluentSyntax {
    target: CompileTarget::Cpp,
    // Use per-tag creators (Dom::create_div(), create_p(), create_body(), …)
    // — `NodeType` is a tagged union, so `create_node` would need union
    // construction; the per-tag creators exist for every common HTML element.
2
    create_node: |tag| alloc::format!("Dom::create_{}()", tag.to_lowercase()),
    create_text: |s| {
        alloc::format!("Dom::create_text_do_not_use_without_block_level_wrapper(String(\"{s}\"))")
    },
    with_css: |s| alloc::format!(".with_css(String(\"{s}\"))"),
    with_class: |s| alloc::format!(".with_class(String(\"{s}\"))"),
    with_id: |s| alloc::format!(".with_id(String(\"{s}\"))"),
1
    with_child: |c| alloc::format!(".with_child({c})"),
};
const PYTHON_SYNTAX: FluentSyntax = FluentSyntax {
    target: CompileTarget::Python,
    // Per-tag creators (azul.Dom.create_div(), …) — see CPP_SYNTAX note.
2
    create_node: |tag| alloc::format!("azul.Dom.create_{}()", tag.to_lowercase()),
    create_text: |s| {
        alloc::format!("azul.Dom.create_text_do_not_use_without_block_level_wrapper(\"{s}\")")
    },
    with_css: |s| alloc::format!(".with_css(\"{s}\")"),
    with_class: |s| alloc::format!(".with_class(\"{s}\")"),
    with_id: |s| alloc::format!(".with_id(\"{s}\")"),
1
    with_child: |c| alloc::format!(".with_child({c})"),
};
/// Walk one element node, emitting a fluent create-expression for `syntax`'s
/// language. Mirrors `compile_node_to_rust_code_inner` but token-parameterized.
#[allow(clippy::result_large_err)]
// returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
// See compile_node_to_rust_code_inner: component_map is forwarded for codegen-path parity.
#[allow(clippy::only_used_in_recursion)]
2
fn compile_node_fluent(
2
    node: &XmlNode,
2
    syntax: &FluentSyntax,
2
    component_map: &ComponentMap,
2
    css: &Css,
2
    mut matcher: CssMatcher,
2
) -> Result<String, CompileError> {
    use azul_css::css::CssDeclaration;
2
    let component_name = normalize_casing(&node.node_type);
2
    let node_type_tag = tag_to_node_type_tag(&component_name);
2
    let tag_dbg = alloc::format!("{:?}", tag_to_node_type(&component_name));
    // Base create-expression. For an exported live page every node is a plain
    // HTML element, so emit a per-tag creator directly via the language hooks
    // (universal + verified) rather than the per-component `compile_fn`, whose
    // C++/Python arms emit stale placeholder syntax (`Dom.div()` etc.).
    // Interactive/data tags (whose creators need args) fall back to `div`. Any
    // element text shows up as a Text child below and is handled there.
2
    let ctor = analyze_node_ctor(&component_name, node);
2
    let mut s = ctor.render_fluent(&syntax.target).map_or_else(
        || (syntax.create_node)(safe_container_tag(&tag_dbg)),
        |expr| expr,
    );
2
    matcher.path.push(CssPathSelector::Type(node_type_tag));
2
    let ids: Vec<String> = node
2
        .attributes
2
        .get_key("id")
2
        .map(|v| {
            v.split_whitespace()
                .map(alloc::string::ToString::to_string)
                .collect()
        })
2
        .unwrap_or_default();
2
    matcher
2
        .path
2
        .extend(ids.iter().map(|id| CssPathSelector::Id(id.clone().into())));
2
    let classes: Vec<String> = node
2
        .attributes
2
        .get_key("class")
2
        .map(|v| {
            v.split_whitespace()
                .map(alloc::string::ToString::to_string)
                .collect()
        })
2
        .unwrap_or_default();
2
    matcher.path.extend(
2
        classes
2
            .iter()
2
            .map(|c| CssPathSelector::Class(c.clone().into())),
    );
    // Inline CSS (matched rules -> `.with_css("..")`, pseudo blocks included).
2
    let blocks = get_css_blocks(css, &matcher);
2
    if !blocks.is_empty() {
        let inline_css = css_blocks_to_inline_string(&blocks);
        if !inline_css.is_empty() {
            let esc = inline_css.replace('\\', "\\\\").replace('"', "\\\"");
            s.push_str(&(syntax.with_css)(&esc));
        }
2
    }
2
    for id in &ids {
        s.push_str(&(syntax.with_id)(
            &id.replace('\\', "\\\\").replace('"', "\\\""),
        ));
    }
2
    for class in &classes {
        s.push_str(&(syntax.with_class)(
            &class.replace('\\', "\\\\").replace('"', "\\\""),
        ));
    }
    // Children (chained `.with_child(..)`). Text folded into the ctor (Tier A/C)
    // is skipped here, as is a `<caption>` already injected by `create_table`.
2
    let mut caption_skipped = false;
2
    for (child_idx, child) in node.children.as_ref().iter().enumerate() {
2
        match child {
            XmlNodeChild::Element(child_node) => {
                if ctor.skip_caption()
                    && !caption_skipped
                    && child_node
                        .node_type
                        .as_str()
                        .eq_ignore_ascii_case("caption")
                {
                    caption_skipped = true;
                    continue;
                }
                let mut m = matcher.clone();
                m.path.push(CssPathSelector::Children);
                m.indices_in_parent.push(child_idx);
                m.children_length.push(node.children.len());
                let child_src = compile_node_fluent(child_node, syntax, component_map, css, m)?;
                s.push_str(&(syntax.with_child)(&child_src));
            }
2
            XmlNodeChild::Text(text) => {
2
                if ctor.consumes_text() {
2
                    continue;
                }
                let text = text.trim();
                if !text.is_empty() {
                    let esc = text.replace('\\', "\\\\").replace('"', "\\\"");
                    s.push_str(&(syntax.with_child)(&(syntax.create_text)(&esc)));
                }
            }
        }
    }
2
    Ok(s)
2
}
/// Build the `<body>` render-expression for `syntax`'s language.
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would
                                   // break the C ABI/api.json
4
fn compile_body_fluent<'a>(
4
    body_node: &'a XmlNode,
4
    syntax: &FluentSyntax,
4
    component_map: &'a ComponentMap,
4
    css: &Css,
4
    mut matcher: CssMatcher,
4
) -> Result<String, CompileError> {
4
    let mut s = (syntax.create_node)("Body");
4
    matcher.path.push(CssPathSelector::Type(NodeTypeTag::Body));
4
    let classes: Vec<String> = body_node
4
        .attributes
4
        .get_key("class")
4
        .map(|v| {
            v.split_whitespace()
                .map(alloc::string::ToString::to_string)
                .collect()
        })
4
        .unwrap_or_default();
4
    matcher.path.extend(
4
        classes
4
            .iter()
4
            .map(|c| CssPathSelector::Class(c.clone().into())),
    );
4
    let blocks = get_css_blocks(css, &matcher);
4
    if !blocks.is_empty() {
        let inline_css = css_blocks_to_inline_string(&blocks);
        if !inline_css.is_empty() {
            let esc = inline_css.replace('\\', "\\\\").replace('"', "\\\"");
            s.push_str(&(syntax.with_css)(&esc));
        }
4
    }
4
    for class in &classes {
        s.push_str(&(syntax.with_class)(
            &class.replace('\\', "\\\\").replace('"', "\\\""),
        ));
    }
4
    for (child_idx, child) in body_node.children.as_ref().iter().enumerate() {
2
        match child {
2
            XmlNodeChild::Element(child_node) => {
2
                let mut m = matcher.clone();
2
                m.path.push(CssPathSelector::Children);
2
                m.indices_in_parent.push(child_idx);
2
                m.children_length.push(body_node.children.len());
2
                let child_src = compile_node_fluent(child_node, syntax, component_map, css, m)?;
2
                s.push_str(&(syntax.with_child)(&child_src));
            }
            XmlNodeChild::Text(text) => {
                let text = text.trim();
                if !text.is_empty() {
                    let esc = text.replace('\\', "\\\\").replace('"', "\\\"");
                    s.push_str(&(syntax.with_child)(&(syntax.create_text)(&esc)));
                }
            }
        }
    }
4
    Ok(s)
4
}
/// Parse the page's `<style>` and seed a matcher rooted at `<body>`. Shared by
/// the C++/Python/C entry points (mirrors the head of `str_to_rust_code`).
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
/// Returns the body by VALUE: `get_html_node` may have synthesised the `<html>`
/// wrapper (a fragment with no root of its own), and a reference into a node
/// this function owns cannot outlive it. Codegen, not a hot path - one clone
/// of the body subtree per compile.
9
fn parse_page_style_and_body(root_nodes: &[XmlNodeChild]) -> Result<(Css, XmlNode), CompileError> {
9
    let html_node = get_html_node(root_nodes)?;
9
    let body_node = get_body_node(html_node.children.as_ref())?.clone();
9
    let mut global_style = Css::empty();
9
    if let Some(head_node) = find_node_by_type(html_node.children.as_ref(), "head") {
6
        if let Some(style_node) = find_node_by_type(head_node.children.as_ref(), "style") {
5
            let text = style_node.get_text_content();
5
            if !text.is_empty() {
1
                global_style = azul_css::parser2::new_from_str(&text).0;
4
            }
1
        }
3
    }
9
    global_style.sort_by_specificity();
9
    Ok((global_style, body_node))
9
}
10
fn body_matcher(body_node: &XmlNode) -> CssMatcher {
10
    CssMatcher {
10
        path: Vec::new(),
10
        indices_in_parent: vec![0],
10
        children_length: vec![body_node.children.as_ref().len()],
10
    }
10
}
/// Compile a full HTML page to a compilable **C++** Azul app.
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
/// # Errors
///
/// Returns an error if the XML cannot be parsed or compiled to C++ code.
2
pub fn str_to_cpp_code<'a>(
2
    root_nodes: &'a [XmlNodeChild],
2
    component_map: &'a ComponentMap,
2
) -> Result<String, CompileError> {
2
    let (global_style, body_node) = parse_page_style_and_body(root_nodes)?;
2
    let body_node = &body_node;
2
    let render = compile_body_fluent(
2
        body_node,
2
        &CPP_SYNTAX,
2
        component_map,
2
        &global_style,
2
        body_matcher(body_node),
    )?;
2
    Ok(alloc::format!(
2
        "// Auto-generated UI source code (C++). Build:\n//   clang++ -std=c++20 -I \
2
         <azul>/target/codegen main.cpp -lazul\n#include \"azul20.hpp\"\nusing namespace \
2
         azul;\n\nstruct Data {{}};\n\nAzDom render(AzRefAny data, AzLayoutCallbackInfo info) \
2
         {{\n    return {render};\n}}\n\nint main() {{\n    RefAny data = \
2
         RefAny::create(Data{{}});\n    WindowCreateOptions window = \
2
         WindowCreateOptions::create(render);\n    App app = App::create(std::move(data), \
2
         AppConfig::default_());\n    app.run(std::move(window));\n    return 0;\n}}\n"
2
    ))
2
}
/// Compile a full HTML page to a compilable **Python** Azul app.
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
/// # Errors
///
/// Returns an error if the XML cannot be parsed or compiled to Python code.
2
pub fn str_to_python_code<'a>(
2
    root_nodes: &'a [XmlNodeChild],
2
    component_map: &'a ComponentMap,
2
) -> Result<String, CompileError> {
2
    let (global_style, body_node) = parse_page_style_and_body(root_nodes)?;
2
    let body_node = &body_node;
2
    let render = compile_body_fluent(
2
        body_node,
2
        &PYTHON_SYNTAX,
2
        component_map,
2
        &global_style,
2
        body_matcher(body_node),
    )?;
2
    Ok(alloc::format!(
2
        "# Auto-generated UI source code (Python). Run: python3 main.py\nimport azul\n\nclass \
2
         Data:\n    pass\n\ndef render(data, info):\n    return (\n        {}\n    )\n\ndef \
2
         main():\n    app = azul.App.create(Data(), azul.AppConfig.create())\n    window = \
2
         azul.WindowCreateOptions.create(render)\n    app.run(window)\n\nif __name__ == \
2
         \"__main__\":\n    main()\n",
2
        render.replace("\r\n", "\n        ")
2
    ))
2
}
// ───────────────────────────────────────────────────────────────────────────
// Imperative C emitter. C has no fluent builder: each node is a statement that
// creates an `AzDom` local, applies css/class (by-value, returns), and pushes
// children via `AzDom_addChild(&parent, child)`. A recursive walk emits the
// statements bottom-up and returns the variable name holding each node.
// ───────────────────────────────────────────────────────────────────────────
/// C per-tag creator suffix: `NodeTypeTag` debug name with first char kept and
/// the rest lowercased (`Div`->`Div`, `BlockQuote`->`Blockquote`, `H1`->`H1`),
/// matching `AzDom_create<Suffix>` in azul.h.
7
fn c_creator_suffix(tag_dbg: &str) -> String {
7
    let mut chars = tag_dbg.chars();
7
    chars.next().map_or_else(
1
        || "Div".to_string(),
6
        |first| {
6
            let rest: String = chars.as_str().to_lowercase();
6
            alloc::format!("{first}{rest}")
6
        },
    )
7
}
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
#[allow(clippy::too_many_lines)] // large but cohesive: one branch per node kind
2
fn compile_node_c(
2
    node: &XmlNode,
2
    component_map: &ComponentMap,
2
    css: &Css,
2
    mut matcher: CssMatcher,
2
    counter: &mut usize,
2
    out: &mut String,
2
) -> Result<String, CompileError> {
2
    let _ = component_map;
2
    let component_name = normalize_casing(&node.node_type);
2
    let node_type_tag = tag_to_node_type_tag(&component_name);
2
    let tag_dbg = alloc::format!("{:?}", tag_to_node_type(&component_name));
2
    let var = alloc::format!("n{}", *counter);
2
    *counter += 1;
2
    let ctor = analyze_node_ctor(&component_name, node);
2
    match ctor.render_c() {
1
        Some(expr) => {
1
            let _ = writeln!(out, "    AzDom {var} = {expr};");
1
        }
1
        None => {
1
            let _ = writeln!(
1
                out,
1
                "    AzDom {} = AzDom_create{}();",
1
                var,
1
                c_creator_suffix(safe_container_tag(&tag_dbg))
1
            );
1
        }
    }
2
    matcher.path.push(CssPathSelector::Type(node_type_tag));
2
    let ids: Vec<String> = node
2
        .attributes
2
        .get_key("id")
2
        .map(|v| {
            v.split_whitespace()
                .map(alloc::string::ToString::to_string)
                .collect()
        })
2
        .unwrap_or_default();
2
    matcher
2
        .path
2
        .extend(ids.iter().map(|id| CssPathSelector::Id(id.clone().into())));
2
    let classes: Vec<String> = node
2
        .attributes
2
        .get_key("class")
2
        .map(|v| {
            v.split_whitespace()
                .map(alloc::string::ToString::to_string)
                .collect()
        })
2
        .unwrap_or_default();
2
    matcher.path.extend(
2
        classes
2
            .iter()
2
            .map(|c| CssPathSelector::Class(c.clone().into())),
    );
2
    let blocks = get_css_blocks(css, &matcher);
2
    if !blocks.is_empty() {
        let inline_css = css_blocks_to_inline_string(&blocks);
        if !inline_css.is_empty() {
            let esc = inline_css.replace('\\', "\\\\").replace('"', "\\\"");
            let _ = writeln!(out, "    {var} = AzDom_withCss({var}, AZ_STR(\"{esc}\"));");
        }
2
    }
2
    for id in &ids {
        let esc = id.replace('\\', "\\\\").replace('"', "\\\"");
        let _ = writeln!(out, "    {var} = AzDom_withId({var}, AZ_STR(\"{esc}\"));");
    }
2
    for class in &classes {
        let esc = class.replace('\\', "\\\\").replace('"', "\\\"");
        let _ = writeln!(
            out,
            "    {var} = AzDom_withClass({var}, AZ_STR(\"{esc}\"));"
        );
    }
2
    let mut caption_skipped = false;
2
    for (child_idx, child) in node.children.as_ref().iter().enumerate() {
2
        match child {
            XmlNodeChild::Element(child_node) => {
                if ctor.skip_caption()
                    && !caption_skipped
                    && child_node
                        .node_type
                        .as_str()
                        .eq_ignore_ascii_case("caption")
                {
                    caption_skipped = true;
                    continue;
                }
                let mut m = matcher.clone();
                m.path.push(CssPathSelector::Children);
                m.indices_in_parent.push(child_idx);
                m.children_length.push(node.children.len());
                let child_var = compile_node_c(child_node, component_map, css, m, counter, out)?;
                let _ = writeln!(out, "    AzDom_addChild(&{var}, {child_var});");
            }
2
            XmlNodeChild::Text(text) => {
2
                if ctor.consumes_text() {
1
                    continue;
1
                }
1
                let text = text.trim();
1
                if !text.is_empty() {
1
                    let esc = text.replace('\\', "\\\\").replace('"', "\\\"");
1
                    let _ = writeln!(
1
                        out,
1
                        "    AzDom_addChild(&{var}, \
1
                         AzDom_createTextDoNotUseWithoutBlockLevelWrapper(AZ_STR(\"{esc}\")));"
1
                    );
1
                }
            }
        }
    }
2
    Ok(var)
2
}
/// Compile a full HTML page to a compilable **C** Azul app.
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
/// # Errors
///
/// Returns an error if the XML cannot be parsed or compiled to C code.
3
pub fn str_to_c_code<'a>(
3
    root_nodes: &'a [XmlNodeChild],
3
    component_map: &'a ComponentMap,
3
) -> Result<String, CompileError> {
3
    let (global_style, body_node) = parse_page_style_and_body(root_nodes)?;
3
    let body_node = &body_node;
3
    let mut body = String::new();
3
    let mut counter = 0usize;
    // Emit the body as the root node, then its children.
3
    let root = alloc::format!("n{counter}");
3
    counter += 1;
3
    let _ = writeln!(body, "    AzDom {root} = AzDom_createBody();");
3
    let mut matcher = body_matcher(body_node);
3
    matcher.path.push(CssPathSelector::Type(NodeTypeTag::Body));
3
    let classes: Vec<String> = body_node
3
        .attributes
3
        .get_key("class")
3
        .map(|v| {
            v.split_whitespace()
                .map(alloc::string::ToString::to_string)
                .collect()
        })
3
        .unwrap_or_default();
3
    matcher.path.extend(
3
        classes
3
            .iter()
3
            .map(|c| CssPathSelector::Class(c.clone().into())),
    );
3
    let blocks = get_css_blocks(&global_style, &matcher);
3
    if !blocks.is_empty() {
        let inline_css = css_blocks_to_inline_string(&blocks);
        if !inline_css.is_empty() {
            let esc = inline_css.replace('\\', "\\\\").replace('"', "\\\"");
            let _ = writeln!(
                body,
                "    {root} = AzDom_withCss({root}, AZ_STR(\"{esc}\"));"
            );
        }
3
    }
3
    for (child_idx, child) in body_node.children.as_ref().iter().enumerate() {
2
        match child {
2
            XmlNodeChild::Element(child_node) => {
2
                let mut m = matcher.clone();
2
                m.path.push(CssPathSelector::Children);
2
                m.indices_in_parent.push(child_idx);
2
                m.children_length.push(body_node.children.len());
2
                let child_var = compile_node_c(
2
                    child_node,
2
                    component_map,
2
                    &global_style,
2
                    m,
2
                    &mut counter,
2
                    &mut body,
                )?;
2
                let _ = writeln!(body, "    AzDom_addChild(&{root}, {child_var});");
            }
            XmlNodeChild::Text(text) => {
                let text = text.trim();
                if !text.is_empty() {
                    let esc = text.replace('\\', "\\\\").replace('"', "\\\"");
                    let _ = writeln!(
                        body,
                        "    AzDom_addChild(&{root}, \
                         AzDom_createTextDoNotUseWithoutBlockLevelWrapper(AZ_STR(\"{esc}\")));"
                    );
                }
            }
        }
    }
3
    Ok(alloc::format!(
3
        "/* Auto-generated UI source code (C). Build:\n*   clang -I <azul>/target/codegen main.c \
3
         -lazul\n */\n#include \"azul.h\"\n#include <string.h>\n#define AZ_STR(s) \
3
         AzString_copyFromBytes((const uint8_t*)(s), 0, strlen(s))\n\nAzDom render(AzRefAny data, \
3
         AzLayoutCallbackInfo info) {{\n{body}    return {root};\n}}\n\nint main(void) {{\n    \
3
         AzString data_type = AZ_STR(\"Data\");\n    AzRefAny data = \
3
         AzRefAny_newC((AzGlVoidPtrConst){{ .ptr = NULL }}, 0, 1, 0, data_type, NULL, 0, 0);\n    \
3
         AzApp app = AzApp_create(data, AzAppConfig_create());\n    AzWindowCreateOptions window \
3
         = AzWindowCreateOptions_create(render);\n    AzApp_run(&app, window);\n    \
3
         AzApp_delete(&app);\n    return 0;\n}}\n"
3
    ))
3
}
#[cfg(test)]
#[path = "xml_test.rs"]
mod xml_test;