wabot_addon_ui_hypertext/lib.rs
1//! # wabot-addon-ui-hypertext
2//!
3//! JSX-shaped views in pure Rust. `hypertext`'s `rsx!` macro compiles
4//! `<div class="x">…</div>` into string-pushing code at build time,
5//! escapes interpolated values by construction, and — unlike Maud —
6//! **validates element and attribute names at compile time**, so a
7//! typo is a build error rather than malformed HTML.
8//!
9//! Zero client payload, no build step: same properties as the Maud
10//! renderer, different syntax. Pick per project; both satisfy the same
11//! [`ViewBody`] seam, so the framework doesn't know which you used.
12//!
13//! ```ignore
14//! use hypertext::prelude::*;
15//! use wabot_addon_ui_hypertext::{island_module, IntoView};
16//!
17//! #[view("/")]
18//! async fn index(&self) -> UiResult<ViewBody> {
19//! Ok(rsx! {
20//! <h1>("Dashboard")</h1>
21//! (island_module(
22//! islands::COUNTER_ID, islands::COUNTER_MODULE,
23//! &CounterProps { start: 3 },
24//! rsx! { <button>("3")</button> }, // server-rendered fallback
25//! ))
26//! }
27//! .into_view())
28//! }
29//! ```
30//!
31//! Interpolation is `(expr)` rather than `{expr}` — `{}` is Rust block
32//! syntax, so hypertext uses parentheses for values.
33
34use hypertext::{Raw, Renderable};
35use serde::Serialize;
36
37/// Re-exported so an application can name the types this crate's
38/// helpers take and return without guessing at a version.
39///
40/// **It does not remove the dependency.** `rsx!` expands to
41/// absolute `::hypertext::…` paths, so the crate has to be reachable by
42/// that name at the application's own crate root — which means a
43/// direct dependency in its `Cargo.toml`:
44///
45/// ```toml
46/// hypertext = "0.12" # must match what this crate compiled against
47/// ```
48///
49/// A different major version there gives two copies in the graph, and
50/// then the types these helpers accept are not the types the macro
51/// produces — an error that reads as nonsense, since both come from
52/// crates with the same name. This re-export is how you check which
53/// one is right.
54pub use ::hypertext;
55
56use wabot_feature_ui_controller::island::{island_host, serialize_props, IslandRef};
57use wabot_feature_ui_controller::scope;
58use wabot_feature_ui_controller::view::ViewBody;
59
60/// HTML that `rsx!` can splice in verbatim. Every helper here returns
61/// one, so island hosts and outlets drop straight into markup.
62pub type RawHtml = Raw<String>;
63
64/// Turn rendered hypertext markup into the framework's [`ViewBody`].
65///
66/// An extension trait rather than a `From` impl because both types are
67/// foreign to this crate, and `rsx! { … }.into_view()` reads better at
68/// the call site.
69pub trait IntoView {
70 fn into_view(self) -> ViewBody;
71}
72
73/// Blanket: anything hypertext can render becomes a view body, so a
74/// view can skip the explicit `.render()` —
75/// `rsx! { … }.into_view()`.
76impl<T: Renderable> IntoView for T {
77 fn into_view(self) -> ViewBody {
78 ViewBody::raw(self.render().into_inner())
79 }
80}
81
82/// Emit an interactive island.
83///
84/// `inner` is server-rendered immediately, so the page works before
85/// (and without) hydration; `props` is serialized into the host element
86/// and handed to the client mount function, so both sides start from
87/// the same state. The island is recorded in the render scope, which
88/// is how the framework learns the page has islands at all.
89pub fn island<P: Serialize, R: Renderable>(id: &str, props: &P, inner: R) -> RawHtml {
90 let props = serialize_props(props);
91 scope::record_island(IslandRef::new(id, props.clone()));
92 let inner_html = inner.render().into_inner();
93 // XSS SAFETY: `island_host` escapes the id and props into
94 // attributes; `inner_html` is hypertext's own escaped output.
95 Raw::dangerously_create(island_host(id, &props, &inner_html))
96}
97
98/// An island with no props.
99pub fn island_bare<R: Renderable>(id: &str, inner: R) -> RawHtml {
100 island(id, &serde_json::Value::Null, inner)
101}
102
103/// Emit an island **and** declare the module that mounts it, so a page
104/// loads only the island bundles it used. Pair with `wabot-ui-bundler`,
105/// which generates both constants from the `.island.tsx` filename.
106pub fn island_module<P: Serialize, R: Renderable>(
107 id: &str,
108 module_src: &str,
109 props: &P,
110 inner: R,
111) -> RawHtml {
112 scope::add_script(module_src);
113 island(id, props, inner)
114}
115
116/// Placeholder a layout renders where the current view goes. Boosted
117/// navigation swaps only this element's contents, so the shell — and
118/// any islands in it — survive.
119///
120/// Takes a reference and returns a borrowed `Raw`, because `rsx!`
121/// expands to an `Fn` closure: anything captured from the surrounding
122/// scope has to be usable by reference, not moved.
123pub fn outlet(view: &ViewBody) -> Raw<&str> {
124 // XSS SAFETY: already-rendered HTML the framework produced.
125 Raw::dangerously_create(view.as_str())
126}
127
128/// Splice pre-rendered HTML from elsewhere — a TSX view rendered by
129/// the QuickJS runtime, say — into rsx markup.
130///
131/// # XSS
132///
133/// The string is emitted verbatim. Only pass HTML a renderer produced,
134/// never user input.
135pub fn raw(html: &str) -> Raw<&str> {
136 Raw::dangerously_create(html)
137}
138
139/// Declare a stylesheet this view needs.
140pub fn style(href: impl Into<String>) {
141 scope::add_style(href);
142}
143
144/// Declare an extra module script this view needs.
145pub fn script(src: impl Into<String>) {
146 scope::add_script(src);
147}
148
149/// Set the document title from inside the markup.
150/// Declare a `<link>` that is not a stylesheet — a favicon, a
151/// preload.
152///
153/// ```ignore
154/// link([("rel", "icon"), ("type", "image/png"), ("href", "/favicon.png")]);
155/// ```
156pub fn link<K, V>(attributes: impl IntoIterator<Item = (K, V)>)
157where
158 K: Into<String>,
159 V: Into<String>,
160{
161 scope::add_link(attributes);
162}
163
164pub fn title(text: impl Into<String>) {
165 scope::set_title(text);
166}
167
168/// Set a `<meta name=… content=…>` pair.
169pub fn meta(name: impl Into<String>, content: impl Into<String>) {
170 scope::set_meta(name, content);
171}
172
173/// Convenience wrapper for the outlet + layout pattern.
174pub fn wrap_outlet<R: Renderable>(shell: R) -> ViewBody {
175 ViewBody::raw(shell.render().into_inner())
176}
177
178#[cfg(test)]
179mod tests {
180 use super::*;
181 use hypertext::prelude::*;
182 use serde::Serialize;
183 use wabot_feature_ui_controller::scope::with_scope;
184
185 #[derive(Serialize)]
186 struct CounterProps {
187 start: u32,
188 }
189
190 #[test]
191 fn rsx_markup_becomes_a_view_body() {
192 let body = rsx! { <h1>("Hello")</h1> }.into_view();
193 assert_eq!(body.as_str(), "<h1>Hello</h1>");
194 }
195
196 #[test]
197 fn interpolated_values_are_escaped() {
198 let evil = "<script>alert(1)</script>";
199 let body = rsx! { <p>(evil)</p> }.into_view();
200 assert_eq!(
201 body.as_str(),
202 "<p><script>alert(1)</script></p>"
203 );
204 }
205
206 #[test]
207 fn control_flow_works_inside_rsx() {
208 let items = vec!["alpha", "beta"];
209 let body = rsx! {
210 <ul>
211 @for item in &items {
212 <li>(item)</li>
213 }
214 </ul>
215 }
216 .into_view();
217 assert_eq!(body.as_str(), "<ul><li>alpha</li><li>beta</li></ul>");
218 }
219
220 #[test]
221 fn island_renders_ssr_content_and_registers_itself() {
222 let (markup, scope) = with_scope(|| {
223 rsx! {
224 <div>
225 (island("counter", &CounterProps { start: 3 }, rsx! { <button>("3")</button> }))
226 </div>
227 }
228 .render()
229 .into_inner()
230 });
231
232 assert!(markup.contains(r#"data-island="counter""#));
233 assert!(markup.contains("data-props=\"{"start":3}\""));
234 assert!(
235 markup.contains("<button>3</button>"),
236 "the island must be server-rendered too: {markup}"
237 );
238 assert_eq!(scope.islands.len(), 1);
239 assert_eq!(scope.islands[0].props["start"], 3);
240 }
241
242 #[test]
243 fn island_module_declares_its_script_once() {
244 let ((), scope) = with_scope(|| {
245 let _ = rsx! {
246 (island_module("counter", "/islands/counter.js",
247 &CounterProps { start: 0 }, rsx! { <button>("0")</button> }))
248 (island_module("counter", "/islands/counter.js",
249 &CounterProps { start: 5 }, rsx! { <button>("5")</button> }))
250 }
251 .render();
252 });
253 assert_eq!(scope.scripts, vec!["/islands/counter.js".to_string()]);
254 assert_eq!(scope.islands.len(), 2);
255 }
256
257 #[test]
258 fn declarations_reach_the_scope() {
259 let ((), scope) = with_scope(|| {
260 title("Dashboard");
261 meta("description", "counts things");
262 style("/app.css");
263 });
264 assert_eq!(scope.title.as_deref(), Some("Dashboard"));
265 assert_eq!(scope.styles, vec!["/app.css".to_string()]);
266 assert_eq!(scope.meta[0].1, "counts things");
267 }
268
269 #[test]
270 fn outlet_and_raw_pass_html_through_untouched() {
271 let view = ViewBody::raw("<h1>view</h1>");
272 let body = rsx! {
273 <main>
274 (outlet(&view))
275 (raw("<aside>from elsewhere</aside>"))
276 </main>
277 }
278 .into_view();
279 assert_eq!(
280 body.as_str(),
281 "<main><h1>view</h1><aside>from elsewhere</aside></main>"
282 );
283 }
284}