use quilt_cell::Cell;
use std::collections::{HashMap, HashSet};
#[derive(Debug, Clone, Default)]
pub struct ReactiveGraph {
pub cells: HashMap<String, Cell>,
pub dependencies: HashMap<String, HashSet<String>>,
pub dirty: HashSet<String>,
}
impl ReactiveGraph {
pub fn new() -> Self { Self::default() }
pub fn add(&mut self, name: &str, kind: &str) {
let cell = Cell::new(name).with_kind(kind);
self.cells.insert(name.to_string(), cell);
self.dependencies.entry(name.to_string()).or_default();
}
pub fn depends_on(&mut self, name: &str, dep: &str) {
self.dependencies.entry(name.to_string()).or_default().insert(dep.to_string());
}
pub fn mark_dirty(&mut self, name: &str) {
self.dirty.insert(name.to_string());
}
pub fn tick_dirty(&mut self) -> usize {
let count = self.dirty.len();
let dirty: Vec<String> = self.dirty.drain().collect();
for name in dirty {
if let Some(cell) = self.cells.get_mut(&name) {
cell.tick();
}
}
count
}
pub fn cell_count(&self) -> usize { self.cells.len() }
pub fn dirty_count(&self) -> usize { self.dirty.len() }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_reactive() {
let mut g = ReactiveGraph::new();
g.add("a", "number");
g.add("b", "formula");
g.depends_on("b", "a");
g.mark_dirty("a");
assert_eq!(g.dirty_count(), 1);
let n = g.tick_dirty();
assert_eq!(n, 1);
}
}