1use async_trait::async_trait;
2use serde_json::Value;
3use std::collections::HashMap;
4use std::marker::PhantomData;
5use std::sync::{Arc, RwLock};
6use pakem::core::error::AppError;
7use pakem::core::blade::BladeEngine;
8use crate::component::LiveComponent;
9
10#[async_trait]
11pub trait LiveComponentHandler: Send + Sync {
12 async fn call(
13 &self,
14 state: Value,
15 action: &str,
16 params: Vec<Value>,
17 engine: &BladeEngine,
18 ) -> Result<(Value, String), AppError>;
19
20 fn render_initial(
21 &self,
22 initial_state: Value,
23 engine: &BladeEngine,
24 ) -> Result<(Value, String), AppError>;
25}
26
27pub struct ComponentHandler<T: LiveComponent> {
28 _marker: PhantomData<T>,
29}
30
31impl<T: LiveComponent> Default for ComponentHandler<T> {
32 fn default() -> Self {
33 Self {
34 _marker: PhantomData,
35 }
36 }
37}
38
39#[async_trait]
40impl<T: LiveComponent> LiveComponentHandler for ComponentHandler<T> {
41 async fn call(
42 &self,
43 state: Value,
44 action: &str,
45 params: Vec<Value>,
46 engine: &BladeEngine,
47 ) -> Result<(Value, String), AppError> {
48 let mut comp: T = serde_json::from_value(state)
49 .map_err(|e| AppError::BadRequest(format!("Gagal hidrasi state komponen: {}", e)))?;
50
51 comp.call_action(action, params).await?;
52
53 let new_state = serde_json::to_value(&comp)
54 .map_err(|e| AppError::Generic(format!("Gagal serialisasi state komponen: {}", e)))?;
55
56 let html = comp.render_html(engine)?;
57 Ok((new_state, html))
58 }
59
60 fn render_initial(
61 &self,
62 initial_state: Value,
63 engine: &BladeEngine,
64 ) -> Result<(Value, String), AppError> {
65 let comp: T = if initial_state.is_null() || initial_state.as_object().map_or(false, |m| m.is_empty()) {
66 T::default()
67 } else {
68 let mut val = serde_json::to_value(T::default())
69 .unwrap_or(serde_json::json!({}));
70 if let (Some(base_obj), Some(init_obj)) = (val.as_object_mut(), initial_state.as_object()) {
71 for (k, v) in init_obj {
72 base_obj.insert(k.clone(), v.clone());
73 }
74 }
75 serde_json::from_value(val)
76 .map_err(|e| AppError::BadRequest(format!("Format data awal komponen salah: {}", e)))?
77 };
78
79 let state = serde_json::to_value(&comp)
80 .map_err(|e| AppError::Generic(format!("Gagal serialisasi state komponen: {}", e)))?;
81
82 let html = comp.render_html(engine)?;
83 Ok((state, html))
84 }
85}
86
87#[derive(Clone, Default)]
88pub struct LiveRegistry {
89 handlers: Arc<RwLock<HashMap<String, Arc<dyn LiveComponentHandler>>>>,
90}
91
92impl LiveRegistry {
93 pub fn new() -> Self {
94 Self {
95 handlers: Arc::new(RwLock::new(HashMap::new())),
96 }
97 }
98
99 pub fn global() -> &'static LiveRegistry {
100 static INSTANCE: std::sync::OnceLock<LiveRegistry> = std::sync::OnceLock::new();
101 INSTANCE.get_or_init(LiveRegistry::new)
102 }
103
104 pub fn register<T: LiveComponent>(&self, name: &str) {
105 let handler = Arc::new(ComponentHandler::<T>::default());
106 let mut handlers = self.handlers.write().unwrap();
107 handlers.insert(name.to_string(), handler.clone());
108
109 let global_handlers = &Self::global().handlers;
110 if !Arc::ptr_eq(&self.handlers, global_handlers) {
111 let mut g = global_handlers.write().unwrap();
112 g.insert(name.to_string(), handler);
113 }
114 }
115
116 pub fn get(&self, name: &str) -> Option<Arc<dyn LiveComponentHandler>> {
117 let handlers = self.handlers.read().unwrap();
118 handlers.get(name).cloned()
119 }
120
121 pub fn has(&self, name: &str) -> bool {
122 let handlers = self.handlers.read().unwrap();
123 handlers.contains_key(name)
124 }
125}