Skip to main content

next_rust_view/
render.rs

1//! HTML rendering: synchronous, async (fully resolved) and streaming.
2//!
3//! ## Streaming protocol
4//!
5//! When a [`Suspense`](crate::Suspense) boundary is encountered while
6//! streaming, the renderer writes
7//!
8//! ```html
9//! <nr-b id="nr-b1">…fallback…</nr-b>
10//! ```
11//!
12//! and continues with the rest of the document. The *shell* (everything that
13//! does not wait) is flushed immediately. Each boundary resolves concurrently;
14//! as soon as one finishes, a chunk is sent:
15//!
16//! ```html
17//! <template id="nr-t1">…content…</template><script>$nr(1)</script>
18//! ```
19//!
20//! `$nr` (≈150 bytes, inlined once in `<head>` only when a page actually
21//! suspends) moves the template content into place. Nested boundaries inside
22//! streamed content work the same way. Without JavaScript the fallback stays
23//! visible, so pages that must work without JS should avoid suspense or be
24//! rendered non-streaming (bots and static generation always are).
25
26use std::collections::HashSet;
27use std::pin::Pin;
28
29use futures_util::future::join_all;
30use futures_util::stream::{FuturesUnordered, Stream, StreamExt};
31
32use crate::escape::{escape_attr, escape_raw_text, escape_text, is_safe_url, is_url_attr, is_valid_attr_name};
33use crate::node::{AttrValue, BoxNodeFuture, Element, Node, View};
34use crate::style::Stylesheet;
35
36/// Inline script used to swap streamed content into place.
37pub const STREAMING_RUNTIME: &str = "function $nr(i){var t=document.getElementById(\"nr-t\"+i),b=document.getElementById(\"nr-b\"+i);if(t&&b){b.replaceWith(t.content);t.remove()}}";
38
39type PendingBoundary = Pin<Box<dyn std::future::Future<Output = (u32, Node)> + Send>>;
40
41/// Features used by a rendered document; the server uses these to decide
42/// which (if any) client scripts to include.
43#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
44pub struct RenderFlags {
45    /// A `Link!` with client navigation was rendered.
46    pub links: bool,
47    /// An interactive island was rendered.
48    pub islands: bool,
49    /// At least one suspense boundary was streamed.
50    pub streamed: bool,
51}
52
53struct Writer {
54    out: String,
55    styles_seen: HashSet<&'static str>,
56    /// When set, stylesheets are collected here instead of written inline.
57    hoisted: Option<Vec<&'static Stylesheet>>,
58    flags: RenderFlags,
59    streaming: bool,
60    next_id: u32,
61    pending: Vec<(u32, BoxNodeFuture)>,
62}
63
64impl Writer {
65    fn new(streaming: bool, hoist: bool) -> Self {
66        Writer {
67            out: String::with_capacity(4096),
68            styles_seen: HashSet::new(),
69            hoisted: hoist.then(Vec::new),
70            flags: RenderFlags::default(),
71            streaming,
72            next_id: 0,
73            pending: Vec::new(),
74        }
75    }
76
77    fn style(&mut self, sheet: &'static Stylesheet) {
78        if !self.styles_seen.insert(sheet.id) {
79            return;
80        }
81        match &mut self.hoisted {
82            Some(list) => list.push(sheet),
83            None => write_style(&mut self.out, sheet),
84        }
85    }
86
87    fn node(&mut self, node: Node, raw_text: bool) {
88        match node {
89            Node::Empty => {}
90            Node::Text(t) => {
91                if raw_text {
92                    self.out.push_str(&escape_raw_text(&t));
93                } else {
94                    self.out.push_str(&escape_text(&t));
95                }
96            }
97            Node::Raw(r) => self.out.push_str(&r),
98            Node::Fragment(children) => {
99                for c in children {
100                    self.node(c, raw_text);
101                }
102            }
103            Node::Style(sheet) => self.style(sheet),
104            Node::Element(el) => self.element(*el),
105            Node::Suspense(s) => {
106                if self.streaming {
107                    self.next_id += 1;
108                    let id = self.next_id;
109                    self.flags.streamed = true;
110                    self.out.push_str(&format!("<nr-b id=\"nr-b{id}\">"));
111                    self.node(s.fallback, false);
112                    self.out.push_str("</nr-b>");
113                    self.pending.push((id, s.content));
114                } else {
115                    // Unresolved suspense in a synchronous render: show the fallback.
116                    self.node(s.fallback, raw_text);
117                }
118            }
119        }
120    }
121
122    fn element(&mut self, el: Element) {
123        for a in &el.attrs {
124            for sheet in &a.sheets {
125                self.style(sheet);
126            }
127        }
128        let tag = el.tag;
129        self.out.push('<');
130        self.out.push_str(&tag);
131        for a in &el.attrs {
132            let Some(value) = &a.value else { continue };
133            if !is_valid_attr_name(&a.name) {
134                continue;
135            }
136            if !a.trusted && a.name.len() > 2 && a.name[..2].eq_ignore_ascii_case("on") {
137                // Event handler attributes from `attr()` are dropped: use `raw_attr`.
138                continue;
139            }
140            match value {
141                AttrValue::Bool(true) => {
142                    self.out.push(' ');
143                    self.out.push_str(&a.name);
144                }
145                AttrValue::Bool(false) => {}
146                AttrValue::Text(t) => {
147                    let safe = if is_url_attr(&a.name) && !is_safe_url(t) { "#" } else { t.as_ref() };
148                    self.out.push(' ');
149                    self.out.push_str(&a.name);
150                    self.out.push_str("=\"");
151                    self.out.push_str(&escape_attr(safe));
152                    self.out.push('"');
153                }
154            }
155            if a.name == "data-nr-link" {
156                self.flags.links = true;
157            }
158        }
159        self.out.push('>');
160        if tag == "nr-island" {
161            self.flags.islands = true;
162        }
163        if el.void {
164            return;
165        }
166        let raw = tag.eq_ignore_ascii_case("script") || tag.eq_ignore_ascii_case("style");
167        for c in el.children {
168            self.node(c, raw);
169        }
170        self.out.push_str("</");
171        self.out.push_str(&tag);
172        self.out.push('>');
173    }
174}
175
176fn write_style(out: &mut String, sheet: &Stylesheet) {
177    out.push_str("<style data-nr-css=\"");
178    out.push_str(sheet.id);
179    out.push_str("\">");
180    out.push_str(&escape_raw_text(sheet.css));
181    out.push_str("</style>");
182}
183
184/// Render synchronously. Suspense boundaries render their fallback.
185pub fn render_static(view: impl View) -> String {
186    let mut w = Writer::new(false, false);
187    w.node(view.into_node(), false);
188    w.out
189}
190
191/// Resolve every suspense boundary in a tree (siblings concurrently).
192pub fn resolve(node: Node) -> Pin<Box<dyn std::future::Future<Output = Node> + Send>> {
193    Box::pin(async move {
194        match node {
195            Node::Suspense(s) => resolve(s.content.await).await,
196            Node::Fragment(children) => Node::Fragment(join_all(children.into_iter().map(resolve)).await),
197            Node::Element(mut el) => {
198                let children = std::mem::take(&mut el.children);
199                el.children = join_all(children.into_iter().map(resolve)).await;
200                Node::Element(el)
201            }
202            other => other,
203        }
204    })
205}
206
207/// Render to a string, awaiting all async content.
208pub async fn render_to_string(view: impl View) -> String {
209    let node = resolve(view.into_node()).await;
210    render_static(node)
211}
212
213/// Everything needed to render a full HTML document.
214pub struct DocumentParts {
215    pub lang: String,
216    /// Pre-rendered `<head>` contents (metadata).
217    pub head: String,
218    /// Extra head markup (e.g. dev scripts). Trusted.
219    pub head_extra: String,
220    pub body: Node,
221    /// CSP nonce applied to framework inline scripts.
222    pub nonce: Option<String>,
223    /// Called once the body is complete; returns markup appended before
224    /// `</body>` (client runtime scripts, depending on the flags).
225    pub tail: Box<dyn FnOnce(RenderFlags) -> String + Send>,
226}
227
228impl DocumentParts {
229    pub fn new(body: impl View) -> Self {
230        DocumentParts {
231            lang: "en".into(),
232            head: String::new(),
233            head_extra: String::new(),
234            body: body.into_node(),
235            nonce: None,
236            tail: Box::new(|_| String::new()),
237        }
238    }
239}
240
241fn nonce_attr(nonce: &Option<String>) -> String {
242    nonce.as_ref().map(|n| format!(" nonce=\"{}\"", escape_attr(n))).unwrap_or_default()
243}
244
245fn open_document(parts: &DocumentParts, w: &mut Writer, body: &str) -> String {
246    let mut s = String::with_capacity(body.len() + parts.head.len() + 256);
247    s.push_str("<!DOCTYPE html><html lang=\"");
248    s.push_str(&escape_attr(&parts.lang));
249    s.push_str("\"><head>");
250    s.push_str(&parts.head);
251    if let Some(sheets) = w.hoisted.take() {
252        for sheet in sheets {
253            write_style(&mut s, sheet);
254        }
255    }
256    if !w.pending.is_empty() {
257        s.push_str("<style>nr-b,nr-island{display:contents}</style>");
258        s.push_str(&format!("<script{}>{STREAMING_RUNTIME}</script>", nonce_attr(&parts.nonce)));
259    } else if w.flags.islands {
260        s.push_str("<style>nr-island{display:contents}</style>");
261    }
262    s.push_str(&parts.head_extra);
263    s.push_str("</head><body>");
264    s.push_str(body);
265    s
266}
267
268/// Render a complete document as a stream of chunks.
269///
270/// With `streaming = false`, all async content is resolved first and the
271/// stream yields exactly one chunk (used for bots, static generation and
272/// when streaming is disabled).
273pub fn stream_document(parts: DocumentParts, streaming: bool) -> impl Stream<Item = String> + Send {
274    enum State {
275        Start(DocumentParts, bool),
276        Streaming {
277            pending: FuturesUnordered<PendingBoundary>,
278            w: Writer,
279            nonce: Option<String>,
280            tail: Box<dyn FnOnce(RenderFlags) -> String + Send>,
281        },
282        Done,
283    }
284
285    futures_util::stream::unfold(State::Start(parts, streaming), |state| async move {
286        match state {
287            State::Done => None,
288            State::Start(mut parts, streaming) => {
289                let body = std::mem::take(&mut parts.body);
290                let body = if streaming { body } else { resolve(body).await };
291                let mut w = Writer::new(streaming, true);
292                w.node(body, false);
293                let body_html = std::mem::take(&mut w.out);
294                let mut chunk = open_document(&parts, &mut w, &body_html);
295                if w.pending.is_empty() {
296                    chunk.push_str(&(parts.tail)(w.flags));
297                    chunk.push_str("</body></html>");
298                    return Some((chunk, State::Done));
299                }
300                let pending = FuturesUnordered::new();
301                for (id, fut) in w.pending.drain(..) {
302                    pending.push(Box::pin(async move { (id, fut.await) })
303                        as Pin<Box<dyn std::future::Future<Output = _> + Send>>);
304                }
305                // Styles in streamed chunks are written inline, deduplicated
306                // against those already hoisted into <head>.
307                w.hoisted = None;
308                Some((chunk, State::Streaming { pending, w, nonce: parts.nonce, tail: parts.tail }))
309            }
310            State::Streaming { mut pending, mut w, nonce, tail } => match pending.next().await {
311                Some((id, node)) => {
312                    w.out.clear();
313                    w.out.push_str(&format!("<template id=\"nr-t{id}\">"));
314                    w.node(node, false);
315                    w.out.push_str(&format!("</template><script{}>$nr({id})</script>", nonce_attr(&nonce)));
316                    for (nid, fut) in w.pending.drain(..) {
317                        pending.push(Box::pin(async move { (nid, fut.await) }));
318                    }
319                    let chunk = std::mem::take(&mut w.out);
320                    Some((chunk, State::Streaming { pending, w, nonce, tail }))
321                }
322                None => {
323                    let mut chunk = tail(w.flags);
324                    chunk.push_str("</body></html>");
325                    Some((chunk, State::Done))
326                }
327            },
328        }
329    })
330}