use laravel::view::{Html, view};
use serde::Serialize;
use serde_json::{Map, Value};
use super::ClientAuthProjection;
use crate::view::{VAR_AUTH_USER, VAR_LOCALE, VAR_SITE, VAR_VIEW_ID};
pub const META_KEYS: &[&str] = &[
"title", "description", "keywords", "robots", "canonical", "og:image", "og:image:alt", "og:type",
];
pub struct SsrOutput {
pub html: Html,
pub meta: Vec<(String, Html)>,
}
pub fn root_view_id(view_key: &str) -> String {
let mut h: u32 = 0x811c_9dc5;
for b in view_key.bytes() {
h = (h ^ u32::from(b)).wrapping_mul(0x0100_0193);
}
format!("r{h:08x}")
}
fn default_user(auth: Option<&ClientAuthProjection>) -> Value {
auth.and_then(|a| a.guards.get(&a.default_guard))
.and_then(|g| g.user.as_ref())
.and_then(|u| serde_json::to_value(u).ok())
.unwrap_or(Value::Null)
}
pub fn render_page<T: Serialize>(
template: &str,
site: Option<&Value>,
system: &[(String, String)],
data: &T,
view_key: &str,
locale: &str,
auth: Option<&ClientAuthProjection>,
extras: &[(&str, String)],
document: bool,
) -> Result<SsrOutput, String> {
let mut map = match serde_json::to_value(data).map_err(|e| e.to_string())? {
Value::Object(m) => m,
Value::Null => Map::new(),
_ => return Err("dữ liệu trang phải là một đối tượng JSON".into()),
};
map.insert("__system__".into(), Value::String("_system.".into()));
for (k, v) in system {
map.insert(k.clone(), Value::String(v.clone()));
}
for (k, v) in extras {
map.insert((*k).into(), Value::String(v.clone()));
}
map.insert(VAR_VIEW_ID.into(), Value::String(root_view_id(view_key)));
map.insert(VAR_LOCALE.into(), Value::String(locale.to_owned()));
map.insert(VAR_AUTH_USER.into(), default_user(auth));
if let Some(site) = site {
map.insert(VAR_SITE.into(), site.clone());
}
let page = || view(template.to_owned(), Value::Object(map.clone()));
let html = page().render().map_err(|e| e.to_string())?;
if document {
return Ok(SsrOutput { html, meta: Vec::new() });
}
let mut meta = Vec::new();
for key in META_KEYS {
let block = format!("section__meta_{}", key.replace(':', "_"));
if let Ok(h) = page().fragment(block).render() {
meta.push((key.replace(':', "_"), h));
}
}
Ok(SsrOutput { html, meta })
}