use async_trait::async_trait;
use serde::{de::DeserializeOwned, Serialize};
use serde_json::Value;
use crate::core::error::AppError;
use crate::core::request::Request;
#[async_trait]
pub trait LiveComponent: Serialize + DeserializeOwned + Default + Send + Sync + 'static {
fn name(&self) -> &'static str;
fn view(&self) -> &'static str;
async fn mount(&mut self, _req: &Request) -> Result<(), AppError> {
Ok(())
}
async fn call_action(&mut self, action: &str, params: Vec<Value>) -> Result<(), AppError>;
fn render_html(&self, engine: &crate::core::blade::BladeEngine) -> Result<String, AppError> {
let val = serde_json::to_value(self)
.map_err(|e| AppError::Generic(format!("Failed to serialize live component: {}", e)))?;
let mut context = crate::core::blade::BladeContext::new();
if let Some(map) = val.as_object() {
for (k, v) in map {
context.insert_val(k, v.clone());
}
}
Ok(engine.render(self.view(), &context))
}
}