another_html_builder/
lib.rs

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
//! Just a simple toolkit for writing html.
//!
//! This provides the basic functions needed to write basic html or create components to build a rich and complete UI.
//!
//! # Example
//!
//! In this example, we create a custom attribute and also a custom `Head` element.
//!
//! ```rust
//! use another_html_builder::{AttributeValue, Body, Buffer};
//!
//! enum Lang {
//!     En,
//!     Fr,
//! }
//!
//! impl AttributeValue for Lang {
//!     fn render(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
//!         f.write_str(match self {
//!             Self::En => "en",
//!             Self::Fr => "fr",
//!         })
//!     }
//! }
//!
//! struct Head {
//!     title: &'static str,
//! }
//!
//! impl Default for Head {
//!     fn default() -> Self {
//!         Self {
//!             title: "Hello world!",
//!         }
//!     }
//! }
//!
//! impl Head {
//!     fn render<'a, W: std::fmt::Write>(&self, buf: Buffer<W, Body<'a>>) -> Buffer<W, Body<'a>> {
//!         buf.node("head")
//!             .content(|buf| buf.node("title").content(|buf| buf.text(self.title)))
//!     }
//! }
//!
//! let head = Head::default();
//! let html = Buffer::default()
//!     .doctype()
//!     .node("html")
//!     .attr(("lang", Lang::Fr))
//!     .content(|buf| head.render(buf))
//!     .into_inner();
//! assert_eq!(
//!     html,
//!     "<!DOCTYPE html><html lang=\"fr\"><head><title>Hello world!</title></head></html>"
//! );
//! ```
use std::fmt::Write;

/// Helper to write `&str` attributes to a [Write] and automatically escape
pub fn write_escaped_attribute_str<W: Write>(f: &mut W, value: &str) -> std::fmt::Result {
    for c in value.chars() {
        match c {
            '"' => f.write_str("\\\"")?,
            other => f.write_char(other)?,
        }
    }
    Ok(())
}

/// Helper to write `&str` content to a [Write] and automatically escape
pub fn write_escaped_content_str<W: Write>(f: &mut W, value: &str) -> std::fmt::Result {
    for c in value.chars() {
        match c {
            '&' => f.write_str("&amp;")?,
            '<' => f.write_str("&lt;")?,
            '>' => f.write_str("&gt;")?,
            '"' => f.write_str("&quot;")?,
            '\'' => f.write_str("&#x27;")?,
            '/' => f.write_str("&#x2F;")?,
            other => f.write_char(other)?,
        }
    }
    Ok(())
}

macro_rules! attribute_value {
    ($type:ty) => {
        impl AttributeValue for $type {
            fn render(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "{self}")
            }
        }
    };
}

/// Represents an element attribute name.
pub trait AttributeName {
    fn render(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
}

impl AttributeName for &str {
    fn render(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self)
    }
}

/// Represents an element attribute value.
///
/// This value should be escaped for double quotes for example.
/// The implementation of this trait on `&str` already implements this.
pub trait AttributeValue {
    fn render(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
}

impl AttributeValue for &str {
    fn render(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write_escaped_attribute_str(f, self)
    }
}

#[inline]
fn render_attr_name_only<N: AttributeName>(
    f: &mut std::fmt::Formatter<'_>,
    name: &N,
) -> std::fmt::Result {
    f.write_char(' ')?;
    name.render(f)
}

#[inline]
fn render_attr<N: AttributeName, V: AttributeValue>(
    f: &mut std::fmt::Formatter<'_>,
    name: &N,
    value: &V,
) -> std::fmt::Result {
    render_attr_name_only(f, name)?;
    f.write_char('=')?;
    f.write_char('"')?;
    value.render(f)?;
    f.write_char('"')
}

/// Wrapper used for displaying attributes in elements
///
/// This wrapper can print attributes with or without values.
/// It can also handle attributes wrapped in an `Option` and will behave accordingly.
///
/// # Examples
///
/// ```rust
/// let html = another_html_builder::Buffer::default()
///     .node("div")
///     .attr("name-only")
///     .attr(("name", "value"))
///     .attr(Some(("other", "value")))
///     .attr(("with-number", 42))
///     .close()
///     .into_inner();
/// assert_eq!(
///     html,
///     "<div name-only name=\"value\" other=\"value\" with-number=\"42\" />"
/// );
/// ```
///
/// # Extending
///
/// It's possible to implement attributes with custom types, just by implementing the [AttributeName] and [AttributeValue] traits.
///
/// ```rust
/// use std::fmt::Write;
///
/// struct ClassNames<'a>(&'a [&'static str]);
///
/// impl<'a> another_html_builder::AttributeValue for ClassNames<'a> {
///     fn render(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
///         for (index, inner) in self.0.iter().enumerate() {
///             if (index > 0) {
///                 f.write_char(' ')?;
///             }
///             // this could be avoided if you consider it is escaped by default
///             another_html_builder::write_escaped_attribute_str(f, inner)?;
///         }
///         Ok(())
///     }
/// }
///
/// let html = another_html_builder::Buffer::default()
///     .node("div")
///     .attr(("class", ClassNames(&["foo", "bar"])))
///     .close()
///     .into_inner();
/// assert_eq!(html, "<div class=\"foo bar\" />");
/// ```
pub struct Attribute<T>(pub T);

impl<N: AttributeName> std::fmt::Display for Attribute<Option<N>> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(ref inner) = self.0 {
            render_attr_name_only(f, inner)
        } else {
            Ok(())
        }
    }
}

impl<N: AttributeName> std::fmt::Display for Attribute<N> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        render_attr_name_only(f, &self.0)
    }
}

impl<N: AttributeName, V: AttributeValue> std::fmt::Display for Attribute<Option<(N, V)>> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some((name, value)) = &self.0 {
            render_attr(f, name, value)
        } else {
            Ok(())
        }
    }
}

impl<N: AttributeName, V: AttributeValue> std::fmt::Display for Attribute<(N, V)> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let (name, value) = &self.0;
        render_attr(f, name, value)
    }
}

attribute_value!(bool);
attribute_value!(u8);
attribute_value!(u16);
attribute_value!(u32);
attribute_value!(u64);
attribute_value!(usize);
attribute_value!(i8);
attribute_value!(i16);
attribute_value!(i32);
attribute_value!(i64);
attribute_value!(isize);

/// Representation of the inside of an element or the root level.
///
/// This component is made for the [Buffer] to be aware of where it is
/// and provide adequat functions.
#[derive(Debug)]
pub enum Body<'a> {
    /// This represents the root of the DOM. It has not name nor parents.
    Root,
    /// This represents any element with a name.
    Element {
        name: &'a str,
        parent: Box<Body<'a>>,
    },
}

impl Body<'_> {
    /// Generates the path of the current element.
    ///
    /// Note: this will not provid a valide CSS path
    pub fn path(&self) -> String {
        match self {
            Self::Root => String::from("$"),
            Self::Element { name, parent } => {
                let mut parent_path = parent.path();
                parent_path.push_str(" > ");
                parent_path.push_str(name);
                parent_path
            }
        }
    }
}

/// Representation of an element
#[derive(Debug)]
pub struct Element<'a> {
    parent: Body<'a>,
    name: &'a str,
}

/// Wrapper arround a writer element.
#[derive(Clone, Debug)]
pub struct Buffer<W, C> {
    inner: W,
    current: C,
}

impl Default for Buffer<String, Body<'static>> {
    fn default() -> Self {
        Self::new()
    }
}

impl Buffer<String, Body<'static>> {
    pub fn new() -> Self {
        Self {
            inner: String::default(),
            current: Body::Root,
        }
    }
}

impl<W> Buffer<W, Body<'_>> {
    pub fn into_inner(self) -> W {
        self.inner
    }
}

impl Buffer<String, Body<'_>> {
    pub fn inner(&self) -> &str {
        self.inner.as_str()
    }
}

impl<W: std::fmt::Write> Buffer<W, Body<'_>> {
    /// Appends the html doctype to the buffer
    pub fn doctype(mut self) -> Self {
        self.inner.write_str("<!DOCTYPE html>").unwrap();
        self
    }

    /// Tries to append the html doctype to the buffer
    pub fn try_doctype(mut self) -> Result<Self, std::fmt::Error> {
        self.inner.write_str("<!DOCTYPE html>")?;
        Ok(self)
    }
}

impl<'a, W: std::fmt::Write> Buffer<W, Body<'a>> {
    /// Conditionally apply some children to an element
    ///
    /// ```rust
    /// let is_error = true;
    /// let html = another_html_builder::Buffer::default()
    ///     .cond(is_error, |buf| {
    ///         buf.node("p").content(|buf| buf.text("ERROR!"))
    ///     })
    ///     .into_inner();
    /// assert_eq!(html, "<p>ERROR!</p>");
    /// ```
    pub fn cond<F>(self, condition: bool, children: F) -> Buffer<W, Body<'a>>
    where
        F: FnOnce(Buffer<W, Body>) -> Buffer<W, Body>,
    {
        if condition {
            children(self)
        } else {
            self
        }
    }

    pub fn try_cond<F>(
        self,
        condition: bool,
        children: F,
    ) -> Result<Buffer<W, Body<'a>>, std::fmt::Error>
    where
        F: FnOnce(Buffer<W, Body>) -> Result<Buffer<W, Body>, std::fmt::Error>,
    {
        if condition {
            children(self)
        } else {
            Ok(self)
        }
    }

    /// Conditionally apply some children to an element depending on an optional
    ///
    /// ```rust
    /// let value: Option<u8> = Some(42);
    /// let html = another_html_builder::Buffer::default()
    ///     .optional(value, |buf, answer| {
    ///         buf.node("p")
    ///             .content(|buf| buf.text("Answer: ").raw(answer))
    ///     })
    ///     .into_inner();
    /// assert_eq!(html, "<p>Answer: 42</p>");
    /// ```
    pub fn optional<V, F>(self, value: Option<V>, children: F) -> Buffer<W, Body<'a>>
    where
        F: FnOnce(Buffer<W, Body>, V) -> Buffer<W, Body>,
    {
        if let Some(inner) = value {
            children(self, inner)
        } else {
            self
        }
    }

    pub fn try_optional<V, F>(
        self,
        value: Option<V>,
        children: F,
    ) -> Result<Buffer<W, Body<'a>>, std::fmt::Error>
    where
        F: FnOnce(Buffer<W, Body>, V) -> Result<Buffer<W, Body>, std::fmt::Error>,
    {
        if let Some(inner) = value {
            children(self, inner)
        } else {
            Ok(self)
        }
    }

    /// Starts a new node in the buffer
    ///
    /// After calling this function, the buffer will only allow to add attributes,
    /// close the current node or add content to the node.
    ///
    /// ```rust
    /// let html = another_html_builder::Buffer::default()
    ///     .node("p")
    ///     .attr(("foo", "bar"))
    ///     .close()
    ///     .into_inner();
    /// assert_eq!(html, "<p foo=\"bar\" />");
    /// ```
    ///
    /// ```rust
    /// let html = another_html_builder::Buffer::default()
    ///     .node("p")
    ///     .content(|buf| buf.text("hello"))
    ///     .into_inner();
    /// assert_eq!(html, "<p>hello</p>");
    /// ```
    pub fn node(mut self, tag: &'a str) -> Buffer<W, Element<'a>> {
        write!(&mut self.inner, "<{tag}").unwrap();
        Buffer {
            inner: self.inner,
            current: Element {
                name: tag,
                parent: self.current,
            },
        }
    }

    pub fn try_node(mut self, tag: &'a str) -> Result<Buffer<W, Element<'a>>, std::fmt::Error> {
        write!(&mut self.inner, "<{tag}")?;
        Ok(Buffer {
            inner: self.inner,
            current: Element {
                name: tag,
                parent: self.current,
            },
        })
    }

    /// Appends some raw content implementing [Display](std::fmt::Display)
    ///
    /// This will not escape the provided value.
    pub fn raw<V: std::fmt::Display>(mut self, value: V) -> Self {
        write!(&mut self.inner, "{value}").unwrap();
        self
    }

    pub fn try_raw<V: std::fmt::Display>(mut self, value: V) -> Result<Self, std::fmt::Error> {
        write!(&mut self.inner, "{value}")?;
        Ok(self)
    }

    /// Appends some text and escape it.
    ///
    /// ```rust
    /// let html = another_html_builder::Buffer::new()
    ///     .node("p")
    ///     .content(|b| b.text("asd\"weiofew!/<>"))
    ///     .into_inner();
    /// assert_eq!(html, "<p>asd&quot;weiofew!&#x2F;&lt;&gt;</p>");
    /// ```
    pub fn text(mut self, content: &str) -> Self {
        write_escaped_content_str(&mut self.inner, content).unwrap();
        self
    }

    pub fn try_text(mut self, content: &str) -> Result<Self, std::fmt::Error> {
        write_escaped_content_str(&mut self.inner, content)?;
        Ok(self)
    }
}

impl<'a, W: std::fmt::Write> Buffer<W, Element<'a>> {
    /// Appends an attribute to the current node.
    ///
    /// For more information about how to extend attributes, take a look at the [Attribute] trait.
    ///
    /// ```rust
    /// let html = another_html_builder::Buffer::new()
    ///     .node("p")
    ///     .attr("single")
    ///     .attr(("hello", "world"))
    ///     .attr(("number", 42))
    ///     .attr(Some(("foo", "bar")))
    ///     .attr(None::<(&str, &str)>)
    ///     .attr(Some("here"))
    ///     .attr(None::<&str>)
    ///     .close()
    ///     .into_inner();
    /// assert_eq!(
    ///     html,
    ///     "<p single hello=\"world\" number=\"42\" foo=\"bar\" here />"
    /// );
    /// ```
    pub fn attr<T>(mut self, attr: T) -> Self
    where
        Attribute<T>: std::fmt::Display,
    {
        write!(&mut self.inner, "{}", Attribute(attr)).unwrap();
        self
    }

    #[inline]
    pub fn try_attr<T>(mut self, attr: T) -> Result<Self, std::fmt::Error>
    where
        Attribute<T>: std::fmt::Display,
    {
        write!(&mut self.inner, "{}", Attribute(attr))?;
        Ok(self)
    }

    /// Conditionally appends some attributes
    ///
    /// ```rust
    /// let html = another_html_builder::Buffer::new()
    ///     .node("p")
    ///     .cond_attr(true, ("foo", "bar"))
    ///     .cond_attr(false, ("foo", "baz"))
    ///     .cond_attr(true, "here")
    ///     .cond_attr(false, "not-here")
    ///     .close()
    ///     .into_inner();
    /// assert_eq!(html, "<p foo=\"bar\" here />");
    /// ```
    #[inline]
    pub fn cond_attr<T>(self, condition: bool, attr: T) -> Self
    where
        Attribute<T>: std::fmt::Display,
    {
        if condition {
            self.attr(attr)
        } else {
            self
        }
    }

    #[inline]
    pub fn try_cond_attr<T>(self, condition: bool, attr: T) -> Result<Self, std::fmt::Error>
    where
        Attribute<T>: std::fmt::Display,
    {
        if condition {
            self.try_attr(attr)
        } else {
            Ok(self)
        }
    }

    /// Closes the current node without providing any content
    ///
    /// ```rust
    /// let html = another_html_builder::Buffer::new()
    ///     .node("p")
    ///     .close()
    ///     .into_inner();
    /// assert_eq!(html, "<p />");
    /// ```
    pub fn close(mut self) -> Buffer<W, Body<'a>> {
        self.inner.write_str(" />").unwrap();
        Buffer {
            inner: self.inner,
            current: self.current.parent,
        }
    }

    pub fn try_close(mut self) -> Result<Buffer<W, Body<'a>>, std::fmt::Error> {
        self.inner.write_str(" />")?;
        Ok(Buffer {
            inner: self.inner,
            current: self.current.parent,
        })
    }

    /// Closes the current node and start writing it's content
    ///
    /// When returning the inner callback, the closing element will be written to the buffer
    ///
    /// ```rust
    /// let html = another_html_builder::Buffer::new()
    ///     .node("div")
    ///     .content(|buf| buf.node("p").close())
    ///     .into_inner();
    /// assert_eq!(html, "<div><p /></div>");
    /// ```
    pub fn content<F>(mut self, children: F) -> Buffer<W, Body<'a>>
    where
        F: FnOnce(Buffer<W, Body>) -> Buffer<W, Body>,
    {
        self.inner.write_char('>').unwrap();
        let child_buffer = Buffer {
            inner: self.inner,
            current: Body::Element {
                name: self.current.name,
                parent: Box::new(self.current.parent),
            },
        };
        let Buffer { mut inner, current } = children(child_buffer);
        match current {
            Body::Element { name, parent } => {
                inner.write_str("</").unwrap();
                inner.write_str(name).unwrap();
                inner.write_char('>').unwrap();
                Buffer {
                    inner,
                    current: *parent,
                }
            }
            // This should never happen
            Body::Root => Buffer {
                inner,
                current: Body::Root,
            },
        }
    }

    pub fn try_content<F>(mut self, children: F) -> Result<Buffer<W, Body<'a>>, std::fmt::Error>
    where
        F: FnOnce(Buffer<W, Body>) -> Result<Buffer<W, Body>, std::fmt::Error>,
    {
        self.inner.write_char('>')?;
        let child_buffer = Buffer {
            inner: self.inner,
            current: Body::Element {
                name: self.current.name,
                parent: Box::new(self.current.parent),
            },
        };
        let Buffer { mut inner, current } = children(child_buffer)?;
        match current {
            Body::Element { name, parent } => {
                inner.write_str("</")?;
                inner.write_str(name)?;
                inner.write_char('>')?;
                Ok(Buffer {
                    inner,
                    current: *parent,
                })
            }
            // This should never happen
            Body::Root => Ok(Buffer {
                inner,
                current: Body::Root,
            }),
        }
    }
}

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

    #[test]
    fn should_rollback_after_content() {
        let buffer = Buffer::new().node("a").content(|buf| buf);
        assert!(
            matches!(buffer.current, Body::Root),
            "found {:?}",
            buffer.current
        );
    }

    #[test]
    fn simple_html() {
        let html = Buffer::new()
            .doctype()
            .node("html")
            .attr(("lang", "en"))
            .content(|buf| {
                buf.node("head")
                    .content(|buf| {
                        let buf = buf.node("meta").attr(("charset", "utf-8")).close();
                        buf.node("meta")
                            .attr(("name", "viewport"))
                            .attr(("content", "width=device-width, initial-scale=1"))
                            .close()
                    })
                    .node("body")
                    .close()
            })
            .into_inner();
        assert_eq!(
            html,
            "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\" /><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /></head><body /></html>"
        );
    }

    #[test]
    fn with_special_characters_in_attributes() {
        let html = Buffer::new()
            .node("a")
            .attr(("title", "Let's add a quote \" like this"))
            .attr(("href", "http://example.com?whatever=here"))
            .content(|b| b.text("Click me!"))
            .into_inner();
        assert_eq!(
            html,
            "<a title=\"Let's add a quote \\\" like this\" href=\"http://example.com?whatever=here\">Click me!</a>"
        );
    }

    #[test]
    fn with_special_characters_in_content() {
        let html = Buffer::new()
            .node("p")
            .content(|b| b.text("asd\"weiofew!/<>"))
            .into_inner();
        assert_eq!(html, "<p>asd&quot;weiofew!&#x2F;&lt;&gt;</p>");
    }

    #[test]
    fn with_optional_attributes() {
        let html = Buffer::new()
            .node("p")
            .attr(Some(("foo", "bar")))
            .attr(None::<(&str, &str)>)
            .attr(Some("here"))
            .attr(None::<&str>)
            .close()
            .into_inner();
        assert_eq!(html, "<p foo=\"bar\" here />");
    }

    #[test]
    fn with_attributes() {
        let html = Buffer::new()
            .node("p")
            .attr(("foo", "bar"))
            .attr(("bool", true))
            .attr(("u8", 42u8))
            .attr(("i8", -1i8))
            .close()
            .into_inner();
        assert_eq!(html, "<p foo=\"bar\" bool=\"true\" u8=\"42\" i8=\"-1\" />");
    }

    #[test]
    fn with_conditional_attributes() {
        let html = Buffer::new()
            .node("p")
            .cond_attr(true, ("foo", "bar"))
            .cond_attr(false, ("foo", "baz"))
            .cond_attr(true, "here")
            .cond_attr(false, "not-here")
            .close()
            .into_inner();
        assert_eq!(html, "<p foo=\"bar\" here />");
    }

    #[test]
    fn with_conditional_content() {
        let notification = false;
        let connected = true;
        let html = Buffer::new()
            .node("div")
            .content(|buf| {
                buf.cond(notification, |buf| {
                    buf.node("p")
                        .content(|buf| buf.text("You have a notification"))
                })
                .cond(connected, |buf| buf.text("Welcome!"))
            })
            .into_inner();
        assert_eq!(html, "<div>Welcome!</div>");
    }

    #[test]
    fn with_optional_content() {
        let error = Some("This is an error");
        let html = Buffer::new()
            .node("div")
            .content(|buf| buf.optional(error, |buf, msg| buf.text(msg)))
            .into_inner();
        assert_eq!(html, "<div>This is an error</div>");
    }
}