1use serenade_http::Response;
4
5use crate::ViewError;
6
7#[cfg(feature = "leptos-ssr")]
8use crate::head::ManagedHead;
9#[cfg(feature = "leptos-ssr")]
10use any_spawner::Executor as LeptosExecutor;
11#[cfg(feature = "leptos-ssr")]
12use futures::StreamExt;
13#[cfg(feature = "leptos-ssr")]
14use hydration_context::SsrSharedContext;
15#[cfg(feature = "leptos-ssr")]
16use leptos::prelude::*;
17#[cfg(feature = "leptos-ssr")]
18use leptos_meta::ServerMetaContext;
19#[cfg(feature = "leptos-ssr")]
20use std::sync::Arc;
21
22#[derive(Clone, Debug, Eq, PartialEq)]
24pub struct DocumentParts<Head, Body> {
25 pub head: Head,
27 pub body: Body,
29}
30
31impl<Head, Body> DocumentParts<Head, Body> {
32 #[must_use]
34 pub const fn new(head: Head, body: Body) -> Self {
35 Self { head, body }
36 }
37}
38
39pub trait DocumentTemplate<Head, Body> {
56 fn render(self, parts: DocumentParts<Head, Body>) -> Result<String, ViewError>;
62}
63
64#[derive(Clone, Copy, Debug, Default)]
69pub struct DefaultDocumentTemplate;
70
71impl<Head: AsRef<str>> DocumentTemplate<Head, String> for DefaultDocumentTemplate {
72 fn render(self, parts: DocumentParts<Head, String>) -> Result<String, ViewError> {
73 Ok(default_document_html(parts.head.as_ref(), &parts.body))
74 }
75}
76
77impl<Head: AsRef<str>> DocumentTemplate<Head, &str> for DefaultDocumentTemplate {
78 fn render(self, parts: DocumentParts<Head, &str>) -> Result<String, ViewError> {
79 Ok(default_document_html(parts.head.as_ref(), parts.body))
80 }
81}
82
83fn default_document_html(head: &str, body: &str) -> String {
84 format!("<!DOCTYPE html><html lang=\"en\"><head>{head}</head><body>{body}</body></html>")
85}
86
87#[derive(Clone, Debug, Default, Eq, PartialEq)]
95pub struct DocumentAssets {
96 head: String,
97 body: String,
98}
99
100impl DocumentAssets {
101 #[must_use]
103 pub fn new(head: impl Into<String>, body: impl Into<String>) -> Self {
104 Self {
105 head: head.into(),
106 body: body.into(),
107 }
108 }
109
110 #[must_use]
112 pub fn head_html(&self) -> &str {
113 &self.head
114 }
115
116 #[must_use]
118 pub fn body_html(&self) -> &str {
119 &self.body
120 }
121
122 #[must_use]
124 pub const fn is_empty(&self) -> bool {
125 self.head.is_empty() && self.body.is_empty()
126 }
127
128 fn insert_into(&self, html: String) -> Result<String, ViewError> {
129 let mut html = html;
130 if !self.head.is_empty() {
131 let index = find_ascii_case_insensitive(&html, "</head>", false).ok_or_else(|| {
132 ViewError::msg("rendered document has no </head> for its head assets")
133 })?;
134 html.insert_str(index, &self.head);
135 }
136 if !self.body.is_empty() {
137 let index = find_ascii_case_insensitive(&html, "</body>", true).ok_or_else(|| {
138 ViewError::msg("rendered document has no </body> for its body assets")
139 })?;
140 html.insert_str(index, &self.body);
141 }
142 Ok(html)
143 }
144}
145
146fn find_ascii_case_insensitive(haystack: &str, needle: &str, last: bool) -> Option<usize> {
147 let (haystack, needle) = (haystack.as_bytes(), needle.as_bytes());
148 let mut windows = haystack.windows(needle.len());
149 let matches = |window: &[u8]| window.eq_ignore_ascii_case(needle);
150 if last {
151 windows.rposition(matches)
152 } else {
153 windows.position(matches)
154 }
155}
156
157#[derive(Clone, Debug, Eq, PartialEq)]
159pub struct Document<Head, Body> {
160 parts: DocumentParts<Head, Body>,
161 assets: DocumentAssets,
162}
163
164impl<Head, Body> Document<Head, Body> {
165 #[must_use]
167 pub const fn new(head: Head, body: Body) -> Self {
168 Self {
169 parts: DocumentParts::new(head, body),
170 assets: DocumentAssets {
171 head: String::new(),
172 body: String::new(),
173 },
174 }
175 }
176
177 #[must_use]
197 pub fn with_assets(mut self, assets: &DocumentAssets) -> Self {
198 self.assets = assets.clone();
199 self
200 }
201
202 pub fn render(self) -> Result<RenderedDocument, ViewError>
224 where
225 DefaultDocumentTemplate: DocumentTemplate<Head, Body>,
226 {
227 self.render_with(DefaultDocumentTemplate)
228 }
229
230 pub fn render_with(
264 self,
265 template: impl DocumentTemplate<Head, Body>,
266 ) -> Result<RenderedDocument, ViewError> {
267 let html = template.render(self.parts)?;
268 self.assets.insert_into(html).map(RenderedDocument)
269 }
270}
271
272#[cfg(feature = "leptos-ssr")]
273pub type DocumentSlot = Children;
275
276#[cfg(feature = "leptos-ssr")]
277impl<Head, Body, HeadView, BodyView> DocumentTemplate<Head, Body> for DefaultDocumentTemplate
278where
279 Head: FnOnce() -> HeadView + Send + 'static,
280 Body: FnOnce() -> BodyView + Send + 'static,
281 HeadView: IntoView + 'static,
282 BodyView: IntoView + 'static,
283{
284 fn render(self, parts: DocumentParts<Head, Body>) -> Result<String, ViewError> {
285 render_view_document(parts, |head, body| {
286 view! {
287 <!DOCTYPE html>
288 <html lang="en">
289 <head>{head()}</head>
290 <body>{body()}</body>
291 </html>
292 }
293 })
294 }
295}
296
297#[cfg(feature = "leptos-ssr")]
298impl<Head, Body, HeadView, BodyView, Template, View> DocumentTemplate<Head, Body> for Template
299where
300 Head: FnOnce() -> HeadView + Send + 'static,
301 Body: FnOnce() -> BodyView + Send + 'static,
302 HeadView: IntoView + 'static,
303 BodyView: IntoView + 'static,
304 Template: FnOnce(DocumentSlot, DocumentSlot) -> View,
305 View: RenderHtml,
306{
307 fn render(self, parts: DocumentParts<Head, Body>) -> Result<String, ViewError> {
308 render_view_document(parts, self)
309 }
310}
311
312#[cfg(feature = "leptos-ssr")]
313fn render_view_document<Head, Body, HeadView, BodyView, View>(
314 parts: DocumentParts<Head, Body>,
315 template: impl FnOnce(DocumentSlot, DocumentSlot) -> View,
316) -> Result<String, ViewError>
317where
318 Head: FnOnce() -> HeadView + Send + 'static,
319 Body: FnOnce() -> BodyView + Send + 'static,
320 HeadView: IntoView + 'static,
321 BodyView: IntoView + 'static,
322 View: RenderHtml,
323{
324 let (meta_context, meta_output) = ServerMetaContext::new();
325 let owner = Owner::new_root(Some(Arc::new(SsrSharedContext::new())));
326 let DocumentParts { head, body } = parts;
327 let html = owner.with(move || {
328 provide_context(meta_context);
329 let head: DocumentSlot =
330 Box::new(move || view! { <ManagedHead>{head()}</ManagedHead> }.into_any());
331 let body: DocumentSlot = Box::new(move || body().into_any());
332 template(head, body).to_html()
333 });
334 owner.cleanup();
335 futures::executor::block_on(async move {
336 let input = futures::stream::iter([html]);
337 let mut output = Box::pin(meta_output.inject_meta_context(input).await);
338 output
339 .next()
340 .await
341 .ok_or_else(|| ViewError::msg("metadata injection produced no document chunk"))
342 })
343}
344
345#[cfg(feature = "leptos-ssr")]
346pub fn initialize_leptos_ssr() -> Result<(), ViewError> {
355 LeptosExecutor::init_futures_executor().map_err(|error| {
356 ViewError::msg(format!(
357 "unable to initialize the Leptos SSR executor: {error:?}"
358 ))
359 })
360}
361
362#[derive(Clone, Debug, Eq, PartialEq)]
364pub struct RenderedDocument(String);
365
366impl RenderedDocument {
367 #[must_use]
369 pub fn as_html(&self) -> &str {
370 &self.0
371 }
372
373 #[must_use]
375 pub fn into_response(self) -> Response {
376 self.into_response_with_status(200)
377 }
378
379 #[must_use]
381 pub fn into_response_with_status(self, status: u16) -> Response {
382 Response::new(status)
383 .with_header("content-type", "text/html; charset=utf-8")
384 .with_body(self.0.into_bytes())
385 }
386
387 #[must_use]
389 pub fn into_static_output(self) -> String {
390 self.0
391 }
392}