use crate::lock::with_session_lock;
use crate::mount::wrap;
use crate::registry;
use crate::state::{load_components, save_components};
use axum::extract::Path;
use axum::http::header::{HeaderName, HeaderValue, CONTENT_TYPE};
use axum::response::{IntoResponse, Response};
use axum::Json;
use larust_core::AppError;
use larust_http::session::Session;
use serde::Deserialize;
use std::collections::HashMap;
const REDIRECT_HEADER: &str = "x-wire-redirect";
const HEAD_PATCH_HEADER: &str = "x-wire-head-patch";
const HEAD_PATCH_STACK: &str = "head";
const RUNTIME_JS: &str = include_str!("../assets/wire-runtime.js");
#[derive(Debug, Deserialize)]
pub struct UpdatePayload {
#[serde(default)]
props: HashMap<String, serde_json::Value>,
#[serde(default)]
action: Option<ActionCall>,
}
#[derive(Debug, Deserialize)]
struct ActionCall {
name: String,
#[serde(default)]
args: serde_json::Value,
}
pub async fn update(
session: Session,
Path(component_id): Path<String>,
Json(payload): Json<UpdatePayload>,
) -> Result<Response, AppError> {
with_session_lock(&session, || async {
let mut components = load_components(&session).await?;
let index = components
.iter()
.position(|(id, _)| id == &component_id)
.ok_or(AppError::NotFound)?;
let entry = registry::lookup(&components[index].1.name).ok_or(AppError::NotFound)?;
let mut state = (entry.set_many)(components[index].1.state.clone(), &payload.props)?;
let mut redirect = None;
if let Some(action) = &payload.action {
let (new_state, action_redirect) =
(entry.call)(state, &session, &action.name, &action.args).await?;
state = new_state;
redirect = action_redirect;
}
let html = (entry.render)(&state).await?;
let head_patch = larust_view::push_registry::drain(HEAD_PATCH_STACK);
components[index].1.state = state;
save_components(&session, &components).await?;
Ok(html_response(
wrap(&component_id, &html),
redirect,
head_patch,
))
})
.await
}
fn html_response(html: String, redirect: Option<String>, head_patch: String) -> Response {
let mut response = ([(CONTENT_TYPE, "text/html; charset=utf-8")], html).into_response();
if let Some(path) = redirect {
let value = HeaderValue::from_str(&path).unwrap_or_else(|_| HeaderValue::from_static("/"));
response
.headers_mut()
.insert(HeaderName::from_static(REDIRECT_HEADER), value);
}
if !head_patch.is_empty() {
let encoded = base64::Engine::encode(
&base64::engine::general_purpose::STANDARD,
head_patch.as_bytes(),
);
response.headers_mut().insert(
HeaderName::from_static(HEAD_PATCH_HEADER),
HeaderValue::from_str(&encoded).expect("base64 output is always a valid header value"),
);
}
response
}
pub async fn runtime_js() -> impl IntoResponse {
(
[(CONTENT_TYPE, "text/javascript; charset=utf-8")],
RUNTIME_JS,
)
}