use crate::component::WireComponent;
use axum::http::StatusCode;
use larust_core::AppError;
use larust_http::session::Session;
use serde_json::Value;
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::OnceLock;
type BoxedFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
type MountFn = Box<
dyn for<'a> Fn(
&'a Session,
&'a HashMap<String, Value>,
) -> BoxedFuture<'a, Result<Value, AppError>>
+ Send
+ Sync,
>;
type RenderFn =
Box<dyn for<'a> Fn(&'a Value) -> BoxedFuture<'a, Result<String, AppError>> + Send + Sync>;
type SetManyFn =
Box<dyn Fn(Value, &HashMap<String, Value>) -> Result<Value, AppError> + Send + Sync>;
type CallFn = Box<
dyn for<'a> Fn(
Value,
&'a Session,
&'a str,
&'a Value,
) -> BoxedFuture<'a, Result<(Value, Option<String>), AppError>>
+ Send
+ Sync,
>;
pub(crate) struct ComponentEntry {
pub(crate) mount: MountFn,
pub(crate) render: RenderFn,
pub(crate) set_many: SetManyFn,
pub(crate) call: CallFn,
}
static REGISTRY: OnceLock<HashMap<&'static str, ComponentEntry>> = OnceLock::new();
pub fn components() -> LiveRegistry {
LiveRegistry {
map: HashMap::new(),
}
}
#[must_use]
pub struct LiveRegistry {
map: HashMap<&'static str, ComponentEntry>,
}
impl LiveRegistry {
pub fn register<C: WireComponent>(mut self) -> Self {
let entry = ComponentEntry {
mount: Box::new(|session, props| {
Box::pin(async move {
serde_json::to_value(C::mount(session, props).await)
.map_err(|source| AppError::Internal(Box::new(source)))
})
}),
render: Box::new(|state| {
Box::pin(async move {
let component = decode::<C>(state.clone())?;
Ok(component.render().await.into_html())
})
}),
set_many: Box::new(|state, props| {
if props.is_empty() {
return Ok(state);
}
let mut merged = as_object(state)?;
for (key, value) in props {
merged.insert(key.clone(), value.clone());
}
let merged = Value::Object(merged);
let component = decode::<C>(merged)?;
serde_json::to_value(component)
.map_err(|source| AppError::Internal(Box::new(source)))
}),
call: Box::new(|state, session, action, args| {
Box::pin(async move {
let mut component = decode::<C>(state)?;
let redirect = component.call(session, action, args).await?;
let new_state = serde_json::to_value(component)
.map_err(|source| AppError::Internal(Box::new(source)))?;
Ok((new_state, redirect))
})
}),
};
let existing = self.map.insert(C::NAME, entry);
assert!(
existing.is_none(),
"duplicate LiveRegistry::register for component NAME {:?} - each wire component \
must be registered exactly once",
C::NAME
);
self
}
pub fn publish(self) {
if REGISTRY.set(self.map).is_err() {
tracing::warn!(
"wire component registry published more than once in this process; \
mount()/update() still use the first registry's components"
);
}
}
}
pub(crate) fn lookup(name: &str) -> Option<&'static ComponentEntry> {
REGISTRY.get().and_then(|map| map.get(name))
}
fn decode<C: WireComponent>(state: Value) -> Result<C, AppError> {
serde_json::from_value(state).map_err(|source| AppError::Http {
status: StatusCode::UNPROCESSABLE_ENTITY,
message: format!("invalid component state: {source}"),
})
}
fn as_object(state: Value) -> Result<serde_json::Map<String, Value>, AppError> {
match state {
Value::Object(map) => Ok(map),
other => Err(AppError::Http {
status: StatusCode::UNPROCESSABLE_ENTITY,
message: format!(
"cannot apply props to this component's state - expected a JSON object, found: {other}"
),
}),
}
}