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