1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use std::{collections::HashMap, any::Any, cell::{RefCell, Cell}};

use crate::IdPathBuf;

// TODO: Use trees to model these id path keys (this should also allow us to take them by ref and delete subtrees easily)

/// A facility that manages view state internally.
pub struct Storage {
    state: RefCell<HashMap<(IdPathBuf, usize), Box<dyn Any>>>,
    changes: RefCell<HashMap<(IdPathBuf, usize), Box<dyn Any>>>,
    preapply: Cell<bool>,
    update_callback: RefCell<Option<Box<dyn Fn()>>>,
}

impl Storage {
    pub fn new() -> Self {
        Self {
            state: RefCell::new(HashMap::new()),
            changes: RefCell::new(HashMap::new()),
            preapply: Cell::new(false),
            update_callback: RefCell::new(None),
        }
    }

    pub(crate) fn initialize_if_needed<V>(&self, key: (IdPathBuf, usize), value: impl FnOnce() -> V) where V: 'static {
        if !self.state.borrow().contains_key(&key) {
            self.state.borrow_mut().insert(key, Box::new(value()));
        }
    }

    pub(crate) fn add_change<V>(&self, key: (IdPathBuf, usize), value: V) where V: 'static {
        self.changes.borrow_mut().insert(key, Box::new(value));
        self.fire_update_callback();
    }

    pub(crate) fn get<T>(&self, key: &(IdPathBuf, usize)) -> T where T: Clone + 'static {
        if self.preapply.get() && let Some(changed) = self.changes.borrow().get(key) {
            changed.downcast_ref::<T>().cloned()
        } else {
            self.state.borrow()[key].downcast_ref::<T>().cloned()
        }
        .expect("State has invalid type")
    }

    pub(crate) fn with_preapplied_changes<T>(&self, action: impl FnOnce() -> T) -> T {
        self.preapply.set(true);
        let result = action();
        self.preapply.set(false);
        result
    }

    pub(crate) fn apply_changes(&self) {
        let mut state = self.state.borrow_mut();
        for (key, value) in self.changes.borrow_mut().drain() {
            state.insert(key, value);
        }
    }

    fn fire_update_callback(&self) {
        if let Some(update_callback) = self.update_callback.borrow().as_ref() {
            update_callback();
        }
    }

    pub fn set_update_callback(&self, update_callback: impl Fn() + 'static) {
        *self.update_callback.borrow_mut() = Some(Box::new(update_callback));
    }
}