Skip to main content

euv_core/reactive/selector/
impl.rs

1use super::*;
2
3/// Keyed O(1) selection operations for `Selector<K>`.
4impl<K> Selector<K>
5where
6    K: Clone + Eq + Hash + 'static,
7{
8    /// Creates a selector tracking the key returned by `source`.
9    ///
10    /// # Arguments
11    ///
12    /// - `F` - Reactive key producer closure.
13    ///
14    /// # Returns
15    ///
16    /// - `Self` - Selector instance supporting O(1) per-key selection checks.
17    #[must_use]
18    pub fn new<F>(mut source: F) -> Self
19    where
20        F: FnMut() -> K + 'static,
21    {
22        let active: Rc<RefCell<Option<K>>> = Rc::new(RefCell::new(None));
23        let subscribers: Rc<RefCell<HashMap<K, Signal<bool>>>> =
24            Rc::new(RefCell::new(HashMap::new()));
25        let active_clone: Rc<RefCell<Option<K>>> = active.clone();
26        let subs_clone: Rc<RefCell<HashMap<K, Signal<bool>>>> = subscribers.clone();
27        let watcher: Effect = Effect::new(move || {
28            let next_key: K = source();
29            let prev_key: Option<K> = active_clone
30                .try_borrow_mut()
31                .ok()
32                .and_then(|mut guard: RefMut<'_, Option<K>>| guard.replace(next_key.clone()));
33            if prev_key.as_ref() == Some(&next_key) {
34                return;
35            }
36            let (old_sig, new_sig): (Option<Signal<bool>>, Option<Signal<bool>>) = subs_clone
37                .try_borrow()
38                .ok()
39                .map(|map: Ref<'_, HashMap<K, Signal<bool>>>| {
40                    let old_s: Option<Signal<bool>> =
41                        prev_key.as_ref().and_then(|k: &K| map.get(k).copied());
42                    let new_s: Option<Signal<bool>> = map.get(&next_key).copied();
43                    (old_s, new_s)
44                })
45                .unwrap_or((None, None));
46            match (old_sig, new_sig) {
47                (Some(old_s), Some(new_s)) => {
48                    batch(|| {
49                        let _: bool = old_s.set(false);
50                        let _: bool = new_s.set(true);
51                    });
52                }
53                (Some(old_s), None) => {
54                    let _: bool = old_s.set(false);
55                }
56                (None, Some(new_s)) => {
57                    let _: bool = new_s.set(true);
58                }
59                (None, None) => {}
60            }
61        });
62        Self {
63            active,
64            subscribers,
65            watcher,
66        }
67    }
68
69    /// Reactively returns whether `key` is currently selected, subscribing only to `key`.
70    ///
71    /// # Arguments
72    ///
73    /// - `&Self` - Selector reference.
74    /// - `K` - Key to test for active selection.
75    ///
76    /// # Returns
77    ///
78    /// - `bool` - True when `key` equals the active selected key.
79    #[must_use]
80    pub fn is_selected(&self, key: K) -> bool {
81        let Self {
82            active,
83            subscribers,
84            ..
85        } = self;
86        let existing: Option<Signal<bool>> = subscribers
87            .try_borrow()
88            .ok()
89            .and_then(|map: Ref<'_, HashMap<K, Signal<bool>>>| map.get(&key).copied());
90        let sig: Signal<bool> = match existing {
91            Some(found) => found,
92            None => {
93                let is_active: bool = active
94                    .try_borrow()
95                    .ok()
96                    .and_then(|guard: Ref<'_, Option<K>>| guard.as_ref().map(|cur: &K| *cur == key))
97                    .unwrap_or(false);
98                let created: Signal<bool> = Signal::new(is_active);
99                if let Ok(mut map) = subscribers.try_borrow_mut() {
100                    map.insert(key, created);
101                }
102                created
103            }
104        };
105        sig.get()
106    }
107
108    /// Disposes the selector's watcher effect and per-key signals.
109    ///
110    /// # Arguments
111    ///
112    /// - `&Self` - Selector to dispose.
113    pub fn dispose(&self) {
114        let Self {
115            subscribers,
116            watcher,
117            ..
118        } = self;
119        watcher.dispose();
120        let signals: Vec<Signal<bool>> = subscribers
121            .try_borrow_mut()
122            .ok()
123            .map(|mut map: RefMut<'_, HashMap<K, Signal<bool>>>| {
124                map.drain().map(|(_, s): (K, Signal<bool>)| s).collect()
125            })
126            .unwrap_or_default();
127        for sig in signals.into_iter() {
128            sig.dispose();
129        }
130    }
131}