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