Skip to main content

hypen_engine/lifecycle/
component.rs

1use crate::ir::NodeId;
2
3/// Lifecycle events for component instances
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum ComponentLifecycleEvent {
6    /// Component instance was mounted to the tree
7    Mounted,
8
9    /// Component instance was unmounted from the tree
10    Unmounted,
11}
12
13/// Callback type for component lifecycle events
14pub type ComponentLifecycleCallback = Box<dyn Fn(NodeId, ComponentLifecycleEvent) + Send + Sync>;
15
16/// Manages component lifecycle callbacks
17pub struct ComponentLifecycle {
18    /// Lifecycle event callback
19    callback: Option<ComponentLifecycleCallback>,
20}
21
22impl ComponentLifecycle {
23    pub fn new() -> Self {
24        Self { callback: None }
25    }
26
27    /// Register a lifecycle callback
28    pub fn on<F>(&mut self, callback: F)
29    where
30        F: Fn(NodeId, ComponentLifecycleEvent) + Send + Sync + 'static,
31    {
32        self.callback = Some(Box::new(callback));
33    }
34
35    /// Notify that a component was mounted
36    pub fn notify_mounted(&self, node_id: NodeId) {
37        if let Some(ref callback) = self.callback {
38            callback(node_id, ComponentLifecycleEvent::Mounted);
39        }
40    }
41
42    /// Notify that a component was unmounted
43    pub fn notify_unmounted(&self, node_id: NodeId) {
44        if let Some(ref callback) = self.callback {
45            callback(node_id, ComponentLifecycleEvent::Unmounted);
46        }
47    }
48}
49
50impl Default for ComponentLifecycle {
51    fn default() -> Self {
52        Self::new()
53    }
54}