saola-kit 0.1.3

Saola core toolkit for Laravel for Rust (contexts, envelope protocol, i18n, masks, modules, Sanctum-compatible tokens)
Documentation
//! Server-side render of a compiled Saola page template (`rust-saoc view-ssr` output) for `PageResponse::ssr`.
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};

/// `@section('meta:…')` keys the shell can read as `saola_ssr_meta_<key>` (`:` → `_`).
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)>,
}

/// Id gốc của view: chỉ cần ổn định trong một lần render (client đọc lại id từ marker `s:v:`),
/// nên băm tên view là đủ và dùng được làm tiền tố class (`[a-z0-9]`).
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)
}

/// `document`: template là TÀI LIỆU HOÀN CHỈNH (chuỗi `@extends` kết thúc ở view hệ thống `__system__ ~ 'app'`): `extras` (saola_boot_json,
/// saola_envelope_json…) được đặt làm biến để view hệ thống in, và không render block meta riêng (chính view hệ thống đã nhận chúng).
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() });
    }
    // Block meta tên `section__meta_<khoá>`; template không có block đó thì fragment báo lỗi và ta bỏ qua.
    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 })
}