Skip to main content

next_rust_view/
components.rs

1//! Built-in components and composition helpers.
2
3use std::borrow::Cow;
4use std::collections::BTreeMap;
5use std::future::Future;
6
7use crate::attrs::{self, AttrText};
8use crate::node::{Element, Node, Suspense, View};
9
10/// Content passed to a layout or template.
11#[derive(Debug, Default)]
12pub struct Children(pub Node);
13
14impl Children {
15    pub fn new(node: impl View) -> Self {
16        Children(node.into_node())
17    }
18}
19
20impl View for Children {
21    fn into_node(self) -> Node {
22        self.0
23    }
24}
25
26/// Parallel-route slots passed to a layout (`@analytics` → `slots.take("analytics")`).
27#[derive(Debug, Default)]
28pub struct Slots(BTreeMap<String, Node>);
29
30impl Slots {
31    pub fn new() -> Self {
32        Self::default()
33    }
34
35    pub fn insert(&mut self, name: impl Into<String>, node: impl View) {
36        self.0.insert(name.into(), node.into_node());
37    }
38
39    /// Take a slot's content (empty if the slot has nothing to render).
40    pub fn take(&mut self, name: &str) -> Node {
41        self.0.remove(name).unwrap_or(Node::Empty)
42    }
43
44    pub fn contains(&self, name: &str) -> bool {
45        self.0.contains_key(name)
46    }
47
48    pub fn names(&self) -> impl Iterator<Item = &str> {
49        self.0.keys().map(String::as_str)
50    }
51}
52
53/// Unescaped HTML. **Never pass untrusted input.**
54pub fn raw_html(html: impl Into<Cow<'static, str>>) -> Node {
55    Node::Raw(html.into())
56}
57
58/// Render `f()` only when `condition` is true.
59pub fn when<V: View>(condition: bool, f: impl FnOnce() -> V) -> Node {
60    if condition { f().into_node() } else { Node::Empty }
61}
62
63/// Render every item of an iterator.
64///
65/// ```
66/// use next_rust_view::*;
67/// let list = ul![each(["a", "b"], |x| li![key(x), x])];
68/// assert_eq!(render_static(list), r#"<ul><li data-nr-key="a">a</li><li data-nr-key="b">b</li></ul>"#);
69/// ```
70pub fn each<I, V>(items: I, f: impl FnMut(I::Item) -> V) -> Node
71where
72    I: IntoIterator,
73    V: View,
74{
75    Node::Fragment(items.into_iter().map(f).map(View::into_node).collect())
76}
77
78/// Collect any iterator of views into a fragment.
79pub fn fragment_of<V: View>(items: impl IntoIterator<Item = V>) -> Node {
80    Node::Fragment(items.into_iter().map(View::into_node).collect())
81}
82
83/// An async boundary. `fallback` renders immediately; `content` is awaited.
84///
85/// With streaming enabled the fallback is sent first and the content is
86/// streamed later in the same HTTP response; otherwise the renderer waits.
87pub fn suspense<V, F>(fallback: impl View, content: F) -> Node
88where
89    F: Future<Output = V> + Send + 'static,
90    V: View + 'static,
91{
92    Node::Suspense(Box::new(Suspense {
93        fallback: fallback.into_node(),
94        content: Box::pin(async move { content.await.into_node() }),
95    }))
96}
97
98/// Wrap server-rendered markup in an island marker so the client runtime can
99/// hydrate it. Used by the `#[client]` macro; `props_json` must be JSON.
100pub fn island(component: &str, props_json: String, ssr: impl View) -> Node {
101    Element::new("nr-island")
102        .with(attrs::data("component", component))
103        .with(attrs::data("props", props_json))
104        .with(ssr)
105        .into_node()
106}
107
108/// Props for `Link!`; the macro uses attribute helpers directly, this type
109/// exists for programmatic construction.
110#[derive(Debug, Default, Clone)]
111pub struct LinkProps {
112    pub href: String,
113    pub class: Option<String>,
114    pub prefetch: bool,
115    pub replace: bool,
116}
117
118/// Default responsive widths for [`ImageProps`] `srcset` generation.
119pub const DEFAULT_IMAGE_WIDTHS: &[u32] = &[640, 750, 828, 1080, 1200, 1920, 2048, 3840];
120
121/// Builder behind `Image!`.
122#[derive(Debug, Clone)]
123pub struct ImageProps {
124    src: String,
125    alt: Option<String>,
126    width: Option<u32>,
127    height: Option<u32>,
128    sizes: Option<String>,
129    quality: u8,
130    priority: bool,
131    class: Option<String>,
132    unoptimized: bool,
133}
134
135impl Default for ImageProps {
136    fn default() -> Self {
137        Self {
138            src: String::new(),
139            alt: None,
140            width: None,
141            height: None,
142            sizes: None,
143            quality: 75,
144            priority: false,
145            class: None,
146            unoptimized: false,
147        }
148    }
149}
150
151impl ImageProps {
152    pub fn src(mut self, v: impl Into<String>) -> Self {
153        self.src = v.into();
154        self
155    }
156    pub fn alt(mut self, v: impl Into<String>) -> Self {
157        self.alt = Some(v.into());
158        self
159    }
160    pub fn width(mut self, v: u32) -> Self {
161        self.width = Some(v);
162        self
163    }
164    pub fn height(mut self, v: u32) -> Self {
165        self.height = Some(v);
166        self
167    }
168    /// `sizes` attribute, e.g. `"(max-width: 768px) 100vw, 50vw"`.
169    pub fn sizes(mut self, v: impl Into<String>) -> Self {
170        self.sizes = Some(v.into());
171        self
172    }
173    pub fn quality(mut self, v: u8) -> Self {
174        self.quality = v.clamp(1, 100);
175        self
176    }
177    /// Above-the-fold image: eager loading and high fetch priority.
178    pub fn priority(mut self, v: bool) -> Self {
179        self.priority = v;
180        self
181    }
182    pub fn class(mut self, v: impl Into<String>) -> Self {
183        self.class = Some(v.into());
184        self
185    }
186    /// Serve `src` as-is (no resizing endpoint).
187    pub fn unoptimized(mut self, v: bool) -> Self {
188        self.unoptimized = v;
189        self
190    }
191
192    fn url(&self, w: u32) -> String {
193        format!("/_next-rust/image?url={}&w={w}&q={}", encode_query(&self.src), self.quality)
194    }
195}
196
197fn encode_query(s: &str) -> String {
198    let mut out = String::with_capacity(s.len());
199    for b in s.bytes() {
200        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
201            out.push(b as char);
202        } else {
203            out.push_str(&format!("%{b:02X}"));
204        }
205    }
206    out
207}
208
209impl View for ImageProps {
210    fn into_node(self) -> Node {
211        // Only local images go through the optimizer; remote URLs are served
212        // unchanged (the optimizer never fetches remote content: no SSRF).
213        let local = self.src.starts_with('/') && !self.src.starts_with("//");
214        let mut el = Element::new_void("img");
215        if self.unoptimized || !local {
216            el = el.with(attrs::src(self.src.clone()));
217        } else {
218            let base_w = self.width.unwrap_or(1080);
219            el = el.with(attrs::src(self.url(base_w)));
220            let mut widths: Vec<u32> = DEFAULT_IMAGE_WIDTHS.iter().copied().filter(|w| *w < base_w).collect();
221            widths.push(base_w);
222            let set: Vec<String> = widths.iter().map(|w| format!("{} {w}w", self.url(*w))).collect();
223            el = el.with(attrs::srcset(set.join(", ")));
224            el = el.with(attrs::sizes(
225                self.sizes.clone().unwrap_or_else(|| format!("(max-width: {base_w}px) 100vw, {base_w}px")),
226            ));
227        }
228        // `alt` is required for accessibility; an empty alt marks decorative images.
229        el = el.with(attrs::alt(self.alt.clone().unwrap_or_default()));
230        if let Some(w) = self.width {
231            el = el.with(attrs::width(w));
232        }
233        if let Some(h) = self.height {
234            el = el.with(attrs::height(h));
235        }
236        if self.priority {
237            el = el.with(attrs::fetchpriority("high"));
238        } else {
239            el = el.with(attrs::loading("lazy"));
240        }
241        el = el.with(attrs::decoding("async"));
242        if let Some(c) = self.class {
243            el = el.with(attrs::class(c));
244        }
245        if self.alt.is_none() && cfg!(debug_assertions) {
246            el = el.with(attrs::data("nr-warning", "missing alt text".into_attr_text()));
247        }
248        el.into_node()
249    }
250}