Skip to main content

serenade_view/
document.rs

1//! Engine-neutral document composition and output delivery.
2
3use 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/// Head and body inputs supplied to a document template.
23#[derive(Clone, Debug, Eq, PartialEq)]
24pub struct DocumentParts<Head, Body> {
25    /// Application-owned head output or view factory.
26    pub head: Head,
27    /// Application-owned body output or view factory.
28    pub body: Body,
29}
30
31impl<Head, Body> DocumentParts<Head, Body> {
32    /// Creates document parts from the head and body inputs.
33    #[must_use]
34    pub const fn new(head: Head, body: Body) -> Self {
35        Self { head, body }
36    }
37}
38
39/// A template engine's document-level composition boundary.
40///
41/// Implementations own the document structure, language, and head/body slots.
42/// They consume the head and body inputs and return one complete HTML document.
43///
44/// The application head template owns title, metadata, canonical links, JSON-LD,
45/// and custom head markup; the body template/component owns page content. Shared
46/// head entries come from the document template. Route-owned entries replace
47/// shared singleton entries only when they declare the same stable key, leaving
48/// unrelated shared entries intact. Repeatable entries use distinct keys and are
49/// retained. Keys are declared by templates/integrations, never recovered by
50/// parsing rendered HTML.
51///
52/// Rust controllers remain responsible for data and orchestration, not markup.
53/// Template-engine and AOT adapters can implement this contract as optional
54/// integrations; the engine-neutral `serenade-view` helpers do not require them.
55pub trait DocumentTemplate<Head, Body> {
56    /// Composes the complete HTML document.
57    ///
58    /// # Errors
59    ///
60    /// Returns an error if the template engine cannot render the document.
61    fn render(self, parts: DocumentParts<Head, Body>) -> Result<String, ViewError>;
62}
63
64/// The framework's default document template.
65///
66/// It composes a complete English-language HTML document from already-rendered
67/// strings or, with the `leptos-ssr` feature, from view factories.
68#[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/// Build-generated markup delivered with every rendered document.
88///
89/// Typically obtained once at startup from
90/// [`TrunkAssetManifest::document_assets`](crate::TrunkAssetManifest::document_assets).
91/// The markup is trusted build output and is inserted verbatim: head markup
92/// immediately before the document's `</head>`, body markup immediately before
93/// its `</body>`. Document templates must not repeat these tags themselves.
94#[derive(Clone, Debug, Default, Eq, PartialEq)]
95pub struct DocumentAssets {
96    head: String,
97    body: String,
98}
99
100impl DocumentAssets {
101    /// Creates document assets from trusted head and body markup.
102    #[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    /// Markup inserted at the end of the document head.
111    #[must_use]
112    pub fn head_html(&self) -> &str {
113        &self.head
114    }
115
116    /// Markup inserted at the end of the document body.
117    #[must_use]
118    pub fn body_html(&self) -> &str {
119        &self.body
120    }
121
122    /// Whether there is no markup to insert.
123    #[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/// Application-provided head and body ready for document composition.
158#[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    /// Starts document composition with application-owned head and body outputs.
166    #[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    /// Delivers build-generated assets, such as Trunk's stylesheets, scripts
178    /// and WASM bootstrap, with the rendered document.
179    ///
180    /// # Examples
181    ///
182    /// ```
183    /// use serenade_view::{Document, DocumentAssets};
184    ///
185    /// let assets = DocumentAssets::new(
186    ///     r#"<link rel="stylesheet" href="/app-1a2b.css">"#,
187    ///     r#"<script type="module" src="/app-1a2b.js"></script>"#,
188    /// );
189    /// let rendered = Document::new("<title>Home</title>", "<main>Welcome</main>")
190    ///     .with_assets(&assets)
191    ///     .render()?;
192    /// assert!(rendered.as_html().contains(r#"href="/app-1a2b.css"></head>"#));
193    /// assert!(rendered.as_html().contains(r#"</script></body>"#));
194    /// # Ok::<(), serenade_view::ViewError>(())
195    /// ```
196    #[must_use]
197    pub fn with_assets(mut self, assets: &DocumentAssets) -> Self {
198        self.assets = assets.clone();
199        self
200    }
201
202    /// Renders the document through the framework's default template.
203    ///
204    /// String inputs must already be rendered and escaped; they are not sanitized.
205    /// View factories require the `leptos-ssr` feature and a process-wide SSR
206    /// executor initialized with `initialize_leptos_ssr` or by the application.
207    ///
208    /// # Examples
209    ///
210    /// ```
211    /// use serenade_view::Document;
212    ///
213    /// let document = Document::new("<title>Home</title>", "<main>Welcome</main>");
214    /// let rendered = document.render()?;
215    /// assert!(rendered.as_html().contains("<main>Welcome</main>"));
216    /// # Ok::<(), serenade_view::ViewError>(())
217    /// ```
218    ///
219    /// # Errors
220    ///
221    /// Returns the default template's rendering error, or an asset insertion
222    /// error as described for [`Self::render_with`].
223    pub fn render(self) -> Result<RenderedDocument, ViewError>
224    where
225        DefaultDocumentTemplate: DocumentTemplate<Head, Body>,
226    {
227        self.render_with(DefaultDocumentTemplate)
228    }
229
230    /// Renders the document through an application-provided template.
231    ///
232    /// With the `leptos-ssr` feature, a template can be a function or closure
233    /// accepting the head and body `DocumentSlot`s. Both slots and the
234    /// template render under the same request-scoped owner. The application
235    /// must initialize the SSR executor before rendering view factories.
236    ///
237    /// # Examples
238    ///
239    /// ```
240    /// use serenade_view::{Document, DocumentParts, DocumentTemplate, ViewError};
241    ///
242    /// struct FrenchTemplate;
243    ///
244    /// impl DocumentTemplate<&str, &str> for FrenchTemplate {
245    ///     fn render(self, parts: DocumentParts<&str, &str>) -> Result<String, ViewError> {
246    ///         Ok(format!(
247    ///             "<!DOCTYPE html><html lang=\"fr\"><head>{}</head><body>{}</body></html>",
248    ///             parts.head, parts.body
249    ///         ))
250    ///     }
251    /// }
252    ///
253    /// let document = Document::new("<title>Accueil</title>", "<main>Bienvenue</main>");
254    /// let rendered = document.render_with(FrenchTemplate)?;
255    /// assert!(rendered.as_html().contains("<html lang=\"fr\">"));
256    /// # Ok::<(), ViewError>(())
257    /// ```
258    ///
259    /// # Errors
260    ///
261    /// Returns the template's rendering error, or an error when assets are
262    /// configured and the rendered document lacks `</head>` or `</body>`.
263    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")]
273/// A one-shot head or body slot passed to a document template.
274pub 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")]
346/// Initializes Leptos SSR with the futures executor.
347///
348/// Applications that use a different runtime should initialize
349/// [`LeptosExecutor`] directly instead.
350///
351/// # Errors
352///
353/// Returns an error if another executor has already been initialized.
354pub 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/// A complete HTML document ready for HTTP or static-file delivery.
363#[derive(Clone, Debug, Eq, PartialEq)]
364pub struct RenderedDocument(String);
365
366impl RenderedDocument {
367    /// Returns the complete HTML document.
368    #[must_use]
369    pub fn as_html(&self) -> &str {
370        &self.0
371    }
372
373    /// Delivers the document as an HTTP 200 response with an HTML content type.
374    #[must_use]
375    pub fn into_response(self) -> Response {
376        self.into_response_with_status(200)
377    }
378
379    /// Delivers the document as an HTTP response with the supplied status.
380    #[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    /// Returns the document for static-output writing.
388    #[must_use]
389    pub fn into_static_output(self) -> String {
390        self.0
391    }
392}