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::ir::Element;
145        use crate::reconcile::tree::InstanceTree;
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::ir::Element;
181        use crate::reconcile::tree::InstanceTree;
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(
195            node2,
196            &Binding::state(vec!["user".to_string(), "name".to_string()]),
197        );
198        graph.add_dependency(
199            node3,
200            &Binding::state(vec!["user".to_string(), "email".to_string()]),
201        );
202        graph.add_dependency(node4, &Binding::state(vec!["posts".to_string()]));
203
204        // When "user" changes, should affect node1, node2, and node3 (but not node4)
205        let affected = graph.get_affected_nodes("user");
206        assert_eq!(affected.len(), 3);
207        assert!(affected.contains(&node1));
208        assert!(affected.contains(&node2));
209        assert!(affected.contains(&node3));
210        assert!(!affected.contains(&node4));
211    }
212
213    #[test]
214    fn test_get_affected_nodes_child_change() {
215        use super::Binding;
216        use crate::ir::Element;
217        use crate::reconcile::tree::InstanceTree;
218
219        let mut graph = DependencyGraph::new();
220
221        // Create real NodeIds using InstanceTree
222        let mut tree = InstanceTree::new();
223        let node1 = tree.create_node(&Element::new("Text"), &serde_json::json!({}));
224        let node2 = tree.create_node(&Element::new("Text"), &serde_json::json!({}));
225
226        graph.add_dependency(node1, &Binding::state(vec!["user".to_string()]));
227        graph.add_dependency(
228            node2,
229            &Binding::state(vec!["user".to_string(), "name".to_string()]),
230        );
231
232        // When "user.name" changes, should affect both parent "user" and child "user.name"
233        let affected = graph.get_affected_nodes("user.name");
234        assert_eq!(affected.len(), 2);
235        assert!(affected.contains(&node1)); // parent "user" affected
236        assert!(affected.contains(&node2)); // exact match "user.name" affected
237    }
238
239    #[test]
240    fn test_get_affected_nodes_exact_match_only() {
241        use super::Binding;
242        use crate::ir::Element;
243        use crate::reconcile::tree::InstanceTree;
244
245        let mut graph = DependencyGraph::new();
246
247        // Create real NodeId using InstanceTree
248        let mut tree = InstanceTree::new();
249        let node1 = tree.create_node(&Element::new("Text"), &serde_json::json!({}));
250
251        graph.add_dependency(
252            node1,
253            &Binding::state(vec!["user".to_string(), "name".to_string()]),
254        );
255
256        // When "user.email" changes, should not affect "user.name"
257        let affected = graph.get_affected_nodes("user.email");
258        assert_eq!(affected.len(), 0);
259    }
260
261    #[test]
262    fn test_prefix_index_performance() {
263        use super::Binding;
264        use crate::ir::Element;
265        use crate::reconcile::tree::InstanceTree;
266
267        let mut graph = DependencyGraph::new();
268        let mut tree = InstanceTree::new();
269
270        // Add many dependencies with nested paths
271        for i in 0..100 {
272            let node_id = tree.create_node(&Element::new("Text"), &serde_json::json!({}));
273            let path = vec![
274                "user".to_string(),
275                "profile".to_string(),
276                "details".to_string(),
277                format!("field{}", i),
278            ];
279            let binding = Binding::state(path);
280            graph.add_dependency(node_id, &binding);
281        }
282
283        // Should efficiently find all affected nodes when parent changes
284        let affected = graph.get_affected_nodes("user");
285        assert_eq!(affected.len(), 100);
286
287        let affected = graph.get_affected_nodes("user.profile");
288        assert_eq!(affected.len(), 100);
289
290        let affected = graph.get_affected_nodes("user.profile.details");
291        assert_eq!(affected.len(), 100);
292    }
293
294    #[test]
295    fn test_clear_clears_prefix_index() {
296        use super::Binding;
297        use crate::ir::Element;
298        use crate::reconcile::tree::InstanceTree;
299
300        let mut graph = DependencyGraph::new();
301
302        // Create real NodeId using InstanceTree
303        let mut tree = InstanceTree::new();
304        let node = tree.create_node(&Element::new("Text"), &serde_json::json!({}));
305
306        graph.add_dependency(
307            node,
308            &Binding::state(vec!["user".to_string(), "name".to_string()]),
309        );
310        assert!(!graph.prefix_index.is_empty());
311
312        graph.clear();
313        assert!(graph.prefix_index.is_empty());
314        assert!(graph.dependencies.is_empty());
315        assert!(graph.node_bindings.is_empty());
316    }
317}