Skip to main content

quilt_react/
lib.rs

1//! quilt-react — reactive cell graph. Automatic re-computation on dependency change.
2
3use quilt_cell::Cell;
4use std::collections::{HashMap, HashSet};
5
6#[derive(Debug, Clone, Default)]
7pub struct ReactiveGraph {
8    pub cells: HashMap<String, Cell>,
9    pub dependencies: HashMap<String, HashSet<String>>,
10    pub dirty: HashSet<String>,
11}
12
13impl ReactiveGraph {
14    pub fn new() -> Self { Self::default() }
15    pub fn add(&mut self, name: &str, kind: &str) {
16        let cell = Cell::new(name).with_kind(kind);
17        self.cells.insert(name.to_string(), cell);
18        self.dependencies.entry(name.to_string()).or_default();
19    }
20    pub fn depends_on(&mut self, name: &str, dep: &str) {
21        self.dependencies.entry(name.to_string()).or_default().insert(dep.to_string());
22    }
23    pub fn mark_dirty(&mut self, name: &str) {
24        self.dirty.insert(name.to_string());
25    }
26    pub fn tick_dirty(&mut self) -> usize {
27        let count = self.dirty.len();
28        let dirty: Vec<String> = self.dirty.drain().collect();
29        for name in dirty {
30            if let Some(cell) = self.cells.get_mut(&name) {
31                cell.tick();
32            }
33        }
34        count
35    }
36    pub fn cell_count(&self) -> usize { self.cells.len() }
37    pub fn dirty_count(&self) -> usize { self.dirty.len() }
38}
39
40#[cfg(test)]
41mod tests {
42    use super::*;
43    #[test]
44    fn test_reactive() {
45        let mut g = ReactiveGraph::new();
46        g.add("a", "number");
47        g.add("b", "formula");
48        g.depends_on("b", "a");
49        g.mark_dirty("a");
50        assert_eq!(g.dirty_count(), 1);
51        let n = g.tick_dirty();
52        assert_eq!(n, 1);
53    }
54}