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::borrow::Cow;
27use std::collections::HashSet;
28use std::pin::Pin;
29
30use futures_util::future::join_all;
31use futures_util::stream::{FuturesUnordered, Stream, StreamExt};
32
33use crate::class_names::{map_class_list, map_raw_html};
34use crate::escape::{escape_attr, escape_raw_text, escape_text, is_safe_url, is_url_attr, is_valid_attr_name};
35use crate::node::{AttrValue, BoxNodeFuture, Element, Node, View};
36use crate::style::Stylesheet;
37
38/// Inline script used to swap streamed content into place.
39pub 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()}}";
40
41type PendingBoundary = Pin<Box<dyn std::future::Future<Output = (u32, Node)> + Send>>;
42
43/// Features used by a rendered document; the server uses these to decide
44/// which (if any) client scripts to include.
45#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
46pub struct RenderFlags {
47    /// Something needing the navigation runtime was rendered: a `Link!`, a
48    /// same-origin anchor, or a form posting to a server action.
49    pub links: bool,
50    /// An interactive island was rendered.
51    pub islands: bool,
52    /// At least one suspense boundary was streamed.
53    pub streamed: bool,
54}
55
56struct Writer {
57    out: String,
58    styles_seen: HashSet<&'static str>,
59    /// Stylesheet ids the browser already has (partial navigations).
60    styles_known: HashSet<String>,
61    /// When set, stylesheets are collected here instead of written inline.
62    hoisted: Option<Vec<&'static Stylesheet>>,
63    flags: RenderFlags,
64    streaming: bool,
65    next_id: u32,
66    pending: Vec<(u32, BoxNodeFuture)>,
67}
68
69impl Writer {
70    fn new(streaming: bool, hoist: bool) -> Self {
71        Writer {
72            out: String::with_capacity(4096),
73            styles_seen: HashSet::new(),
74            styles_known: HashSet::new(),
75            hoisted: hoist.then(Vec::new),
76            flags: RenderFlags::default(),
77            streaming,
78            next_id: 0,
79            pending: Vec::new(),
80        }
81    }
82
83    fn style(&mut self, sheet: &'static Stylesheet) {
84        if !self.styles_seen.insert(sheet.id) || self.styles_known.contains(sheet.id) {
85            return;
86        }
87        match &mut self.hoisted {
88            Some(list) => list.push(sheet),
89            None => write_style(&mut self.out, sheet),
90        }
91    }
92
93    fn node(&mut self, node: Node, raw_text: bool) {
94        match node {
95            Node::Empty => {}
96            Node::Text(t) => {
97                if raw_text {
98                    self.out.push_str(&escape_raw_text(&t));
99                } else {
100                    self.out.push_str(&escape_text(&t));
101                }
102            }
103            Node::Raw(r) => self.out.push_str(&map_raw_html(&r)),
104            Node::Fragment(children) => {
105                for c in children {
106                    self.node(c, raw_text);
107                }
108            }
109            Node::Style(sheet) => self.style(sheet),
110            Node::Element(el) => self.element(*el),
111            Node::Suspense(s) => {
112                if self.streaming {
113                    self.next_id += 1;
114                    let id = self.next_id;
115                    self.flags.streamed = true;
116                    self.out.push_str(&format!("<nr-b id=\"nr-b{id}\">"));
117                    self.node(s.fallback, false);
118                    self.out.push_str("</nr-b>");
119                    self.pending.push((id, s.content));
120                } else {
121                    // Unresolved suspense in a synchronous render: show the fallback.
122                    self.node(s.fallback, raw_text);
123                }
124            }
125        }
126    }
127
128    fn element(&mut self, el: Element) {
129        for a in &el.attrs {
130            for sheet in &a.sheets {
131                self.style(sheet);
132            }
133        }
134        let tag = el.tag;
135        self.out.push('<');
136        self.out.push_str(&tag);
137        for a in &el.attrs {
138            let Some(value) = &a.value else { continue };
139            if !is_valid_attr_name(&a.name) {
140                continue;
141            }
142            if !a.trusted && a.name.len() > 2 && a.name[..2].eq_ignore_ascii_case("on") {
143                // Event handler attributes from `attr()` are dropped: use `raw_attr`.
144                continue;
145            }
146            match value {
147                AttrValue::Bool(true) => {
148                    self.out.push(' ');
149                    self.out.push_str(&attr_name(&a.name));
150                }
151                AttrValue::Bool(false) => {}
152                AttrValue::Text(t) => {
153                    let t = match a.name.as_ref() {
154                        "class" | "data-nr-active" | "data-nr-active-prefix" => map_class_list(t),
155                        _ => Cow::Borrowed(t.as_ref()),
156                    };
157                    let safe = if is_url_attr(&a.name) && !is_safe_url(&t) { "#" } else { t.as_ref() };
158                    self.out.push(' ');
159                    self.out.push_str(&attr_name(&a.name));
160                    self.out.push_str("=\"");
161                    self.out.push_str(&escape_attr(safe));
162                    self.out.push('"');
163                }
164            }
165            // `Link!`, plain same-origin anchors and action forms all need the
166            // client runtime: the first two for navigation, the last so the
167            // form submits without a full page load.
168            if a.name == "data-nr-link"
169                || a.name == "data-nr-action"
170                || (tag == "a" && a.name == "href" && is_internal_href(value))
171            {
172                self.flags.links = true;
173            }
174        }
175        self.out.push('>');
176        if tag == "nr-island" {
177            self.flags.islands = true;
178        }
179        if el.void {
180            return;
181        }
182        let raw = tag.eq_ignore_ascii_case("script") || tag.eq_ignore_ascii_case("style");
183        for c in el.children {
184            self.node(c, raw);
185        }
186        self.out.push_str("</");
187        self.out.push_str(&tag);
188        self.out.push('>');
189    }
190}
191
192/// An attribute name as written: `data-nr-class-<class>` toggles a class on
193/// the client, so the class part gets its short name.
194fn attr_name(name: &str) -> Cow<'_, str> {
195    match name.strip_prefix("data-nr-class-").and_then(crate::class_names::short_class_name) {
196        Some(short) => Cow::Owned(format!("data-nr-class-{short}")),
197        None => Cow::Borrowed(name),
198    }
199}
200
201fn write_style(out: &mut String, sheet: &Stylesheet) {
202    out.push_str("<style data-nr-css=\"");
203    out.push_str(sheet.id);
204    out.push_str("\">");
205    out.push_str(&escape_raw_text(sheet.css));
206    out.push_str("</style>");
207}
208
209/// Render synchronously. Suspense boundaries render their fallback.
210pub fn render_static(view: impl View) -> String {
211    let mut w = Writer::new(false, false);
212    w.node(view.into_node(), false);
213    w.out
214}
215
216/// Resolve every suspense boundary in a tree (siblings concurrently).
217pub fn resolve(node: Node) -> Pin<Box<dyn std::future::Future<Output = Node> + Send>> {
218    Box::pin(async move {
219        match node {
220            Node::Suspense(s) => resolve(s.content.await).await,
221            Node::Fragment(children) => Node::Fragment(join_all(children.into_iter().map(resolve)).await),
222            Node::Element(mut el) => {
223                let children = std::mem::take(&mut el.children);
224                el.children = join_all(children.into_iter().map(resolve)).await;
225                Node::Element(el)
226            }
227            other => other,
228        }
229    })
230}
231
232/// Render to a string, awaiting all async content.
233pub async fn render_to_string(view: impl View) -> String {
234    let node = resolve(view.into_node()).await;
235    render_static(node)
236}
237
238/// Everything needed to render a full HTML document.
239pub struct DocumentParts {
240    pub lang: String,
241    /// Pre-rendered `<head>` contents (metadata).
242    pub head: String,
243    /// Extra head markup (e.g. dev scripts). Trusted.
244    pub head_extra: String,
245    pub body: Node,
246    /// CSP nonce applied to framework inline scripts.
247    pub nonce: Option<String>,
248    /// Called once the body is complete; returns markup appended before
249    /// `</body>` (client runtime scripts, depending on the flags).
250    pub tail: Box<dyn FnOnce(RenderFlags) -> String + Send>,
251    /// Ids of stylesheets the browser already has; they are not written again.
252    pub known_styles: Vec<String>,
253}
254
255impl DocumentParts {
256    pub fn new(body: impl View) -> Self {
257        DocumentParts {
258            lang: "en".into(),
259            head: String::new(),
260            head_extra: String::new(),
261            body: body.into_node(),
262            nonce: None,
263            tail: Box::new(|_| String::new()),
264            known_styles: Vec::new(),
265        }
266    }
267}
268
269fn nonce_attr(nonce: &Option<String>) -> String {
270    nonce.as_ref().map(|n| format!(" nonce=\"{}\"", escape_attr(n))).unwrap_or_default()
271}
272
273fn open_document(parts: &DocumentParts, w: &mut Writer, body: &str) -> String {
274    let mut s = String::with_capacity(body.len() + parts.head.len() + 256);
275    s.push_str("<!DOCTYPE html><html lang=\"");
276    s.push_str(&escape_attr(&parts.lang));
277    s.push_str("\"><head>");
278    s.push_str(&parts.head);
279    if let Some(sheets) = w.hoisted.take() {
280        for sheet in sheets {
281            write_style(&mut s, sheet);
282        }
283    }
284    if !w.pending.is_empty() {
285        s.push_str("<style>nr-b,nr-island{display:contents}</style>");
286        s.push_str(&format!("<script{}>{STREAMING_RUNTIME}</script>", nonce_attr(&parts.nonce)));
287    } else if w.flags.islands {
288        s.push_str("<style>nr-island{display:contents}</style>");
289    }
290    s.push_str(&parts.head_extra);
291    s.push_str("</head><body>");
292    s.push_str(body);
293    s
294}
295
296/// Render a complete document as a stream of chunks.
297///
298/// With `streaming = false`, all async content is resolved first and the
299/// stream yields exactly one chunk (used for bots, static generation and
300/// when streaming is disabled).
301pub fn stream_document(parts: DocumentParts, streaming: bool) -> impl Stream<Item = String> + Send {
302    enum State {
303        Start(DocumentParts, bool),
304        Streaming {
305            pending: FuturesUnordered<PendingBoundary>,
306            w: Writer,
307            nonce: Option<String>,
308            tail: Box<dyn FnOnce(RenderFlags) -> String + Send>,
309        },
310        Done,
311    }
312
313    futures_util::stream::unfold(State::Start(parts, streaming), |state| async move {
314        match state {
315            State::Done => None,
316            State::Start(mut parts, streaming) => {
317                let body = std::mem::take(&mut parts.body);
318                let body = if streaming { body } else { resolve(body).await };
319                let mut w = Writer::new(streaming, true);
320                w.styles_known = std::mem::take(&mut parts.known_styles).into_iter().collect();
321                w.node(body, false);
322                let body_html = std::mem::take(&mut w.out);
323                let mut chunk = open_document(&parts, &mut w, &body_html);
324                if w.pending.is_empty() {
325                    chunk.push_str(&(parts.tail)(w.flags));
326                    chunk.push_str("</body></html>");
327                    return Some((chunk, State::Done));
328                }
329                let pending = FuturesUnordered::new();
330                for (id, fut) in w.pending.drain(..) {
331                    pending.push(Box::pin(async move { (id, fut.await) })
332                        as Pin<Box<dyn std::future::Future<Output = _> + Send>>);
333                }
334                // Styles in streamed chunks are written inline, deduplicated
335                // against those already hoisted into <head>.
336                w.hoisted = None;
337                Some((chunk, State::Streaming { pending, w, nonce: parts.nonce, tail: parts.tail }))
338            }
339            State::Streaming { mut pending, mut w, nonce, tail } => match pending.next().await {
340                Some((id, node)) => {
341                    w.out.clear();
342                    w.out.push_str(&format!("<template id=\"nr-t{id}\">"));
343                    w.node(node, false);
344                    w.out.push_str(&format!("</template><script{}>$nr({id})</script>", nonce_attr(&nonce)));
345                    for (nid, fut) in w.pending.drain(..) {
346                        pending.push(Box::pin(async move { (nid, fut.await) }));
347                    }
348                    let chunk = std::mem::take(&mut w.out);
349                    Some((chunk, State::Streaming { pending, w, nonce, tail }))
350                }
351                None => {
352                    let mut chunk = tail(w.flags);
353                    chunk.push_str("</body></html>");
354                    Some((chunk, State::Done))
355                }
356            },
357        }
358    })
359}
360
361/// A link the client runtime can navigate to without a full reload:
362/// root-relative (`/about`), not protocol-relative (`//cdn`).
363fn is_internal_href(value: &AttrValue) -> bool {
364    matches!(value, AttrValue::Text(href) if href.starts_with('/') && !href.starts_with("//"))
365}