Skip to main content

crabshell_reactive/
signal.rs

1//! Signals: values you set, and read-only views of them.
2
3use std::cell::RefCell;
4use std::marker::PhantomData;
5use std::rc::Rc;
6
7use crate::handle::{Marker, handle_impls};
8use crate::runtime::{self, NodeId, drop_isolated};
9
10/// A value you set. A memo or effect that reads it reruns after it changes.
11///
12/// Create one with [`Owner::signal`](crate::Owner::signal). The handle is a
13/// small `Copy` key, so closures capture it by value. The value itself lives
14/// in this thread's runtime until the signal's owner is disposed.
15pub struct Signal<T> {
16  id: NodeId,
17  _marker: Marker<T>,
18}
19
20handle_impls!(Signal<T>);
21
22impl<T: 'static> Signal<T> {
23  #[track_caller]
24  pub(crate) fn new(owner: NodeId, value: T) -> Self {
25    let value: Rc<RefCell<Option<T>>> = Rc::new(RefCell::new(Some(value)));
26    Signal {
27      id: runtime::create_signal(owner, value),
28      _marker: PhantomData,
29    }
30  }
31
32  /// How many memos and effects read this on their last run.
33  #[cfg(test)]
34  pub(crate) fn subscriber_count(&self) -> usize {
35    runtime::subscriber_count(self.id)
36  }
37
38  /// The slot index and version of this signal's key.
39  #[cfg(test)]
40  pub(crate) fn slot(&self) -> (u32, u32) {
41    runtime::slot_of(self.id)
42  }
43
44  /// A read-only view of this signal, for code that should only read it.
45  pub fn read_only(&self) -> ReadSignal<T> {
46    ReadSignal {
47      id: self.id,
48      _marker: PhantomData,
49    }
50  }
51
52  /// Returns a clone of the value. Inside a memo or effect, this makes it
53  /// depend on the signal.
54  ///
55  /// # Panics
56  ///
57  /// If the signal's owner was disposed. [`try_get`](Self::try_get)
58  /// returns `None` instead.
59  #[track_caller]
60  pub fn get(&self) -> T
61  where
62    T: Clone,
63  {
64    self.with(T::clone)
65  }
66
67  /// Calls `f` with a reference to the value, without cloning it. Inside a
68  /// memo or effect, this makes it depend on the signal.
69  ///
70  /// # Panics
71  ///
72  /// If the signal's owner was disposed, or if `f` writes this signal.
73  #[track_caller]
74  pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
75    runtime::read_or_panic(self.id, true, "Signal", f)
76  }
77
78  /// Like [`get`](Self::get), but records no dependency.
79  #[track_caller]
80  pub fn get_untracked(&self) -> T
81  where
82    T: Clone,
83  {
84    self.with_untracked(T::clone)
85  }
86
87  /// Like [`with`](Self::with), but records no dependency.
88  #[track_caller]
89  pub fn with_untracked<R>(&self, f: impl FnOnce(&T) -> R) -> R {
90    runtime::read_or_panic(self.id, false, "Signal", f)
91  }
92
93  /// Like [`get`](Self::get), but returns `None` if the owner was disposed.
94  #[track_caller]
95  pub fn try_get(&self) -> Option<T>
96  where
97    T: Clone,
98  {
99    self.try_with(T::clone)
100  }
101
102  /// Like [`with`](Self::with), but returns `None` if the owner was
103  /// disposed.
104  #[track_caller]
105  pub fn try_with<R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
106    runtime::read(self.id, true, "Signal", f).ok()
107  }
108
109  /// Stores a new value, marks every memo and effect that read this signal
110  /// as stale, and queues the effects. Nothing runs until the next
111  /// [`Runtime::flush`](crate::Runtime::flush). Dependents are notified
112  /// even when the new value equals the old one.
113  ///
114  /// # Panics
115  ///
116  /// If the signal's owner was disposed, if this runs inside a memo (use an
117  /// effect to write signals), or if it runs inside a [`with`](Self::with)
118  /// call on the same signal.
119  #[track_caller]
120  pub fn set(&self, value: T) {
121    if let Some(old) = runtime::write_or_panic(self.id, |slot: &mut Option<T>| slot.replace(value))
122    {
123      drop_isolated(old);
124    }
125  }
126
127  /// Changes the value in place, then notifies like [`set`](Self::set).
128  ///
129  /// # Panics
130  ///
131  /// Like [`set`](Self::set), and also if `f` reads this signal.
132  #[track_caller]
133  pub fn update(&self, f: impl FnOnce(&mut T)) {
134    runtime::write_or_panic(self.id, |slot: &mut Option<T>| update_slot(slot, f));
135  }
136
137  /// Like [`set`](Self::set), but if the owner was disposed it does
138  /// nothing and returns `false`.
139  #[track_caller]
140  pub fn try_set(&self, value: T) -> bool {
141    match runtime::write(self.id, |slot: &mut Option<T>| slot.replace(value)) {
142      Ok(old) => {
143        drop_isolated(old);
144        true
145      }
146      Err(_) => false,
147    }
148  }
149
150  /// Like [`update`](Self::update), but if the owner was disposed it does
151  /// nothing and returns `false`.
152  #[track_caller]
153  pub fn try_update(&self, f: impl FnOnce(&mut T)) -> bool {
154    runtime::write(self.id, |slot: &mut Option<T>| update_slot(slot, f)).is_ok()
155  }
156
157  /// Gives the signal a debug name, such as a widget path.
158  pub fn named(self, name: impl Into<String>) -> Self {
159    runtime::set_name(self.id, name.into());
160    self
161  }
162}
163
164fn update_slot<T>(slot: &mut Option<T>, f: impl FnOnce(&mut T)) {
165  f(slot
166    .as_mut()
167    .expect("invariant: a signal always holds a value"));
168}
169
170/// A read-only view of a [`Signal`], made with [`Signal::read_only`].
171/// Services hand these out so only they can change the value.
172pub struct ReadSignal<T> {
173  id: NodeId,
174  _marker: Marker<T>,
175}
176
177handle_impls!(ReadSignal<T>);
178
179impl<T: 'static> ReadSignal<T> {
180  /// See [`Signal::get`].
181  #[track_caller]
182  pub fn get(&self) -> T
183  where
184    T: Clone,
185  {
186    self.with(T::clone)
187  }
188
189  /// See [`Signal::with`].
190  #[track_caller]
191  pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
192    runtime::read_or_panic(self.id, true, "ReadSignal", f)
193  }
194
195  /// See [`Signal::get_untracked`].
196  #[track_caller]
197  pub fn get_untracked(&self) -> T
198  where
199    T: Clone,
200  {
201    self.with_untracked(T::clone)
202  }
203
204  /// See [`Signal::with_untracked`].
205  #[track_caller]
206  pub fn with_untracked<R>(&self, f: impl FnOnce(&T) -> R) -> R {
207    runtime::read_or_panic(self.id, false, "ReadSignal", f)
208  }
209
210  /// See [`Signal::try_get`].
211  #[track_caller]
212  pub fn try_get(&self) -> Option<T>
213  where
214    T: Clone,
215  {
216    self.try_with(T::clone)
217  }
218
219  /// See [`Signal::try_with`].
220  #[track_caller]
221  pub fn try_with<R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
222    runtime::read(self.id, true, "ReadSignal", f).ok()
223  }
224}