ruitl 0.2.2

Template compiler for type-safe, server-rendered HTML components in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
//! HTML rendering and manipulation utilities

use crate::error::{Result, RuitlError};
use html_escape::{encode_quoted_attribute, encode_text};
use std::fmt::{self, Display, Write};

/// Represents an HTML element with attributes and children.
///
/// Attributes are a `Vec<(String, HtmlAttribute)>` (not a `HashMap`) so
/// insertion order is preserved in the rendered output — matches templ's
/// behavior and keeps rendering deterministic.
#[derive(Debug, Clone, PartialEq)]
pub struct HtmlElement {
    pub tag: String,
    pub attributes: Vec<(String, HtmlAttribute)>,
    pub children: Vec<Html>,
    pub self_closing: bool,
}

/// Represents an HTML attribute with optional value
#[derive(Debug, Clone, PartialEq)]
pub enum HtmlAttribute {
    /// Attribute with a value (e.g., class="example")
    Value(String),
    /// Boolean attribute (e.g., disabled)
    Boolean,
    /// Multiple values (e.g., class="one two three")
    List(Vec<String>),
}

/// Main HTML content type that can be rendered
#[derive(Debug, Clone, PartialEq)]
pub enum Html {
    /// Text content (will be escaped)
    Text(String),
    /// Raw HTML content (will not be escaped)
    Raw(String),
    /// HTML element
    Element(HtmlElement),
    /// Fragment containing multiple HTML nodes
    Fragment(Vec<Html>),
    /// Empty/void content
    Empty,
}

impl HtmlElement {
    /// Create a new HTML element
    pub fn new<S: Into<String>>(tag: S) -> Self {
        Self {
            tag: tag.into(),
            attributes: Vec::new(),
            children: Vec::new(),
            self_closing: false,
        }
    }

    /// Create a self-closing element (like <img>, <br>, etc.)
    pub fn self_closing<S: Into<String>>(tag: S) -> Self {
        Self {
            tag: tag.into(),
            attributes: Vec::new(),
            children: Vec::new(),
            self_closing: true,
        }
    }

    /// Add an attribute with a value.
    ///
    /// Duplicate keys are preserved in insertion order (templ-style) — if you
    /// need overwrite semantics for a singleton key like `class` or `id`, use
    /// the dedicated `class()` / `id()` helpers which replace existing entries.
    pub fn attr<K: Into<String>, V: Into<String>>(mut self, key: K, value: V) -> Self {
        self.attributes
            .push((key.into(), HtmlAttribute::Value(value.into())));
        self
    }

    /// Add a boolean attribute
    pub fn bool_attr<K: Into<String>>(mut self, key: K) -> Self {
        self.attributes.push((key.into(), HtmlAttribute::Boolean));
        self
    }

    /// Add a class attribute (merged with any existing `class` entry)
    pub fn class<S: Into<String>>(mut self, class: S) -> Self {
        let class_name = class.into();
        let existing = self
            .attributes
            .iter_mut()
            .find(|(k, _)| k == "class")
            .map(|(_, v)| v);
        match existing {
            Some(HtmlAttribute::Value(existing)) => {
                *existing = format!("{} {}", existing, class_name);
            }
            Some(HtmlAttribute::List(list)) => {
                list.push(class_name);
            }
            _ => {
                self.attributes
                    .push(("class".to_string(), HtmlAttribute::Value(class_name)));
            }
        }
        self
    }

    /// Add multiple classes (replaces any existing `class` entry)
    pub fn classes<I, S>(mut self, classes: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        let class_list: Vec<String> = classes.into_iter().map(|s| s.into()).collect();
        if !class_list.is_empty() {
            self.attributes.retain(|(k, _)| k != "class");
            self.attributes
                .push(("class".to_string(), HtmlAttribute::List(class_list)));
        }
        self
    }

    /// Add an ID attribute (replaces any existing `id` entry)
    pub fn id<S: Into<String>>(mut self, id: S) -> Self {
        self.attributes.retain(|(k, _)| k != "id");
        self.attributes
            .push(("id".to_string(), HtmlAttribute::Value(id.into())));
        self
    }

    /// Add a child element
    pub fn child(mut self, child: Html) -> Self {
        self.children.push(child);
        self
    }

    /// Add an attribute conditionally
    pub fn attr_if<K: Into<String>, V: Into<String>>(
        mut self,
        key: K,
        condition: bool,
        value: V,
    ) -> Self {
        if condition {
            self.attributes
                .push((key.into(), HtmlAttribute::Value(value.into())));
        }
        self
    }

    /// Add an optional attribute (only if Some)
    pub fn attr_optional<K: Into<String>>(mut self, key: K, value: &Option<String>) -> Self {
        if let Some(ref val) = value {
            self.attributes
                .push((key.into(), HtmlAttribute::Value(val.clone())));
        }
        self
    }

    /// Add multiple children
    pub fn children<I>(mut self, children: I) -> Self
    where
        I: IntoIterator<Item = Html>,
    {
        self.children.extend(children);
        self
    }

    /// Add text content as a child
    pub fn text<S: Into<String>>(mut self, text: S) -> Self {
        self.children.push(Html::Text(text.into()));
        self
    }

    /// Add raw HTML content as a child
    pub fn raw<S: Into<String>>(mut self, html: S) -> Self {
        self.children.push(Html::Raw(html.into()));
        self
    }

    /// Check if this element has children
    pub fn has_children(&self) -> bool {
        !self.children.is_empty()
    }

    /// Check if this element is self-closing
    pub fn is_self_closing(&self) -> bool {
        self.self_closing || is_void_element(&self.tag)
    }
}

/// Apply the `minify-html` pass when the `minify` feature is on. No-op
/// otherwise. Kept out of the hot path so callers who care about exact
/// output (tests, snapshot tooling) can observe unminified HTML simply by
/// not building with the feature.
#[cfg(feature = "minify")]
fn maybe_minify(html: String) -> String {
    let cfg = minify_html::Cfg {
        keep_closing_tags: true,
        keep_comments: false,
        ..Default::default()
    };
    let bytes = minify_html::minify(html.as_bytes(), &cfg);
    String::from_utf8(bytes).unwrap_or(html)
}

#[cfg(not(feature = "minify"))]
fn maybe_minify(html: String) -> String {
    html
}

impl HtmlAttribute {
    /// Render the attribute as a string
    pub fn render(&self) -> String {
        match self {
            HtmlAttribute::Value(value) => format!("\"{}\"", encode_quoted_attribute(value)),
            HtmlAttribute::Boolean => String::new(),
            HtmlAttribute::List(list) => {
                let joined = list.join(" ");
                format!("\"{}\"", encode_quoted_attribute(&joined))
            }
        }
    }

    /// Check if this is a boolean attribute
    pub fn is_boolean(&self) -> bool {
        matches!(self, HtmlAttribute::Boolean)
    }
}

impl Html {
    /// Create text content
    pub fn text<S: Into<String>>(content: S) -> Self {
        Html::Text(content.into())
    }

    /// Create raw HTML content
    pub fn raw<S: Into<String>>(content: S) -> Self {
        Html::Raw(content.into())
    }

    /// Create an element
    pub fn element<S: Into<String>>(tag: S) -> HtmlElement {
        HtmlElement::new(tag)
    }

    /// Create a fragment
    pub fn fragment<I>(children: I) -> Self
    where
        I: IntoIterator<Item = Html>,
    {
        Html::Fragment(children.into_iter().collect())
    }

    /// Create empty content
    pub fn empty() -> Self {
        Html::Empty
    }

    /// Render the HTML to a string.
    ///
    /// When the `minify` feature is enabled, the output is run through
    /// `minify_html::minify` as a final pass with conservative defaults
    /// (`keep_closing_tags: true`). Without the feature, output is returned
    /// as-built.
    pub fn render(&self) -> String {
        let mut output = String::new();
        self.render_to(&mut output).unwrap_or_default();
        maybe_minify(output)
    }

    /// Render into a caller-supplied buffer so hot loops (hyper handlers,
    /// SSG crawlers) can reuse a single allocation across many renders.
    /// The buffer is **appended to** — callers who want a fresh payload
    /// should `buf.clear()` beforehand. Minification runs after the write
    /// when the `minify` feature is on, identical to `Html::render`.
    pub fn render_into(&self, buf: &mut String) -> Result<()> {
        let pre_len = buf.len();
        self.render_to(buf)?;
        #[cfg(feature = "minify")]
        {
            let written = buf.split_off(pre_len);
            buf.push_str(&maybe_minify(written));
        }
        #[cfg(not(feature = "minify"))]
        {
            let _ = pre_len;
        }
        Ok(())
    }

    /// Allocate with a given capacity up-front, then render. Useful when the
    /// caller has a tighter size estimate than `Html::len_hint` can produce
    /// — for instance, a cached prior-render length.
    pub fn render_with_capacity(&self, capacity: usize) -> String {
        let mut s = String::with_capacity(capacity);
        let _ = self.render_to(&mut s);
        maybe_minify(s)
    }

    /// Cheap lower-bound estimate of the rendered byte length, used to
    /// pre-size `String` buffers. Walks the tree once and sums a rough
    /// approximation of tag + attribute + child sizes. Underestimates mean
    /// one extra realloc during rendering; overestimates waste a bit of
    /// memory. Both are fine — this is a heuristic, not a contract.
    pub fn len_hint(&self) -> usize {
        match self {
            Html::Text(s) | Html::Raw(s) => s.len(),
            Html::Element(e) => {
                let attrs: usize = e
                    .attributes
                    .iter()
                    .map(|(k, v)| {
                        k.len()
                            + match v {
                                HtmlAttribute::Value(s) => s.len() + 4, // `="…" `
                                HtmlAttribute::Boolean => 1,
                                HtmlAttribute::List(items) => {
                                    items.iter().map(|s| s.len() + 1).sum::<usize>() + 3
                                }
                            }
                    })
                    .sum();
                let children: usize = e.children.iter().map(|c| c.len_hint()).sum();
                // Tag open + close = `<tag></tag>` ≈ 5 + 2*tag.len().
                e.tag.len() * 2 + 5 + attrs + children
            }
            Html::Fragment(children) => children.iter().map(|c| c.len_hint()).sum(),
            Html::Empty => 0,
        }
    }

    /// Split rendering into chunks aligned to top-level `Fragment` children,
    /// so a caller can stream them over an HTTP response body without holding
    /// the whole document in memory at once. For non-`Fragment` inputs this
    /// yields exactly one chunk (identical to `render()`). Each returned
    /// `Vec<u8>` is independently written (same encoding rules as `render_to`),
    /// so the concatenation equals `render()`.
    ///
    /// Typical usage with `hyper::Body::wrap_stream`:
    /// ```ignore
    /// let chunks = html.to_chunks();
    /// let stream = futures::stream::iter(chunks.into_iter().map(Ok::<_, std::io::Error>));
    /// hyper::Body::wrap_stream(stream)
    /// ```
    pub fn to_chunks(&self) -> Vec<Vec<u8>> {
        match self {
            Html::Fragment(children) if !children.is_empty() => children
                .iter()
                .map(|c| {
                    let mut s = String::with_capacity(c.len_hint());
                    let _ = c.render_to(&mut s);
                    s.into_bytes()
                })
                .collect(),
            _ => {
                let mut s = String::with_capacity(self.len_hint());
                let _ = self.render_to(&mut s);
                vec![s.into_bytes()]
            }
        }
    }

    /// Render the HTML to a writer
    pub fn render_to<W: Write>(&self, writer: &mut W) -> Result<()> {
        match self {
            Html::Text(text) => {
                write!(writer, "{}", encode_text(text))
                    .map_err(|e| RuitlError::render(format!("Failed to write text: {}", e)))?;
            }
            Html::Raw(html) => {
                write!(writer, "{}", html)
                    .map_err(|e| RuitlError::render(format!("Failed to write raw HTML: {}", e)))?;
            }
            Html::Element(element) => {
                element.render_to(writer)?;
            }
            Html::Fragment(children) => {
                for child in children {
                    child.render_to(writer)?;
                }
            }
            Html::Empty => {
                // Nothing to render
            }
        }
        Ok(())
    }

    /// Check if this HTML is empty
    pub fn is_empty(&self) -> bool {
        match self {
            Html::Empty => true,
            Html::Text(text) => text.is_empty(),
            Html::Raw(html) => html.is_empty(),
            Html::Fragment(children) => {
                children.is_empty() || children.iter().all(|c| c.is_empty())
            }
            Html::Element(_) => false, // Elements are never considered empty
        }
    }

    /// Get the text content (without HTML tags)
    pub fn text_content(&self) -> String {
        match self {
            Html::Text(text) => text.clone(),
            Html::Raw(_) => String::new(), // Raw HTML doesn't contribute to text content
            Html::Element(element) => element
                .children
                .iter()
                .map(|c| c.text_content())
                .collect::<Vec<_>>()
                .join(""),
            Html::Fragment(children) => children
                .iter()
                .map(|c| c.text_content())
                .collect::<Vec<_>>()
                .join(""),
            Html::Empty => String::new(),
        }
    }
}

impl HtmlElement {
    /// Render the element to a string
    pub fn render(&self) -> String {
        let mut output = String::new();
        self.render_to(&mut output).unwrap_or_default();
        output
    }

    /// Render the element to a writer
    pub fn render_to<W: Write>(&self, writer: &mut W) -> Result<()> {
        // Opening tag
        write!(writer, "<{}", self.tag)
            .map_err(|e| RuitlError::render(format!("Failed to write opening tag: {}", e)))?;

        // Attributes
        for (key, value) in &self.attributes {
            match value {
                HtmlAttribute::Boolean => {
                    write!(writer, " {}", key).map_err(|e| {
                        RuitlError::render(format!("Failed to write boolean attribute: {}", e))
                    })?;
                }
                _ => {
                    write!(writer, " {}={}", key, value.render()).map_err(|e| {
                        RuitlError::render(format!("Failed to write attribute: {}", e))
                    })?;
                }
            }
        }

        if self.is_self_closing() {
            write!(writer, " />").map_err(|e| {
                RuitlError::render(format!("Failed to write self-closing tag: {}", e))
            })?;
        } else {
            write!(writer, ">")
                .map_err(|e| RuitlError::render(format!("Failed to write tag close: {}", e)))?;

            // Children
            for child in &self.children {
                child.render_to(writer)?;
            }

            // Closing tag
            write!(writer, "</{}>", self.tag)
                .map_err(|e| RuitlError::render(format!("Failed to write closing tag: {}", e)))?;
        }

        Ok(())
    }
}

impl Display for Html {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.render())
    }
}

impl Display for HtmlElement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", Html::Element(self.clone()).render())
    }
}

impl From<HtmlElement> for Html {
    fn from(element: HtmlElement) -> Self {
        Html::Element(element)
    }
}

impl From<String> for Html {
    fn from(text: String) -> Self {
        Html::Text(text)
    }
}

impl From<&str> for Html {
    fn from(text: &str) -> Self {
        Html::Text(text.to_string())
    }
}

/// Check if a tag is a void element (self-closing)
fn is_void_element(tag: &str) -> bool {
    matches!(
        tag.to_lowercase().as_str(),
        "area"
            | "base"
            | "br"
            | "col"
            | "embed"
            | "hr"
            | "img"
            | "input"
            | "link"
            | "meta"
            | "param"
            | "source"
            | "track"
            | "wbr"
    )
}

/// Convenient HTML builder functions
pub fn html() -> HtmlElement {
    HtmlElement::new("html")
}

pub fn head() -> HtmlElement {
    HtmlElement::new("head")
}

pub fn body() -> HtmlElement {
    HtmlElement::new("body")
}

pub fn div() -> HtmlElement {
    HtmlElement::new("div")
}

pub fn p() -> HtmlElement {
    HtmlElement::new("p")
}

pub fn h1() -> HtmlElement {
    HtmlElement::new("h1")
}

pub fn h2() -> HtmlElement {
    HtmlElement::new("h2")
}

pub fn h3() -> HtmlElement {
    HtmlElement::new("h3")
}

pub fn h4() -> HtmlElement {
    HtmlElement::new("h4")
}

pub fn h5() -> HtmlElement {
    HtmlElement::new("h5")
}

pub fn h6() -> HtmlElement {
    HtmlElement::new("h6")
}

pub fn span() -> HtmlElement {
    HtmlElement::new("span")
}

pub fn a() -> HtmlElement {
    HtmlElement::new("a")
}

pub fn img() -> HtmlElement {
    HtmlElement::self_closing("img")
}

pub fn br() -> HtmlElement {
    HtmlElement::self_closing("br")
}

pub fn hr() -> HtmlElement {
    HtmlElement::self_closing("hr")
}

pub fn input() -> HtmlElement {
    HtmlElement::self_closing("input")
}

pub fn button() -> HtmlElement {
    HtmlElement::new("button")
}

pub fn form() -> HtmlElement {
    HtmlElement::new("form")
}

pub fn ul() -> HtmlElement {
    HtmlElement::new("ul")
}

pub fn ol() -> HtmlElement {
    HtmlElement::new("ol")
}

pub fn li() -> HtmlElement {
    HtmlElement::new("li")
}

pub fn table() -> HtmlElement {
    HtmlElement::new("table")
}

pub fn tr() -> HtmlElement {
    HtmlElement::new("tr")
}

pub fn td() -> HtmlElement {
    HtmlElement::new("td")
}

pub fn th() -> HtmlElement {
    HtmlElement::new("th")
}

pub fn thead() -> HtmlElement {
    HtmlElement::new("thead")
}

pub fn tbody() -> HtmlElement {
    HtmlElement::new("tbody")
}

pub fn section() -> HtmlElement {
    HtmlElement::new("section")
}

pub fn article() -> HtmlElement {
    HtmlElement::new("article")
}

pub fn nav() -> HtmlElement {
    HtmlElement::new("nav")
}

pub fn header() -> HtmlElement {
    HtmlElement::new("header")
}

pub fn footer() -> HtmlElement {
    HtmlElement::new("footer")
}

pub fn main() -> HtmlElement {
    HtmlElement::new("main")
}

pub fn aside() -> HtmlElement {
    HtmlElement::new("aside")
}

pub fn title() -> HtmlElement {
    HtmlElement::new("title")
}

pub fn style() -> HtmlElement {
    HtmlElement::new("style")
}

/// Create a text node
pub fn text<S: Into<String>>(content: S) -> Html {
    Html::text(content)
}

/// Create a raw HTML node
pub fn raw<S: Into<String>>(content: S) -> Html {
    Html::raw(content)
}

/// Create an empty fragment
pub fn fragment<I>(children: I) -> Html
where
    I: IntoIterator<Item = Html>,
{
    Html::fragment(children)
}

/// Extension methods used by generated code for conditional attributes.
pub trait HtmlElementExt {
    fn attr_if(self, name: &str, condition: bool, value: &str) -> Self;
    fn attr_optional<K: Into<String>>(self, name: K, value: &Option<String>) -> Self;
}

impl HtmlElementExt for HtmlElement {
    fn attr_if(self, name: &str, condition: bool, value: &str) -> Self {
        if condition {
            self.attr(name, value)
        } else {
            self
        }
    }

    fn attr_optional<K: Into<String>>(self, name: K, value: &Option<String>) -> Self {
        if let Some(ref val) = value {
            self.attr(name, val)
        } else {
            self
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_basic_element() {
        let element = div().class("test").text("Hello, world!");
        let html = element.render();
        assert_eq!(html, r#"<div class="test">Hello, world!</div>"#);
    }

    #[test]
    fn test_render_into_reuses_buffer() {
        let elem = Html::Element(div().text("one"));
        let mut buf = String::from("prefix:");
        elem.render_into(&mut buf).unwrap();
        assert_eq!(buf, "prefix:<div>one</div>");

        // Same buffer, cleared, second render
        buf.clear();
        let elem2 = Html::Element(div().text("two"));
        elem2.render_into(&mut buf).unwrap();
        assert_eq!(buf, "<div>two</div>");
    }

    #[test]
    fn test_render_with_capacity_matches_render() {
        let elem = Html::Element(div().class("x").child(Html::text("hi")));
        let a = elem.render();
        let b = elem.render_with_capacity(elem.len_hint());
        assert_eq!(a, b);
    }

    #[test]
    fn test_len_hint_non_zero_for_non_empty() {
        let elem = Html::Element(div().child(Html::text("hello")));
        assert!(elem.len_hint() > 0);
        assert_eq!(Html::Empty.len_hint(), 0);
    }

    #[test]
    fn test_to_chunks_splits_top_level_fragment() {
        let f = Html::Fragment(vec![
            Html::Element(div().text("one")),
            Html::Element(div().text("two")),
            Html::Element(div().text("three")),
        ]);
        let chunks = f.to_chunks();
        assert_eq!(chunks.len(), 3);
        let joined = String::from_utf8(chunks.concat()).unwrap();
        assert_eq!(joined, f.render());
    }

    #[test]
    fn test_to_chunks_single_element_one_chunk() {
        let e = Html::Element(div().text("solo"));
        let chunks = e.to_chunks();
        assert_eq!(chunks.len(), 1);
        assert_eq!(String::from_utf8(chunks[0].clone()).unwrap(), e.render());
    }

    #[test]
    fn test_self_closing_element() {
        let element = img().attr("src", "test.jpg").attr("alt", "Test");
        let html = element.render();
        assert_eq!(html, r#"<img src="test.jpg" alt="Test" />"#);
    }

    #[test]
    fn test_boolean_attribute() {
        let element = input().attr("type", "checkbox").bool_attr("checked");
        let html = element.render();
        assert_eq!(html, r#"<input type="checkbox" checked />"#);
    }

    #[test]
    fn test_nested_elements() {
        let element = div()
            .class("container")
            .child(Html::Element(h1().text("Title")))
            .child(Html::Element(p().text("Content")));

        let html = Html::Element(element).render();
        assert!(html.contains(r#"<div class="container">"#));
        assert!(html.contains("<h1>Title</h1>"));
        assert!(html.contains("<p>Content</p>"));
        assert!(html.contains("</div>"));
    }

    #[test]
    fn test_text_escaping() {
        let element = div().text("<script>alert('xss')</script>");
        let html = element.render();
        assert!(html.contains("&lt;script&gt;"));
        assert!(!html.contains("<script>"));
    }

    #[test]
    fn test_raw_html() {
        let element = div().raw("<em>emphasized</em>");
        let html = element.render();
        assert!(html.contains("<em>emphasized</em>"));
    }

    #[test]
    fn test_fragment() {
        let frag = fragment(vec![
            text("Hello "),
            Html::Element(span().text("world")),
            text("!"),
        ]);
        let html = frag.render();
        assert_eq!(html, "Hello <span>world</span>!");
    }

    #[test]
    fn test_multiple_classes() {
        let element = div().classes(vec!["one", "two", "three"]);
        let html = element.render();
        assert!(html.contains(r#"class="one two three""#));
    }

    #[test]
    fn test_void_elements() {
        assert!(is_void_element("br"));
        assert!(is_void_element("img"));
        assert!(is_void_element("input"));
        assert!(!is_void_element("div"));
        assert!(!is_void_element("span"));
    }

    #[test]
    fn test_text_content() {
        let element = div()
            .child(text("Hello "))
            .child(Html::Element(span().text("world")))
            .child(text("!"));

        let html = Html::Element(element);
        assert_eq!(html.text_content(), "Hello world!");
    }

    #[test]
    fn test_empty_html() {
        assert!(Html::empty().is_empty());
        assert!(Html::text("").is_empty());
        assert!(Html::fragment(vec![]).is_empty());
        assert!(!Html::text("content").is_empty());
    }
}