1#[macro_export]
35macro_rules! tls_group {
36 ($( $(#[$attr:meta])* $vis:vis static $name:ident : $ty:ty = $init:expr ; )+) => {
37 #[allow(non_snake_case)]
38 struct TlsGroupSlots { $( $name: $ty, )+ }
39 ::std::thread_local! {
40 static TLS_GROUP: TlsGroupSlots = TlsGroupSlots { $( $name: $init, )+ };
41 }
42 $(
43 $(#[$attr])*
44 #[allow(non_camel_case_types, dead_code)]
45 #[derive(Clone, Copy)]
46 $vis struct $name;
47 impl $name {
48 #[inline]
49 #[allow(dead_code)]
50 $vis fn with<R>(self, f: impl ::core::ops::FnOnce(&$ty) -> R) -> R {
51 TLS_GROUP.with(|g| f(&g.$name))
52 }
53 #[inline]
54 #[allow(dead_code)]
55 $vis fn try_with<R>(
56 self,
57 f: impl ::core::ops::FnOnce(&$ty) -> R,
58 ) -> ::core::result::Result<R, ::std::thread::AccessError> {
59 TLS_GROUP.try_with(|g| f(&g.$name))
60 }
61 }
62 )+
63 };
64}
65
66#[macro_export]
78macro_rules! tls_root {
79 ($( $(#[$attr:meta])* $field:ident : $ty:ty ),+ $(,)?) => {
80 #[allow(non_snake_case)]
81 pub(crate) struct TlsRoot { $( $(#[$attr])* pub(crate) $field: $ty, )+ }
82 ::std::thread_local! {
83 static TLS_ROOT: TlsRoot =
84 TlsRoot { $( $(#[$attr])* $field: ::core::default::Default::default(), )+ };
85 }
86 #[inline]
89 pub(crate) fn tls_root<R>(f: impl ::core::ops::FnOnce(&TlsRoot) -> R) -> R {
90 TLS_ROOT.with(f)
91 }
92 #[inline]
94 #[allow(dead_code)]
95 pub(crate) fn try_tls_root<R>(
96 f: impl ::core::ops::FnOnce(&TlsRoot) -> R,
97 ) -> ::core::result::Result<R, ::std::thread::AccessError> {
98 TLS_ROOT.try_with(f)
99 }
100 };
101}
102
103#[allow(clippy::crate_in_macro_def)]
108#[macro_export]
109macro_rules! tls_slots {
110 ($field:ident; $( $(#[$attr:meta])* $vis:vis static $name:ident : $ty:ty = $init:expr ; )+) => {
111 #[allow(non_snake_case)]
112 pub(crate) struct TlsGroupSlots { $( $name: $ty, )+ }
113 impl ::core::default::Default for TlsGroupSlots {
114 fn default() -> Self { Self { $( $name: $init, )+ } }
115 }
116 $(
117 $(#[$attr])*
118 #[allow(non_camel_case_types, dead_code)]
119 #[derive(Clone, Copy)]
120 $vis struct $name;
121 impl $name {
122 #[inline]
123 #[allow(dead_code)]
124 $vis fn with<R>(self, f: impl ::core::ops::FnOnce(&$ty) -> R) -> R {
125 crate::tls_root(|r| f(&r.$field.$name))
126 }
127 #[inline]
128 #[allow(dead_code)]
129 $vis fn try_with<R>(
130 self,
131 f: impl ::core::ops::FnOnce(&$ty) -> R,
132 ) -> ::core::result::Result<R, ::std::thread::AccessError> {
133 crate::try_tls_root(|r| f(&r.$field.$name))
134 }
135 }
136 )+
137 };
138}
139
140use std::any::{Any, TypeId};
141use std::cell::{Cell, RefCell};
142use std::collections::{HashMap, HashSet};
143use std::future::Future;
144use std::marker::PhantomData;
145use std::panic::Location;
146use std::pin::Pin;
147use std::rc::Rc;
148use std::sync::Arc;
149
150use slotmap::{Key, SlotMap, new_key_type};
151
152new_key_type! {
153 pub struct NodeKey;
154 pub struct ScopeKey;
155}
156
157#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
162enum NodeState {
163 Clean,
164 Check,
165 Dirty,
166}
167
168#[derive(Clone, Copy, PartialEq, Eq)]
169enum NodeKind {
170 Signal,
171 Memo,
172 Reaction,
174}
175
176type MemoEq = fn(&dyn Any, &dyn Any) -> bool;
178
179type NodeValue = Rc<RefCell<Box<dyn Any>>>;
188
189struct Node {
190 kind: NodeKind,
191 state: NodeState,
192 value: Option<NodeValue>,
193 memo_compute: Option<Rc<dyn Fn() -> Box<dyn Any>>>,
195 memo_eq: Option<MemoEq>,
196 reaction: Option<Rc<dyn Fn()>>,
198 sources: Vec<NodeKey>,
199 run_cleanups: Vec<Box<dyn FnOnce()>>,
203 observers: Vec<NodeKey>,
204 scope: ScopeKey,
206 priority: u8,
208 depth: u32,
209 seq: u64,
210 last_changed: u64,
211 last_run: u64,
212 queued: bool,
213 created_at: &'static Location<'static>,
214}
215
216struct ScopeData {
217 parent: ScopeKey,
218 children: Vec<ScopeKey>,
219 nodes: Vec<NodeKey>,
220 cleanups: Vec<Box<dyn FnOnce()>>,
221 context: HashMap<TypeId, Box<dyn Any>>,
222 depth: u32,
223}
224
225struct Runtime {
226 nodes: SlotMap<NodeKey, Node>,
227 scopes: SlotMap<ScopeKey, ScopeData>,
228 root_scope: ScopeKey,
229 current_scope: ScopeKey,
230 observers: Vec<Option<NodeKey>>,
232 pending: Vec<NodeKey>,
233 batch_depth: u32,
234 draining: bool,
235 tick: u64,
236 next_seq: u64,
237 scheduler: Option<Rc<dyn Fn()>>,
238 schedule_posted: bool,
239 spawner: Option<Spawner>,
242 turn_end: Vec<Rc<dyn Fn()>>,
243 turn_end_once: Vec<Box<dyn FnOnce()>>,
245 warned_writes: HashSet<*const Location<'static>>,
246}
247
248impl Runtime {
249 fn new() -> Self {
250 let mut scopes = SlotMap::with_key();
251 let root_scope = scopes.insert(ScopeData {
252 parent: ScopeKey::null(),
253 children: Vec::new(),
254 nodes: Vec::new(),
255 cleanups: Vec::new(),
256 context: HashMap::new(),
257 depth: 0,
258 });
259 Runtime {
260 nodes: SlotMap::with_key(),
261 scopes,
262 root_scope,
263 current_scope: root_scope,
264 observers: Vec::new(),
265 pending: Vec::new(),
266 batch_depth: 0,
267 draining: false,
268 tick: 1,
269 next_seq: 0,
270 scheduler: None,
271 schedule_posted: false,
272 turn_end_once: Vec::new(),
273 spawner: None,
274 turn_end: Vec::new(),
275 warned_writes: HashSet::new(),
276 }
277 }
278}
279
280crate::tls_group! {
281 static RT: RefCell<Runtime> = RefCell::new(Runtime::new());
282
283}
284
285const RERUN_CAP: u32 = 100;
287
288const TURN_ROUND_CAP: u32 = 8;
293
294fn with_rt<R>(f: impl FnOnce(&mut Runtime) -> R) -> R {
295 RT.with(|rt| f(&mut rt.borrow_mut()))
296}
297
298#[track_caller]
303fn create_node(rt: &mut Runtime, kind: NodeKind, scope: ScopeKey) -> NodeKey {
304 let depth = rt.scopes.get(scope).map_or(0, |s| s.depth);
305 let seq = rt.next_seq;
306 rt.next_seq += 1;
307 let key = rt.nodes.insert(Node {
308 kind,
309 state: NodeState::Clean,
310 value: None,
311 memo_compute: None,
312 memo_eq: None,
313 reaction: None,
314 sources: Vec::new(),
315 run_cleanups: Vec::new(),
316 observers: Vec::new(),
317 scope,
318 priority: 1,
319 depth,
320 seq,
321 last_changed: 0,
322 last_run: 0,
323 queued: false,
324 created_at: Location::caller(),
325 });
326 if let Some(s) = rt.scopes.get_mut(scope) {
327 s.nodes.push(key);
328 }
329 key
330}
331
332fn track_read(rt: &mut Runtime, source: NodeKey) {
334 if let Some(Some(obs)) = rt.observers.last().copied() {
335 if obs == source {
336 return;
337 }
338 let already = rt.nodes[obs].sources.contains(&source);
339 if !already {
340 rt.nodes[obs].sources.push(source);
341 rt.nodes[source].observers.push(obs);
342 }
343 }
344}
345
346#[must_use]
350fn clear_sources(rt: &mut Runtime, key: NodeKey) -> Vec<Box<dyn FnOnce()>> {
351 let sources = std::mem::take(&mut rt.nodes[key].sources);
352 for s in sources {
353 if let Some(n) = rt.nodes.get_mut(s)
354 && let Some(pos) = n.observers.iter().position(|&o| o == key)
355 {
356 n.observers.swap_remove(pos);
357 }
358 }
359 std::mem::take(&mut rt.nodes[key].run_cleanups)
360}
361
362fn mark_observers(rt: &mut Runtime, source: NodeKey, level: NodeState) {
365 let mut stack: Vec<(NodeKey, NodeState)> = rt.nodes[source]
367 .observers
368 .iter()
369 .map(|&o| (o, level))
370 .collect();
371 while let Some((key, level)) = stack.pop() {
372 let Some(node) = rt.nodes.get_mut(key) else {
373 continue;
374 };
375 if node.state >= level {
376 continue; }
378 node.state = level;
379 match node.kind {
380 NodeKind::Reaction => {
381 if !node.queued {
382 node.queued = true;
383 rt.pending.push(key);
384 }
385 }
386 NodeKind::Memo => {
387 for &o in &rt.nodes[key].observers {
388 stack.push((o, NodeState::Check));
389 }
390 }
391 NodeKind::Signal => {}
392 }
393 }
394}
395
396fn compute_in_owner<T>(key: NodeKey, f: impl FnOnce() -> T) -> Option<T> {
400 let owner = with_rt(|rt| {
401 let owner = rt.nodes.get(key)?.scope;
402 rt.scopes.contains_key(owner).then_some(owner)
403 })?;
404 let scope = Scope {
405 key: owner,
406 _not_send: PhantomData,
407 };
408 Some(scope.enter(|| {
409 with_rt(|rt| rt.observers.push(Some(key)));
410 let _guard = rt_guard(|rt: &mut Runtime| {
411 rt.observers.pop();
412 });
413 f()
414 }))
415}
416
417fn refresh_memo(key: NodeKey) {
419 let Some((state, kind)) = with_rt(|rt| rt.nodes.get(key).map(|n| (n.state, n.kind))) else {
420 return;
421 };
422 if kind != NodeKind::Memo || state == NodeState::Clean {
423 return;
424 }
425 if state == NodeState::Check {
426 let (sources, last_run) =
428 with_rt(|rt| (rt.nodes[key].sources.clone(), rt.nodes[key].last_run));
429 let mut any_changed = false;
430 for s in sources {
431 refresh_memo(s);
432 if with_rt(|rt| rt.nodes.get(s).is_some_and(|n| n.last_changed > last_run)) {
433 any_changed = true;
434 }
435 }
436 if !any_changed {
437 with_rt(|rt| {
438 if let Some(n) = rt.nodes.get_mut(key) {
439 n.state = NodeState::Clean;
440 }
441 });
442 return;
443 }
444 }
445 let compute = with_rt(|rt| rt.nodes[key].memo_compute.clone());
447 let Some(compute) = compute else { return };
448 let cleanups = with_rt(|rt| clear_sources(rt, key));
449 for f in cleanups {
450 f();
451 }
452 let Some(new_value) = compute_in_owner(key, || compute()) else {
453 return;
454 };
455 with_rt(|rt| {
456 let tick = rt.tick;
457 let Some(node) = rt.nodes.get_mut(key) else {
458 return;
459 };
460 let changed = match (node.value.as_ref(), node.memo_eq) {
461 (Some(old), Some(eq)) => {
462 let old = old.borrow();
464 !eq(old.as_ref(), new_value.as_ref())
465 }
466 _ => true,
467 };
468 node.last_run = tick;
469 node.state = NodeState::Clean;
470 if changed {
471 node.value = Some(Rc::new(RefCell::new(new_value)));
474 node.last_changed = tick;
475 rt.tick += 1;
476 }
477 });
480}
481
482fn run_reaction(key: NodeKey) {
484 let info = with_rt(|rt| {
485 rt.nodes.get_mut(key).map(|n| {
486 n.queued = false;
487 (n.state, n.sources.clone(), n.last_run)
488 })
489 });
490 let Some((state, sources, last_run)) = info else {
491 return;
492 };
493 if state == NodeState::Clean {
494 return;
495 }
496 if state == NodeState::Check {
497 let mut any_changed = false;
498 for s in &sources {
499 refresh_memo(*s);
500 if with_rt(|rt| rt.nodes.get(*s).is_some_and(|n| n.last_changed > last_run)) {
501 any_changed = true;
502 break;
503 }
504 }
505 if !any_changed {
506 with_rt(|rt| {
507 if let Some(n) = rt.nodes.get_mut(key) {
508 n.state = NodeState::Clean;
509 }
510 });
511 return;
512 }
513 }
514 let reaction = with_rt(|rt| rt.nodes.get(key).and_then(|n| n.reaction.clone()));
515 let Some(reaction) = reaction else { return };
516 let cleanups = with_rt(|rt| {
517 let cleanups = clear_sources(rt, key);
518 if let Some(n) = rt.nodes.get_mut(key) {
519 n.state = NodeState::Clean;
520 }
521 cleanups
522 });
523 for f in cleanups {
525 f();
526 }
527 compute_in_owner(key, || reaction());
528 with_rt(|rt| {
529 let tick = rt.tick;
530 rt.tick += 1;
531 if let Some(n) = rt.nodes.get_mut(key) {
532 n.last_run = tick;
533 }
534 });
535}
536
537pub fn flush_sync() {
553 let already = with_rt(|rt| {
554 if rt.draining {
555 return true;
556 }
557 rt.draining = true;
558 false
559 });
560 if already {
561 return; }
563 let mut round = 0u32;
564 loop {
565 round += 1;
566 let mut run_counts: HashMap<NodeKey, u32> = HashMap::new();
568 loop {
569 let mut batch = with_rt(|rt| std::mem::take(&mut rt.pending));
570 if batch.is_empty() {
571 break;
572 }
573 with_rt(|rt| {
575 batch.sort_by_key(|&k| {
576 rt.nodes.get(k).map_or((u8::MAX, u32::MAX, u64::MAX), |n| {
577 (n.priority, n.depth, n.seq)
578 })
579 });
580 });
581 for key in batch {
582 let count = run_counts.entry(key).or_insert(0);
583 *count += 1;
584 if *count > RERUN_CAP {
585 if *count == RERUN_CAP + 1 {
586 let loc = with_rt(|rt| rt.nodes.get(key).map(|n| n.created_at));
587 if let Some(loc) = loc {
588 debug_assert!(
589 false,
590 "day-reactive: effect created at {loc} re-ran more than {RERUN_CAP} times in one drain (reactive cycle?)"
591 );
592 log::warn!(
593 "day-reactive: effect created at {loc} exceeded the re-run cap; skipping it for the rest of this drain (the next source write re-arms it)"
594 );
595 }
596 }
597 with_rt(|rt| {
603 if let Some(n) = rt.nodes.get_mut(key) {
604 n.queued = false;
605 n.state = NodeState::Clean;
606 }
607 });
608 continue;
609 }
610 run_reaction(key);
611 }
612 }
613 let (once, turn_end) = with_rt(|rt| {
614 rt.draining = false;
615 rt.schedule_posted = false;
616 (std::mem::take(&mut rt.turn_end_once), rt.turn_end.clone())
617 });
618 for cb in once {
621 cb();
622 }
623 for cb in turn_end {
624 cb();
625 }
626 let more = with_rt(|rt| {
628 if rt.pending.is_empty() {
629 return false;
630 }
631 rt.draining = true;
632 true
633 });
634 if !more {
635 return;
636 }
637 if round >= TURN_ROUND_CAP {
638 with_rt(|rt| rt.draining = false);
642 debug_assert!(
643 false,
644 "day-reactive: turn-end callbacks scheduled new reactive work for {TURN_ROUND_CAP} straight rounds in one turn (hooks feeding each other?)"
645 );
646 log::warn!(
647 "day-reactive: turn-end callbacks still scheduling work after {TURN_ROUND_CAP} rounds; deferring the rest to the next turn"
648 );
649 return;
650 }
651 }
652}
653
654pub fn recover_from_panic() {
661 with_rt(|rt| {
662 rt.draining = false;
663 rt.schedule_posted = false;
664 rt.batch_depth = 0;
665 rt.turn_end_once.clear();
666 rt.pending.clear();
667 rt.observers.clear();
668 rt.current_scope = rt.root_scope;
672 });
673}
674
675fn schedule_after_write(rt: &mut Runtime) -> Option<Rc<dyn Fn()>> {
678 if rt.batch_depth > 0 || rt.draining {
679 return None;
680 }
681 if rt.schedule_posted {
682 return None;
683 }
684 rt.schedule_posted = true;
685 rt.scheduler.clone()
686}
687
688fn signal_write_boxed(key: NodeKey, apply: impl FnOnce(&mut Box<dyn Any>) -> bool) {
689 let poster = with_rt(|rt| {
690 let node = rt.nodes.get_mut(key)?;
691 let cell = node.value.as_ref()?.clone();
692 let Ok(mut value) = cell.try_borrow_mut() else {
696 panic!(
697 "day-reactive: wrote to a Signal while a with()/try_with() read of it is still \
698 in flight — the write would be lost. Finish the read closure first (copy the \
699 value out with get()) and write after it returns."
700 )
701 };
702 let changed = apply(&mut value);
703 drop(value);
704 let node = rt.nodes.get_mut(key)?;
705 if !changed {
706 return None;
707 }
708 node.last_changed = rt.tick;
709 rt.tick += 1;
710 mark_observers(rt, key, NodeState::Dirty);
711 schedule_after_write(rt)
712 });
713 if let Some(post) = poster {
714 post();
715 }
716}
717
718fn rt_guard(f: impl FnOnce(&mut Runtime)) -> impl Drop {
729 std::mem::DropGuard::new((), |()| with_rt(f))
730}
731
732pub fn batch<R>(f: impl FnOnce() -> R) -> R {
733 with_rt(|rt| rt.batch_depth += 1);
734 let r = {
735 let _g = rt_guard(|rt: &mut Runtime| rt.batch_depth = rt.batch_depth.saturating_sub(1));
740 f()
741 };
742 let should_drain = with_rt(|rt| {
743 rt.batch_depth == 0
744 && !rt.draining
745 && (!rt.pending.is_empty() || !rt.turn_end_once.is_empty())
746 });
747 if should_drain {
748 flush_sync();
749 }
750 r
751}
752
753pub fn flush_now() {
760 let saved = with_rt(|rt| std::mem::replace(&mut rt.batch_depth, 0));
761 let _g = rt_guard(move |rt: &mut Runtime| rt.batch_depth = saved);
764 flush_sync();
765}
766
767pub fn untrack<R>(f: impl FnOnce() -> R) -> R {
769 with_rt(|rt| rt.observers.push(None));
770 let _g = rt_guard(|rt: &mut Runtime| {
773 rt.observers.pop();
774 });
775 f()
776}
777
778#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
782pub struct RunId(NodeKey);
783
784pub fn active_run() -> Option<RunId> {
786 with_rt(|rt| rt.observers.last().copied().flatten()).map(RunId)
787}
788
789pub fn on_run_retrack(f: impl FnOnce() + 'static) -> bool {
794 with_rt(|rt| {
795 let Some(Some(key)) = rt.observers.last().copied() else {
796 return false;
797 };
798 match rt.nodes.get_mut(key) {
799 Some(n) => {
800 n.run_cleanups.push(Box::new(f));
801 true
802 }
803 None => false,
804 }
805 })
806}
807
808pub fn install_scheduler(post: impl Fn() + 'static) {
810 with_rt(|rt| rt.scheduler = Some(Rc::new(post)));
811}
812
813pub type LocalBoxFuture = Pin<Box<dyn Future<Output = ()> + 'static>>;
815
816type Spawner = Rc<dyn Fn(LocalBoxFuture) -> Box<dyn FnOnce()>>;
818
819pub fn install_spawner(spawn: impl Fn(LocalBoxFuture) -> Box<dyn FnOnce()> + 'static) {
825 with_rt(|rt| rt.spawner = Some(Rc::new(spawn)));
826}
827
828fn spawn_local(fut: LocalBoxFuture) -> Box<dyn FnOnce()> {
830 let spawner = with_rt(|rt| rt.spawner.clone());
831 match spawner {
832 Some(s) => s(fut),
833 None => panic!("day-reactive: no spawner installed (backend not started)"),
834 }
835}
836
837pub fn on_turn_end(cb: impl Fn() + 'static) {
839 with_rt(|rt| rt.turn_end.push(Rc::new(cb)));
840}
841
842pub fn at_turn_end(cb: impl FnOnce() + 'static) {
849 let now = with_rt(|rt| {
850 if rt.draining || rt.batch_depth > 0 {
851 rt.turn_end_once.push(Box::new(cb));
852 None
853 } else {
854 Some(cb)
855 }
856 });
857 if let Some(cb) = now {
858 cb();
859 }
860}
861
862type MainPoster = Box<dyn Fn(Box<dyn FnOnce() + Send>) + Send + Sync>;
867static MAIN_POSTER: std::sync::OnceLock<MainPoster> = std::sync::OnceLock::new();
868
869pub fn install_main_poster(post: impl Fn(Box<dyn FnOnce() + Send>) + Send + Sync + 'static) {
871 let _ = MAIN_POSTER.set(Box::new(post));
872}
873
874pub fn has_main_poster() -> bool {
880 MAIN_POSTER.get().is_some()
881}
882
883pub fn on_main(f: impl FnOnce() + Send + 'static) {
889 match MAIN_POSTER.get() {
890 Some(post) => post(Box::new(f)),
891 None => panic!("day-reactive: no main poster installed (backend not started)"),
892 }
893}
894
895type DelayedPoster = Box<dyn Fn(u32, Box<dyn FnOnce() + Send>) + Send + Sync>;
896static DELAYED_POSTER: std::sync::OnceLock<DelayedPoster> = std::sync::OnceLock::new();
897
898pub fn install_delayed_poster(
900 post: impl Fn(u32, Box<dyn FnOnce() + Send>) + Send + Sync + 'static,
901) {
902 let _ = DELAYED_POSTER.set(Box::new(post));
903}
904
905pub fn on_main_delayed(ms: u32, f: impl FnOnce() + Send + 'static) {
912 match DELAYED_POSTER.get() {
913 Some(post) => post(ms, Box::new(f)),
914 None => panic!("day-reactive: no delayed poster installed (backend not started)"),
915 }
916}
917
918#[derive(Clone, Copy, PartialEq, Eq)]
924pub struct Scope {
925 key: ScopeKey,
926 _not_send: PhantomData<*const ()>,
927}
928
929impl Scope {
930 pub fn current() -> Scope {
931 Scope {
932 key: with_rt(|rt| rt.current_scope),
933 _not_send: PhantomData,
934 }
935 }
936
937 pub fn root() -> Scope {
938 Scope {
939 key: with_rt(|rt| rt.root_scope),
940 _not_send: PhantomData,
941 }
942 }
943
944 pub fn child() -> Scope {
946 Scope::current().create_child()
947 }
948
949 #[must_use]
950 pub fn create_child(self) -> Scope {
951 let key = with_rt(|rt| {
952 let depth = rt.scopes.get(self.key).map_or(1, |s| s.depth + 1);
953 let child = rt.scopes.insert(ScopeData {
954 parent: self.key,
955 children: Vec::new(),
956 nodes: Vec::new(),
957 cleanups: Vec::new(),
958 context: HashMap::new(),
959 depth,
960 });
961 if let Some(p) = rt.scopes.get_mut(self.key) {
962 p.children.push(child);
963 }
964 child
965 });
966 Scope {
967 key,
968 _not_send: PhantomData,
969 }
970 }
971
972 pub fn detached() -> Scope {
974 let key = with_rt(|rt| {
975 rt.scopes.insert(ScopeData {
976 parent: ScopeKey::null(),
977 children: Vec::new(),
978 nodes: Vec::new(),
979 cleanups: Vec::new(),
980 context: HashMap::new(),
981 depth: 0,
982 })
983 });
984 Scope {
985 key,
986 _not_send: PhantomData,
987 }
988 }
989
990 pub fn enter<R>(self, f: impl FnOnce() -> R) -> R {
992 let prev = with_rt(|rt| std::mem::replace(&mut rt.current_scope, self.key));
993 let _g = rt_guard(move |rt: &mut Runtime| rt.current_scope = prev);
997 f()
998 }
999
1000 pub fn on_cleanup(self, f: impl FnOnce() + 'static) {
1001 with_rt(|rt| {
1002 if let Some(s) = rt.scopes.get_mut(self.key) {
1003 s.cleanups.push(Box::new(f));
1004 }
1005 });
1006 }
1007
1008 #[must_use]
1009 pub fn is_alive(self) -> bool {
1010 with_rt(|rt| rt.scopes.contains_key(self.key))
1011 }
1012
1013 pub fn dispose(self) {
1015 let Some(children) = with_rt(|rt| rt.scopes.get(self.key).map(|s| s.children.clone()))
1016 else {
1017 return;
1018 };
1019 for c in children {
1020 (Scope {
1021 key: c,
1022 _not_send: PhantomData,
1023 })
1024 .dispose();
1025 }
1026 let Some((nodes, cleanups, parent)) = with_rt(|rt| {
1027 rt.scopes
1028 .remove(self.key)
1029 .map(|s| (s.nodes, s.cleanups, s.parent))
1030 }) else {
1031 return;
1032 };
1033 let mut run_cleanups: Vec<Box<dyn FnOnce()>> = Vec::new();
1034 with_rt(|rt| {
1035 if let Some(p) = rt.scopes.get_mut(parent)
1036 && let Some(pos) = p.children.iter().position(|&c| c == self.key)
1037 {
1038 p.children.swap_remove(pos);
1039 }
1040 for key in nodes {
1041 run_cleanups.extend(clear_sources(rt, key));
1042 if let Some(node) = rt.nodes.get_mut(key) {
1044 let observers = std::mem::take(&mut node.observers);
1045 for o in observers {
1046 if let Some(on) = rt.nodes.get_mut(o)
1047 && let Some(pos) = on.sources.iter().position(|&s| s == key)
1048 {
1049 on.sources.swap_remove(pos);
1050 }
1051 }
1052 }
1053 rt.nodes.remove(key);
1054 }
1056 });
1057 for f in run_cleanups {
1060 f();
1061 }
1062 for c in cleanups {
1063 c();
1064 }
1065 }
1066
1067 pub fn provide<T: 'static>(self, value: T) {
1069 with_rt(|rt| {
1070 if let Some(s) = rt.scopes.get_mut(self.key) {
1071 s.context.insert(TypeId::of::<T>(), Box::new(value));
1072 }
1073 });
1074 }
1075
1076 #[must_use]
1078 pub fn use_context<T: Clone + 'static>(self) -> Option<T> {
1079 with_rt(|rt| {
1080 let mut cur = self.key;
1081 while let Some(s) = rt.scopes.get(cur) {
1082 if let Some(v) = s.context.get(&TypeId::of::<T>()) {
1083 return v.downcast_ref::<T>().cloned();
1084 }
1085 cur = s.parent;
1086 }
1087 None
1088 })
1089 }
1090}
1091
1092pub struct Signal<T: 'static> {
1098 key: NodeKey,
1099 created_at: &'static Location<'static>,
1100 _m: PhantomData<*const T>,
1101}
1102
1103impl<T: 'static> Clone for Signal<T> {
1104 fn clone(&self) -> Self {
1105 *self
1106 }
1107}
1108impl<T: 'static> Copy for Signal<T> {}
1109
1110impl<T: 'static> std::fmt::Debug for Signal<T> {
1111 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1112 write!(f, "Signal({:?})", self.key)
1113 }
1114}
1115
1116impl<T: 'static> Signal<T> {
1117 #[track_caller]
1118 pub fn new(value: T) -> Self {
1119 Self::new_in(Scope::current(), value)
1120 }
1121
1122 #[track_caller]
1129 pub fn global(value: T) -> Self {
1130 Self::new_in(Scope::root(), value)
1131 }
1132
1133 #[track_caller]
1134 pub fn new_in(scope: Scope, value: T) -> Self {
1135 let created_at = Location::caller();
1136 let key = with_rt(|rt| {
1137 let k = create_node(rt, NodeKind::Signal, scope.key);
1138 rt.nodes[k].value = Some(Rc::new(RefCell::new(Box::new(value) as Box<dyn Any>)));
1139 rt.nodes[k].created_at = created_at;
1140 k
1141 });
1142 Signal {
1143 key,
1144 created_at,
1145 _m: PhantomData,
1146 }
1147 }
1148
1149 #[track_caller]
1156 pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
1157 match self.try_with(f) {
1158 Some(r) => r,
1159 None => panic!(
1160 "day-reactive: read of disposed Signal created at {} (use try_with in closures that can outlive their scope)",
1161 self.created_at
1162 ),
1163 }
1164 }
1165
1166 pub fn try_with<R>(self, f: impl FnOnce(&T) -> R) -> Option<R> {
1167 let cell = with_rt(|rt| {
1172 track_read(rt, self.key);
1173 rt.nodes.get(self.key).and_then(|n| n.value.clone())
1174 })?;
1175 let value = cell.borrow();
1176 value.downcast_ref::<T>().map(f)
1177 }
1178
1179 pub fn with_untracked<R>(self, f: impl FnOnce(&T) -> R) -> R {
1180 untrack(|| self.with(f))
1181 }
1182
1183 #[track_caller]
1184 #[must_use]
1185 pub fn get(self) -> T
1186 where
1187 T: Clone,
1188 {
1189 self.with(std::clone::Clone::clone)
1190 }
1191
1192 #[must_use]
1193 pub fn try_get(self) -> Option<T>
1194 where
1195 T: Clone,
1196 {
1197 self.try_with(std::clone::Clone::clone)
1198 }
1199
1200 #[must_use]
1201 pub fn get_untracked(self) -> T
1202 where
1203 T: Clone,
1204 {
1205 untrack(|| self.get())
1206 }
1207
1208 pub fn track(self) {
1210 with_rt(|rt| track_read(rt, self.key));
1211 }
1212
1213 #[track_caller]
1214 pub fn set(self, value: T) {
1215 self.write_check(move |slot| {
1216 *slot = value;
1217 true
1218 });
1219 }
1220
1221 #[track_caller]
1222 pub fn set_if_changed(self, value: T)
1223 where
1224 T: PartialEq,
1225 {
1226 self.write_check(move |slot| {
1227 if *slot == value {
1228 false
1229 } else {
1230 *slot = value;
1231 true
1232 }
1233 });
1234 }
1235
1236 #[track_caller]
1237 pub fn update(self, f: impl FnOnce(&mut T)) {
1238 self.write_check(move |slot| {
1239 f(slot);
1240 true
1241 });
1242 }
1243
1244 #[track_caller]
1245 fn write_check(self, apply: impl FnOnce(&mut T) -> bool) {
1246 let alive = with_rt(|rt| rt.nodes.contains_key(self.key));
1247 if !alive {
1248 let loc = Location::caller();
1250 let first = with_rt(|rt| rt.warned_writes.insert(std::ptr::from_ref(loc)));
1251 if first && cfg!(debug_assertions) {
1252 log::warn!(
1253 "day-reactive: write at {loc} to a disposed signal (created at {}) ignored",
1254 self.created_at
1255 );
1256 }
1257 return;
1258 }
1259 signal_write_boxed(self.key, |boxed| match boxed.downcast_mut::<T>() {
1260 Some(slot) => apply(slot),
1261 None => false,
1262 });
1263 }
1264
1265 #[must_use]
1267 pub fn setter(self) -> Setter<T>
1268 where
1269 T: Send,
1270 {
1271 Setter {
1272 key: self.key,
1273 _m: PhantomData,
1274 }
1275 }
1276}
1277
1278pub struct Setter<T: Send + 'static> {
1281 key: NodeKey,
1282 _m: PhantomData<fn(T)>,
1283}
1284
1285impl<T: Send + 'static> Clone for Setter<T> {
1286 fn clone(&self) -> Self {
1287 *self
1288 }
1289}
1290impl<T: Send + 'static> Copy for Setter<T> {}
1291
1292impl<T: Send + 'static> Setter<T> {
1293 pub fn set(self, value: T) {
1294 let key = self.key;
1295 on_main(move || {
1296 let poster = with_rt(|rt| {
1297 let cell = rt.nodes.get(key)?.value.clone()?;
1298 {
1299 let mut boxed = cell.try_borrow_mut().ok()?;
1300 let slot = boxed.downcast_mut::<T>()?;
1301 *slot = value;
1302 }
1303 let node = rt.nodes.get_mut(key)?;
1304 node.last_changed = rt.tick;
1305 rt.tick += 1;
1306 mark_observers(rt, key, NodeState::Dirty);
1307 schedule_after_write(rt)
1308 });
1309 if let Some(post) = poster {
1310 post();
1311 }
1312 });
1313 }
1314}
1315
1316pub struct Memo<T: 'static> {
1322 key: NodeKey,
1323 created_at: &'static Location<'static>,
1324 _m: PhantomData<*const T>,
1325}
1326
1327impl<T: 'static> Clone for Memo<T> {
1328 fn clone(&self) -> Self {
1329 *self
1330 }
1331}
1332impl<T: 'static> Copy for Memo<T> {}
1333
1334impl<T: 'static> Memo<T> {
1335 #[track_caller]
1336 pub fn new(f: impl Fn() -> T + 'static) -> Self
1337 where
1338 T: PartialEq,
1339 {
1340 Self::new_with_eq(f, |a, b| a == b)
1341 }
1342
1343 #[track_caller]
1344 pub fn new_with_eq(f: impl Fn() -> T + 'static, eq: fn(&T, &T) -> bool) -> Self {
1345 let created_at = Location::caller();
1346 let key = with_rt(|rt| {
1349 let scope = rt.current_scope;
1350 create_node(rt, NodeKind::Memo, scope)
1351 });
1352 let compute: Rc<dyn Fn() -> Box<dyn Any>> =
1353 Rc::new(move || Box::new(EqBox { value: f(), eq }) as Box<dyn Any>);
1354 with_rt(|rt| {
1355 let node = &mut rt.nodes[key];
1356 node.memo_compute = Some(compute);
1357 node.memo_eq = Some(eqbox_eq::<T>);
1358 node.state = NodeState::Dirty; node.created_at = created_at;
1360 });
1361 Memo {
1362 key,
1363 created_at,
1364 _m: PhantomData,
1365 }
1366 }
1367
1368 #[track_caller]
1374 pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
1375 refresh_memo(self.key);
1376 let value = with_rt(|rt| {
1377 track_read(rt, self.key);
1378 rt.nodes.get(self.key).and_then(|n| n.value.clone())
1379 });
1380 match value {
1381 Some(cell) => {
1383 let boxed = cell.borrow();
1384 boxed.downcast_ref::<EqBox<T>>().map_or_else(
1385 || panic!("day-reactive: memo type mismatch"),
1386 |e| f(&e.value),
1387 )
1388 }
1389 None => panic!(
1390 "day-reactive: read of disposed Memo created at {}",
1391 self.created_at
1392 ),
1393 }
1394 }
1395
1396 #[track_caller]
1397 #[must_use]
1398 pub fn get(self) -> T
1399 where
1400 T: Clone,
1401 {
1402 self.with(std::clone::Clone::clone)
1403 }
1404}
1405
1406struct EqBox<T> {
1408 value: T,
1409 eq: fn(&T, &T) -> bool,
1410}
1411
1412fn eqbox_eq<T: 'static>(a: &dyn Any, b: &dyn Any) -> bool {
1413 match (a.downcast_ref::<EqBox<T>>(), b.downcast_ref::<EqBox<T>>()) {
1414 (Some(a), Some(b)) => (a.eq)(&a.value, &b.value),
1415 _ => false,
1416 }
1417}
1418
1419pub struct Effect;
1427
1428impl Effect {
1429 #[allow(clippy::new_ret_no_self)]
1432 #[track_caller]
1433 pub fn new(f: impl Fn() + 'static) {
1434 create_reaction(Rc::new(f), 1);
1435 }
1436}
1437
1438#[track_caller]
1439fn create_reaction(f: Rc<dyn Fn()>, priority: u8) -> NodeKey {
1440 let created_at = Location::caller();
1441 let key = with_rt(|rt| {
1442 let scope = rt.current_scope;
1443 let k = create_node(rt, NodeKind::Reaction, scope);
1444 rt.nodes[k].reaction = Some(f);
1445 rt.nodes[k].priority = priority;
1446 rt.nodes[k].created_at = created_at;
1447 k
1448 });
1449 let reaction = with_rt(|rt| rt.nodes[key].reaction.clone());
1450 if let Some(reaction) = reaction {
1451 compute_in_owner(key, || reaction());
1452 }
1453 with_rt(|rt| {
1454 let tick = rt.tick;
1455 rt.tick += 1;
1456 if let Some(n) = rt.nodes.get_mut(key) {
1457 n.last_run = tick;
1458 }
1459 });
1460 key
1461}
1462
1463#[track_caller]
1467pub fn bind<V: PartialEq + 'static>(
1468 compute: impl Fn() -> V + 'static,
1469 apply: impl Fn(&V) + 'static,
1470) {
1471 let last: RefCell<Option<V>> = RefCell::new(None);
1472 create_reaction(
1473 Rc::new(move || {
1474 let v = compute();
1475 if last.borrow().as_ref() != Some(&v) {
1476 untrack(|| apply(&v));
1477 *last.borrow_mut() = Some(v);
1478 }
1479 }),
1480 0,
1481 );
1482}
1483
1484#[track_caller]
1487pub fn bind_seeded<V: PartialEq + 'static>(
1488 seed: V,
1489 compute: impl Fn() -> V + 'static,
1490 apply: impl Fn(&V) + 'static,
1491) {
1492 let last: RefCell<Option<V>> = RefCell::new(Some(seed));
1493 create_reaction(
1494 Rc::new(move || {
1495 let v = compute();
1496 if last.borrow().as_ref() != Some(&v) {
1497 untrack(|| apply(&v));
1498 *last.borrow_mut() = Some(v);
1499 }
1500 }),
1501 0,
1502 );
1503}
1504
1505#[track_caller]
1507pub fn bind_always<V: 'static>(compute: impl Fn() -> V + 'static, apply: impl Fn(V) + 'static) {
1508 create_reaction(
1509 Rc::new(move || {
1510 let v = compute();
1511 untrack(|| apply(v));
1512 }),
1513 0,
1514 );
1515}
1516
1517#[track_caller]
1522pub fn watch<S: Clone + 'static>(
1523 source: impl Fn() -> S + 'static,
1524 cb: impl Fn(&S, Option<&S>) + 'static,
1525) {
1526 let prev: RefCell<Option<S>> = RefCell::new(None);
1527 create_reaction(
1528 Rc::new(move || {
1529 let new = source();
1530 let old = prev.borrow_mut().replace(new.clone());
1531 if old.is_some() {
1532 untrack(|| cb(&new, old.as_ref()));
1533 }
1534 }),
1535 1,
1536 );
1537}
1538
1539#[derive(Clone, Copy)]
1541pub struct Trigger {
1542 signal: Signal<u64>,
1543}
1544
1545impl Trigger {
1546 #[track_caller]
1547 #[must_use]
1548 pub fn new() -> Self {
1549 Trigger {
1550 signal: Signal::new(0),
1551 }
1552 }
1553 pub fn track(self) {
1554 self.signal.track();
1555 }
1556 pub fn notify(self) {
1557 self.signal.update(|v| *v = v.wrapping_add(1));
1558 }
1559}
1560
1561impl Default for Trigger {
1562 fn default() -> Self {
1563 Self::new()
1564 }
1565}
1566
1567pub trait Binding<T: 'static>: Clone + 'static {
1577 fn read(&self) -> T;
1579 fn peek(&self) -> T;
1581 fn write(&self, v: T);
1583 fn write_preview(&self, v: T) {
1587 self.write(v);
1588 }
1589 fn write_commit(&self, v: T) {
1593 self.write(v);
1594 }
1595 fn write_teardown(&self, v: T) {
1598 self.write_commit(v);
1599 }
1600 fn end_preview(&self) {}
1605}
1606
1607impl<T: Clone + 'static> Binding<T> for Signal<T> {
1608 fn read(&self) -> T {
1609 self.get()
1610 }
1611 fn peek(&self) -> T {
1612 self.get_untracked()
1613 }
1614 fn write(&self, v: T) {
1615 self.set(v);
1616 }
1617 fn write_teardown(&self, _v: T) {}
1618}
1619
1620trait ErasedBinding<T: 'static> {
1623 fn erased_read(&self) -> T;
1624 fn erased_peek(&self) -> T;
1625 fn erased_write(&self, v: T);
1626 fn erased_write_preview(&self, v: T);
1627 fn erased_write_commit(&self, v: T);
1628 fn erased_write_teardown(&self, v: T);
1629 fn erased_end_preview(&self);
1630}
1631
1632impl<T: 'static, B: Binding<T>> ErasedBinding<T> for B {
1633 fn erased_read(&self) -> T {
1634 Binding::read(self)
1635 }
1636 fn erased_peek(&self) -> T {
1637 Binding::peek(self)
1638 }
1639 fn erased_write(&self, v: T) {
1640 Binding::write(self, v);
1641 }
1642 fn erased_write_preview(&self, v: T) {
1643 Binding::write_preview(self, v);
1644 }
1645 fn erased_write_commit(&self, v: T) {
1646 Binding::write_commit(self, v);
1647 }
1648 fn erased_write_teardown(&self, v: T) {
1649 Binding::write_teardown(self, v);
1650 }
1651 fn erased_end_preview(&self) {
1652 Binding::end_preview(self);
1653 }
1654}
1655
1656pub struct AnyBinding<T: 'static> {
1664 slot: Signal<Rc<dyn ErasedBinding<T>>>,
1665}
1666
1667impl<T: 'static> Clone for AnyBinding<T> {
1668 fn clone(&self) -> Self {
1669 *self
1670 }
1671}
1672impl<T: 'static> Copy for AnyBinding<T> {}
1673
1674impl<T: 'static> AnyBinding<T> {
1675 pub fn new(binding: impl Binding<T>) -> Self {
1677 let erased: Rc<dyn ErasedBinding<T>> = Rc::new(binding);
1678 AnyBinding {
1679 slot: Signal::new(erased),
1680 }
1681 }
1682 fn inner(self) -> Rc<dyn ErasedBinding<T>> {
1683 self.slot.get_untracked()
1684 }
1685 #[must_use]
1687 pub fn get(self) -> T {
1688 self.inner().erased_read()
1689 }
1690 #[must_use]
1692 pub fn try_get(self) -> Option<T> {
1693 self.slot.try_get().map(|b| b.erased_read())
1694 }
1695 #[must_use]
1697 pub fn get_untracked(self) -> T {
1698 self.inner().erased_peek()
1699 }
1700 pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
1702 let v = self.inner().erased_read();
1703 f(&v)
1704 }
1705 pub fn set(self, v: T) {
1707 self.inner().erased_write(v);
1708 }
1709 pub fn set_if_changed(self, v: T)
1711 where
1712 T: PartialEq,
1713 {
1714 let b = self.inner();
1715 if b.erased_peek() != v {
1716 b.erased_write(v);
1717 }
1718 }
1719 pub fn update(self, f: impl FnOnce(&mut T)) {
1721 let b = self.inner();
1722 let mut v = b.erased_peek();
1723 f(&mut v);
1724 b.erased_write(v);
1725 }
1726}
1727
1728impl<T: 'static> Binding<T> for AnyBinding<T> {
1729 fn read(&self) -> T {
1730 self.inner().erased_read()
1731 }
1732 fn peek(&self) -> T {
1733 self.inner().erased_peek()
1734 }
1735 fn write(&self, v: T) {
1736 self.inner().erased_write(v);
1737 }
1738 fn write_preview(&self, v: T) {
1739 self.inner().erased_write_preview(v);
1740 }
1741 fn write_commit(&self, v: T) {
1742 self.inner().erased_write_commit(v);
1743 }
1744 fn write_teardown(&self, v: T) {
1745 self.inner().erased_write_teardown(v);
1746 }
1747 fn end_preview(&self) {
1748 self.inner().erased_end_preview();
1749 }
1750}
1751
1752#[derive(Clone)]
1759pub enum Load<T> {
1760 Loading,
1761 Ready(T),
1762 Failed(Arc<dyn std::error::Error + Send + Sync>),
1763}
1764
1765impl<T> Load<T> {
1766 pub fn ready(&self) -> Option<&T> {
1768 match self {
1769 Load::Ready(v) => Some(v),
1770 _ => None,
1771 }
1772 }
1773 pub fn is_loading(&self) -> bool {
1774 matches!(self, Load::Loading)
1775 }
1776 pub fn is_ready(&self) -> bool {
1777 matches!(self, Load::Ready(_))
1778 }
1779 pub fn error(&self) -> Option<&(dyn std::error::Error + Send + Sync + 'static)> {
1781 match self {
1782 Load::Failed(e) => Some(e.as_ref()),
1783 _ => None,
1784 }
1785 }
1786}
1787
1788impl<T: std::fmt::Debug> std::fmt::Debug for Load<T> {
1789 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1790 match self {
1791 Load::Loading => write!(f, "Loading"),
1792 Load::Ready(v) => f.debug_tuple("Ready").field(v).finish(),
1793 Load::Failed(e) => f.debug_tuple("Failed").field(&e.to_string()).finish(),
1794 }
1795 }
1796}
1797
1798struct FetchState {
1800 generation: Cell<u64>,
1801 abort: RefCell<Option<Box<dyn FnOnce()>>>,
1802}
1803
1804impl FetchState {
1805 fn supersede(&self) -> u64 {
1809 let next = self.generation.get() + 1;
1810 self.generation.set(next);
1811 let old = self.abort.borrow_mut().take();
1812 if let Some(abort) = old {
1813 abort();
1814 }
1815 next
1816 }
1817}
1818
1819pub struct Resource<T: 'static> {
1834 state: Signal<Load<T>>,
1835 refetch_count: Signal<u64>,
1836 _not_send: PhantomData<*const T>,
1837}
1838
1839impl<T> Clone for Resource<T> {
1840 fn clone(&self) -> Self {
1841 *self
1842 }
1843}
1844impl<T> Copy for Resource<T> {}
1845
1846impl<T: 'static> Resource<T> {
1847 #[track_caller]
1852 pub fn new<S, Fut, E>(
1853 source: impl Fn() -> S + 'static,
1854 fetcher: impl Fn(S) -> Fut + 'static,
1855 ) -> Resource<T>
1856 where
1857 S: Clone + PartialEq + 'static,
1858 Fut: Future<Output = Result<T, E>> + 'static,
1859 E: std::error::Error + Send + Sync + 'static,
1860 {
1861 let state: Signal<Load<T>> = Signal::new(Load::Loading);
1862 let refetch_count: Signal<u64> = Signal::new(0);
1863 let fs = Rc::new(FetchState {
1864 generation: Cell::new(0),
1865 abort: RefCell::new(None),
1866 });
1867 let reaction_fs = fs.clone();
1868 let prev: RefCell<Option<(S, u64)>> = RefCell::new(None);
1869 create_reaction(
1870 Rc::new(move || {
1871 let count = refetch_count.get();
1874 let s = source();
1875 let fs = reaction_fs.clone();
1876 untrack(|| {
1877 let same = prev
1881 .borrow()
1882 .as_ref()
1883 .is_some_and(|(ps, pc)| ps == &s && *pc == count);
1884 if same {
1885 return;
1886 }
1887 *prev.borrow_mut() = Some((s.clone(), count));
1888 let my_generation = fs.supersede();
1889 state.set(Load::Loading);
1890 let fut = fetcher(s);
1891 let done = fs.clone();
1892 let abort = spawn_local(Box::pin(async move {
1893 let result = fut.await;
1894 if done.generation.get() != my_generation {
1895 return; }
1897 done.abort.borrow_mut().take(); match result {
1899 Ok(v) => state.set(Load::Ready(v)),
1900 Err(e) => state.set(Load::Failed(Arc::new(e))),
1901 }
1902 }));
1903 *fs.abort.borrow_mut() = Some(abort);
1908 });
1909 }),
1910 1,
1911 );
1912 let cleanup_fs = fs;
1916 Scope::current().on_cleanup(move || {
1917 cleanup_fs.supersede();
1918 });
1919 Resource {
1920 state,
1921 refetch_count,
1922 _not_send: PhantomData,
1923 }
1924 }
1925
1926 #[must_use]
1928 pub fn signal(self) -> Signal<Load<T>> {
1929 self.state
1930 }
1931
1932 #[must_use]
1934 pub fn get(self) -> Load<T>
1935 where
1936 T: Clone,
1937 {
1938 self.state.get()
1939 }
1940
1941 pub fn with<R>(self, f: impl FnOnce(&Load<T>) -> R) -> R {
1943 self.state.with(f)
1944 }
1945
1946 pub fn loading(self) -> bool {
1948 self.with(Load::is_loading)
1949 }
1950
1951 pub fn ready(self) -> bool {
1953 self.with(Load::is_ready)
1954 }
1955
1956 pub fn refetch(self) {
1958 self.refetch_count.update(|c| *c = c.wrapping_add(1));
1959 }
1960}
1961
1962#[cfg(test)]
1967mod tests {
1968 use super::*;
1969 use std::cell::Cell as StdCell;
1970 use std::rc::Rc;
1971
1972 fn counter() -> (Rc<StdCell<u32>>, impl Fn()) {
1973 let c = Rc::new(StdCell::new(0));
1974 let c2 = c.clone();
1975 (c, move || c2.set(c2.get() + 1))
1976 }
1977
1978 #[test]
1979 fn signal_get_set() {
1980 let s = Signal::new(1);
1981 assert_eq!(s.get(), 1);
1982 s.set(5);
1983 assert_eq!(s.get(), 5);
1984 s.update(|v| *v += 1);
1985 assert_eq!(s.get(), 6);
1986 }
1987
1988 #[test]
1989 fn signal_teardown_does_not_write_after_scope_disposal() {
1990 let scope = Scope::child();
1991 let warned = with_rt(|rt| rt.warned_writes.len());
1992 scope.enter(|| {
1993 let signal = Signal::new(String::new());
1994 signal.write_preview("Fixture final edit".into());
1995 assert_eq!(signal.peek(), "Fixture final edit");
1996 Scope::current().on_cleanup(move || {
1997 signal.write_teardown("Fixture final edit".into());
1998 });
1999 });
2000 scope.dispose();
2001 assert_eq!(with_rt(|rt| rt.warned_writes.len()), warned);
2002 }
2003
2004 #[test]
2005 fn persistent_binding_teardown_seals_preview() {
2006 #[derive(Clone)]
2007 struct FixtureBinding(Rc<RefCell<Vec<String>>>);
2008 impl Binding<String> for FixtureBinding {
2009 fn read(&self) -> String {
2010 String::new()
2011 }
2012 fn peek(&self) -> String {
2013 self.read()
2014 }
2015 fn write(&self, value: String) {
2016 self.0.borrow_mut().push(value);
2017 }
2018 fn write_preview(&self, _value: String) {}
2019 }
2020 let committed = Rc::new(RefCell::new(Vec::new()));
2021 let binding = FixtureBinding(committed.clone());
2022 let scope = Scope::child();
2023 scope.enter(|| {
2024 binding.write_preview("Fixture edit".into());
2025 Scope::current().on_cleanup(move || binding.write_teardown("Fixture edit".into()));
2026 });
2027 assert!(committed.borrow().is_empty());
2028 scope.dispose();
2029 assert_eq!(*committed.borrow(), ["Fixture edit"]);
2030 }
2031
2032 #[test]
2033 fn effect_reruns_on_change() {
2034 let s = Signal::new(1);
2035 let (count, bump) = counter();
2036 Effect::new(move || {
2037 s.track();
2038 bump();
2039 });
2040 assert_eq!(count.get(), 1); batch(|| s.set(2));
2042 assert_eq!(count.get(), 2);
2043 batch(|| s.set(3));
2044 assert_eq!(count.get(), 3);
2045 }
2046
2047 #[test]
2048 fn batch_coalesces() {
2049 let s = Signal::new(0);
2050 let (count, bump) = counter();
2051 Effect::new(move || {
2052 s.track();
2053 bump();
2054 });
2055 batch(|| {
2056 s.set(1);
2057 s.set(2);
2058 s.set(3);
2059 });
2060 assert_eq!(count.get(), 2); assert_eq!(s.get(), 3);
2062 }
2063
2064 #[test]
2065 fn set_if_changed_no_op() {
2066 let s = Signal::new(7);
2067 let (count, bump) = counter();
2068 Effect::new(move || {
2069 s.track();
2070 bump();
2071 });
2072 batch(|| s.set_if_changed(7));
2073 assert_eq!(count.get(), 1); }
2075
2076 #[test]
2077 fn memo_caches_and_diffs() {
2078 let s = Signal::new(1);
2079 let computes = Rc::new(StdCell::new(0));
2080 let c2 = computes.clone();
2081 let doubled = Memo::new(move || {
2082 c2.set(c2.get() + 1);
2083 s.get() * 2
2084 });
2085 assert_eq!(doubled.get(), 2);
2086 assert_eq!(doubled.get(), 2);
2087 assert_eq!(computes.get(), 1); let (effect_runs, bump) = counter();
2089 Effect::new(move || {
2090 let _ = doubled.get();
2091 bump();
2092 });
2093 assert_eq!(effect_runs.get(), 1);
2094 batch(|| s.set(1)); assert_eq!(effect_runs.get(), 1); batch(|| s.set(5));
2098 assert_eq!(doubled.get(), 10);
2099 assert_eq!(effect_runs.get(), 2);
2100 }
2101
2102 #[test]
2103 fn bind_applies_on_change_only() {
2104 let s = Signal::new(1);
2105 let applied: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
2106 let a2 = applied.clone();
2107 bind(
2108 move || s.get().to_string(),
2109 move |v| a2.borrow_mut().push(v.clone()),
2110 );
2111 assert_eq!(*applied.borrow(), vec!["1"]);
2112 batch(|| s.set(2));
2113 assert_eq!(*applied.borrow(), vec!["1", "2"]);
2114 batch(|| s.update(|v| *v = 2)); assert_eq!(*applied.borrow(), vec!["1", "2"]);
2116 }
2117
2118 #[test]
2119 fn watch_skips_initial_and_passes_old() {
2120 type Log = Rc<RefCell<Vec<(i32, Option<i32>)>>>;
2121 let s = Signal::new(10);
2122 let log: Log = Rc::new(RefCell::new(Vec::new()));
2123 let l2 = log.clone();
2124 watch(
2125 move || s.get(),
2126 move |new, old| l2.borrow_mut().push((*new, old.copied())),
2127 );
2128 assert!(log.borrow().is_empty());
2129 batch(|| s.set(11));
2130 assert_eq!(*log.borrow(), vec![(11, Some(10))]);
2131 }
2132
2133 #[test]
2134 fn scope_dispose_stops_effects_and_write_is_noop() {
2135 let s = Signal::new(0);
2136 let (count, bump) = counter();
2137 let scope = Scope::child();
2138 let inner = scope.enter(|| {
2139 let inner = Signal::new(1);
2140 Effect::new(move || {
2141 s.track();
2142 bump();
2143 });
2144 inner
2145 });
2146 assert_eq!(count.get(), 1);
2147 batch(|| s.set(1));
2148 assert_eq!(count.get(), 2);
2149 scope.dispose();
2150 batch(|| s.set(2));
2151 assert_eq!(count.get(), 2); inner.set(9); assert_eq!(inner.try_get(), None);
2154 }
2155
2156 #[test]
2157 fn dispose_during_drain_skips_pending() {
2158 let s = Signal::new(0);
2159 let scope = Scope::child();
2160 let (count, bump) = counter();
2161 let scope_cell = Rc::new(StdCell::new(Some(scope)));
2163 let sc = scope_cell.clone();
2164 Effect::new(move || {
2165 if s.get() == 1
2166 && let Some(scope) = sc.take()
2167 {
2168 scope.dispose();
2169 }
2170 });
2171 scope.enter(|| {
2172 Effect::new(move || {
2173 s.track();
2174 bump();
2175 });
2176 });
2177 assert_eq!(count.get(), 1);
2178 batch(|| s.set(1));
2179 assert_eq!(count.get(), 1);
2182 }
2183
2184 #[test]
2185 fn fixpoint_extends_drain() {
2186 let a = Signal::new(0);
2187 let b = Signal::new(0);
2188 let (count, bump) = counter();
2189 Effect::new(move || {
2190 if a.get() == 1 {
2191 b.set(1); }
2193 });
2194 Effect::new(move || {
2195 b.track();
2196 bump();
2197 });
2198 assert_eq!(count.get(), 1);
2199 batch(|| a.set(1));
2200 assert_eq!(count.get(), 2);
2201 assert_eq!(b.get(), 1);
2202 }
2203
2204 #[cfg(debug_assertions)]
2207 #[test]
2208 #[should_panic(expected = "re-ran more than")]
2209 fn rerun_cap_panics_in_debug() {
2210 let s = Signal::new(0);
2211 Effect::new(move || {
2212 let v = s.get();
2213 s.set(v + 1); });
2215 batch(|| s.set(1));
2216 }
2217
2218 #[test]
2219 fn context_provides_down() {
2220 #[derive(Clone, PartialEq, Debug)]
2221 struct Theme(u32);
2222 let scope = Scope::child();
2223 scope.provide(Theme(7));
2224 let child = scope.create_child();
2225 assert_eq!(child.use_context::<Theme>(), Some(Theme(7)));
2226 scope.dispose();
2227 }
2228
2229 #[test]
2230 fn trigger_notifies() {
2231 let t = Trigger::new();
2232 let (count, bump) = counter();
2233 Effect::new(move || {
2234 t.track();
2235 bump();
2236 });
2237 batch(|| t.notify());
2238 assert_eq!(count.get(), 2);
2239 }
2240
2241 #[test]
2242 fn turn_end_runs_after_fixpoint() {
2243 let s = Signal::new(0);
2244 let order: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
2245 let o1 = order.clone();
2246 Effect::new(move || {
2247 s.track();
2248 o1.borrow_mut().push("effect");
2249 });
2250 let o2 = order.clone();
2251 on_turn_end(move || o2.borrow_mut().push("turn-end"));
2252 order.borrow_mut().clear();
2253 batch(|| s.set(1));
2254 assert_eq!(*order.borrow(), vec!["effect", "turn-end"]);
2255 }
2256
2257 #[test]
2258 fn at_turn_end_waits_for_the_turn_and_runs_once() {
2259 let s = Signal::new(0);
2260 let order: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
2261 let o = order.clone();
2263 at_turn_end(move || o.borrow_mut().push("now".into()));
2264 assert_eq!(*order.borrow(), vec!["now".to_string()]);
2265 order.borrow_mut().clear();
2266 let o1 = order.clone();
2268 Effect::new(move || {
2269 let v = s.get();
2270 o1.borrow_mut().push(format!("effect {v}"));
2271 });
2272 let o2 = order.clone();
2273 on_turn_end(move || o2.borrow_mut().push("standing".into()));
2274 order.borrow_mut().clear();
2275 let o3 = order.clone();
2276 batch(|| {
2277 at_turn_end(move || o3.borrow_mut().push("once".into()));
2278 s.set(1);
2279 });
2280 assert_eq!(*order.borrow(), vec!["effect 1", "once", "standing"]);
2281 order.borrow_mut().clear();
2283 let o4 = order.clone();
2284 batch(|| at_turn_end(move || o4.borrow_mut().push("quiet".into())));
2285 assert_eq!(*order.borrow(), vec!["quiet", "standing"]);
2286 }
2287
2288 #[test]
2289 fn bindings_run_before_effects() {
2290 let s = Signal::new(0);
2291 let order: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
2292 let o1 = order.clone();
2293 Effect::new(move || {
2295 s.track();
2296 o1.borrow_mut().push("effect");
2297 });
2298 let o2 = order.clone();
2299 bind(move || s.get(), move |_| o2.borrow_mut().push("bind"));
2300 order.borrow_mut().clear();
2301 batch(|| s.set(1));
2302 assert_eq!(*order.borrow(), vec!["bind", "effect"]);
2303 }
2304}
2305
2306#[cfg(test)]
2307mod resource_tests {
2308 use super::*;
2309 use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
2310
2311 thread_local! {
2317 static TEST_TASKS: RefCell<Vec<(u64, Option<LocalBoxFuture>)>> =
2318 const { RefCell::new(Vec::new()) };
2319 static NEXT_ID: Cell<u64> = const { Cell::new(1) };
2320 static ABORTED: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
2321 static INSTALLED: Cell<bool> = const { Cell::new(false) };
2322 }
2323
2324 fn noop_waker() -> Waker {
2325 fn raw() -> RawWaker {
2326 RawWaker::new(std::ptr::null(), &VT)
2327 }
2328 static VT: RawWakerVTable = RawWakerVTable::new(|_| raw(), |_| {}, |_| {}, |_| {});
2329 unsafe { Waker::from_raw(raw()) }
2331 }
2332
2333 fn poll_one(fut: &mut LocalBoxFuture) -> bool {
2334 let waker = noop_waker();
2335 let mut cx = Context::from_waker(&waker);
2336 fut.as_mut().poll(&mut cx).is_ready()
2337 }
2338
2339 fn install_test_spawner() {
2340 if INSTALLED.with(|c| c.replace(true)) {
2341 return;
2342 }
2343 install_spawner(|mut fut| {
2344 let id = NEXT_ID.with(|c| {
2345 let v = c.get();
2346 c.set(v + 1);
2347 v
2348 });
2349 if !poll_one(&mut fut) {
2350 TEST_TASKS.with(|t| t.borrow_mut().push((id, Some(fut))));
2351 }
2352 Box::new(move || {
2353 let removed = TEST_TASKS.with(|t| {
2354 let mut t = t.borrow_mut();
2355 let before = t.len();
2356 t.retain(|(i, _)| *i != id);
2357 before != t.len()
2358 });
2359 if removed {
2360 ABORTED.with(|a| a.borrow_mut().push(id));
2361 }
2362 })
2363 });
2364 }
2365
2366 fn aborted_count() -> usize {
2367 ABORTED.with(|a| a.borrow().len())
2368 }
2369
2370 fn pump() {
2372 let ids: Vec<u64> = TEST_TASKS.with(|t| t.borrow().iter().map(|(i, _)| *i).collect());
2373 for id in ids {
2374 let fut = TEST_TASKS.with(|t| {
2375 t.borrow_mut()
2376 .iter_mut()
2377 .find(|(i, _)| *i == id)
2378 .and_then(|(_, s)| s.take())
2379 });
2380 let Some(mut fut) = fut else { continue };
2381 if poll_one(&mut fut) {
2382 TEST_TASKS.with(|t| t.borrow_mut().retain(|(i, _)| *i != id));
2383 } else {
2384 TEST_TASKS.with(|t| {
2385 if let Some((_, s)) = t.borrow_mut().iter_mut().find(|(i, _)| *i == id) {
2386 *s = Some(fut);
2387 }
2388 });
2389 }
2390 }
2391 flush_sync();
2394 }
2395
2396 type Slot<T> = Rc<RefCell<Option<Result<T, TestErr>>>>;
2397
2398 fn manual_future<T: 'static>(slot: Slot<T>) -> impl Future<Output = Result<T, TestErr>> {
2401 std::future::poll_fn(move |_| match slot.borrow_mut().take() {
2402 Some(r) => Poll::Ready(r),
2403 None => Poll::Pending,
2404 })
2405 }
2406
2407 #[derive(Debug)]
2408 struct TestErr(&'static str);
2409 impl std::fmt::Display for TestErr {
2410 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2411 write!(f, "{}", self.0)
2412 }
2413 }
2414 impl std::error::Error for TestErr {}
2415
2416 #[test]
2417 fn resource_sync_fetcher_is_ready_immediately() {
2418 install_test_spawner();
2419 let r = Resource::new(|| (), |()| async { Ok::<_, std::convert::Infallible>(42) });
2420 assert!(r.ready());
2421 assert_eq!(r.with(|l| l.ready().copied()), Some(42));
2422 }
2423
2424 #[test]
2425 fn resource_loading_then_ready() {
2426 install_test_spawner();
2427 let slot: Slot<i32> = Rc::new(RefCell::new(None));
2428 let s2 = slot.clone();
2429 let r = Resource::new(move || (), move |()| manual_future(s2.clone()));
2430 assert!(r.loading());
2431 *slot.borrow_mut() = Some(Ok(7));
2432 pump();
2433 assert_eq!(r.with(|l| l.ready().copied()), Some(7));
2434 }
2435
2436 #[test]
2437 fn resource_failed_preserves_error() {
2438 install_test_spawner();
2439 let r = Resource::new(|| (), |()| async { Err::<i32, _>(TestErr("boom")) });
2440 assert!(!r.ready());
2441 assert_eq!(
2442 r.with(|l| l.error().map(std::string::ToString::to_string)),
2443 Some("boom".into())
2444 );
2445 }
2446
2447 #[test]
2448 fn resource_refetches_on_source_change() {
2449 install_test_spawner();
2450 let src = Signal::new(1i32);
2451 let fetches = Rc::new(Cell::new(0));
2452 let f = fetches.clone();
2453 let r = Resource::new(
2454 move || src.get(),
2455 move |v| {
2456 f.set(f.get() + 1);
2457 async move { Ok::<_, TestErr>(v * 10) }
2458 },
2459 );
2460 assert_eq!(fetches.get(), 1);
2461 assert_eq!(r.with(|l| l.ready().copied()), Some(10));
2462 batch(|| src.set(2));
2463 assert_eq!(fetches.get(), 2);
2464 assert_eq!(r.with(|l| l.ready().copied()), Some(20));
2465 }
2466
2467 #[test]
2468 fn resource_source_equality_gates() {
2469 install_test_spawner();
2470 let a = Signal::new(1i32);
2471 let b = Signal::new(10i32);
2472 let fetches = Rc::new(Cell::new(0));
2473 let f = fetches.clone();
2474 let r = Resource::new(
2475 move || {
2476 let _ = b.get(); a.get()
2478 },
2479 move |v| {
2480 f.set(f.get() + 1);
2481 async move { Ok::<_, TestErr>(v) }
2482 },
2483 );
2484 assert_eq!(fetches.get(), 1);
2485 batch(|| b.set(20)); assert_eq!(fetches.get(), 1);
2487 assert_eq!(r.with(|l| l.ready().copied()), Some(1));
2488 batch(|| a.set(2)); assert_eq!(fetches.get(), 2);
2490 }
2491
2492 #[test]
2493 fn resource_refetch_forces() {
2494 install_test_spawner();
2495 let fetches = Rc::new(Cell::new(0));
2496 let f = fetches.clone();
2497 let r = Resource::new(
2498 || (),
2499 move |()| {
2500 f.set(f.get() + 1);
2501 async { Ok::<_, TestErr>(0) }
2502 },
2503 );
2504 assert_eq!(fetches.get(), 1);
2505 batch(|| r.refetch()); assert_eq!(fetches.get(), 2);
2507 }
2508
2509 #[test]
2510 fn resource_latest_wins() {
2511 install_test_spawner();
2512 let src = Signal::new(1i32);
2513 let slots: Rc<RefCell<Vec<Slot<i32>>>> = Rc::new(RefCell::new(Vec::new()));
2514 let sl = slots.clone();
2515 let r = Resource::new(
2516 move || src.get(),
2517 move |_| {
2518 let slot: Slot<i32> = Rc::new(RefCell::new(None));
2519 sl.borrow_mut().push(slot.clone());
2520 manual_future(slot)
2521 },
2522 );
2523 assert!(r.loading());
2524 let before = aborted_count();
2525 batch(|| src.set(2)); assert_eq!(aborted_count(), before + 1, "the stale task was aborted");
2527 *slots.borrow()[0].borrow_mut() = Some(Ok(111));
2529 pump();
2530 assert!(r.loading(), "a stale result writes nothing");
2531 *slots.borrow()[1].borrow_mut() = Some(Ok(222));
2532 pump();
2533 assert_eq!(r.with(|l| l.ready().copied()), Some(222));
2534 }
2535
2536 #[test]
2537 fn resource_scope_disposal_aborts() {
2538 install_test_spawner();
2539 let scope = Scope::child();
2540 let slot: Slot<i32> = Rc::new(RefCell::new(None));
2541 let s2 = slot.clone();
2542 let r = scope.enter(|| Resource::new(move || (), move |()| manual_future(s2.clone())));
2543 assert!(r.loading());
2544 let before = aborted_count();
2545 scope.dispose();
2546 assert_eq!(aborted_count(), before + 1, "disposal aborted the fetch");
2547 *slot.borrow_mut() = Some(Ok(1));
2549 pump();
2550 }
2551
2552 #[test]
2553 fn resource_ready_is_tracked() {
2554 install_test_spawner();
2555 let slot: Slot<i32> = Rc::new(RefCell::new(None));
2556 let s2 = slot.clone();
2557 let r = Resource::new(move || (), move |()| manual_future(s2.clone()));
2558 let runs = Rc::new(Cell::new(0));
2559 let rn = runs.clone();
2560 Effect::new(move || {
2561 let _ = r.ready();
2562 rn.set(rn.get() + 1);
2563 });
2564 assert_eq!(runs.get(), 1);
2565 *slot.borrow_mut() = Some(Ok(1));
2566 pump();
2567 assert!(runs.get() >= 2, "ready() re-ran the effect on completion");
2568 }
2569
2570 #[test]
2571 #[should_panic(expected = "no spawner installed")]
2572 fn spawner_missing_panics() {
2573 let _r = Resource::new(|| (), |()| async { Ok::<_, std::convert::Infallible>(1) });
2575 }
2576}
2577
2578#[cfg(test)]
2579mod unwind_safety_tests {
2580 use super::*;
2581
2582 fn contained(f: impl FnOnce() + std::panic::UnwindSafe) {
2584 let prev = std::panic::take_hook();
2585 std::panic::set_hook(Box::new(|_| {}));
2586 let r = std::panic::catch_unwind(f);
2587 std::panic::set_hook(prev);
2588 assert!(r.is_err(), "expected the closure to panic");
2589 }
2590
2591 #[test]
2595 fn panic_in_scope_enter_restores_current_scope() {
2596 let before = with_rt(|rt| rt.current_scope);
2597 let scope = Scope::detached();
2598 contained(|| scope.enter(|| panic!("boom in enter")));
2599 assert_eq!(with_rt(|rt| rt.current_scope), before, "scope not restored");
2600 let s = Signal::new(7u32);
2602 assert_eq!(s.get(), 7);
2603 }
2604
2605 #[test]
2612 fn panic_in_effect_body_pops_its_observer_frame() {
2613 let depth = with_rt(|rt| rt.observers.len());
2614 let boom = Signal::new(false);
2615 Effect::new(move || {
2616 assert!(!boom.get(), "effect boom");
2617 });
2618 assert_eq!(with_rt(|rt| rt.observers.len()), depth);
2619 contained(|| batch(|| boom.set(true)));
2620 assert_eq!(
2621 with_rt(|rt| rt.observers.len()),
2622 depth,
2623 "observer frame stranded by the panicking effect run"
2624 );
2625 recover_from_panic(); }
2627
2628 #[test]
2629 fn panic_in_untrack_restores_tracking() {
2630 let depth = with_rt(|rt| rt.observers.len());
2631 contained(|| untrack(|| panic!("boom in untrack")));
2632 assert_eq!(with_rt(|rt| rt.observers.len()), depth, "observer stranded");
2633
2634 let src = Signal::new(0i32);
2636 let runs = Rc::new(RefCell::new(0));
2637 let r2 = runs.clone();
2638 Effect::new(move || {
2639 let _ = src.get();
2640 *r2.borrow_mut() += 1;
2641 });
2642 flush_sync();
2643 let before = *runs.borrow();
2644 src.set(1);
2645 flush_sync();
2646 assert!(
2647 *runs.borrow() > before,
2648 "effect did not re-run — tracking is off"
2649 );
2650 }
2651
2652 #[test]
2655 fn panic_in_batch_restores_depth() {
2656 let depth = with_rt(|rt| rt.batch_depth);
2657 contained(|| batch(|| panic!("boom in batch")));
2658 assert_eq!(with_rt(|rt| rt.batch_depth), depth, "batch depth stranded");
2659 }
2660
2661 #[test]
2665 fn panic_in_with_leaves_the_value_intact() {
2666 let s = Signal::new(String::from("intact"));
2667 contained(|| s.with(|_| panic!("boom in with")));
2668 assert_eq!(s.with(std::clone::Clone::clone), "intact");
2669 }
2670
2671 #[test]
2674 fn reentrant_read_inside_with_succeeds() {
2675 let s = Signal::new(5u32);
2676 let doubled = s.with(|outer| *outer + s.with(|inner| *inner));
2677 assert_eq!(doubled, 10);
2678 assert_eq!(
2679 s.with(|v| *v),
2680 5,
2681 "value still in place after the nested read"
2682 );
2683 }
2684
2685 #[test]
2688 fn nested_reads_of_distinct_signals_succeed() {
2689 let a = Signal::new(2u32);
2690 let b = Signal::new(3u32);
2691 assert_eq!(a.with(|x| *x * b.with(|y| *y)), 6);
2692 }
2693
2694 #[test]
2696 fn write_during_read_panics_with_a_clear_message() {
2697 let s = Signal::new(1u32);
2698 let prev = std::panic::take_hook();
2699 std::panic::set_hook(Box::new(|_| {}));
2700 let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2701 s.with(|_| s.set(2));
2702 }));
2703 std::panic::set_hook(prev);
2704 let payload = r.unwrap_err();
2705 let msg = payload
2707 .downcast_ref::<&str>()
2708 .map(std::string::ToString::to_string)
2709 .or_else(|| payload.downcast_ref::<String>().cloned())
2710 .expect("panic payload should be a string");
2711 assert!(
2712 msg.contains("in flight") && msg.contains("Signal"),
2713 "message should name the cause, got: {msg}"
2714 );
2715 }
2716
2717 #[cfg(not(debug_assertions))]
2722 #[test]
2723 fn rerun_cap_defers_instead_of_killing_the_binding() {
2724 let s = Signal::new(0u32);
2725 let runs = std::rc::Rc::new(std::cell::Cell::new(0u32));
2726 let r2 = runs.clone();
2727 Effect::new(move || {
2728 let v = s.get();
2729 r2.set(r2.get() + 1);
2730 if v < 1_000_000 {
2731 s.set(v + 1); }
2733 });
2734 flush_sync();
2735 let after_cycle = runs.get();
2736 assert!(
2737 after_cycle <= RERUN_CAP + 1,
2738 "cap did not bound the drain: {after_cycle} runs"
2739 );
2740
2741 batch(|| s.set(2_000_000)); assert_eq!(
2744 runs.get(),
2745 after_cycle + 1,
2746 "binding stayed dead after hitting the re-run cap"
2747 );
2748 }
2749}
2750
2751#[cfg(test)]
2752mod owner_scope_tests {
2753 use super::*;
2754
2755 #[test]
2756 fn reactions_and_lazy_memos_keep_their_owner_and_restore_the_caller() {
2757 let outer = Scope::child();
2758 outer.provide("outer fixture");
2759 let first = outer.create_child();
2760 let second = outer.create_child();
2761 first.provide("first fixture");
2762 second.provide("second fixture");
2763 let source = Signal::new(0);
2764 let seen = Rc::new(RefCell::new(Vec::new()));
2765 let lazy = first.enter(|| {
2766 Memo::new(move || {
2767 (
2768 source.get(),
2769 Scope::current().use_context::<&str>().unwrap(),
2770 )
2771 })
2772 });
2773 let nested = second.enter(|| {
2774 Memo::new(move || (lazy.get(), Scope::current().use_context::<&str>().unwrap()))
2775 });
2776 second.enter(|| assert_eq!(lazy.get(), (0, "first fixture")));
2777 assert_eq!(nested.get(), ((0, "first fixture"), "second fixture"));
2778 for (scope, name) in [(first, "first fixture"), (second, "second fixture")] {
2779 let seen = seen.clone();
2780 scope.enter(|| {
2781 Effect::new(move || {
2782 seen.borrow_mut()
2783 .push((source.get(), Scope::current().use_context::<&str>()));
2784 assert_eq!(Scope::current().use_context::<&str>(), Some(name));
2785 });
2786 });
2787 }
2788 second.enter(|| {
2789 batch(|| source.set(1));
2790 assert_eq!(
2791 Scope::current().use_context::<&str>(),
2792 Some("second fixture")
2793 );
2794 });
2795 assert_eq!(nested.get(), ((1, "first fixture"), "second fixture"));
2796 assert_eq!(seen.borrow().len(), 4);
2797 outer.dispose();
2798 batch(|| source.set(2));
2799 assert_eq!(seen.borrow().len(), 4, "disposed reactions must not run");
2800 }
2801
2802 #[test]
2803 fn watches_allocate_state_and_cleanup_in_their_owner() {
2804 let owner = Scope::child();
2805 let trigger = Signal::new(0);
2806 let allocated = Rc::new(Cell::new(None::<Signal<i32>>));
2807 let cleaned = Rc::new(Cell::new(0));
2808 owner.enter(|| {
2809 let allocated = allocated.clone();
2810 let cleaned = cleaned.clone();
2811 watch(
2812 move || trigger.get(),
2813 move |value, _| {
2814 allocated.set(Some(Signal::new(*value)));
2815 let cleaned = cleaned.clone();
2816 Scope::current().on_cleanup(move || cleaned.set(cleaned.get() + 1));
2817 },
2818 );
2819 });
2820 batch(|| trigger.set(1));
2821 let state = allocated.get().unwrap();
2822 assert_eq!(state.get(), 1);
2823 owner.dispose();
2824 assert_eq!(cleaned.get(), 1);
2825 assert!(state.try_get().is_none());
2826 }
2827
2828 #[test]
2829 fn panic_in_owned_computations_restores_scope_and_tracking() {
2830 let owner = Scope::child();
2831 owner.provide("owner fixture");
2832 let caller = Scope::child();
2833 caller.provide("caller fixture");
2834 let trigger = Signal::new(false);
2835 let memo = owner.enter(|| {
2836 Memo::new(move || {
2837 assert_eq!(
2838 Scope::current().use_context::<&str>(),
2839 Some("owner fixture")
2840 );
2841 assert!(!trigger.get(), "synthetic memo failure");
2842 7
2843 })
2844 });
2845 assert_eq!(memo.get(), 7);
2846 batch(|| trigger.set(true));
2847 caller.enter(|| {
2848 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| memo.get()));
2849 assert!(result.is_err());
2850 assert_eq!(
2851 Scope::current().use_context::<&str>(),
2852 Some("caller fixture")
2853 );
2854 assert!(with_rt(|rt| rt.observers.is_empty()));
2855 });
2856 owner.dispose();
2857 caller.dispose();
2858 }
2859}