avosetta 0.1.5

A fast, minimal html templating language for 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
//! # avosetta
//!
//! A fast, minimal html templating language for Rust.
//!
//! ## about
//!
//! `avosetta` is a minimal templating library for that utilises procedural
//! macros to generate as close to optimal code as possible for rendering html
//! content at runtime. It has no `unsafe` code, only a handful of dependencies, and
//! does not allocate any values on the heap.
//!
//! We implement a terse, simple syntax for specifying templates that is
//! straightforward to parse, has little ambiguity and integrates into `Rust`
//! code better. And unlike other templating libraries such as `maud`, our syntax
//! typically only has a single way of writing various constructs, reducing
//! code-style clashing.
//!
//! Optimisations include automatically escaping static string literals at
//! compile-time and collapsing contiguous [`String::push_str`] calls into a single one.
//! Therefore, if your html fragment is entirely static, the generated code will
//! just be a single [`String::push_str`] with a [`&str`].
//!
//! ## getting started
//!
//! To start using `avosetta`, you'll first need to add our package to your
//! `Cargo.toml` manifest:
//!
//! ```sh
//! cargo add avosetta
//! ```
//!
//! Then you can start writing html templates directly in your `Rust` source
//! code.
//!
//! ```rust
//! use avosetta::prelude::*;
//!
//! fn main() {
//!   let mut s = String::new();
//!   index().write(&mut s);
//!
//!   println!("{s}");
//! }
//!
//! fn index() -> impl Html {
//!   html! {
//!     @layout(
//!       html! {
//!         title { "avosetta" }
//!       },
//!
//!       html! {
//!         h1 { "Hello, World!" }
//!       },
//!     )
//!   }
//! }
//!
//! fn layout(
//!   head: impl Html,
//!   body: impl Html,
//! ) -> impl Html {
//!   html! {
//!     "!DOCTYPE"[html];
//!     html[lang="en"] {
//!       head {
//!         meta[charset="UTF-8"];
//!         meta[name="viewport", content="width=device-width,initial-scale=1"];
//!
//!         @head
//!       }
//!
//!       body {
//!         main {
//!           @body
//!         }
//!       }
//!     }
//!   }
//! }
//! ```
//!
//! ## reference
//!
//! The syntax that this macro accepts is unique to `avosetta`, however, it
//! shares some major similarities with crates such as `maud` and `markup`. All of
//! these crates implement a terse, pug-like syntax which integrates into rust code
//! better and is less error-prone.
//!
//! Unlike the other crates, however, `avosetta` has a more minimal syntax.
//!
//! ### elements
//!
//! There are two types of elements that can be defined: `normal` and `void`.
//! `void` elements cannot have a body and must be terminated with a `semicolon`.
//!
//! ```rust
//! # use avosetta::prelude::*;
//! html! {
//!   // A `normal` element that will be rendered as: `<article></article>`
//!   article {}
//!
//!   // A `void` element that will be rendered as: `<br>`
//!   br;
//!
//!   // Element names can also be string literals:
//!   "x-custom-element" {}
//!
//!   "x-custom-element";
//! };
//! ```
//!
//! ### attributes
//!
//! Elements can also have attributes, which is a `comma` delimited list of
//! `key=value` pairs. Note, that attribute values can be dynamic (interpolated at
//! runtime), where as attribute names must be known at compile time.
//!
//! ```rust
//! # use avosetta::prelude::*;
//! html! {
//!   // A `meta` element with an attribute:
//!   meta[charset="UTF-8"];
//!
//!   // Elements can have multiple attributes:
//!   meta[name="viewport", content="width=device-width,initial-scale=1"];
//!
//!   // Attribute names can also be string literals:
//!   div["x-data"="Hello, World!"] {}
//!
//!   // Attribute values can be any `Rust` expression:
//!   input[value={4 + 3}];
//!
//!   // Attributes without a value are implicitly a `true` boolean attribute:
//!   input["type"="checkbox", checked];
//!   input["type"="checkbox", checked=true]; // These two elements are equivalent.
//! };
//! ```
//!
//! ### interpolation
//!
//! The process of "injecting" or writing dynamic content into the html is
//! called `interpolation`. This might be used for displaying a local variable
//! containing a username, or for performing a conditional `if` check before
//! rendering some sub-content.
//!
//! All interpolations start with an `@`, however, depending on the context,
//! different interpolations will be generated in the [`Html`] implementation.
//!
//! ```rust
//! # use avosetta::prelude::*;
//! let x = 9;
//!
//! html! {
//!   // The most basic interpolation of a simple expression:
//!   @x
//!
//!   // More complicated expressions can also be interpolated:
//!   @x + 2
//!
//!   // Depending on what you're interpolating, it may remove ambiguity to use
//!   // a block expression:
//!   @{ x + 2 }
//!
//!   // `Html` is implemented for `()`, therefore, expressions don't need to
//!   // return any html content:
//!   @{
//!     // This will be executed when the [`Html`] is written to a [`String`].
//!     println!("Hello, World!");
//!   }
//!
//!   // You can conditionally render content using the normal `Rust` syntax:
//!   @if x > 8 {
//!     // Notice how these arms take [`html!`] syntax and not `Rust` syntax.
//!     h1 { "Hello, World!" }
//!   } else if x < 2 {
//!     h2 { "Hello, World!" }
//!   } else {
//!     h3 { "Hello, World!" }
//!   }
//!
//!   // The same concept applies to both the `match` and `for` keywords:
//!   @match x {
//!     // Each arm must be wrapped in braces.
//!     8 => {
//!       h1 { "Hello, World!" }
//!     }
//!
//!     // Except for simple string literals.
//!     _ => "Hello, World!"
//!   }
//!
//!   @for i in 0..24 {
//!     // Nested interpolation works as you'd expect.
//!     span { @i }
//!   }
//! };
//! ```
//!
//! ### string literals
//!
//! Static string literals can be written directly without the need for an
//! interpolation. This form of "non-interpolated" static string is always escaped
//! at compile time, whereas, the interpolated variant will only be escaped at
//! compile time if the expression is simple enough for `avosetta` to parse.
//!
//! ```rust
//! # use avosetta::prelude::*;
//! html! {
//!   // All of these statements will result in the same output.
//!   h1 { @"Hello, World!" }
//!
//!   h1 { "Hello, World!" }
//!
//!   // This will not be escaped at compile-time because the extra braces make
//!   // this expression too complex for `avosetta` to try and parse.
//!   h1 { @{ "Hello, World!" } }
//! };
//! ```

#[cfg(feature = "macros")]
pub use ::avosetta_macros::html;

pub mod prelude {
    pub use crate::Html;

    #[cfg(feature = "macros")]
    pub use crate::html;
}

/// Represents a fragment of valid html that can be written to a `String`.
///
/// This trait is the backbone of `avosetta` and is implemented for most
/// primitives, such as integers, floats and strings. In some sense, this is a
/// specialized equivalent of the [`std::fmt::Display`] but without the overhead
/// associated with the [`std::fmt`] family of functions.
pub trait Html {
    fn write(self, s: &mut String);
}

/// Text that should not be escaped at runtime, such as dynamically generated
/// html, or some content that has already been escaped.
///
/// Note, that string literals are automatically escaped at compile-time when
/// used within [`html!`], therefore, one should not wrap static content with `Raw` in
/// an attempt to improve performance.
///
/// ```rust
/// # use avosetta::prelude::*;
/// html! {
///    @avosetta::raw("Hello, World!")
/// };
/// ```
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Raw<T>(pub T);

/// Text that should not be escaped at runtime, such as dynamically generated
/// html, or some content that has already been escaped.
///
/// Note, that string literals are automatically escaped at compile-time when
/// used within [`html!`], therefore, one should not wrap static content with `Raw` in
/// an attempt to improve performance.
///
/// ```rust
/// # use avosetta::prelude::*;
/// html! {
///    @avosetta::raw("Hello, World!")
/// };
/// ```
#[inline]
pub const fn raw<T>(x: T) -> Raw<T> {
    Raw(x)
}

impl Html for () {
    #[inline]
    fn write(self, _: &mut String) {}
}

impl Html for bool {
    #[inline]
    fn write(self, s: &mut String) {
        if self {
            s.push_str("true");
        } else {
            s.push_str("false");
        }
    }
}

impl Html for char {
    #[inline]
    fn write(self, s: &mut String) {
        match self {
            '&' => s.push_str("&amp;"),

            '<' => s.push_str("&lt;"),
            '>' => s.push_str("&gt;"),

            '\'' => s.push_str("&apos;"),
            '\"' => s.push_str("&quot;"),

            ch => {
                s.push(ch);
            }
        }
    }
}

impl Html for &str {
    #[inline]
    fn write(self, s: &mut String) {
        for ch in self.chars() {
            ch.write(s);
        }
    }
}

impl Html for String {
    #[inline]
    fn write(self, s: &mut String) {
        self.as_str().write(s);
    }
}

impl Html for Box<str> {
    #[inline]
    fn write(self, s: &mut String) {
        self.as_ref().write(s);
    }
}

impl Html for std::rc::Rc<str> {
    #[inline]
    fn write(self, s: &mut String) {
        self.as_ref().write(s);
    }
}

impl Html for std::sync::Arc<str> {
    #[inline]
    fn write(self, s: &mut String) {
        self.as_ref().write(s);
    }
}

impl Html for Raw<&str> {
    #[inline]
    fn write(self, s: &mut String) {
        s.push_str(self.0);
    }
}

impl Html for Raw<String> {
    #[inline]
    fn write(self, s: &mut String) {
        Raw(self.0.as_str()).write(s);
    }
}

impl Html for Raw<Box<str>> {
    #[inline]
    fn write(self, s: &mut String) {
        Raw(self.0.as_ref()).write(s);
    }
}

impl Html for Raw<std::rc::Rc<str>> {
    #[inline]
    fn write(self, s: &mut String) {
        Raw(self.0.as_ref()).write(s);
    }
}

impl Html for Raw<std::sync::Arc<str>> {
    #[inline]
    fn write(self, s: &mut String) {
        Raw(self.0.as_ref()).write(s);
    }
}

impl<T> Html for Option<T>
where
    T: Html,
{
    #[inline]
    fn write(self, s: &mut String) {
        if let Some(x) = self {
            x.write(s);
        }
    }
}

impl<T> Html for T
where
    T: FnOnce(&mut String),
{
    #[inline]
    fn write(self, s: &mut String) {
        (self)(s)
    }
}

macro_rules! __impl_html_integer {
    ($ty:ty) => {
        impl $crate::Html for $ty {
            #[inline]
            fn write(self, s: &mut ::std::string::String) {
                s.push_str(::itoa::Buffer::new().format(self));
            }
        }
    };
}

__impl_html_integer!(usize);
__impl_html_integer!(isize);

__impl_html_integer!(u8);
__impl_html_integer!(i8);

__impl_html_integer!(u16);
__impl_html_integer!(i16);

__impl_html_integer!(u32);
__impl_html_integer!(i32);

__impl_html_integer!(u64);
__impl_html_integer!(i64);

__impl_html_integer!(u128);
__impl_html_integer!(i128);

macro_rules! __impl_html_float {
    ($ty:ty) => {
        impl $crate::Html for $ty {
            #[inline]
            fn write(self, s: &mut ::std::string::String) {
                s.push_str(::ryu::Buffer::new().format(self));
            }
        }
    };
}

__impl_html_float!(f32);
__impl_html_float!(f64);

/// A html attribute, containing both a key and value.
///
/// For most value types, this struct simply renders out `K=\"V\"`, where
/// `K` is written as a [`&str`] directly, without any escaping and `V` is converted
/// to its [`Html`] representation. However, there are two edge case types that are
/// handled differently:
///
/// - [`bool`]: If the value is [`false`], then the entire attribute is ommitted from the
/// output html. If the value is [`true`], then just the `K` is written out.
///
/// - [`Option<T>`]: This struct will omit the attribute, if the provided [`Option<T>`] is [`None`],
/// and will use the [`Attr<&str, T>`] implementation if the provided value is [`Some`].
///
/// Note: This struct only implements [`Html`] for [`&str`] keys, since html
/// attributes have very stringent requirements on what constitutes a valid name.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Attr<K, V>(pub K, pub V);

impl Html for Attr<&str, &str> {
    #[inline]
    fn write(self, s: &mut String) {
        s.push_str(self.0);
        s.push_str("=\"");
        self.1.write(s);
        s.push_str("\"");
    }
}

impl Html for Attr<&str, String> {
    #[inline]
    fn write(self, s: &mut String) {
        Attr(self.0, self.1.as_str()).write(s);
    }
}

impl Html for Attr<&str, Box<str>> {
    #[inline]
    fn write(self, s: &mut String) {
        Attr(self.0, self.1.as_ref()).write(s);
    }
}

impl Html for Attr<&str, std::rc::Rc<str>> {
    #[inline]
    fn write(self, s: &mut String) {
        Attr(self.0, self.1.as_ref()).write(s);
    }
}

impl Html for Attr<&str, std::sync::Arc<str>> {
    #[inline]
    fn write(self, s: &mut String) {
        Attr(self.0, self.1.as_ref()).write(s);
    }
}

impl Html for Attr<&str, Raw<&str>> {
    #[inline]
    fn write(self, s: &mut String) {
        s.push_str(self.0);
        s.push_str("=\"");
        self.1.write(s);
        s.push_str("\"");
    }
}

impl Html for Attr<&str, Raw<String>> {
    #[inline]
    fn write(self, s: &mut String) {
        Attr(self.0, Raw(self.1.0.as_str())).write(s);
    }
}

impl Html for Attr<&str, Raw<Box<str>>> {
    #[inline]
    fn write(self, s: &mut String) {
        Attr(self.0, Raw(self.1.0.as_ref())).write(s);
    }
}

impl Html for Attr<&str, Raw<std::rc::Rc<str>>> {
    #[inline]
    fn write(self, s: &mut String) {
        Attr(self.0, Raw(self.1.0.as_ref())).write(s);
    }
}

impl Html for Attr<&str, Raw<std::sync::Arc<str>>> {
    #[inline]
    fn write(self, s: &mut String) {
        Attr(self.0, Raw(self.1.0.as_ref())).write(s);
    }
}

impl Html for Attr<&str, char> {
    #[inline]
    fn write(self, s: &mut String) {
        s.push_str(self.0);
        s.push_str("=\"");
        self.1.write(s);
        s.push_str("\"");
    }
}

impl Html for Attr<&str, bool> {
    #[inline]
    fn write(self, s: &mut String) {
        if self.1 {
            s.push_str(self.0);
        }
    }
}

impl<T> Html for Attr<&str, Option<T>>
where
    for<'a> Attr<&'a str, T>: Html,
{
    #[inline]
    fn write(self, s: &mut String) {
        if let Some(x) = self.1 {
            Attr(self.0, x).write(s);
        }
    }
}

impl<T> Html for Attr<&str, T>
where
    T: FnOnce(&mut String),
{
    #[inline]
    fn write(self, s: &mut String) {
        s.push_str(self.0);
        s.push_str("=\"");
        (self.1)(s);
        s.push_str("\"");
    }
}

macro_rules! __impl_attr_integer {
    ($ty:ty) => {
        impl $crate::Html for $crate::Attr<&str, $ty> {
            #[inline]
            fn write(self, s: &mut ::std::string::String) {
                s.push_str(self.0);
                s.push_str("=\"");
                s.push_str(::itoa::Buffer::new().format(self.1));
                s.push_str("\"");
            }
        }
    };
}

__impl_attr_integer!(usize);
__impl_attr_integer!(isize);

__impl_attr_integer!(u8);
__impl_attr_integer!(i8);

__impl_attr_integer!(u16);
__impl_attr_integer!(i16);

__impl_attr_integer!(u32);
__impl_attr_integer!(i32);

__impl_attr_integer!(u64);
__impl_attr_integer!(i64);

__impl_attr_integer!(u128);
__impl_attr_integer!(i128);

macro_rules! __impl_attr_float {
    ($ty:ty) => {
        impl $crate::Html for $crate::Attr<&str, $ty> {
            #[inline]
            fn write(self, s: &mut ::std::string::String) {
                s.push_str(self.0);
                s.push_str("=\"");
                s.push_str(::ryu::Buffer::new().format(self.1));
                s.push_str("\"");
            }
        }
    };
}

__impl_attr_float!(f32);
__impl_attr_float!(f64);