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