laby/
lib.rs

1//
2// Copyright (c) 2021 chiya.dev
3//
4// Use of this source code is governed by the MIT License
5// which can be found in the LICENSE file and at:
6//
7//   https://opensource.org/licenses/MIT
8//
9//! laby is a small *macro* library for writing fast HTML templates in Rust. It focuses on three
10//! things:
11//!
12//! - **Simplicity**: laby has minimal dependencies, works out of the box without any
13//! configuration, and can be easily extended to add extra functionality where necessary.
14//! - **Performance**: laby generates specialized code that generate HTML. It requires no heap
15//! allocation at runtime other than the buffer that the resulting HTML gets rendered to. Any
16//! operation that involves extra heap allocations is opt-in. All rendering code is statically type
17//! checked at compile time and inlined for performance.
18//! - **Familiarity**: laby provides macros that can accept any valid Rust code and expand to
19//! regular Rust code; learning a new [DSL][1] for HTML templating is not necessary. Macros can be
20//! nested, composed, formatted by [rustfmt][2], separated into components and returned by
21//! functions just like regular Rust code.
22//!
23//! Much of laby's high-performance code was inherited from [sailfish][3], an extremely fast HTML
24//! templating engine for Rust. However, whereas sailfish processes HTML template files *with
25//! special syntax*, laby provides macros that are embedded *into your code directly*. Which
26//! library to adopt is up to your coding style and personal preference.
27//!
28//! laby targets *Rust stable* and supports embedded environments with [no_std][4]. No
29//! configuration is required.
30//!
31//! # Installation
32//!
33//! In your project, add the following line to your `Cargo.toml` in the `[dependencies]` section:
34//!
35//! ```toml
36//! [dependencies]
37//! laby = "0.4"
38//! ```
39//!
40//! Additionally, you may want to import laby into your code like this:
41//!
42//! ```
43//! use laby::*;
44//! ```
45//!
46//! This is purely for convenience because laby exports a large amount of macros, each of which
47//! represent an [HTML tag][5]. Of course, it is possible to import only the macros you use
48//! individually. The rest of this guide assumes that you have imported the necessary macros
49//! already.
50//!
51//! laby does not provide integration support for popular web frameworks. It returns a plain old
52//! [`String`][7] as the rendered result, so you are encouraged to write your own macro that writes
53//! that [`String`][7] to the response stream. Most web frameworks can do this out of the box.
54//!
55//! # Basics
56//!
57//! laby provides procedural macros that generate specialized Rust code at compile time, which in
58//! turn generate HTML code when rendered at runtime. In order to use laby effectively,
59//! understanding how it transforms your code is necessary. Consider the following example.
60//!
61//! ```
62//! # use laby::*;
63//! // construct a tree of html nodes
64//! let n = html!(
65//!     head!(
66//!         title!("laby"),
67//!     ),
68//!     body!(
69//!         class = "dark",
70//!         p!("hello, world"),
71//!     ),
72//! );
73//!
74//! // convert the tree into a string
75//! let s = render!(n);
76//!
77//! // check the result
78//! assert_eq!(s, "\
79//!     <html>\
80//!         <head>\
81//!             <title>laby</title>\
82//!         </head>\
83//!         <body class=\"dark\">\
84//!             <p>hello, world</p>\
85//!         </body>\
86//!     </html>\
87//! ");
88//! ```
89//!
90//! The above code uses the macros [`html!`], [`head!`], [`title!`], [`body!`] and [`p!`] to
91//! construct a basic HTML structure. Then, the [`render!`] macro is used to convert the tree into
92//! a [`String`][7] representation. The result is compared to another string which is spread over
93//! multiple lines for readability.
94//!
95//! Notice how the children of a node are passed as regular positional arguments, while the
96//! attributes of a node are specified as assignment expressions. This is a perfectly valid Rust
97//! syntax, which means it can be formatted using [rustfmt][2].
98//!
99//! Under the hood, laby transforms the above code into code that looks something like this:
100//!
101//! ```
102//! # use laby::*;
103//! let n = {
104//!     struct _html {}
105//!     impl Render for _html {
106//!         #[inline]
107//!         fn render(self, buf: &mut laby::internal::Buffer) {
108//!             buf.push_str("<html><head><title>laby</title></head><body class=\"dark\"><p>hello, world</p></body></html>");
109//!         }
110//!     }
111//!     _html {}
112//! };
113//!
114//! let s = render!(n);
115//! // assert_eq!(s, ...);
116//! ```
117//!
118//! This is, in essence, all that laby macros do; they simply declare a new specialized struct for
119//! a tree of nodes, implement the [`Render`] trait for that struct, construct that struct, and
120//! return the constructed value.
121//!
122//! When this code is compiled for release, all that wrapper code is stripped away and the
123//! rendering code is inlined, leaving something like this for execution:
124//!
125//! ```
126//! # use laby::*;
127//! let mut buf = laby::internal::Buffer::new();
128//! buf.push_str("<html><head><title>laby</title></head><body class=\"dark\"><p>hello, world</p></body></html>");
129//!
130//! let s = buf.into_string();
131//! // assert_eq!(s, ...);
132//! ```
133//!
134//! # Templating
135//!
136//! laby accepts any valid expression in place of attribute names and values and child nodes, and
137//! can access variables in the local scope just like regular code. It is not limited to only
138//! string literals.
139//!
140//! The only requirement is for the expression to evaluate to a value that implements the
141//! [`Render`] trait. Refer to the [list of foreign impls](Render#foreign-impls) to see which types
142//! implement this trait out of the box. The evaluated value is stored in the specialized struct
143//! and rendered when the [`render!`] macro is called. Consider the following example.
144//!
145//! ```
146//! # use laby::*;
147//! // retrieve an article from a database
148//! let title = "laby";
149//! let content = "hello, 'world'";
150//! let date = "2030-01-01";
151//!
152//! // construct a tree of nodes, with templated expressions
153//! let n = article!(
154//!     class = format!("date-{}", date),
155//!     h1!({
156//!         let mut title = title.to_owned();
157//!         title.truncate(30);
158//!         title
159//!     }),
160//!     p!(content),
161//! );
162//!
163//! // convert the tree into a string
164//! let s = render!(n);
165//!
166//! // check the result
167//! assert_eq!(s, "\
168//!     <article class=\"date-2030-01-01\">\
169//!         <h1>laby</h1>\
170//!         <p>hello, &#39;world&#39;</p>\
171//!     </article>\
172//! ");
173//! ```
174//!
175//! The above code constructs a basic HTML structure for an article with the title, content and
176//! class attribute templated.
177//!
178//! - `class` attribute: a `format!` macro expression is expanded and evaluated.
179//! - `<h1>` node: an expression that truncates the title to at most thirty characters is
180//! evaluated.
181//! - `<p>` node: a simple local variable expression is evaluated.
182//!
183//! Note, that these expressions are evaluated where the node is *constructed* (i.e. `let n =
184//! ...`), not where the [`render!`] macro is called.
185//!
186//! Additionally, the apostrophes in the article contents are escaped with the HTML entity `&#39;`.
187//! laby escapes all templated expressions by default unless the [`raw!`] macro is used.
188//!
189//! Under the hood, laby transforms the above code into code that looks something like this:
190//!
191//! ```
192//! # use laby::*;
193//! let title = "laby";
194//! let content = "hello, 'world'";
195//! let date = "2030-01-01";
196//!
197//! let n = {
198//!     struct _article<T1, T2, T3> { t1: T1, t2: T2, t3: T3 }
199//!     impl<T1, T2, T3> Render for _article<T1, T2, T3>
200//!         where T1: Render, T2: Render, T3: Render {
201//!         #[inline]
202//!         fn render(self, buf: &mut laby::internal::Buffer) {
203//!             buf.push_str("<article class=\"");
204//!             self.t1.render(buf); // date
205//!             buf.push_str("\"><h1>");
206//!             self.t2.render(buf); // title
207//!             buf.push_str("</h1><p>");
208//!             self.t3.render(buf); // content
209//!             buf.push_str("</p></article>");
210//!         }
211//!     }
212//!     _article {
213//!         t1: format!("date-{}", date),
214//!         t2: {
215//!             let mut title = title.to_owned();
216//!             title.truncate(30);
217//!             title
218//!         },
219//!         t3: content
220//!     }
221//! };
222//!
223//! let s = render!(n);
224//! // assert_eq!(s, ...);
225//! ```
226//!
227//! Notice how the fields of the generated specialized struct are generic over the templated
228//! expressions. When that struct is constructed (i.e. `_article { ... }`), the compiler is able to
229//! infer the generic type arguments from the field assignments and monomorphize the struct. Iff
230//! all field expressions evaluate to a value that implements the [`Render`] trait, then that trait
231//! will also be implemented for the generated struct, allowing for it to be rendered by
232//! [`render!`].
233//!
234//! # Componentization
235//!
236//! Writing a large template for rendering an entire HTML document quickly becomes unwieldy and
237//! unmaintainable, so it is often necessary to break up the document into several smaller
238//! components. There are two popular techniques around this problem: *include* and *inherit*. laby
239//! supports both patterns, using the language features provided by Rust.
240//!
241//! In practice, these patterns are often mixed and matched together to form a complete and
242//! coherent document. Examples of both approaches are explored below.
243//!
244//! #### Template inheritance
245//!
246//! This is a [top-down approach][6] that breaks down a large document into small components. This
247//! leads to a consistent but rigid structure that is difficult to extend or change easily.
248//!
249//! ```
250//! # use laby::*;
251//! // a large template that takes small components
252//! fn page(title: impl Render, header: impl Render, body: impl Render) -> impl Render {
253//!     html!(
254//!         head!(
255//!             title!(title),
256//!         ),
257//!         body!(
258//!             header!(header),
259//!             main!(body),
260//!         ),
261//!     )
262//! }
263//!
264//! // a component that *inherits* a large template
265//! fn home() -> impl Render {
266//!     page(
267//!         "Home",
268//!         h1!("About laby"),
269//!         p!("laby is an HTML macro library for Rust."),
270//!     )
271//! }
272//!
273//! assert_eq!(render!(home()), "\
274//!     <html>\
275//!         <head>\
276//!             <title>Home</title>\
277//!         </head>\
278//!         <body>\
279//!             <header>\
280//!                 <h1>About laby</h1>\
281//!             </header>\
282//!             <main>\
283//!                 <p>laby is an HTML macro library for Rust.</p>\
284//!             </main>\
285//!         </body>\
286//!     </html>\
287//! ");
288//! ```
289//!
290//! #### Template inclusion
291//!
292//! This is a [bottom-up approach][6] that consolidates small components to form a large document.
293//! This leads to a flexible but possibly inconsistent structure that may also result in more
294//! boilerplate code.
295//!
296//! ```
297//! # use laby::*;
298//! // small individual components
299//! fn title() -> impl Render {
300//!     "Home"
301//! }
302//!
303//! fn header() -> impl Render {
304//!     h1!("About laby")
305//! }
306//!
307//! fn body() -> impl Render {
308//!     p!("laby is an HTML macro library for Rust.")
309//! }
310//!
311//! // a large component that *includes* the small components
312//! fn home() -> impl Render {
313//!     html!(
314//!         head!(
315//!             title!(title()),
316//!         ),
317//!         body!(
318//!             header!(header()),
319//!             main!(body()),
320//!         ),
321//!     )
322//! }
323//!
324//! assert_eq!(render!(home()), "\
325//!     <html>\
326//!         <head>\
327//!             <title>Home</title>\
328//!         </head>\
329//!         <body>\
330//!             <header>\
331//!                 <h1>About laby</h1>\
332//!             </header>\
333//!             <main>\
334//!                 <p>laby is an HTML macro library for Rust.</p>\
335//!             </main>\
336//!         </body>\
337//!     </html>\
338//! ");
339//! ```
340//!
341//! ## Naming arguments
342//!
343//! Sometimes components can get big and accept a long list of positional arguments that hurts
344//! readability. laby provides an attribute macro called [`#[laby]`][13] which lets you call
345//! arbitrary functions with explicitly named arguments and optional values, similar to HTML
346//! macros.
347//!
348//! To enable support, simply prepend the attribute before the component function and call it using
349//! the generated macro.
350//!
351//! ```
352//! # use laby::*;
353//! #[laby]
354//! fn page(title: impl Render, header: impl Render, body: impl Render) -> impl Render {
355//!     html!(
356//!         head!(
357//!             title!(title),
358//!         ),
359//!         body!(
360//!             header!(header),
361//!             main!(body),
362//!         ),
363//!     )
364//! }
365//!
366//! #[laby]
367//! fn home() -> impl Render {
368//!     // `page` function called using the generated `page!` macro
369//!     page!(
370//!         title = "Home",
371//!         header = h1!("About laby"),
372//!         body = p!("laby is an HTML macro library for Rust."),
373//!     )
374//! }
375//! ```
376//!
377//! # Extensions
378//!
379//! laby can be extended by simply implementing the [`Render`] trait, which is a low-level trait
380//! that represents the smallest unit of a rendering operation. If what laby provides out of the
381//! box is too limiting for your specific use case, or if laby does not provide a [`Render`]
382//! implementation for a type you need, implementing this trait yourself may be a viable solution.
383//!
384//! The general pattern for creating an extension is like this:
385//!
386//! 1. Write a struct that stores all necessary data for your rendering operation.
387//! 2. Implement the [`Render`] trait for that struct.
388//! 3. Provide a simple, short macro that constructs that struct conveniently.
389//!
390//! In fact, the macros [`iter!`], [`raw!`] and [`disp!`] are implemented in this way. They are not
391//! magic; they are simply extensions of laby's core rendering system. You can even ignore laby's
392//! HTML macros and write your own transformations to implement the [`Render`] trait.
393//!
394//! # License
395//!
396//! laby is written by [chiya.dev][0], licensed under the [MIT License][9]. Portions of code were
397//! taken from [sailfish][3] which is written by [Ryohei Machida][10], also licensed under the [MIT
398//! License][8]. Documentation for HTML tags were taken from [MDN][11], licensed under [CC-BY-SA
399//! 2.5][12].
400//!
401//! [0]: https://chiya.dev/
402//! [1]: https://en.wikipedia.org/wiki/Domain-specific_language
403//! [2]: https://github.com/rust-lang/rustfmt
404//! [3]: https://docs.rs/sailfish/
405//! [4]: https://docs.rust-embedded.org/book/intro/no-std.html
406//! [5]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element
407//! [6]: https://en.wikipedia.org/wiki/Top-down_and_bottom-up_design
408//! [7]: alloc::string::String
409//! [8]: https://github.com/Kogia-sima/sailfish/blob/master/LICENSE
410//! [9]: https://fossil.chiya.dev/laby/file?name=LICENSE
411//! [10]: https://github.com/Kogia-sima
412//! [11]: https://developer.mozilla.org/
413//! [12]: https://github.com/mdn/content/blob/main/LICENSE.md
414//! [13]: laby
415#![no_std]
416#![deny(missing_docs)]
417extern crate alloc;
418
419mod doctype;
420mod helpers;
421
422pub use doctype::*;
423pub use helpers::*;
424pub use laby_common::*;
425pub use laby_macros::{
426    __laby_internal_call_fn_named, __laby_internal_set_hygiene_call_site, a, abbr, address, area,
427    article, aside, audio, b, base, bdi, bdo, blockquote, body, br, button, canvas, caption, cite,
428    code, col, colgroup, data, datalist, dd, del, details, dfn, dialog, div, dl, dt, em, embed,
429    fieldset, figcaption, figure, footer, form, h1, h2, h3, h4, h5, h6, head, header, hgroup, hr,
430    html, i, iframe, img, input, ins, kbd, label, legend, li, link, main, map, mark, menu,
431    menuitem, meta, meter, nav, noscript, object, ol, optgroup, option, output, p, param, picture,
432    pre, progress, q, rb, rp, rt, rtc, ruby, s, samp, script, section, select, slot, small, source,
433    span, strong, style, sub, summary, sup, table, tbody, td, template, textarea, tfoot, th, thead,
434    time, title, tr, track, u, ul, var, video, wbr,
435};
436
437/// Generates a macro that calls a function with named arguments.
438///
439/// Named arguments can be useful when a function accepts several arguments, because explicitly
440/// stating the arguments with parameter names can improve readability.
441///
442/// This attribute macro generates a *function-like macro*, with the same visibility and path as
443/// the target function, which allows callers to call that function with the arguments specified in
444/// any arbitrary order using *assignment-like expressions* (`name = value`).
445///
446/// Although this attribute is provided for use in laby components, its implementation is not
447/// specific to laby. It may be applied to any function, albeit with some caveats documented below.
448/// Refer to the crate-level documentation for more usage examples.
449///
450/// # `#[default]` arguments
451///
452/// By default, all arguments must be specified explicitly, even [`Option<T>`] types. Omittable
453/// arguments are opt-in. To mark a parameter as omittable, prepend the `#[default]` attribute to
454/// the parameter.
455///
456/// ```
457/// # use laby::*;
458/// #[laby]
459/// fn foo(x: Option<&str>) {
460///     assert!(x.is_none());
461/// }
462///
463/// #[laby]
464/// fn bar(#[default] x: Option<&str>) {
465///     assert!(x.is_none());
466/// }
467///
468/// foo!(x = None); // required
469/// bar!(x = None); // omittable
470/// bar!(); // omitted; equivalent to the above line
471/// ```
472///
473/// This attribute by default defaults to [`Default::default()`]. This behavior can be customized
474/// by passing a default expression as the attribute argument. The expression is evaluated in the
475/// macro expansion context.
476///
477/// ```
478/// # use laby::*;
479/// #[laby]
480/// fn test(left: &str, #[default("b")] right: &str) {
481///     assert_eq!(left, right);
482/// }
483///
484/// test!(left = "a", right = "a");
485/// test!(left = "b", right = "b");
486/// test!(left = "b"); // omitted; equivalent to the above line
487/// ```
488///
489/// It is not possible to apply `#[default]` on generic parameters like `impl Render` because the
490/// compiler cannot infer which default implementation of [`Render`] should be used. This can be
491/// circumvented by using the unit type `()` implementation of [`Render`] as the default
492/// expression, which simply renders nothing.
493///
494/// ```
495/// # use laby::*;
496/// #[laby]
497/// fn component(#[default(())] title: impl Render) -> impl Render {
498///     article!(
499///         h1!(title),
500///     )
501/// }
502///
503/// assert_eq!(render!(component!()), "<article><h1></h1></article>");
504/// assert_eq!(render!(component!(title = a!("title"))), "<article><h1><a>title</a></h1></article>");
505/// ```
506///
507/// # `#[rest]` arguments
508///
509/// By default, all arguments must be specified with their respective parameter name. A function
510/// may declare at most one parameter with this attribute, which binds all arguments without a
511/// specified name to that parameter, wrapped together using [`frag!`]. This behavior is similar to
512/// [React children][2].
513///
514/// ```
515/// # use laby::*;
516/// #[laby]
517/// fn component(#[default(())] title: impl Render, #[rest] children: impl Render) -> impl Render {
518///     article!(
519///         h1!(title),
520///         main!(children),
521///     )
522/// }
523///
524/// assert_eq!(render!(component!()), "<article><h1></h1><main></main></article>");
525/// assert_eq!(render!(component!("para")), "<article><h1></h1><main>para</main></article>");
526/// assert_eq!(render!(component!(p!("para1"), p!("para2"))), "<article><h1></h1><main><p>para1</p><p>para2</p></main></article>");
527/// assert_eq!(render!(component!(title = "laby", p!("para1"), p!("para2"))), "<article><h1>laby</h1><main><p>para1</p><p>para2</p></main></article>");
528/// ```
529///
530/// # Caveats
531///
532/// ## Function must be free-standing
533///
534/// The target function with this attribute must be free-standing; it must be declared at the
535/// module-level, not within a `trait` or `impl` block. This is because Rust simply does not
536/// support macro declarations in such places.
537///
538/// ```compile_fail
539/// struct Foo;
540///
541/// #[laby]
542/// fn good(x: &Foo) {}
543///
544/// impl Foo {
545///     // this will not compile:
546///     #[laby]
547///     fn bad(&self) {}
548/// }
549/// ```
550///
551/// ## Function should not be named after an HTML tag
552///
553/// When a markup macro named after an HTML tag is invoked within another markup macro, laby
554/// recognizes this pattern and inlines that nested HTML macro into the parent macro as an
555/// optimization, regardless of whether that HTML macro is indeed an HTML macro or another macro
556/// with a conflicting name that actually does something completely different. As a workaround, you
557/// may alias the function with a different name.
558///
559/// ```compile_fail
560/// # use laby::*;
561/// #[laby]
562/// fn article() -> impl Render {
563///     "foo"
564/// }
565///
566/// fn good() {
567///     use article as foo;
568///
569///     let s = render!(div!(foo!()));
570///     assert_eq!(s, "<div>foo</div>");
571/// }
572///
573/// fn bad() {
574///     // refers to `laby::article`, not the `article` macro declared above!
575///     let s = render!(div!(article!()));
576///     assert_eq!(s, "<div><article></article></div>");
577/// }
578/// # good(); bad();
579/// ```
580///
581/// ## Macro must be imported into scope
582///
583/// When calling the target function using the generated macro, both that function and the macro
584/// must be imported directly into the current scope. It cannot be called by relative or fully
585/// qualified paths. This is due to hygiene limitations of `macro_rules!` which prevent functions
586/// from being referenced within macros unambiguously.
587///
588/// This caveat can be circumvented by enabling the `decl_macro` feature.
589///
590/// ```compile_fail
591/// # use laby::*;
592/// mod foo {
593///     #[laby]
594///     pub fn bar() {}
595/// }
596///
597/// fn good() {
598///     use foo::bar;
599///     bar!();
600/// }
601///
602/// fn bad() {
603///     foo::bar!(); // no function named `bar` in scope
604/// }
605/// # good(); bad();
606/// ```
607///
608/// ## Macro is not exported outside the crate
609///
610/// The generated macro is defined using `macro_rules!` which prevents macros from being exported
611/// in modules other than the crate root. Due to this limitation, the maximum visibility of the
612/// generated macro is restricted to `pub(crate)` even if the target function is `pub`.
613///
614/// This caveat can be circumvented by enabling the `decl_macro` feature.
615///
616/// ```compile_fail
617/// # use laby::*;
618/// // crate_a
619/// #[laby]
620/// pub fn foo() {}
621///
622/// fn good() {
623///     foo!();
624/// }
625///
626/// // crate_b
627/// fn bad() {
628///     use crate_a::foo; // macro `foo` is private
629///     foo!();
630/// }
631/// # good(); bad();
632/// ```
633///
634/// # Macros 2.0 support
635///
636/// laby comes with support for the experimental [Declarative Macros 2.0][1] compiler feature which
637/// can be enabled using the feature flag `decl_macro`. This requires a nightly toolchain.
638///
639/// To enable this feature, add laby's feature flag in your `Cargo.toml`,
640///
641/// ```toml
642/// [dependencies]
643/// laby = { version = "...", features = ["decl_macro"] }
644/// ```
645///
646/// and enable the compiler's feature flag in your crate root.
647///
648/// ```
649/// #![feature(decl_macro)]
650/// ```
651///
652/// The generated macros will now use the new `macro foo { ... }` syntax instead of `macro_rules!
653/// foo { ... }`.
654///
655/// [1]: https://rust-lang.github.io/rfcs/1584-macros.html
656/// [2]: https://reactjs.org/docs/composition-vs-inheritance.html
657pub use laby_macros::laby;
658
659/// Wraps multiple values implementing [`Render`][2] into one.
660///
661/// This macro is similar to [React fragments][1] which wrap multiple nodes into one. It is useful
662/// when passing multiple values to a function that accepts only one value, or when returning
663/// multiple values as one return value.
664///
665/// All wrapped values will be rendered sequentially in the order of arguments without delimiters.
666///
667/// [1]: https://reactjs.org/docs/fragments.html
668/// [2]: laby_common::Render
669///
670/// # Example
671///
672/// The following example passes multiple nodes to a function that accepts only one node, by
673/// wrapping the arguments in [`frag!`]. By using fragments, intermediary container elements like
674/// [`div`](div!) or [`span`](span!), which changes the semantics of the markup, can be avoided.
675///
676/// This example passes multiple nodes to a function which takes only one value.
677///
678/// ```
679/// # use laby::*;
680/// fn component(node: impl Render) -> impl Render {
681///     ul!(node)
682/// }
683///
684/// let s = render!(component(frag!(
685///     li!("one"),
686///     li!("two"),
687/// )));
688///
689/// assert_eq!(s, "<ul><li>one</li><li>two</li></ul>");
690/// ```
691///
692/// This example returns multiple nodes from a function which returns only one value.
693///
694/// ```
695/// # use laby::*;
696/// fn component() -> impl Render {
697///     frag!(
698///         li!("one"),
699///         li!("two"),
700///     )
701/// }
702///
703/// let s = render!(ul!(component()));
704/// assert_eq!(s, "<ul><li>one</li><li>two</li></ul>");
705/// ```
706pub use laby_macros::frag;
707
708/// Wraps a `match` or `if` expression returning [`Render`][1] into one.
709///
710/// This macro allows a `match` or `if` expression to return different types of [`Render`][1]
711/// implementations. This would otherwise be disallowed because all branches of a `match` or `if`
712/// expression must return the same type of [`Render`][1] implementation.
713///
714/// This macro was named `frag_match` because it uses a set of [`Option`] variables for each
715/// variant and the [`frag!`][2] macro for rendering.
716///
717/// # Expansion
718///
719/// ```ignore
720/// // frag_match!(match $expr { $pat => $expr, ... })
721/// {
722///     let mut variant1 = None, mut variant2 = None, ..;
723///
724///     match $expr {
725///         $pat => variant1 = Some($expr),
726///         $pat => variant2 = Some($expr), ..
727///     }
728///
729///     frag!(variant1, variant2, ..)
730/// }
731/// ```
732///
733/// # Examples
734///
735/// This example adds different types of nodes to a [`Vec<T>`][3] using the [`frag_match!`] macro.
736///
737/// ```
738/// # use laby::*;
739/// let mut vec = Vec::new();
740///
741/// for value in ["div", "span", "img"] {
742///     vec.push(frag_match!(match value {
743///         "div" => div!(),
744///         "span" => span!(),
745///         "img" => img!(),
746///         _ => unreachable!(),
747///     }));
748/// }
749///
750/// let s = render!(iter!(vec));
751/// assert_eq!(s, "<div></div><span></span><img>");
752/// ```
753///
754/// [1]: laby_common::Render
755/// [2]: laby_macros::frag
756/// [3]: alloc::vec::Vec
757pub use laby_macros::frag_match;
758
759/// Wraps multiple values implementing [`Render`][1] into one, with whitespace as the delimiter.
760///
761/// This macro behaves similarly to the [`frag!`] macro. The only difference is that all wrapped
762/// values will be rendered sequentially in the order of arguments, but with a single whitespace
763/// character `' '` to delimit each value.
764///
765/// It is intended to be used to generate an interpolated string for the `class` attribute in an
766/// HTML markup.
767///
768/// [1]: laby_common::Render
769///
770/// # Example
771///
772/// The following example generates a class string with several values interpolated. Note that
773/// `four` is not included because it is [`None`], but the whitespace that delimits `four` is
774/// still rendered regardless.
775///
776/// ```
777/// # use laby::*;
778/// let two = Some("two");
779/// let four: Option<&str> = None;
780/// let six = 6;
781///
782/// let s = classes!("one", two, "three", four, "five", six);
783/// assert_eq!(render!(s), "one two three  five 6");
784/// ```
785pub use laby_macros::classes;