Skip to main content

plexus_ui_engine/signals/
mod.rs

1//! UI-6: **the signal runtime** — no framework. A [`Signal<T>`] holds a
2//! value; a binding ([`Runtime::bind`]) is a closure that is run once, its
3//! reads of signals tracked, and run again exactly when one of the signals
4//! it read last time is set to a different value. Nothing else re-runs.
5//!
6//! Each run tracks afresh, so a binding that reads `y` only when `x` holds
7//! is not woken by `y` while `x` does not. A binding made while another
8//! runs is its own (its reads are its own); bindings woken together run
9//! oldest first, so an outer binding that disposes an inner one runs before
10//! it. [`Runtime::untracked`] reads without tracking.
11//!
12//! Single-threaded (the page's one thread): handles are `Rc`s.
13
14use std::any::Any;
15use std::cell::{Cell, RefCell};
16use std::collections::{BTreeMap, BTreeSet};
17use std::marker::PhantomData;
18use std::rc::Rc;
19
20/// A binding's handle: [`Runtime::dispose`] stops it.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
22pub struct BindingId(pub u64);
23
24/// No binding: what [`Runtime::untracked`] pushes.
25const NONE: u64 = 0;
26
27struct Slot {
28    value: Rc<dyn Any>,
29    readers: BTreeSet<u64>,
30}
31
32struct Binding {
33    /// Taken while it runs.
34    f: Option<Box<dyn FnMut()>>,
35    deps: BTreeSet<u64>,
36}
37
38#[derive(Default)]
39struct Inner {
40    signals: RefCell<Vec<Slot>>,
41    bindings: RefCell<BTreeMap<u64, Binding>>,
42    next_binding: Cell<u64>,
43    stack: RefCell<Vec<u64>>,
44    pending: RefCell<BTreeSet<u64>>,
45    batch: Cell<u32>,
46    flushing: Cell<bool>,
47    runs: Cell<u64>,
48}
49
50/// The runtime: every signal and binding of one page (or one test).
51#[derive(Clone, Default)]
52pub struct Runtime {
53    inner: Rc<Inner>,
54}
55
56impl std::fmt::Debug for Runtime {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        write!(f, "Runtime({} signals, {} bindings)", self.inner.signals.borrow().len(), self.inner.bindings.borrow().len())
59    }
60}
61
62impl Runtime {
63    /// A runtime with no signals.
64    pub fn new() -> Self {
65        Self::default()
66    }
67
68    /// A signal holding `value`.
69    pub fn signal<T: Clone + PartialEq + 'static>(&self, value: T) -> Signal<T> {
70        let mut signals = self.inner.signals.borrow_mut();
71        signals.push(Slot { value: Rc::new(value), readers: BTreeSet::new() });
72        Signal { id: signals.len() as u64 - 1, rt: self.clone(), _t: PhantomData }
73    }
74
75    /// Runs `f` now, tracking the signals it reads, and again whenever one
76    /// of them changes.
77    pub fn bind(&self, f: impl FnMut() + 'static) -> BindingId {
78        let id = self.inner.next_binding.get() + 1;
79        self.inner.next_binding.set(id);
80        self.inner.bindings.borrow_mut().insert(id, Binding { f: Some(Box::new(f)), deps: BTreeSet::new() });
81        self.run(id);
82        BindingId(id)
83    }
84
85    /// Stops the binding: it never runs again, and its reads are forgotten.
86    pub fn dispose(&self, id: BindingId) {
87        let Some(b) = self.inner.bindings.borrow_mut().remove(&id.0) else { return };
88        let mut signals = self.inner.signals.borrow_mut();
89        for d in b.deps {
90            signals[d as usize].readers.remove(&id.0);
91        }
92        self.inner.pending.borrow_mut().remove(&id.0);
93    }
94
95    /// Runs `f` with every set inside it batched: each binding runs once
96    /// after `f`, however many of its signals moved.
97    pub fn batch<R>(&self, f: impl FnOnce() -> R) -> R {
98        self.inner.batch.set(self.inner.batch.get() + 1);
99        let r = f();
100        self.inner.batch.set(self.inner.batch.get() - 1);
101        self.flush();
102        r
103    }
104
105    /// Runs `f` reading signals without tracking them.
106    pub fn untracked<R>(&self, f: impl FnOnce() -> R) -> R {
107        self.inner.stack.borrow_mut().push(NONE);
108        let r = f();
109        self.inner.stack.borrow_mut().pop();
110        r
111    }
112
113    /// How many times any binding has run — the tests' evaluation counter.
114    pub fn runs(&self) -> u64 {
115        self.inner.runs.get()
116    }
117
118    /// How many bindings are live.
119    pub fn bindings(&self) -> usize {
120        self.inner.bindings.borrow().len()
121    }
122
123    fn run(&self, id: u64) {
124        let f = {
125            let mut bindings = self.inner.bindings.borrow_mut();
126            let Some(b) = bindings.get_mut(&id) else { return };
127            let deps = std::mem::take(&mut b.deps);
128            let f = b.f.take();
129            drop(bindings);
130            let mut signals = self.inner.signals.borrow_mut();
131            for d in deps {
132                signals[d as usize].readers.remove(&id);
133            }
134            f
135        };
136        let Some(mut f) = f else { return };
137        self.inner.stack.borrow_mut().push(id);
138        self.inner.runs.set(self.inner.runs.get() + 1);
139        f();
140        self.inner.stack.borrow_mut().pop();
141        if let Some(b) = self.inner.bindings.borrow_mut().get_mut(&id) {
142            b.f = Some(f);
143        }
144    }
145
146    fn track(&self, signal: u64) {
147        let top = self.inner.stack.borrow().last().copied().unwrap_or(NONE);
148        if top == NONE {
149            return;
150        }
151        if let Some(b) = self.inner.bindings.borrow_mut().get_mut(&top) {
152            b.deps.insert(signal);
153            self.inner.signals.borrow_mut()[signal as usize].readers.insert(top);
154        }
155    }
156
157    fn wake(&self, signal: u64) {
158        let readers = std::mem::take(&mut self.inner.signals.borrow_mut()[signal as usize].readers);
159        self.inner.pending.borrow_mut().extend(readers);
160        self.flush();
161    }
162
163    fn flush(&self) {
164        if self.inner.batch.get() > 0 || self.inner.flushing.get() {
165            return;
166        }
167        self.inner.flushing.set(true);
168        loop {
169            let next = self.inner.pending.borrow_mut().pop_first();
170            match next {
171                Some(id) => self.run(id),
172                None => break,
173            }
174        }
175        self.inner.flushing.set(false);
176    }
177}
178
179/// A value bindings read.
180pub struct Signal<T> {
181    id: u64,
182    rt: Runtime,
183    _t: PhantomData<T>,
184}
185
186impl<T> Clone for Signal<T> {
187    fn clone(&self) -> Self {
188        Self { id: self.id, rt: self.rt.clone(), _t: PhantomData }
189    }
190}
191
192impl<T> std::fmt::Debug for Signal<T> {
193    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
194        write!(f, "Signal({})", self.id)
195    }
196}
197
198impl<T: Clone + PartialEq + 'static> Signal<T> {
199    /// Its value — tracked: the binding running now reads it.
200    pub fn get(&self) -> T {
201        self.rt.track(self.id);
202        self.peek()
203    }
204
205    /// FRAME-17: `f` of its value, borrowed — tracked, and never cloned.
206    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
207        self.rt.track(self.id);
208        let v = self.shared_untracked();
209        f(v.downcast_ref::<T>().expect("a signal holds its own type"))
210    }
211
212    /// FRAME-17: its value as held — tracked; the same `Rc` until it is
213    /// set again, so a reader may keep what it made of it and know when
214    /// that is stale (`Rc::ptr_eq`).
215    pub fn shared(&self) -> Rc<dyn Any> {
216        self.rt.track(self.id);
217        self.shared_untracked()
218    }
219
220    fn shared_untracked(&self) -> Rc<dyn Any> {
221        self.rt.inner.signals.borrow()[self.id as usize].value.clone()
222    }
223
224    /// Its value, untracked.
225    pub fn peek(&self) -> T {
226        let v = self.rt.inner.signals.borrow()[self.id as usize].value.clone();
227        v.downcast_ref::<T>().expect("a signal holds its own type").clone()
228    }
229
230    /// Sets it; the bindings that read it run again when the value differs.
231    pub fn set(&self, value: T) {
232        self.set_if(value);
233    }
234
235    /// FRAME-20: [`Self::set`], answering whether the value differed (and
236    /// so whether its bindings ran again).
237    pub fn set_if(&self, value: T) -> bool {
238        {
239            let mut signals = self.rt.inner.signals.borrow_mut();
240            let slot = &mut signals[self.id as usize];
241            if slot.value.downcast_ref::<T>() == Some(&value) {
242                return false;
243            }
244            slot.value = Rc::new(value);
245        }
246        self.rt.wake(self.id);
247        true
248    }
249
250    /// Sets it to `f` of its value.
251    pub fn update(&self, f: impl FnOnce(&mut T)) {
252        let mut v = self.peek();
253        f(&mut v);
254        self.set(v);
255    }
256}
257
258#[cfg(test)]
259mod tests;