1use 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
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()}}";
41
42type PendingBoundary = Pin<Box<dyn std::future::Future<Output = (u32, Node)> + Send>>;
43
44#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
47pub struct RenderFlags {
48 pub links: bool,
51 pub islands: bool,
53 pub streamed: bool,
55 pub ui: bool,
58}
59
60struct Writer {
61 out: String,
62 styles_seen: HashSet<&'static str>,
63 styles_known: HashSet<String>,
65 hoisted: Option<Vec<&'static Stylesheet>>,
67 split: bool,
69 split_sheets: Vec<(&'static Stylesheet, Pieces)>,
71 classes: HashSet<String>,
73 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 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 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 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 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 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
261fn 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
275fn 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
292pub 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
299pub 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
315pub async fn render_to_string(view: impl View) -> String {
317 let node = resolve(view.into_node()).await;
318 render_static(node)
319}
320
321pub struct DocumentParts {
323 pub lang: String,
324 pub head: String,
326 pub head_extra: String,
328 pub body: Node,
329 pub nonce: Option<String>,
331 pub tail: Box<dyn FnOnce(RenderFlags) -> String + Send>,
334 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 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
381pub 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 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 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
450fn is_internal_href(value: &AttrValue) -> bool {
453 matches!(value, AttrValue::Text(href) if href.starts_with('/') && !href.starts_with("//"))
454}