Skip to main content

lexical_ui/
ref_counted_registry.rs

1//! `LexicalRefCountedRegistry.ts`: registrations reference counted by key.
2
3use crate::Unregister;
4use std::cell::{Cell, RefCell};
5use std::rc::Rc;
6
7/// What a key's activation returned, and its live registrations' tokens.
8struct Entry {
9    holders: Vec<u64>,
10    dispose: Option<Unregister>,
11}
12
13/// `activate(key, options)`.
14type Activate<K, O> = Box<dyn Fn(&K, Option<O>) -> Unregister>;
15
16struct Inner<K, O> {
17    activate: Activate<K, O>,
18    /// By key, in the order first registered (JS's `Map`).
19    entries: RefCell<Vec<(K, Entry)>>,
20    next_token: Cell<u64>,
21}
22
23/// `RefCountedRegistry<Key, Options>`: the first registration of a key runs
24/// the activation; what it returned runs once the last registration of
25/// that key is released. A handle; cloning it shares the registry.
26pub struct RefCountedRegistry<K, O = ()>(Rc<Inner<K, O>>);
27
28impl<K, O> Clone for RefCountedRegistry<K, O> {
29    fn clone(&self) -> Self {
30        Self(self.0.clone())
31    }
32}
33
34/// `createRefCountedRegistry(activate)`.
35pub fn create_ref_counted_registry<K: PartialEq + Clone + 'static, O: 'static>(
36    activate: impl Fn(&K, Option<O>) -> Unregister + 'static,
37) -> RefCountedRegistry<K, O> {
38    RefCountedRegistry(Rc::new(Inner {
39        activate: Box::new(activate),
40        entries: RefCell::new(Vec::new()),
41        next_token: Cell::new(0),
42    }))
43}
44
45impl<K: PartialEq + Clone + 'static, O: 'static> RefCountedRegistry<K, O> {
46    /// `register(key, options)`: registers `key` and returns its disposer.
47    /// `options` are read only by the activating (first) registration of
48    /// the key. A stale disposer (one called after the registry was
49    /// disposed or the key registered again) does nothing.
50    pub fn register(&self, key: K, options: Option<O>) -> Unregister {
51        let exists = self.0.entries.borrow().iter().any(|(k, _)| *k == key);
52        if !exists {
53            // The activation may register other keys, so it runs without
54            // the entries borrowed.
55            let dispose = (self.0.activate)(&key, options);
56            self.0.entries.borrow_mut().push((
57                key.clone(),
58                Entry {
59                    holders: Vec::new(),
60                    dispose: Some(dispose),
61                },
62            ));
63        }
64        let token = self.0.next_token.replace(self.0.next_token.get() + 1);
65        if let Some((_, entry)) = self
66            .0
67            .entries
68            .borrow_mut()
69            .iter_mut()
70            .find(|(k, _)| *k == key)
71        {
72            entry.holders.push(token);
73        }
74        let weak = Rc::downgrade(&self.0);
75        Box::new(move || {
76            let Some(inner) = weak.upgrade() else { return };
77            let dispose = {
78                let mut entries = inner.entries.borrow_mut();
79                let Some(index) = entries.iter().position(|(k, _)| *k == key) else {
80                    return;
81                };
82                let entry = &mut entries[index].1;
83                let Some(at) = entry.holders.iter().position(|t| *t == token) else {
84                    return;
85                };
86                entry.holders.remove(at);
87                if !entry.holders.is_empty() {
88                    return;
89                }
90                entries.remove(index).1.dispose
91            };
92            if let Some(dispose) = dispose {
93                dispose();
94            }
95        })
96    }
97
98    /// `dispose()`: disposes every live registration and clears the
99    /// registry.
100    pub fn dispose(&self) {
101        let entries = std::mem::take(&mut *self.0.entries.borrow_mut());
102        for (_, entry) in entries {
103            if let Some(dispose) = entry.dispose {
104                dispose();
105            }
106        }
107    }
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113
114    fn registry(log: &Rc<RefCell<Vec<String>>>) -> RefCountedRegistry<&'static str, u32> {
115        let log = log.clone();
116        create_ref_counted_registry(move |key: &&'static str, options: Option<u32>| {
117            log.borrow_mut().push(format!("activate {key} {options:?}"));
118            let log = log.clone();
119            let key = *key;
120            Box::new(move || log.borrow_mut().push(format!("dispose {key}")))
121        })
122    }
123
124    #[test]
125    fn the_last_release_disposes_the_activation() {
126        let log = Rc::new(RefCell::new(Vec::new()));
127        let registry = registry(&log);
128        let a = registry.register("a", Some(1));
129        // Later options are ignored while the key is live.
130        let b = registry.register("a", Some(2));
131        a();
132        assert_eq!(*log.borrow(), ["activate a Some(1)"]);
133        b();
134        assert_eq!(*log.borrow(), ["activate a Some(1)", "dispose a"]);
135        // Registering again activates again, with the new options.
136        let c = registry.register("a", Some(3));
137        c();
138        assert_eq!(
139            *log.borrow(),
140            [
141                "activate a Some(1)",
142                "dispose a",
143                "activate a Some(3)",
144                "dispose a"
145            ]
146        );
147    }
148
149    #[test]
150    fn a_stale_release_does_nothing() {
151        let log = Rc::new(RefCell::new(Vec::new()));
152        let registry = registry(&log);
153        let stale = registry.register("a", None);
154        let other = registry.register("b", None);
155        registry.dispose();
156        assert_eq!(
157            *log.borrow(),
158            [
159                "activate a None",
160                "activate b None",
161                "dispose a",
162                "dispose b"
163            ]
164        );
165        let live = registry.register("a", None);
166        stale();
167        other();
168        assert_eq!(log.borrow().len(), 5);
169        live();
170        assert_eq!(log.borrow().last().unwrap(), "dispose a");
171    }
172}