Skip to main content

hypen_engine/reactive/
graph.rs

1use super::Binding;
2use crate::ir::NodeId;
3use indexmap::{IndexMap, IndexSet};
4use std::collections::BTreeMap;
5
6/// Tracks which nodes depend on which state paths
7pub struct DependencyGraph {
8    /// Maps state path → set of NodeIds that depend on it
9    dependencies: IndexMap<String, IndexSet<NodeId>>,
10
11    /// Maps NodeId → set of state paths it depends on
12    node_bindings: IndexMap<NodeId, IndexSet<String>>,
13
14    /// Prefix index for efficient path lookups
15    /// Maps path prefix → set of full paths that start with this prefix
16    /// This enables O(log n) lookup instead of O(n) scan
17    prefix_index: BTreeMap<String, IndexSet<String>>,
18}
19
20impl DependencyGraph {
21    pub fn new() -> Self {
22        Self {
23            dependencies: IndexMap::new(),
24            node_bindings: IndexMap::new(),
25            prefix_index: BTreeMap::new(),
26        }
27    }
28
29    /// Record that a node depends on a binding
30    pub fn add_dependency(&mut self, node_id: NodeId, binding: &Binding) {
31        let path = binding.full_path();
32
33        // Add to dependencies map
34        self.dependencies
35            .entry(path.clone())
36            .or_default()
37            .insert(node_id);
38
39        // Add to node_bindings map
40        self.node_bindings
41            .entry(node_id)
42            .or_default()
43            .insert(path.clone());
44
45        // Update prefix index for efficient lookups
46        // Add all prefixes of this path to the index
47        self.add_path_to_prefix_index(&path);
48    }
49
50    /// Add a path and all its prefixes to the prefix index
51    fn add_path_to_prefix_index(&mut self, path: &str) {
52        // Add the full path to its own prefix
53        self.prefix_index
54            .entry(path.to_string())
55            .or_default()
56            .insert(path.to_string());
57
58        // Add all parent prefixes
59        let mut current = path;
60        while let Some(dot_pos) = current.rfind('.') {
61            current = &current[..dot_pos];
62            self.prefix_index
63                .entry(current.to_string())
64                .or_default()
65                .insert(path.to_string());
66        }
67    }
68
69    /// Remove all dependencies for a node (when unmounting)
70    pub fn remove_node(&mut self, node_id: NodeId) {
71        if let Some(paths) = self.node_bindings.shift_remove(&node_id) {
72            for path in paths {
73                if let Some(nodes) = self.dependencies.get_mut(&path) {
74                    nodes.shift_remove(&node_id);
75                }
76            }
77        }
78    }
79
80    /// Get all nodes that depend on a specific state path
81    pub fn get_dependent_nodes(&self, path: &str) -> Option<&IndexSet<NodeId>> {
82        self.dependencies.get(path)
83    }
84
85    /// Get all nodes affected by a state patch (considers nested paths)
86    /// E.g., if "user" changes, both "user" and "user.name" subscribers are affected
87    /// Uses prefix index for O(log n) lookup instead of O(n) scan
88    pub fn get_affected_nodes(&self, changed_path: &str) -> IndexSet<NodeId> {
89        let mut affected = IndexSet::new();
90        let mut affected_paths = IndexSet::new();
91
92        // Strategy: Find all paths that could be affected by this change
93        // 1. Exact match: changed_path itself
94        if self.dependencies.contains_key(changed_path) {
95            affected_paths.insert(changed_path.to_string());
96        }
97
98        // 2. Parent paths: all prefixes of changed_path (e.g., "user.name" affects "user")
99        let mut current = changed_path;
100        while let Some(dot_pos) = current.rfind('.') {
101            current = &current[..dot_pos];
102            if self.dependencies.contains_key(current) {
103                affected_paths.insert(current.to_string());
104            }
105        }
106
107        // 3. Child paths: all paths that start with changed_path (e.g., "user" affects "user.name")
108        // Use prefix index for efficient lookup
109        if let Some(child_paths) = self.prefix_index.get(changed_path) {
110            affected_paths.extend(child_paths.iter().cloned());
111        }
112
113        // Collect nodes from all affected paths
114        for path in affected_paths {
115            if let Some(nodes) = self.dependencies.get(&path) {
116                affected.extend(nodes.iter().copied());
117            }
118        }
119
120        affected
121    }
122
123    /// Clear all dependencies
124    pub fn clear(&mut self) {
125        self.dependencies.clear();
126        self.node_bindings.clear();
127        self.prefix_index.clear();
128    }
129}
130
131impl Default for DependencyGraph {
132    fn default() -> Self {
133        Self::new()
134    }
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140
141    #[test]
142    fn test_prefix_index_basic() {
143        use super::Binding;
144        use crate::reconcile::tree::InstanceTree;
145        use crate::ir::Element;
146
147        let mut graph = DependencyGraph::new();
148
149        // Create real NodeIds using InstanceTree
150        let mut tree = InstanceTree::new();
151        let node1 = tree.create_node(&Element::new("Text"), &serde_json::json!({}));
152        let node2 = tree.create_node(&Element::new("Text"), &serde_json::json!({}));
153        let node3 = tree.create_node(&Element::new("Text"), &serde_json::json!({}));
154
155        // Add dependencies
156        let binding1 = Binding::state(vec!["user".to_string()]);
157        let binding2 = Binding::state(vec!["user".to_string(), "name".to_string()]);
158        let binding3 = Binding::state(vec!["user".to_string(), "email".to_string()]);
159
160        graph.add_dependency(node1, &binding1);
161        graph.add_dependency(node2, &binding2);
162        graph.add_dependency(node3, &binding3);
163
164        // Verify prefix index was built correctly
165        assert!(graph.prefix_index.contains_key("user"));
166        assert!(graph.prefix_index.contains_key("user.name"));
167        assert!(graph.prefix_index.contains_key("user.email"));
168
169        // user prefix should contain all three paths
170        let user_paths = graph.prefix_index.get("user").unwrap();
171        assert_eq!(user_paths.len(), 3);
172        assert!(user_paths.contains("user"));
173        assert!(user_paths.contains("user.name"));
174        assert!(user_paths.contains("user.email"));
175    }
176
177    #[test]
178    fn test_get_affected_nodes_with_prefix_index() {
179        use super::Binding;
180        use crate::reconcile::tree::InstanceTree;
181        use crate::ir::Element;
182
183        let mut graph = DependencyGraph::new();
184
185        // Create real NodeIds using InstanceTree
186        let mut tree = InstanceTree::new();
187        let node1 = tree.create_node(&Element::new("Text"), &serde_json::json!({}));
188        let node2 = tree.create_node(&Element::new("Text"), &serde_json::json!({}));
189        let node3 = tree.create_node(&Element::new("Text"), &serde_json::json!({}));
190        let node4 = tree.create_node(&Element::new("Text"), &serde_json::json!({}));
191
192        // Add dependencies
193        graph.add_dependency(node1, &Binding::state(vec!["user".to_string()]));
194        graph.add_dependency(node2, &Binding::state(vec!["user".to_string(), "name".to_string()]));
195        graph.add_dependency(node3, &Binding::state(vec!["user".to_string(), "email".to_string()]));
196        graph.add_dependency(node4, &Binding::state(vec!["posts".to_string()]));
197
198        // When "user" changes, should affect node1, node2, and node3 (but not node4)
199        let affected = graph.get_affected_nodes("user");
200        assert_eq!(affected.len(), 3);
201        assert!(affected.contains(&node1));
202        assert!(affected.contains(&node2));
203        assert!(affected.contains(&node3));
204        assert!(!affected.contains(&node4));
205    }
206
207    #[test]
208    fn test_get_affected_nodes_child_change() {
209        use super::Binding;
210        use crate::reconcile::tree::InstanceTree;
211        use crate::ir::Element;
212
213        let mut graph = DependencyGraph::new();
214
215        // Create real NodeIds using InstanceTree
216        let mut tree = InstanceTree::new();
217        let node1 = tree.create_node(&Element::new("Text"), &serde_json::json!({}));
218        let node2 = tree.create_node(&Element::new("Text"), &serde_json::json!({}));
219
220        graph.add_dependency(node1, &Binding::state(vec!["user".to_string()]));
221        graph.add_dependency(node2, &Binding::state(vec!["user".to_string(), "name".to_string()]));
222
223        // When "user.name" changes, should affect both parent "user" and child "user.name"
224        let affected = graph.get_affected_nodes("user.name");
225        assert_eq!(affected.len(), 2);
226        assert!(affected.contains(&node1)); // parent "user" affected
227        assert!(affected.contains(&node2)); // exact match "user.name" affected
228    }
229
230    #[test]
231    fn test_get_affected_nodes_exact_match_only() {
232        use super::Binding;
233        use crate::reconcile::tree::InstanceTree;
234        use crate::ir::Element;
235
236        let mut graph = DependencyGraph::new();
237
238        // Create real NodeId using InstanceTree
239        let mut tree = InstanceTree::new();
240        let node1 = tree.create_node(&Element::new("Text"), &serde_json::json!({}));
241
242        graph.add_dependency(node1, &Binding::state(vec!["user".to_string(), "name".to_string()]));
243
244        // When "user.email" changes, should not affect "user.name"
245        let affected = graph.get_affected_nodes("user.email");
246        assert_eq!(affected.len(), 0);
247    }
248
249    #[test]
250    fn test_prefix_index_performance() {
251        use super::Binding;
252        use crate::reconcile::tree::InstanceTree;
253        use crate::ir::Element;
254
255        let mut graph = DependencyGraph::new();
256        let mut tree = InstanceTree::new();
257
258        // Add many dependencies with nested paths
259        for i in 0..100 {
260            let node_id = tree.create_node(&Element::new("Text"), &serde_json::json!({}));
261            let path = vec![
262                "user".to_string(),
263                "profile".to_string(),
264                "details".to_string(),
265                format!("field{}", i),
266            ];
267            let binding = Binding::state(path);
268            graph.add_dependency(node_id, &binding);
269        }
270
271        // Should efficiently find all affected nodes when parent changes
272        let affected = graph.get_affected_nodes("user");
273        assert_eq!(affected.len(), 100);
274
275        let affected = graph.get_affected_nodes("user.profile");
276        assert_eq!(affected.len(), 100);
277
278        let affected = graph.get_affected_nodes("user.profile.details");
279        assert_eq!(affected.len(), 100);
280    }
281
282    #[test]
283    fn test_clear_clears_prefix_index() {
284        use super::Binding;
285        use crate::reconcile::tree::InstanceTree;
286        use crate::ir::Element;
287
288        let mut graph = DependencyGraph::new();
289
290        // Create real NodeId using InstanceTree
291        let mut tree = InstanceTree::new();
292        let node = tree.create_node(&Element::new("Text"), &serde_json::json!({}));
293
294        graph.add_dependency(node, &Binding::state(vec!["user".to_string(), "name".to_string()]));
295        assert!(!graph.prefix_index.is_empty());
296
297        graph.clear();
298        assert!(graph.prefix_index.is_empty());
299        assert!(graph.dependencies.is_empty());
300        assert!(graph.node_bindings.is_empty());
301    }
302}