use serenade_http::Response;
use crate::ViewError;
#[cfg(feature = "leptos-ssr")]
use crate::head::ManagedHead;
#[cfg(feature = "leptos-ssr")]
use any_spawner::Executor as LeptosExecutor;
#[cfg(feature = "leptos-ssr")]
use futures::StreamExt;
#[cfg(feature = "leptos-ssr")]
use hydration_context::SsrSharedContext;
#[cfg(feature = "leptos-ssr")]
use leptos::prelude::*;
#[cfg(feature = "leptos-ssr")]
use leptos_meta::ServerMetaContext;
#[cfg(feature = "leptos-ssr")]
use std::sync::Arc;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DocumentParts<Head, Body> {
pub head: Head,
pub body: Body,
}
impl<Head, Body> DocumentParts<Head, Body> {
#[must_use]
pub const fn new(head: Head, body: Body) -> Self {
Self { head, body }
}
}
pub trait DocumentTemplate<Head, Body> {
fn render(self, parts: DocumentParts<Head, Body>) -> Result<String, ViewError>;
}
#[derive(Clone, Copy, Debug, Default)]
pub struct DefaultDocumentTemplate;
impl<Head: AsRef<str>> DocumentTemplate<Head, String> for DefaultDocumentTemplate {
fn render(self, parts: DocumentParts<Head, String>) -> Result<String, ViewError> {
Ok(default_document_html(parts.head.as_ref(), &parts.body))
}
}
impl<Head: AsRef<str>> DocumentTemplate<Head, &str> for DefaultDocumentTemplate {
fn render(self, parts: DocumentParts<Head, &str>) -> Result<String, ViewError> {
Ok(default_document_html(parts.head.as_ref(), parts.body))
}
}
fn default_document_html(head: &str, body: &str) -> String {
format!("<!DOCTYPE html><html lang=\"en\"><head>{head}</head><body>{body}</body></html>")
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct DocumentAssets {
head: String,
body: String,
}
impl DocumentAssets {
#[must_use]
pub fn new(head: impl Into<String>, body: impl Into<String>) -> Self {
Self {
head: head.into(),
body: body.into(),
}
}
#[must_use]
pub fn head_html(&self) -> &str {
&self.head
}
#[must_use]
pub fn body_html(&self) -> &str {
&self.body
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.head.is_empty() && self.body.is_empty()
}
fn insert_into(&self, html: String) -> Result<String, ViewError> {
let mut html = html;
if !self.head.is_empty() {
let index = find_ascii_case_insensitive(&html, "</head>", false).ok_or_else(|| {
ViewError::msg("rendered document has no </head> for its head assets")
})?;
html.insert_str(index, &self.head);
}
if !self.body.is_empty() {
let index = find_ascii_case_insensitive(&html, "</body>", true).ok_or_else(|| {
ViewError::msg("rendered document has no </body> for its body assets")
})?;
html.insert_str(index, &self.body);
}
Ok(html)
}
}
fn find_ascii_case_insensitive(haystack: &str, needle: &str, last: bool) -> Option<usize> {
let (haystack, needle) = (haystack.as_bytes(), needle.as_bytes());
let mut windows = haystack.windows(needle.len());
let matches = |window: &[u8]| window.eq_ignore_ascii_case(needle);
if last {
windows.rposition(matches)
} else {
windows.position(matches)
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Document<Head, Body> {
parts: DocumentParts<Head, Body>,
assets: DocumentAssets,
}
impl<Head, Body> Document<Head, Body> {
#[must_use]
pub const fn new(head: Head, body: Body) -> Self {
Self {
parts: DocumentParts::new(head, body),
assets: DocumentAssets {
head: String::new(),
body: String::new(),
},
}
}
#[must_use]
pub fn with_assets(mut self, assets: &DocumentAssets) -> Self {
self.assets = assets.clone();
self
}
pub fn render(self) -> Result<RenderedDocument, ViewError>
where
DefaultDocumentTemplate: DocumentTemplate<Head, Body>,
{
self.render_with(DefaultDocumentTemplate)
}
pub fn render_with(
self,
template: impl DocumentTemplate<Head, Body>,
) -> Result<RenderedDocument, ViewError> {
let html = template.render(self.parts)?;
self.assets.insert_into(html).map(RenderedDocument)
}
}
#[cfg(feature = "leptos-ssr")]
pub type DocumentSlot = Children;
#[cfg(feature = "leptos-ssr")]
impl<Head, Body, HeadView, BodyView> DocumentTemplate<Head, Body> for DefaultDocumentTemplate
where
Head: FnOnce() -> HeadView + Send + 'static,
Body: FnOnce() -> BodyView + Send + 'static,
HeadView: IntoView + 'static,
BodyView: IntoView + 'static,
{
fn render(self, parts: DocumentParts<Head, Body>) -> Result<String, ViewError> {
render_view_document(parts, |head, body| {
view! {
<!DOCTYPE html>
<html lang="en">
<head>{head()}</head>
<body>{body()}</body>
</html>
}
})
}
}
#[cfg(feature = "leptos-ssr")]
impl<Head, Body, HeadView, BodyView, Template, View> DocumentTemplate<Head, Body> for Template
where
Head: FnOnce() -> HeadView + Send + 'static,
Body: FnOnce() -> BodyView + Send + 'static,
HeadView: IntoView + 'static,
BodyView: IntoView + 'static,
Template: FnOnce(DocumentSlot, DocumentSlot) -> View,
View: RenderHtml,
{
fn render(self, parts: DocumentParts<Head, Body>) -> Result<String, ViewError> {
render_view_document(parts, self)
}
}
#[cfg(feature = "leptos-ssr")]
fn render_view_document<Head, Body, HeadView, BodyView, View>(
parts: DocumentParts<Head, Body>,
template: impl FnOnce(DocumentSlot, DocumentSlot) -> View,
) -> Result<String, ViewError>
where
Head: FnOnce() -> HeadView + Send + 'static,
Body: FnOnce() -> BodyView + Send + 'static,
HeadView: IntoView + 'static,
BodyView: IntoView + 'static,
View: RenderHtml,
{
let (meta_context, meta_output) = ServerMetaContext::new();
let owner = Owner::new_root(Some(Arc::new(SsrSharedContext::new())));
let DocumentParts { head, body } = parts;
let html = owner.with(move || {
provide_context(meta_context);
let head: DocumentSlot =
Box::new(move || view! { <ManagedHead>{head()}</ManagedHead> }.into_any());
let body: DocumentSlot = Box::new(move || body().into_any());
template(head, body).to_html()
});
owner.cleanup();
futures::executor::block_on(async move {
let input = futures::stream::iter([html]);
let mut output = Box::pin(meta_output.inject_meta_context(input).await);
output
.next()
.await
.ok_or_else(|| ViewError::msg("metadata injection produced no document chunk"))
})
}
#[cfg(feature = "leptos-ssr")]
pub fn initialize_leptos_ssr() -> Result<(), ViewError> {
LeptosExecutor::init_futures_executor().map_err(|error| {
ViewError::msg(format!(
"unable to initialize the Leptos SSR executor: {error:?}"
))
})
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RenderedDocument(String);
impl RenderedDocument {
#[must_use]
pub fn as_html(&self) -> &str {
&self.0
}
#[must_use]
pub fn into_response(self) -> Response {
self.into_response_with_status(200)
}
#[must_use]
pub fn into_response_with_status(self, status: u16) -> Response {
Response::new(status)
.with_header("content-type", "text/html; charset=utf-8")
.with_body(self.0.into_bytes())
}
#[must_use]
pub fn into_static_output(self) -> String {
self.0
}
}