use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::{Arc, OnceLock};
use serde::Serialize;
use serde_json::{Map, Value, json};
use crate::context::HttpContext;
use crate::error::{Error, Result};
use crate::http::Response;
use crate::middleware::{BoxFuture, Middleware, Next};
const PREVIOUS_URL: &str = "__luxid_previous_url";
const ERRORS: &str = "errors";
#[derive(Debug, Clone, Default)]
pub struct InertiaRequest {
inner: Option<Arc<RequestState>>,
}
#[derive(Debug)]
struct RequestState {
is_inertia: bool,
url: String,
version: Option<String>,
shared: Value,
shell: Arc<Shell>,
only: Option<Vec<String>>,
except: Option<Vec<String>>,
partial_component: Option<String>,
}
impl InertiaRequest {
pub fn is_inertia_request(&self) -> bool {
self.inner.as_ref().is_some_and(|state| state.is_inertia)
}
pub fn is_active(&self) -> bool {
self.inner.is_some()
}
fn state(&self) -> Result<&RequestState> {
self.inner.as_deref().ok_or_else(|| {
Error::internal(
"this route does not have Inertia enabled. Add \
`.middleware((Auth::session(), Inertia::new(\"resources/js/app.jsx\")))` \
to the route group.",
)
})
}
}
impl HttpContext {
pub fn inertia(self, component: &str, props: impl Serialize) -> Result<Response> {
let props = serde_json::to_value(props)
.map_err(|err| Error::internal(format!("inertia props for `{component}`: {err}")))?;
let state = self.inertia.state()?;
let response = self.response;
let mut merged = match state.shared.clone() {
Value::Object(map) => map,
_ => Map::new(),
};
if let Value::Object(map) = props {
merged.extend(map);
}
let component_matches = state
.partial_component
.as_deref()
.is_some_and(|name| name == component);
if component_matches {
if let Some(only) = &state.only {
merged.retain(|key, _| only.iter().any(|wanted| wanted == key));
}
if let Some(except) = &state.except {
merged.retain(|key, _| !except.iter().any(|unwanted| unwanted == key));
}
}
let mut page = json!({
"component": component,
"props": Value::Object(merged),
"url": state.url,
});
if let Some(version) = &state.version {
page["version"] = json!(version);
}
if state.is_inertia {
return response
.header("x-inertia", "true")
.header("vary", "X-Inertia")
.json(page);
}
response.html(state.shell.render(&page))
}
}
#[derive(Debug)]
pub struct Shell {
title: String,
entry: String,
dev: bool,
dev_server: String,
manifest_path: PathBuf,
asset_base: String,
manifest: OnceLock<BTreeMap<String, ManifestEntry>>,
}
#[derive(Debug, Clone, serde::Deserialize)]
struct ManifestEntry {
file: String,
#[serde(default)]
css: Vec<String>,
}
impl Shell {
fn render(&self, page: &Value) -> String {
let serialized = serde_json::to_string(page).unwrap_or_else(|_| "{}".to_owned());
format!(
"<!doctype html>\n\
<html lang=\"en\">\n\
<head>\n\
<meta charset=\"utf-8\">\n\
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\
<title>{title}</title>\n\
{tags}\n\
</head>\n\
<body>\n\
<div id=\"app\" data-page=\"{page}\"></div>\n\
</body>\n\
</html>\n",
title = escape_html(&self.title),
tags = self.tags(),
page = escape_html(&serialized),
)
}
fn tags(&self) -> String {
if self.dev {
return format!(
"<script type=\"module\" src=\"{server}/@vite/client\"></script>\n\
<script type=\"module\" src=\"{server}/{entry}\"></script>",
server = self.dev_server.trim_end_matches('/'),
entry = self.entry,
);
}
let manifest = self.manifest.get_or_init(|| {
std::fs::read_to_string(&self.manifest_path)
.ok()
.and_then(|raw| serde_json::from_str(&raw).ok())
.unwrap_or_default()
});
let Some(entry) = manifest.get(&self.entry) else {
return format!(
"<!-- luxid: no manifest entry for `{entry}` in `{path}`. \
Run your frontend build, or set `.dev(true)`. -->",
entry = escape_html(&self.entry),
path = escape_html(&self.manifest_path.display().to_string()),
);
};
let base = self.asset_base.trim_end_matches('/');
let mut tags: Vec<String> = entry
.css
.iter()
.map(|href| format!("<link rel=\"stylesheet\" href=\"{base}/{href}\">"))
.collect();
tags.push(format!(
"<script type=\"module\" src=\"{base}/{file}\"></script>",
file = entry.file,
));
tags.join("\n")
}
}
fn escape_html(raw: &str) -> String {
let mut out = String::with_capacity(raw.len());
for ch in raw.chars() {
match ch {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
'\'' => out.push_str("'"),
_ => out.push(ch),
}
}
out
}
type SharedProps = Arc<dyn Fn(&HttpContext) -> Result<Value> + Send + Sync>;
pub struct Inertia {
shell: Arc<Shell>,
version: Option<String>,
shared: Vec<SharedProps>,
}
impl Inertia {
pub fn new(entry: impl Into<String>) -> Self {
Self {
shell: Arc::new(Shell {
title: "Luxid".to_owned(),
entry: entry.into(),
dev: cfg!(debug_assertions),
dev_server: "http://localhost:5173".to_owned(),
manifest_path: PathBuf::from("public/build/.vite/manifest.json"),
asset_base: "/build".to_owned(),
manifest: OnceLock::new(),
}),
version: None,
shared: Vec::new(),
}
}
fn shell_mut(&mut self) -> &mut Shell {
Arc::get_mut(&mut self.shell).expect("the shell is not shared during construction")
}
pub fn title(mut self, title: impl Into<String>) -> Self {
self.shell_mut().title = title.into();
self
}
pub fn dev(mut self, dev: bool) -> Self {
self.shell_mut().dev = dev;
self
}
pub fn dev_server(mut self, url: impl Into<String>) -> Self {
self.shell_mut().dev_server = url.into();
self
}
pub fn manifest(mut self, path: impl Into<PathBuf>) -> Self {
self.shell_mut().manifest_path = path.into();
self
}
pub fn asset_base(mut self, base: impl Into<String>) -> Self {
self.shell_mut().asset_base = base.into();
self
}
pub fn version(mut self, version: impl Into<String>) -> Self {
self.version = Some(version.into());
self
}
pub fn share(
mut self,
props: impl Fn(&HttpContext) -> Result<Value> + Send + Sync + 'static,
) -> Self {
self.shared.push(Arc::new(props));
self
}
}
impl Middleware for Inertia {
fn handle<'a>(&'a self, mut ctx: HttpContext, next: Next) -> BoxFuture<'a, Result<Response>> {
Box::pin(async move {
let is_inertia = ctx.request.header("x-inertia").is_some();
let is_get = ctx.request.method().as_str() == "GET";
let url = full_path(&ctx);
if is_inertia && is_get {
let presented = ctx.request.header("x-inertia-version").unwrap_or("");
let current = self.version.as_deref().unwrap_or("");
if presented != current {
return Ok(Response::default()
.status(409)
.header("x-inertia-location", url));
}
}
let mut shared = Map::new();
let flashed_errors: Value = ctx
.session
.flashed(ERRORS)
.unwrap_or(None)
.unwrap_or_else(|| json!({}));
shared.insert(ERRORS.to_owned(), flashed_errors);
for provider in &self.shared {
if let Value::Object(map) = provider(&ctx)? {
shared.extend(map);
}
}
let session = ctx.session.clone();
let has_session = session.is_active();
if is_get && !is_inertia_partial(&ctx) && has_session {
let _ = session.put(PREVIOUS_URL, &url);
}
let back = session
.get::<String>(PREVIOUS_URL)
.unwrap_or(None)
.unwrap_or_else(|| "/".to_owned());
ctx.inertia = InertiaRequest {
inner: Some(Arc::new(RequestState {
is_inertia,
url,
version: self.version.clone(),
shared: Value::Object(shared),
shell: self.shell.clone(),
only: header_list(&ctx, "x-inertia-partial-data"),
except: header_list(&ctx, "x-inertia-partial-except"),
partial_component: ctx
.request
.header("x-inertia-partial-component")
.map(str::to_owned),
})),
};
match next.run(ctx).await {
Ok(response) => Ok(response),
Err(Error::Validation(errors)) if is_inertia => {
if !has_session {
return Err(Error::internal(
"Inertia needs a session to report validation errors. Add \
`Auth::session()` outside `Inertia::new(..)` on this group, \
and bind a `SessionStore` in `providers()`.",
));
}
let first: Map<String, Value> = errors
.fields()
.filter_map(|(field, messages)| {
messages.first().map(|m| (field.clone(), json!(m)))
})
.collect();
session.flash(ERRORS, Value::Object(first))?;
Response::default().redirect(back)
}
Err(other) => Err(other),
}
})
}
}
fn full_path(ctx: &HttpContext) -> String {
let uri = ctx.request.uri();
match uri.query() {
Some(query) => format!("{}?{}", uri.path(), query),
None => uri.path().to_owned(),
}
}
fn is_inertia_partial(ctx: &HttpContext) -> bool {
ctx.request.header("x-inertia-partial-component").is_some()
}
fn header_list(ctx: &HttpContext, name: &str) -> Option<Vec<String>> {
ctx.request.header(name).map(|raw| {
raw.split(',')
.map(str::trim)
.filter(|part| !part.is_empty())
.map(str::to_owned)
.collect()
})
}