Skip to main content

wabot_addon_ui_maud/
lib.rs

1//! # wabot-addon-ui-maud
2//!
3//! The default renderer for wabot's UI controllers. Maud compiles
4//! `html! { … }` into string-pushing code at build time and escapes
5//! interpolated values by construction, so a view is a normal Rust
6//! function that happens to return HTML.
7//!
8//! Chosen over Leptos/Dioxus because it adds no client payload and no
9//! build step — see `docs/ui-renderer-review.md` for the full
10//! comparison.
11//!
12//! ```ignore
13//! use maud::html;
14//! use wabot_addon_ui_maud::{island, IntoView};
15//!
16//! #[view("/")]
17//! async fn index(&self) -> UiResult<ViewBody> {
18//!     Ok(html! {
19//!         h1 { "Dashboard" }
20//!         (island("counter", &CounterProps { start: 3 }, html! {
21//!             button { "3" }        // server-rendered, works without JS
22//!         }))
23//!     }
24//!     .into_view())
25//! }
26//! ```
27//!
28//! The island's markup is what the server sends and what a visitor
29//! sees before (or without) JavaScript. `wabot.island('counter', …)`
30//! in the app's own script takes it from there.
31
32use maud::{Markup, PreEscaped};
33use serde::Serialize;
34
35/// Re-exported so an application can name the types this crate's
36/// helpers take and return without guessing at a version.
37///
38/// **It does not remove the dependency.** `html!` expands to
39/// absolute `::maud::…` paths, so the crate has to be reachable by
40/// that name at the application's own crate root — which means a
41/// direct dependency in its `Cargo.toml`:
42///
43/// ```toml
44/// maud = "0.27"   # must match what this crate compiled against
45/// ```
46///
47/// A different major version there gives two copies in the graph, and
48/// then the types these helpers accept are not the types the macro
49/// produces — an error that reads as nonsense, since both come from
50/// crates with the same name. This re-export is how you check which
51/// one is right.
52pub use ::maud;
53
54use wabot_feature_ui_controller::island::{island_host, serialize_props, IslandRef};
55use wabot_feature_ui_controller::scope;
56use wabot_feature_ui_controller::view::ViewBody;
57
58/// Turn Maud markup into the framework's [`ViewBody`].
59///
60/// An extension trait rather than a `From` impl because both types are
61/// foreign to this crate — and it reads better at the call site
62/// (`html! { … }.into_view()`).
63pub trait IntoView {
64    fn into_view(self) -> ViewBody;
65}
66
67impl IntoView for Markup {
68    fn into_view(self) -> ViewBody {
69        ViewBody::raw(self.into_string())
70    }
71}
72
73/// Emit an interactive island.
74///
75/// `inner` is server-rendered immediately, so the page works before
76/// hydration and for visitors with JavaScript off. `props` is
77/// serialized into the host element and handed back to the client
78/// mount function, so both sides agree on the starting state.
79///
80/// The island is also recorded in the current render scope, which is
81/// how the framework learns the page has islands at all.
82pub fn island<P: Serialize>(id: &str, props: &P, inner: Markup) -> Markup {
83    let props = serialize_props(props);
84    scope::record_island(IslandRef::new(id, props.clone()));
85    PreEscaped(island_host(id, &props, &inner.into_string()))
86}
87
88/// Emit an island with no props.
89pub fn island_bare(id: &str, inner: Markup) -> Markup {
90    island(id, &serde_json::Value::Null, inner)
91}
92
93/// Emit an island *and* declare the module that mounts it, so the page
94/// loads only the island bundles it actually used.
95///
96/// Pair it with `wabot-ui-bundler`, which generates both constants
97/// from the `.island.tsx` filename:
98///
99/// ```ignore
100/// island_module(islands::NOTES_FORM_ID, islands::NOTES_FORM_MODULE, &props, html! {
101///     form { input name="text"; button { "Add" } }   // works without JS
102/// })
103/// ```
104///
105/// Renaming the `.tsx` file then breaks the Rust build rather than
106/// leaving a `<wabot-island>` that nothing ever mounts.
107pub fn island_module<P: Serialize>(id: &str, module_src: &str, props: &P, inner: Markup) -> Markup {
108    scope::add_script(module_src);
109    island(id, props, inner)
110}
111
112/// Placeholder a layout renders where the current view goes.
113///
114/// Boosted navigation swaps only this element's contents, so anything
115/// the layout puts around it — nav bars, sidebars, islands with open
116/// state — survives navigation.
117pub fn outlet(view: ViewBody) -> Markup {
118    // The body is already-rendered HTML from the framework, which
119    // wrapped it in `<wabot-outlet>` before calling the layout.
120    PreEscaped(view.into_string())
121}
122
123/// Declare a stylesheet this view needs. Re-exported so a view file
124/// only imports from this crate.
125pub fn style(href: impl Into<String>) {
126    scope::add_style(href);
127}
128
129/// Declare an extra module script this view needs — typically the JS
130/// that registers its islands.
131pub fn script(src: impl Into<String>) {
132    scope::add_script(src);
133}
134
135/// Set the document title from inside the markup.
136/// Declare a `<link>` that is not a stylesheet — a favicon, a
137/// preload.
138///
139/// ```ignore
140/// link([("rel", "icon"), ("type", "image/png"), ("href", "/favicon.png")]);
141/// ```
142pub fn link<K, V>(attributes: impl IntoIterator<Item = (K, V)>)
143where
144    K: Into<String>,
145    V: Into<String>,
146{
147    scope::add_link(attributes);
148}
149
150pub fn title(text: impl Into<String>) {
151    scope::set_title(text);
152}
153
154/// Set a `<meta name=… content=…>` pair.
155pub fn meta(name: impl Into<String>, content: impl Into<String>) {
156    scope::set_meta(name, content);
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162    use maud::html;
163    use serde::Serialize;
164    use wabot_feature_ui_controller::scope::with_scope;
165
166    #[derive(Serialize)]
167    struct CounterProps {
168        start: u32,
169    }
170
171    #[test]
172    fn markup_becomes_a_view_body() {
173        let body = html! { h1 { "Hello" } }.into_view();
174        assert_eq!(body.as_str(), "<h1>Hello</h1>");
175    }
176
177    #[test]
178    fn maud_escapes_interpolated_text() {
179        let evil = "<script>alert(1)</script>";
180        let body = html! { p { (evil) } }.into_view();
181        assert_eq!(
182            body.as_str(),
183            "<p>&lt;script&gt;alert(1)&lt;/script&gt;</p>"
184        );
185    }
186
187    #[test]
188    fn island_renders_ssr_content_and_registers_itself() {
189        let (markup, scope) = with_scope(|| {
190            html! {
191                div {
192                    (island("counter", &CounterProps { start: 3 }, html! { button { "3" } }))
193                }
194            }
195        });
196
197        let html = markup.into_string();
198        assert!(html.contains("data-island=\"counter\""));
199        assert!(html.contains("data-props=\"{&quot;start&quot;:3}\""));
200        assert!(
201            html.contains("<button>3</button>"),
202            "the island must be server-rendered too: {html}"
203        );
204
205        assert_eq!(scope.islands.len(), 1);
206        assert_eq!(scope.islands[0].id, "counter");
207        assert_eq!(scope.islands[0].props["start"], 3);
208    }
209
210    #[test]
211    fn several_islands_record_in_document_order() {
212        let ((), scope) = with_scope(|| {
213            let _ = html! {
214                (island_bare("first", html! { "a" }))
215                (island_bare("second", html! { "b" }))
216            };
217        });
218        let ids: Vec<&str> = scope.islands.iter().map(|i| i.id.as_str()).collect();
219        assert_eq!(ids, vec!["first", "second"]);
220    }
221
222    #[test]
223    fn declarations_reach_the_scope() {
224        let ((), scope) = with_scope(|| {
225            title("Dashboard");
226            meta("description", "counts things");
227            style("/app.css");
228            script("/islands/counter.js");
229        });
230        assert_eq!(scope.title.as_deref(), Some("Dashboard"));
231        assert_eq!(
232            scope.meta[0],
233            ("description".into(), "counts things".into())
234        );
235        assert_eq!(scope.styles, vec!["/app.css".to_string()]);
236        assert_eq!(scope.scripts, vec!["/islands/counter.js".to_string()]);
237    }
238
239    #[test]
240    fn island_module_declares_its_script_once() {
241        let ((), scope) = with_scope(|| {
242            let _ = html! {
243                (island_module("counter", "/islands/counter.js",
244                               &CounterProps { start: 0 }, html! { "0" }))
245                // The same island twice on one page must not load the
246                // module twice.
247                (island_module("counter", "/islands/counter.js",
248                               &CounterProps { start: 5 }, html! { "5" }))
249            };
250        });
251        assert_eq!(scope.scripts, vec!["/islands/counter.js".to_string()]);
252        assert_eq!(scope.islands.len(), 2, "both hosts are still recorded");
253    }
254
255    #[test]
256    fn outlet_passes_the_view_through_unescaped() {
257        let markup = outlet(ViewBody::raw("<h1>view</h1>"));
258        assert_eq!(markup.into_string(), "<h1>view</h1>");
259    }
260}