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::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
38pub 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#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
46pub struct RenderFlags {
47 pub links: bool,
49 pub islands: bool,
51 pub streamed: bool,
53}
54
55struct Writer {
56 out: String,
57 styles_seen: HashSet<&'static str>,
58 styles_known: HashSet<String>,
60 hoisted: Option<Vec<&'static Stylesheet>>,
62 flags: RenderFlags,
63 streaming: bool,
64 next_id: u32,
65 pending: Vec<(u32, BoxNodeFuture)>,
66}
67
68impl Writer {
69 fn new(streaming: bool, hoist: bool) -> Self {
70 Writer {
71 out: String::with_capacity(4096),
72 styles_seen: HashSet::new(),
73 styles_known: HashSet::new(),
74 hoisted: hoist.then(Vec::new),
75 flags: RenderFlags::default(),
76 streaming,
77 next_id: 0,
78 pending: Vec::new(),
79 }
80 }
81
82 fn style(&mut self, sheet: &'static Stylesheet) {
83 if !self.styles_seen.insert(sheet.id) || self.styles_known.contains(sheet.id) {
84 return;
85 }
86 match &mut self.hoisted {
87 Some(list) => list.push(sheet),
88 None => write_style(&mut self.out, sheet),
89 }
90 }
91
92 fn node(&mut self, node: Node, raw_text: bool) {
93 match node {
94 Node::Empty => {}
95 Node::Text(t) => {
96 if raw_text {
97 self.out.push_str(&escape_raw_text(&t));
98 } else {
99 self.out.push_str(&escape_text(&t));
100 }
101 }
102 Node::Raw(r) => self.out.push_str(&map_raw_html(&r)),
103 Node::Fragment(children) => {
104 for c in children {
105 self.node(c, raw_text);
106 }
107 }
108 Node::Style(sheet) => self.style(sheet),
109 Node::Element(el) => self.element(*el),
110 Node::Suspense(s) => {
111 if self.streaming {
112 self.next_id += 1;
113 let id = self.next_id;
114 self.flags.streamed = true;
115 self.out.push_str(&format!("<nr-b id=\"nr-b{id}\">"));
116 self.node(s.fallback, false);
117 self.out.push_str("</nr-b>");
118 self.pending.push((id, s.content));
119 } else {
120 self.node(s.fallback, raw_text);
122 }
123 }
124 }
125 }
126
127 fn element(&mut self, el: Element) {
128 for a in &el.attrs {
129 for sheet in &a.sheets {
130 self.style(sheet);
131 }
132 }
133 let tag = el.tag;
134 self.out.push('<');
135 self.out.push_str(&tag);
136 for a in &el.attrs {
137 let Some(value) = &a.value else { continue };
138 if !is_valid_attr_name(&a.name) {
139 continue;
140 }
141 if !a.trusted && a.name.len() > 2 && a.name[..2].eq_ignore_ascii_case("on") {
142 continue;
144 }
145 match value {
146 AttrValue::Bool(true) => {
147 self.out.push(' ');
148 self.out.push_str(&attr_name(&a.name));
149 }
150 AttrValue::Bool(false) => {}
151 AttrValue::Text(t) => {
152 let t = match a.name.as_ref() {
153 "class" | "data-nr-active" | "data-nr-active-prefix" => map_class_list(t),
154 _ => Cow::Borrowed(t.as_ref()),
155 };
156 let safe = if is_url_attr(&a.name) && !is_safe_url(&t) { "#" } else { t.as_ref() };
157 self.out.push(' ');
158 self.out.push_str(&attr_name(&a.name));
159 self.out.push_str("=\"");
160 self.out.push_str(&escape_attr(safe));
161 self.out.push('"');
162 }
163 }
164 if a.name == "data-nr-link" || (tag == "a" && a.name == "href" && is_internal_href(value)) {
166 self.flags.links = true;
167 }
168 }
169 self.out.push('>');
170 if tag == "nr-island" {
171 self.flags.islands = true;
172 }
173 if el.void {
174 return;
175 }
176 let raw = tag.eq_ignore_ascii_case("script") || tag.eq_ignore_ascii_case("style");
177 for c in el.children {
178 self.node(c, raw);
179 }
180 self.out.push_str("</");
181 self.out.push_str(&tag);
182 self.out.push('>');
183 }
184}
185
186fn attr_name(name: &str) -> Cow<'_, str> {
189 match name.strip_prefix("data-nr-class-").and_then(crate::class_names::short_class_name) {
190 Some(short) => Cow::Owned(format!("data-nr-class-{short}")),
191 None => Cow::Borrowed(name),
192 }
193}
194
195fn write_style(out: &mut String, sheet: &Stylesheet) {
196 out.push_str("<style data-nr-css=\"");
197 out.push_str(sheet.id);
198 out.push_str("\">");
199 out.push_str(&escape_raw_text(sheet.css));
200 out.push_str("</style>");
201}
202
203pub fn render_static(view: impl View) -> String {
205 let mut w = Writer::new(false, false);
206 w.node(view.into_node(), false);
207 w.out
208}
209
210pub fn resolve(node: Node) -> Pin<Box<dyn std::future::Future<Output = Node> + Send>> {
212 Box::pin(async move {
213 match node {
214 Node::Suspense(s) => resolve(s.content.await).await,
215 Node::Fragment(children) => Node::Fragment(join_all(children.into_iter().map(resolve)).await),
216 Node::Element(mut el) => {
217 let children = std::mem::take(&mut el.children);
218 el.children = join_all(children.into_iter().map(resolve)).await;
219 Node::Element(el)
220 }
221 other => other,
222 }
223 })
224}
225
226pub async fn render_to_string(view: impl View) -> String {
228 let node = resolve(view.into_node()).await;
229 render_static(node)
230}
231
232pub struct DocumentParts {
234 pub lang: String,
235 pub head: String,
237 pub head_extra: String,
239 pub body: Node,
240 pub nonce: Option<String>,
242 pub tail: Box<dyn FnOnce(RenderFlags) -> String + Send>,
245 pub known_styles: Vec<String>,
247}
248
249impl DocumentParts {
250 pub fn new(body: impl View) -> Self {
251 DocumentParts {
252 lang: "en".into(),
253 head: String::new(),
254 head_extra: String::new(),
255 body: body.into_node(),
256 nonce: None,
257 tail: Box::new(|_| String::new()),
258 known_styles: Vec::new(),
259 }
260 }
261}
262
263fn nonce_attr(nonce: &Option<String>) -> String {
264 nonce.as_ref().map(|n| format!(" nonce=\"{}\"", escape_attr(n))).unwrap_or_default()
265}
266
267fn open_document(parts: &DocumentParts, w: &mut Writer, body: &str) -> String {
268 let mut s = String::with_capacity(body.len() + parts.head.len() + 256);
269 s.push_str("<!DOCTYPE html><html lang=\"");
270 s.push_str(&escape_attr(&parts.lang));
271 s.push_str("\"><head>");
272 s.push_str(&parts.head);
273 if let Some(sheets) = w.hoisted.take() {
274 for sheet in sheets {
275 write_style(&mut s, sheet);
276 }
277 }
278 if !w.pending.is_empty() {
279 s.push_str("<style>nr-b,nr-island{display:contents}</style>");
280 s.push_str(&format!("<script{}>{STREAMING_RUNTIME}</script>", nonce_attr(&parts.nonce)));
281 } else if w.flags.islands {
282 s.push_str("<style>nr-island{display:contents}</style>");
283 }
284 s.push_str(&parts.head_extra);
285 s.push_str("</head><body>");
286 s.push_str(body);
287 s
288}
289
290pub fn stream_document(parts: DocumentParts, streaming: bool) -> impl Stream<Item = String> + Send {
296 enum State {
297 Start(DocumentParts, bool),
298 Streaming {
299 pending: FuturesUnordered<PendingBoundary>,
300 w: Writer,
301 nonce: Option<String>,
302 tail: Box<dyn FnOnce(RenderFlags) -> String + Send>,
303 },
304 Done,
305 }
306
307 futures_util::stream::unfold(State::Start(parts, streaming), |state| async move {
308 match state {
309 State::Done => None,
310 State::Start(mut parts, streaming) => {
311 let body = std::mem::take(&mut parts.body);
312 let body = if streaming { body } else { resolve(body).await };
313 let mut w = Writer::new(streaming, true);
314 w.styles_known = std::mem::take(&mut parts.known_styles).into_iter().collect();
315 w.node(body, false);
316 let body_html = std::mem::take(&mut w.out);
317 let mut chunk = open_document(&parts, &mut w, &body_html);
318 if w.pending.is_empty() {
319 chunk.push_str(&(parts.tail)(w.flags));
320 chunk.push_str("</body></html>");
321 return Some((chunk, State::Done));
322 }
323 let pending = FuturesUnordered::new();
324 for (id, fut) in w.pending.drain(..) {
325 pending.push(Box::pin(async move { (id, fut.await) })
326 as Pin<Box<dyn std::future::Future<Output = _> + Send>>);
327 }
328 w.hoisted = None;
331 Some((chunk, State::Streaming { pending, w, nonce: parts.nonce, tail: parts.tail }))
332 }
333 State::Streaming { mut pending, mut w, nonce, tail } => match pending.next().await {
334 Some((id, node)) => {
335 w.out.clear();
336 w.out.push_str(&format!("<template id=\"nr-t{id}\">"));
337 w.node(node, false);
338 w.out.push_str(&format!("</template><script{}>$nr({id})</script>", nonce_attr(&nonce)));
339 for (nid, fut) in w.pending.drain(..) {
340 pending.push(Box::pin(async move { (nid, fut.await) }));
341 }
342 let chunk = std::mem::take(&mut w.out);
343 Some((chunk, State::Streaming { pending, w, nonce, tail }))
344 }
345 None => {
346 let mut chunk = tail(w.flags);
347 chunk.push_str("</body></html>");
348 Some((chunk, State::Done))
349 }
350 },
351 }
352 })
353}
354
355fn is_internal_href(value: &AttrValue) -> bool {
358 matches!(value, AttrValue::Text(href) if href.starts_with('/') && !href.starts_with("//"))
359}