elvis_shared/tree/
state.rs

1use crate::Error;
2use std::collections::HashMap;
3
4/// store closures
5pub trait FnBox<P> {
6    /// Call function
7    fn call(&mut self, props: &P) -> Result<(), Error>;
8}
9
10/// Func hook
11type Hook<P> = Box<dyn FnBox<P>>;
12
13/// state for tree
14pub struct State<W, P> {
15    /// Host widget
16    pub widget: W,
17    /// Function Hook
18    pub trigger: Hook<P>,
19    state: HashMap<String, String>,
20}
21
22impl<W, P> State<W, P> {
23    /// New state
24    pub fn new(widget: W, trigger: Hook<P>) -> State<W, P> {
25        State {
26            state: HashMap::new(),
27            widget,
28            trigger,
29        }
30    }
31
32    /// Trigger function
33    pub fn process(&mut self, p: &P) -> Result<(), Error> {
34        self.trigger.call(p)
35    }
36
37    /// Get state
38    pub fn get(&self, k: String) -> String {
39        self.state.get(&k).unwrap_or(&"".to_string()).to_string()
40    }
41
42    /// Set state
43    pub fn set(&mut self, k: &str, v: &str) {
44        self.state.insert(k.to_string(), v.to_string());
45    }
46}