Skip to main content

next_rust_view/
node.rs

1use std::borrow::Cow;
2use std::fmt;
3use std::future::Future;
4use std::pin::Pin;
5
6use crate::style::Stylesheet;
7
8/// A rendered view tree.
9#[derive(Default)]
10pub enum Node {
11    #[default]
12    Empty,
13    /// Escaped text.
14    Text(Cow<'static, str>),
15    /// Unescaped HTML created with [`crate::raw_html`].
16    Raw(Cow<'static, str>),
17    Element(Box<Element>),
18    Fragment(Vec<Node>),
19    /// Async boundary (see [`crate::suspense`]).
20    Suspense(Box<Suspense>),
21    /// A stylesheet used by this subtree; emitted once per document.
22    Style(&'static Stylesheet),
23}
24
25impl fmt::Debug for Node {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        match self {
28            Node::Empty => f.write_str("Empty"),
29            Node::Text(t) => f.debug_tuple("Text").field(t).finish(),
30            Node::Raw(t) => f.debug_tuple("Raw").field(t).finish(),
31            Node::Element(e) => e.fmt(f),
32            Node::Fragment(c) => f.debug_tuple("Fragment").field(c).finish(),
33            Node::Suspense(_) => f.write_str("Suspense(..)"),
34            Node::Style(s) => f.debug_tuple("Style").field(&s.id).finish(),
35        }
36    }
37}
38
39pub type BoxNodeFuture = Pin<Box<dyn Future<Output = Node> + Send + 'static>>;
40
41/// An async boundary: `fallback` is rendered immediately, `content` replaces
42/// it once resolved (in place when not streaming, out-of-order when streaming).
43pub struct Suspense {
44    pub fallback: Node,
45    pub content: BoxNodeFuture,
46}
47
48/// Attribute value.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub enum AttrValue {
51    Text(Cow<'static, str>),
52    /// Boolean attribute: rendered as `name` when true, omitted when false.
53    Bool(bool),
54}
55
56/// An attribute. Create with the helpers in [`crate::attrs`].
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct Attr {
59    pub name: Cow<'static, str>,
60    pub value: Option<AttrValue>,
61    /// Allows event-handler attributes (`on*`). Only set by `raw_attr`.
62    pub(crate) trusted: bool,
63    pub(crate) sheets: Vec<&'static Stylesheet>,
64}
65
66impl Attr {
67    pub fn new(name: impl Into<Cow<'static, str>>, value: impl Into<Cow<'static, str>>) -> Self {
68        Attr { name: name.into(), value: Some(AttrValue::Text(value.into())), trusted: false, sheets: Vec::new() }
69    }
70
71    pub fn boolean(name: impl Into<Cow<'static, str>>, on: bool) -> Self {
72        Attr { name: name.into(), value: Some(AttrValue::Bool(on)), trusted: false, sheets: Vec::new() }
73    }
74
75    /// An attribute that renders nothing (useful for conditionals).
76    pub fn none() -> Self {
77        Attr { name: Cow::Borrowed(""), value: None, trusted: false, sheets: Vec::new() }
78    }
79}
80
81/// An HTML element.
82#[derive(Debug)]
83pub struct Element {
84    pub tag: Cow<'static, str>,
85    pub attrs: Vec<Attr>,
86    pub children: Vec<Node>,
87    pub void: bool,
88}
89
90impl Element {
91    /// A normal element with a trusted, static tag name.
92    pub fn new(tag: &'static str) -> Self {
93        Element { tag: Cow::Borrowed(tag), attrs: Vec::new(), children: Vec::new(), void: false }
94    }
95
96    /// A void element (`<img>`, `<input>`, ...).
97    pub fn new_void(tag: &'static str) -> Self {
98        Element { tag: Cow::Borrowed(tag), attrs: Vec::new(), children: Vec::new(), void: true }
99    }
100
101    /// An element with a runtime tag name. Invalid names render as `<div>`
102    /// with a `data-invalid-tag` attribute rather than producing broken HTML.
103    pub fn custom(tag: impl Into<String>) -> Self {
104        let tag: String = tag.into();
105        if crate::escape::is_valid_tag_name(&tag) {
106            Element { tag: Cow::Owned(tag), attrs: Vec::new(), children: Vec::new(), void: false }
107        } else {
108            Element::new("div").with(Attr::new("data-invalid-tag", tag))
109        }
110    }
111
112    /// Add an attribute or child.
113    pub fn with<P: Part>(mut self, part: P) -> Self {
114        part.apply(&mut self);
115        self
116    }
117
118    /// Add a child.
119    pub fn child(mut self, child: impl View) -> Self {
120        self.children.push(child.into_node());
121        self
122    }
123
124    /// Set or merge an attribute. `class` values are appended; other
125    /// attributes are replaced.
126    pub fn set_attr(&mut self, attr: Attr) {
127        if attr.value.is_none() && attr.sheets.is_empty() {
128            return;
129        }
130        if let Some(existing) = self.attrs.iter_mut().find(|a| a.name == attr.name) {
131            if attr.name == "class"
132                && let (Some(AttrValue::Text(old)), Some(AttrValue::Text(new))) = (&existing.value, &attr.value)
133            {
134                let merged = if old.is_empty() {
135                    new.clone()
136                } else if new.is_empty() {
137                    old.clone()
138                } else {
139                    Cow::Owned(format!("{old} {new}"))
140                };
141                existing.value = Some(AttrValue::Text(merged));
142                existing.sheets.extend(attr.sheets);
143                return;
144            }
145            *existing = attr;
146        } else {
147            self.attrs.push(attr);
148        }
149    }
150
151    pub fn attr(&self, name: &str) -> Option<&str> {
152        self.attrs.iter().find(|a| a.name == name).and_then(|a| match &a.value {
153            Some(AttrValue::Text(t)) => Some(t.as_ref()),
154            _ => None,
155        })
156    }
157}
158
159/// Something that can be placed inside an element macro.
160pub trait Part {
161    fn apply(self, el: &mut Element);
162}
163
164impl Part for Attr {
165    fn apply(self, el: &mut Element) {
166        el.set_attr(self);
167    }
168}
169
170impl Part for Vec<Attr> {
171    fn apply(self, el: &mut Element) {
172        for a in self {
173            el.set_attr(a);
174        }
175    }
176}
177
178impl<V: View> Part for V {
179    fn apply(self, el: &mut Element) {
180        el.children.push(self.into_node());
181    }
182}
183
184/// Anything renderable.
185pub trait View {
186    fn into_node(self) -> Node;
187}
188
189impl View for Node {
190    fn into_node(self) -> Node {
191        self
192    }
193}
194
195impl View for Element {
196    fn into_node(self) -> Node {
197        Node::Element(Box::new(self))
198    }
199}
200
201impl View for &str {
202    fn into_node(self) -> Node {
203        Node::Text(Cow::Owned(self.to_owned()))
204    }
205}
206
207impl View for &String {
208    fn into_node(self) -> Node {
209        Node::Text(Cow::Owned(self.clone()))
210    }
211}
212
213impl View for String {
214    fn into_node(self) -> Node {
215        Node::Text(Cow::Owned(self))
216    }
217}
218
219impl View for Cow<'static, str> {
220    fn into_node(self) -> Node {
221        Node::Text(self)
222    }
223}
224
225impl View for char {
226    fn into_node(self) -> Node {
227        Node::Text(Cow::Owned(self.to_string()))
228    }
229}
230
231macro_rules! display_views {
232    ($($t:ty),*) => {$(
233        impl View for $t {
234            fn into_node(self) -> Node {
235                Node::Text(Cow::Owned(self.to_string()))
236            }
237        }
238    )*};
239}
240display_views!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64);
241
242impl<V: View> View for Option<V> {
243    fn into_node(self) -> Node {
244        match self {
245            Some(v) => v.into_node(),
246            None => Node::Empty,
247        }
248    }
249}
250
251impl<V: View> View for Vec<V> {
252    fn into_node(self) -> Node {
253        Node::Fragment(self.into_iter().map(View::into_node).collect())
254    }
255}
256
257impl<V: View, const N: usize> View for [V; N] {
258    fn into_node(self) -> Node {
259        Node::Fragment(self.into_iter().map(View::into_node).collect())
260    }
261}
262
263impl<V: View> View for Box<V> {
264    fn into_node(self) -> Node {
265        (*self).into_node()
266    }
267}
268
269impl View for () {
270    fn into_node(self) -> Node {
271        Node::Empty
272    }
273}
274
275macro_rules! tuple_views {
276    ($($name:ident),+) => {
277        impl<$($name: View),+> View for ($($name,)+) {
278            #[allow(non_snake_case)]
279            fn into_node(self) -> Node {
280                let ($($name,)+) = self;
281                Node::Fragment(vec![$($name.into_node()),+])
282            }
283        }
284    };
285}
286tuple_views!(A);
287tuple_views!(A, B);
288tuple_views!(A, B, C);
289tuple_views!(A, B, C, D);
290tuple_views!(A, B, C, D, E);
291tuple_views!(A, B, C, D, E, F);
292tuple_views!(A, B, C, D, E, F, G);
293tuple_views!(A, B, C, D, E, F, G, H);
294
295/// Conversion of a component's return value into a render result: accepts
296/// `impl View` as well as `Result<impl View, E>`. Used by generated code.
297pub trait IntoViewResult<E> {
298    fn into_view_result(self) -> Result<Node, E>;
299}
300
301impl<V: View, E> IntoViewResult<E> for V {
302    fn into_view_result(self) -> Result<Node, E> {
303        Ok(self.into_node())
304    }
305}
306
307impl<V: View, E, E2: Into<E>> IntoViewResult<E> for Result<V, E2> {
308    fn into_view_result(self) -> Result<Node, E> {
309        self.map(View::into_node).map_err(Into::into)
310    }
311}