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(|s| s.depth).unwrap_or(0);
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.iter() {
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 = RtGuard(|rt: &mut Runtime| {
411 rt.observers.pop();
412 });
413 f()
414 }))
415}
416
417fn refresh_memo(key: NodeKey) {
419 let (state, kind) = match with_rt(|rt| rt.nodes.get(key).map(|n| (n.state, n.kind))) {
420 Some(v) => v,
421 None => return,
422 };
423 if kind != NodeKind::Memo || state == NodeState::Clean {
424 return;
425 }
426 if state == NodeState::Check {
427 let (sources, last_run) =
429 with_rt(|rt| (rt.nodes[key].sources.clone(), rt.nodes[key].last_run));
430 let mut any_changed = false;
431 for s in sources {
432 refresh_memo(s);
433 if with_rt(|rt| {
434 rt.nodes
435 .get(s)
436 .map(|n| n.last_changed > last_run)
437 .unwrap_or(false)
438 }) {
439 any_changed = true;
440 }
441 }
442 if !any_changed {
443 with_rt(|rt| {
444 if let Some(n) = rt.nodes.get_mut(key) {
445 n.state = NodeState::Clean;
446 }
447 });
448 return;
449 }
450 }
451 let compute = with_rt(|rt| rt.nodes[key].memo_compute.clone());
453 let Some(compute) = compute else { return };
454 let cleanups = with_rt(|rt| clear_sources(rt, key));
455 for f in cleanups {
456 f();
457 }
458 let Some(new_value) = compute_in_owner(key, || compute()) else {
459 return;
460 };
461 with_rt(|rt| {
462 let tick = rt.tick;
463 let Some(node) = rt.nodes.get_mut(key) else {
464 return;
465 };
466 let changed = match (node.value.as_ref(), node.memo_eq) {
467 (Some(old), Some(eq)) => {
468 let old = old.borrow();
470 !eq(old.as_ref(), new_value.as_ref())
471 }
472 _ => true,
473 };
474 node.last_run = tick;
475 node.state = NodeState::Clean;
476 if changed {
477 node.value = Some(Rc::new(RefCell::new(new_value)));
480 node.last_changed = tick;
481 rt.tick += 1;
482 }
483 });
486}
487
488fn run_reaction(key: NodeKey) {
490 let info = with_rt(|rt| {
491 rt.nodes.get_mut(key).map(|n| {
492 n.queued = false;
493 (n.state, n.sources.clone(), n.last_run)
494 })
495 });
496 let Some((state, sources, last_run)) = info else {
497 return;
498 };
499 if state == NodeState::Clean {
500 return;
501 }
502 if state == NodeState::Check {
503 let mut any_changed = false;
504 for s in &sources {
505 refresh_memo(*s);
506 if with_rt(|rt| {
507 rt.nodes
508 .get(*s)
509 .map(|n| n.last_changed > last_run)
510 .unwrap_or(false)
511 }) {
512 any_changed = true;
513 break;
514 }
515 }
516 if !any_changed {
517 with_rt(|rt| {
518 if let Some(n) = rt.nodes.get_mut(key) {
519 n.state = NodeState::Clean;
520 }
521 });
522 return;
523 }
524 }
525 let reaction = with_rt(|rt| rt.nodes.get(key).and_then(|n| n.reaction.clone()));
526 let Some(reaction) = reaction else { return };
527 let cleanups = with_rt(|rt| {
528 let cleanups = clear_sources(rt, key);
529 if let Some(n) = rt.nodes.get_mut(key) {
530 n.state = NodeState::Clean;
531 }
532 cleanups
533 });
534 for f in cleanups {
536 f();
537 }
538 compute_in_owner(key, || reaction());
539 with_rt(|rt| {
540 let tick = rt.tick;
541 rt.tick += 1;
542 if let Some(n) = rt.nodes.get_mut(key) {
543 n.last_run = tick;
544 }
545 });
546}
547
548pub fn flush_sync() {
558 let already = with_rt(|rt| {
559 if rt.draining {
560 return true;
561 }
562 rt.draining = true;
563 false
564 });
565 if already {
566 return; }
568 let mut round = 0u32;
569 'turn: loop {
570 round += 1;
571 let mut run_counts: HashMap<NodeKey, u32> = HashMap::new();
573 loop {
574 let mut batch = with_rt(|rt| std::mem::take(&mut rt.pending));
575 if batch.is_empty() {
576 break;
577 }
578 with_rt(|rt| {
580 batch.sort_by_key(|&k| {
581 rt.nodes
582 .get(k)
583 .map(|n| (n.priority, n.depth, n.seq))
584 .unwrap_or((u8::MAX, u32::MAX, u64::MAX))
585 })
586 });
587 for key in batch {
588 let count = run_counts.entry(key).or_insert(0);
589 *count += 1;
590 if *count > RERUN_CAP {
591 if *count == RERUN_CAP + 1 {
592 let loc = with_rt(|rt| rt.nodes.get(key).map(|n| n.created_at));
593 if let Some(loc) = loc {
594 if cfg!(debug_assertions) {
595 panic!(
596 "day-reactive: effect created at {loc} re-ran more than {RERUN_CAP} times in one drain (reactive cycle?)"
597 );
598 } else {
599 log::warn!(
600 "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)"
601 );
602 }
603 }
604 }
605 with_rt(|rt| {
611 if let Some(n) = rt.nodes.get_mut(key) {
612 n.queued = false;
613 n.state = NodeState::Clean;
614 }
615 });
616 continue;
617 }
618 run_reaction(key);
619 }
620 }
621 let (once, turn_end) = with_rt(|rt| {
622 rt.draining = false;
623 rt.schedule_posted = false;
624 (std::mem::take(&mut rt.turn_end_once), rt.turn_end.clone())
625 });
626 for cb in once {
629 cb();
630 }
631 for cb in turn_end {
632 cb();
633 }
634 let more = with_rt(|rt| {
636 if rt.pending.is_empty() {
637 return false;
638 }
639 rt.draining = true;
640 true
641 });
642 if !more {
643 return;
644 }
645 if round >= TURN_ROUND_CAP {
646 with_rt(|rt| rt.draining = false);
650 if cfg!(debug_assertions) {
651 panic!(
652 "day-reactive: turn-end callbacks scheduled new reactive work for {TURN_ROUND_CAP} straight rounds in one turn (hooks feeding each other?)"
653 );
654 } else {
655 log::warn!(
656 "day-reactive: turn-end callbacks still scheduling work after {TURN_ROUND_CAP} rounds; deferring the rest to the next turn"
657 );
658 }
659 return;
660 }
661 continue 'turn;
662 }
663}
664
665pub fn recover_from_panic() {
672 with_rt(|rt| {
673 rt.draining = false;
674 rt.schedule_posted = false;
675 rt.batch_depth = 0;
676 rt.turn_end_once.clear();
677 rt.pending.clear();
678 rt.observers.clear();
679 rt.current_scope = rt.root_scope;
683 });
684}
685
686fn schedule_after_write(rt: &mut Runtime) -> Option<Rc<dyn Fn()>> {
689 if rt.batch_depth > 0 || rt.draining {
690 return None;
691 }
692 if rt.schedule_posted {
693 return None;
694 }
695 rt.schedule_posted = true;
696 rt.scheduler.clone()
697}
698
699fn signal_write_boxed(key: NodeKey, apply: impl FnOnce(&mut Box<dyn Any>) -> bool) {
700 let poster = with_rt(|rt| {
701 let node = rt.nodes.get_mut(key)?;
702 let cell = node.value.as_ref()?.clone();
703 let mut value = match cell.try_borrow_mut() {
704 Ok(v) => v,
705 Err(_) => panic!(
709 "day-reactive: wrote to a Signal while a with()/try_with() read of it is still \
710 in flight — the write would be lost. Finish the read closure first (copy the \
711 value out with get()) and write after it returns."
712 ),
713 };
714 let changed = apply(&mut value);
715 drop(value);
716 let node = rt.nodes.get_mut(key)?;
717 if !changed {
718 return None;
719 }
720 node.last_changed = rt.tick;
721 rt.tick += 1;
722 mark_observers(rt, key, NodeState::Dirty);
723 schedule_after_write(rt)
724 });
725 if let Some(post) = poster {
726 post();
727 }
728}
729
730struct RtGuard<F: FnMut(&mut Runtime)>(F);
741
742impl<F: FnMut(&mut Runtime)> Drop for RtGuard<F> {
743 fn drop(&mut self) {
744 with_rt(|rt| (self.0)(rt));
745 }
746}
747
748pub fn batch<R>(f: impl FnOnce() -> R) -> R {
749 with_rt(|rt| rt.batch_depth += 1);
750 let r = {
751 let _g = RtGuard(|rt: &mut Runtime| rt.batch_depth = rt.batch_depth.saturating_sub(1));
756 f()
757 };
758 let should_drain = with_rt(|rt| {
759 rt.batch_depth == 0
760 && !rt.draining
761 && (!rt.pending.is_empty() || !rt.turn_end_once.is_empty())
762 });
763 if should_drain {
764 flush_sync();
765 }
766 r
767}
768
769pub fn flush_now() {
776 let saved = with_rt(|rt| std::mem::replace(&mut rt.batch_depth, 0));
777 let _g = RtGuard(move |rt: &mut Runtime| rt.batch_depth = saved);
780 flush_sync();
781}
782
783pub fn untrack<R>(f: impl FnOnce() -> R) -> R {
785 with_rt(|rt| rt.observers.push(None));
786 let _g = RtGuard(|rt: &mut Runtime| {
789 rt.observers.pop();
790 });
791 f()
792}
793
794#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
798pub struct RunId(NodeKey);
799
800pub fn active_run() -> Option<RunId> {
802 with_rt(|rt| rt.observers.last().copied().flatten()).map(RunId)
803}
804
805pub fn on_run_retrack(f: impl FnOnce() + 'static) -> bool {
810 with_rt(|rt| {
811 let Some(Some(key)) = rt.observers.last().copied() else {
812 return false;
813 };
814 match rt.nodes.get_mut(key) {
815 Some(n) => {
816 n.run_cleanups.push(Box::new(f));
817 true
818 }
819 None => false,
820 }
821 })
822}
823
824pub fn install_scheduler(post: impl Fn() + 'static) {
826 with_rt(|rt| rt.scheduler = Some(Rc::new(post)));
827}
828
829pub type LocalBoxFuture = Pin<Box<dyn Future<Output = ()> + 'static>>;
831
832type Spawner = Rc<dyn Fn(LocalBoxFuture) -> Box<dyn FnOnce()>>;
834
835pub fn install_spawner(spawn: impl Fn(LocalBoxFuture) -> Box<dyn FnOnce()> + 'static) {
841 with_rt(|rt| rt.spawner = Some(Rc::new(spawn)));
842}
843
844fn spawn_local(fut: LocalBoxFuture) -> Box<dyn FnOnce()> {
846 let spawner = with_rt(|rt| rt.spawner.clone());
847 match spawner {
848 Some(s) => s(fut),
849 None => panic!("day-reactive: no spawner installed (backend not started)"),
850 }
851}
852
853pub fn on_turn_end(cb: impl Fn() + 'static) {
855 with_rt(|rt| rt.turn_end.push(Rc::new(cb)));
856}
857
858pub fn at_turn_end(cb: impl FnOnce() + 'static) {
865 let now = with_rt(|rt| {
866 if rt.draining || rt.batch_depth > 0 {
867 rt.turn_end_once.push(Box::new(cb));
868 None
869 } else {
870 Some(cb)
871 }
872 });
873 if let Some(cb) = now {
874 cb();
875 }
876}
877
878type MainPoster = Box<dyn Fn(Box<dyn FnOnce() + Send>) + Send + Sync>;
883static MAIN_POSTER: std::sync::OnceLock<MainPoster> = std::sync::OnceLock::new();
884
885pub fn install_main_poster(post: impl Fn(Box<dyn FnOnce() + Send>) + Send + Sync + 'static) {
887 let _ = MAIN_POSTER.set(Box::new(post));
888}
889
890pub fn has_main_poster() -> bool {
896 MAIN_POSTER.get().is_some()
897}
898
899pub fn on_main(f: impl FnOnce() + Send + 'static) {
901 match MAIN_POSTER.get() {
902 Some(post) => post(Box::new(f)),
903 None => panic!("day-reactive: no main poster installed (backend not started)"),
904 }
905}
906
907type DelayedPoster = Box<dyn Fn(u32, Box<dyn FnOnce() + Send>) + Send + Sync>;
908static DELAYED_POSTER: std::sync::OnceLock<DelayedPoster> = std::sync::OnceLock::new();
909
910pub fn install_delayed_poster(
912 post: impl Fn(u32, Box<dyn FnOnce() + Send>) + Send + Sync + 'static,
913) {
914 let _ = DELAYED_POSTER.set(Box::new(post));
915}
916
917pub fn on_main_delayed(ms: u32, f: impl FnOnce() + Send + 'static) {
920 match DELAYED_POSTER.get() {
921 Some(post) => post(ms, Box::new(f)),
922 None => panic!("day-reactive: no delayed poster installed (backend not started)"),
923 }
924}
925
926#[derive(Clone, Copy, PartialEq, Eq)]
932pub struct Scope {
933 key: ScopeKey,
934 _not_send: PhantomData<*const ()>,
935}
936
937impl Scope {
938 pub fn current() -> Scope {
939 Scope {
940 key: with_rt(|rt| rt.current_scope),
941 _not_send: PhantomData,
942 }
943 }
944
945 pub fn root() -> Scope {
946 Scope {
947 key: with_rt(|rt| rt.root_scope),
948 _not_send: PhantomData,
949 }
950 }
951
952 pub fn child() -> Scope {
954 Scope::current().create_child()
955 }
956
957 pub fn create_child(self) -> Scope {
958 let key = with_rt(|rt| {
959 let depth = rt.scopes.get(self.key).map(|s| s.depth + 1).unwrap_or(1);
960 let child = rt.scopes.insert(ScopeData {
961 parent: self.key,
962 children: Vec::new(),
963 nodes: Vec::new(),
964 cleanups: Vec::new(),
965 context: HashMap::new(),
966 depth,
967 });
968 if let Some(p) = rt.scopes.get_mut(self.key) {
969 p.children.push(child);
970 }
971 child
972 });
973 Scope {
974 key,
975 _not_send: PhantomData,
976 }
977 }
978
979 pub fn detached() -> Scope {
981 let key = with_rt(|rt| {
982 rt.scopes.insert(ScopeData {
983 parent: ScopeKey::null(),
984 children: Vec::new(),
985 nodes: Vec::new(),
986 cleanups: Vec::new(),
987 context: HashMap::new(),
988 depth: 0,
989 })
990 });
991 Scope {
992 key,
993 _not_send: PhantomData,
994 }
995 }
996
997 pub fn enter<R>(self, f: impl FnOnce() -> R) -> R {
999 let prev = with_rt(|rt| std::mem::replace(&mut rt.current_scope, self.key));
1000 let _g = RtGuard(move |rt: &mut Runtime| rt.current_scope = prev);
1004 f()
1005 }
1006
1007 pub fn on_cleanup(self, f: impl FnOnce() + 'static) {
1008 with_rt(|rt| {
1009 if let Some(s) = rt.scopes.get_mut(self.key) {
1010 s.cleanups.push(Box::new(f));
1011 }
1012 });
1013 }
1014
1015 pub fn is_alive(self) -> bool {
1016 with_rt(|rt| rt.scopes.contains_key(self.key))
1017 }
1018
1019 pub fn dispose(self) {
1021 let children = match with_rt(|rt| rt.scopes.get(self.key).map(|s| s.children.clone())) {
1022 Some(c) => c,
1023 None => return,
1024 };
1025 for c in children {
1026 (Scope {
1027 key: c,
1028 _not_send: PhantomData,
1029 })
1030 .dispose();
1031 }
1032 let (nodes, cleanups, parent) = match with_rt(|rt| {
1033 rt.scopes
1034 .remove(self.key)
1035 .map(|s| (s.nodes, s.cleanups, s.parent))
1036 }) {
1037 Some(v) => v,
1038 None => return,
1039 };
1040 let mut run_cleanups: Vec<Box<dyn FnOnce()>> = Vec::new();
1041 with_rt(|rt| {
1042 if let Some(p) = rt.scopes.get_mut(parent)
1043 && let Some(pos) = p.children.iter().position(|&c| c == self.key)
1044 {
1045 p.children.swap_remove(pos);
1046 }
1047 for key in nodes {
1048 run_cleanups.extend(clear_sources(rt, key));
1049 if let Some(node) = rt.nodes.get_mut(key) {
1051 let observers = std::mem::take(&mut node.observers);
1052 for o in observers {
1053 if let Some(on) = rt.nodes.get_mut(o)
1054 && let Some(pos) = on.sources.iter().position(|&s| s == key)
1055 {
1056 on.sources.swap_remove(pos);
1057 }
1058 }
1059 }
1060 rt.nodes.remove(key);
1061 }
1063 });
1064 for f in run_cleanups {
1067 f();
1068 }
1069 for c in cleanups {
1070 c();
1071 }
1072 }
1073
1074 pub fn provide<T: 'static>(self, value: T) {
1076 with_rt(|rt| {
1077 if let Some(s) = rt.scopes.get_mut(self.key) {
1078 s.context.insert(TypeId::of::<T>(), Box::new(value));
1079 }
1080 });
1081 }
1082
1083 pub fn use_context<T: Clone + 'static>(self) -> Option<T> {
1085 with_rt(|rt| {
1086 let mut cur = self.key;
1087 while let Some(s) = rt.scopes.get(cur) {
1088 if let Some(v) = s.context.get(&TypeId::of::<T>()) {
1089 return v.downcast_ref::<T>().cloned();
1090 }
1091 cur = s.parent;
1092 }
1093 None
1094 })
1095 }
1096}
1097
1098pub struct Signal<T: 'static> {
1104 key: NodeKey,
1105 created_at: &'static Location<'static>,
1106 _m: PhantomData<*const T>,
1107}
1108
1109impl<T: 'static> Clone for Signal<T> {
1110 fn clone(&self) -> Self {
1111 *self
1112 }
1113}
1114impl<T: 'static> Copy for Signal<T> {}
1115
1116impl<T: 'static> std::fmt::Debug for Signal<T> {
1117 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1118 write!(f, "Signal({:?})", self.key)
1119 }
1120}
1121
1122impl<T: 'static> Signal<T> {
1123 #[track_caller]
1124 pub fn new(value: T) -> Self {
1125 Self::new_in(Scope::current(), value)
1126 }
1127
1128 #[track_caller]
1135 pub fn global(value: T) -> Self {
1136 Self::new_in(Scope::root(), value)
1137 }
1138
1139 #[track_caller]
1140 pub fn new_in(scope: Scope, value: T) -> Self {
1141 let created_at = Location::caller();
1142 let key = with_rt(|rt| {
1143 let k = create_node(rt, NodeKind::Signal, scope.key);
1144 rt.nodes[k].value = Some(Rc::new(RefCell::new(Box::new(value) as Box<dyn Any>)));
1145 rt.nodes[k].created_at = created_at;
1146 k
1147 });
1148 Signal {
1149 key,
1150 created_at,
1151 _m: PhantomData,
1152 }
1153 }
1154
1155 #[track_caller]
1157 pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
1158 match self.try_with(f) {
1159 Some(r) => r,
1160 None => panic!(
1161 "day-reactive: read of disposed Signal created at {} (use try_with in closures that can outlive their scope)",
1162 self.created_at
1163 ),
1164 }
1165 }
1166
1167 pub fn try_with<R>(self, f: impl FnOnce(&T) -> R) -> Option<R> {
1168 let cell = with_rt(|rt| {
1173 track_read(rt, self.key);
1174 rt.nodes.get(self.key).and_then(|n| n.value.clone())
1175 })?;
1176 let value = cell.borrow();
1177 value.downcast_ref::<T>().map(f)
1178 }
1179
1180 pub fn with_untracked<R>(self, f: impl FnOnce(&T) -> R) -> R {
1181 untrack(|| self.with(f))
1182 }
1183
1184 #[track_caller]
1185 pub fn get(self) -> T
1186 where
1187 T: Clone,
1188 {
1189 self.with(|v| v.clone())
1190 }
1191
1192 pub fn try_get(self) -> Option<T>
1193 where
1194 T: Clone,
1195 {
1196 self.try_with(|v| v.clone())
1197 }
1198
1199 pub fn get_untracked(self) -> T
1200 where
1201 T: Clone,
1202 {
1203 untrack(|| self.get())
1204 }
1205
1206 pub fn track(self) {
1208 with_rt(|rt| track_read(rt, self.key));
1209 }
1210
1211 #[track_caller]
1212 pub fn set(self, value: T) {
1213 self.write_check(move |slot| {
1214 *slot = value;
1215 true
1216 });
1217 }
1218
1219 #[track_caller]
1220 pub fn set_if_changed(self, value: T)
1221 where
1222 T: PartialEq,
1223 {
1224 self.write_check(move |slot| {
1225 if *slot == value {
1226 false
1227 } else {
1228 *slot = value;
1229 true
1230 }
1231 });
1232 }
1233
1234 #[track_caller]
1235 pub fn update(self, f: impl FnOnce(&mut T)) {
1236 self.write_check(move |slot| {
1237 f(slot);
1238 true
1239 });
1240 }
1241
1242 #[track_caller]
1243 fn write_check(self, apply: impl FnOnce(&mut T) -> bool) {
1244 let alive = with_rt(|rt| rt.nodes.contains_key(self.key));
1245 if !alive {
1246 let loc = Location::caller();
1248 let first = with_rt(|rt| rt.warned_writes.insert(loc as *const _));
1249 if first && cfg!(debug_assertions) {
1250 log::warn!(
1251 "day-reactive: write at {loc} to a disposed signal (created at {}) ignored",
1252 self.created_at
1253 );
1254 }
1255 return;
1256 }
1257 signal_write_boxed(self.key, |boxed| match boxed.downcast_mut::<T>() {
1258 Some(slot) => apply(slot),
1259 None => false,
1260 });
1261 }
1262
1263 pub fn setter(self) -> Setter<T>
1265 where
1266 T: Send,
1267 {
1268 Setter {
1269 key: self.key,
1270 _m: PhantomData,
1271 }
1272 }
1273}
1274
1275pub struct Setter<T: Send + 'static> {
1278 key: NodeKey,
1279 _m: PhantomData<fn(T)>,
1280}
1281
1282impl<T: Send + 'static> Clone for Setter<T> {
1283 fn clone(&self) -> Self {
1284 *self
1285 }
1286}
1287impl<T: Send + 'static> Copy for Setter<T> {}
1288
1289impl<T: Send + 'static> Setter<T> {
1290 pub fn set(self, value: T) {
1291 let key = self.key;
1292 on_main(move || {
1293 let poster = with_rt(|rt| {
1294 let cell = rt.nodes.get(key)?.value.clone()?;
1295 {
1296 let mut boxed = cell.try_borrow_mut().ok()?;
1297 let slot = boxed.downcast_mut::<T>()?;
1298 *slot = value;
1299 }
1300 let node = rt.nodes.get_mut(key)?;
1301 node.last_changed = rt.tick;
1302 rt.tick += 1;
1303 mark_observers(rt, key, NodeState::Dirty);
1304 schedule_after_write(rt)
1305 });
1306 if let Some(post) = poster {
1307 post();
1308 }
1309 });
1310 }
1311}
1312
1313pub struct Memo<T: 'static> {
1319 key: NodeKey,
1320 created_at: &'static Location<'static>,
1321 _m: PhantomData<*const T>,
1322}
1323
1324impl<T: 'static> Clone for Memo<T> {
1325 fn clone(&self) -> Self {
1326 *self
1327 }
1328}
1329impl<T: 'static> Copy for Memo<T> {}
1330
1331impl<T: 'static> Memo<T> {
1332 #[track_caller]
1333 pub fn new(f: impl Fn() -> T + 'static) -> Self
1334 where
1335 T: PartialEq,
1336 {
1337 Self::new_with_eq(f, |a, b| a == b)
1338 }
1339
1340 #[track_caller]
1341 pub fn new_with_eq(f: impl Fn() -> T + 'static, eq: fn(&T, &T) -> bool) -> Self {
1342 let created_at = Location::caller();
1343 let key = with_rt(|rt| {
1346 let scope = rt.current_scope;
1347 create_node(rt, NodeKind::Memo, scope)
1348 });
1349 let compute: Rc<dyn Fn() -> Box<dyn Any>> =
1350 Rc::new(move || Box::new(EqBox { value: f(), eq }) as Box<dyn Any>);
1351 with_rt(|rt| {
1352 let node = &mut rt.nodes[key];
1353 node.memo_compute = Some(compute);
1354 node.memo_eq = Some(eqbox_eq::<T>);
1355 node.state = NodeState::Dirty; node.created_at = created_at;
1357 });
1358 Memo {
1359 key,
1360 created_at,
1361 _m: PhantomData,
1362 }
1363 }
1364
1365 #[track_caller]
1366 pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
1367 refresh_memo(self.key);
1368 let value = with_rt(|rt| {
1369 track_read(rt, self.key);
1370 rt.nodes.get(self.key).and_then(|n| n.value.clone())
1371 });
1372 match value {
1373 Some(cell) => {
1375 let boxed = cell.borrow();
1376 boxed
1377 .downcast_ref::<EqBox<T>>()
1378 .map(|e| f(&e.value))
1379 .unwrap_or_else(|| panic!("day-reactive: memo type mismatch"))
1380 }
1381 None => panic!(
1382 "day-reactive: read of disposed Memo created at {}",
1383 self.created_at
1384 ),
1385 }
1386 }
1387
1388 #[track_caller]
1389 pub fn get(self) -> T
1390 where
1391 T: Clone,
1392 {
1393 self.with(|v| v.clone())
1394 }
1395}
1396
1397struct EqBox<T> {
1399 value: T,
1400 eq: fn(&T, &T) -> bool,
1401}
1402
1403fn eqbox_eq<T: 'static>(a: &dyn Any, b: &dyn Any) -> bool {
1404 match (a.downcast_ref::<EqBox<T>>(), b.downcast_ref::<EqBox<T>>()) {
1405 (Some(a), Some(b)) => (a.eq)(&a.value, &b.value),
1406 _ => false,
1407 }
1408}
1409
1410pub struct Effect;
1418
1419impl Effect {
1420 #[allow(clippy::new_ret_no_self)]
1423 #[track_caller]
1424 pub fn new(f: impl Fn() + 'static) {
1425 create_reaction(Rc::new(f), 1);
1426 }
1427}
1428
1429#[track_caller]
1430fn create_reaction(f: Rc<dyn Fn()>, priority: u8) -> NodeKey {
1431 let created_at = Location::caller();
1432 let key = with_rt(|rt| {
1433 let scope = rt.current_scope;
1434 let k = create_node(rt, NodeKind::Reaction, scope);
1435 rt.nodes[k].reaction = Some(f);
1436 rt.nodes[k].priority = priority;
1437 rt.nodes[k].created_at = created_at;
1438 k
1439 });
1440 let reaction = with_rt(|rt| rt.nodes[key].reaction.clone());
1441 if let Some(reaction) = reaction {
1442 compute_in_owner(key, || reaction());
1443 }
1444 with_rt(|rt| {
1445 let tick = rt.tick;
1446 rt.tick += 1;
1447 if let Some(n) = rt.nodes.get_mut(key) {
1448 n.last_run = tick;
1449 }
1450 });
1451 key
1452}
1453
1454#[track_caller]
1458pub fn bind<V: PartialEq + 'static>(
1459 compute: impl Fn() -> V + 'static,
1460 apply: impl Fn(&V) + 'static,
1461) {
1462 let last: RefCell<Option<V>> = RefCell::new(None);
1463 create_reaction(
1464 Rc::new(move || {
1465 let v = compute();
1466 if last.borrow().as_ref() != Some(&v) {
1467 untrack(|| apply(&v));
1468 *last.borrow_mut() = Some(v);
1469 }
1470 }),
1471 0,
1472 );
1473}
1474
1475#[track_caller]
1478pub fn bind_seeded<V: PartialEq + 'static>(
1479 seed: V,
1480 compute: impl Fn() -> V + 'static,
1481 apply: impl Fn(&V) + 'static,
1482) {
1483 let last: RefCell<Option<V>> = RefCell::new(Some(seed));
1484 create_reaction(
1485 Rc::new(move || {
1486 let v = compute();
1487 if last.borrow().as_ref() != Some(&v) {
1488 untrack(|| apply(&v));
1489 *last.borrow_mut() = Some(v);
1490 }
1491 }),
1492 0,
1493 );
1494}
1495
1496#[track_caller]
1498pub fn bind_always<V: 'static>(compute: impl Fn() -> V + 'static, apply: impl Fn(V) + 'static) {
1499 create_reaction(
1500 Rc::new(move || {
1501 let v = compute();
1502 untrack(|| apply(v));
1503 }),
1504 0,
1505 );
1506}
1507
1508#[track_caller]
1513pub fn watch<S: Clone + 'static>(
1514 source: impl Fn() -> S + 'static,
1515 cb: impl Fn(&S, Option<&S>) + 'static,
1516) {
1517 let prev: RefCell<Option<S>> = RefCell::new(None);
1518 create_reaction(
1519 Rc::new(move || {
1520 let new = source();
1521 let old = prev.borrow_mut().replace(new.clone());
1522 if old.is_some() {
1523 untrack(|| cb(&new, old.as_ref()));
1524 }
1525 }),
1526 1,
1527 );
1528}
1529
1530#[derive(Clone, Copy)]
1532pub struct Trigger {
1533 signal: Signal<u64>,
1534}
1535
1536impl Trigger {
1537 #[track_caller]
1538 pub fn new() -> Self {
1539 Trigger {
1540 signal: Signal::new(0),
1541 }
1542 }
1543 pub fn track(self) {
1544 self.signal.track();
1545 }
1546 pub fn notify(self) {
1547 self.signal.update(|v| *v = v.wrapping_add(1));
1548 }
1549}
1550
1551impl Default for Trigger {
1552 fn default() -> Self {
1553 Self::new()
1554 }
1555}
1556
1557pub trait Binding<T: 'static>: Clone + 'static {
1567 fn read(&self) -> T;
1569 fn peek(&self) -> T;
1571 fn write(&self, v: T);
1573 fn write_preview(&self, v: T) {
1577 self.write(v);
1578 }
1579 fn write_commit(&self, v: T) {
1583 self.write(v);
1584 }
1585 fn write_teardown(&self, v: T) {
1588 self.write_commit(v);
1589 }
1590}
1591
1592impl<T: Clone + 'static> Binding<T> for Signal<T> {
1593 fn read(&self) -> T {
1594 self.get()
1595 }
1596 fn peek(&self) -> T {
1597 self.get_untracked()
1598 }
1599 fn write(&self, v: T) {
1600 self.set(v);
1601 }
1602 fn write_teardown(&self, _v: T) {}
1603}
1604
1605trait ErasedBinding<T: 'static> {
1608 fn erased_read(&self) -> T;
1609 fn erased_peek(&self) -> T;
1610 fn erased_write(&self, v: T);
1611 fn erased_write_preview(&self, v: T);
1612 fn erased_write_commit(&self, v: T);
1613 fn erased_write_teardown(&self, v: T);
1614}
1615
1616impl<T: 'static, B: Binding<T>> ErasedBinding<T> for B {
1617 fn erased_read(&self) -> T {
1618 Binding::read(self)
1619 }
1620 fn erased_peek(&self) -> T {
1621 Binding::peek(self)
1622 }
1623 fn erased_write(&self, v: T) {
1624 Binding::write(self, v)
1625 }
1626 fn erased_write_preview(&self, v: T) {
1627 Binding::write_preview(self, v)
1628 }
1629 fn erased_write_commit(&self, v: T) {
1630 Binding::write_commit(self, v)
1631 }
1632 fn erased_write_teardown(&self, v: T) {
1633 Binding::write_teardown(self, v)
1634 }
1635}
1636
1637pub struct AnyBinding<T: 'static> {
1645 slot: Signal<Rc<dyn ErasedBinding<T>>>,
1646}
1647
1648impl<T: 'static> Clone for AnyBinding<T> {
1649 fn clone(&self) -> Self {
1650 *self
1651 }
1652}
1653impl<T: 'static> Copy for AnyBinding<T> {}
1654
1655impl<T: 'static> AnyBinding<T> {
1656 pub fn new(binding: impl Binding<T>) -> Self {
1658 let erased: Rc<dyn ErasedBinding<T>> = Rc::new(binding);
1659 AnyBinding {
1660 slot: Signal::new(erased),
1661 }
1662 }
1663 fn inner(self) -> Rc<dyn ErasedBinding<T>> {
1664 self.slot.get_untracked()
1665 }
1666 pub fn get(self) -> T {
1668 self.inner().erased_read()
1669 }
1670 pub fn try_get(self) -> Option<T> {
1672 self.slot.try_get().map(|b| b.erased_read())
1673 }
1674 pub fn get_untracked(self) -> T {
1676 self.inner().erased_peek()
1677 }
1678 pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
1680 let v = self.inner().erased_read();
1681 f(&v)
1682 }
1683 pub fn set(self, v: T) {
1685 self.inner().erased_write(v)
1686 }
1687 pub fn set_if_changed(self, v: T)
1689 where
1690 T: PartialEq,
1691 {
1692 let b = self.inner();
1693 if b.erased_peek() != v {
1694 b.erased_write(v);
1695 }
1696 }
1697 pub fn update(self, f: impl FnOnce(&mut T)) {
1699 let b = self.inner();
1700 let mut v = b.erased_peek();
1701 f(&mut v);
1702 b.erased_write(v);
1703 }
1704}
1705
1706impl<T: 'static> Binding<T> for AnyBinding<T> {
1707 fn read(&self) -> T {
1708 self.inner().erased_read()
1709 }
1710 fn peek(&self) -> T {
1711 self.inner().erased_peek()
1712 }
1713 fn write(&self, v: T) {
1714 self.inner().erased_write(v)
1715 }
1716 fn write_preview(&self, v: T) {
1717 self.inner().erased_write_preview(v)
1718 }
1719 fn write_commit(&self, v: T) {
1720 self.inner().erased_write_commit(v)
1721 }
1722 fn write_teardown(&self, v: T) {
1723 self.inner().erased_write_teardown(v)
1724 }
1725}
1726
1727#[derive(Clone)]
1734pub enum Load<T> {
1735 Loading,
1736 Ready(T),
1737 Failed(Arc<dyn std::error::Error + Send + Sync>),
1738}
1739
1740impl<T> Load<T> {
1741 pub fn ready(&self) -> Option<&T> {
1743 match self {
1744 Load::Ready(v) => Some(v),
1745 _ => None,
1746 }
1747 }
1748 pub fn is_loading(&self) -> bool {
1749 matches!(self, Load::Loading)
1750 }
1751 pub fn is_ready(&self) -> bool {
1752 matches!(self, Load::Ready(_))
1753 }
1754 pub fn error(&self) -> Option<&(dyn std::error::Error + Send + Sync + 'static)> {
1756 match self {
1757 Load::Failed(e) => Some(e.as_ref()),
1758 _ => None,
1759 }
1760 }
1761}
1762
1763impl<T: std::fmt::Debug> std::fmt::Debug for Load<T> {
1764 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1765 match self {
1766 Load::Loading => write!(f, "Loading"),
1767 Load::Ready(v) => f.debug_tuple("Ready").field(v).finish(),
1768 Load::Failed(e) => f.debug_tuple("Failed").field(&e.to_string()).finish(),
1769 }
1770 }
1771}
1772
1773struct FetchState {
1775 generation: Cell<u64>,
1776 abort: RefCell<Option<Box<dyn FnOnce()>>>,
1777}
1778
1779impl FetchState {
1780 fn supersede(&self) -> u64 {
1784 let next = self.generation.get() + 1;
1785 self.generation.set(next);
1786 let old = self.abort.borrow_mut().take();
1787 if let Some(abort) = old {
1788 abort();
1789 }
1790 next
1791 }
1792}
1793
1794pub struct Resource<T: 'static> {
1809 state: Signal<Load<T>>,
1810 refetch_count: Signal<u64>,
1811 _not_send: PhantomData<*const T>,
1812}
1813
1814impl<T> Clone for Resource<T> {
1815 fn clone(&self) -> Self {
1816 *self
1817 }
1818}
1819impl<T> Copy for Resource<T> {}
1820
1821impl<T: 'static> Resource<T> {
1822 #[track_caller]
1827 pub fn new<S, Fut, E>(
1828 source: impl Fn() -> S + 'static,
1829 fetcher: impl Fn(S) -> Fut + 'static,
1830 ) -> Resource<T>
1831 where
1832 S: Clone + PartialEq + 'static,
1833 Fut: Future<Output = Result<T, E>> + 'static,
1834 E: std::error::Error + Send + Sync + 'static,
1835 {
1836 let state: Signal<Load<T>> = Signal::new(Load::Loading);
1837 let refetch_count: Signal<u64> = Signal::new(0);
1838 let fs = Rc::new(FetchState {
1839 generation: Cell::new(0),
1840 abort: RefCell::new(None),
1841 });
1842 let reaction_fs = fs.clone();
1843 let prev: RefCell<Option<(S, u64)>> = RefCell::new(None);
1844 create_reaction(
1845 Rc::new(move || {
1846 let count = refetch_count.get();
1849 let s = source();
1850 let fs = reaction_fs.clone();
1851 untrack(|| {
1852 let same = prev
1856 .borrow()
1857 .as_ref()
1858 .is_some_and(|(ps, pc)| ps == &s && *pc == count);
1859 if same {
1860 return;
1861 }
1862 *prev.borrow_mut() = Some((s.clone(), count));
1863 let my_generation = fs.supersede();
1864 state.set(Load::Loading);
1865 let fut = fetcher(s);
1866 let done = fs.clone();
1867 let abort = spawn_local(Box::pin(async move {
1868 let result = fut.await;
1869 if done.generation.get() != my_generation {
1870 return; }
1872 done.abort.borrow_mut().take(); match result {
1874 Ok(v) => state.set(Load::Ready(v)),
1875 Err(e) => state.set(Load::Failed(Arc::new(e))),
1876 }
1877 }));
1878 *fs.abort.borrow_mut() = Some(abort);
1883 });
1884 }),
1885 1,
1886 );
1887 let cleanup_fs = fs;
1891 Scope::current().on_cleanup(move || {
1892 cleanup_fs.supersede();
1893 });
1894 Resource {
1895 state,
1896 refetch_count,
1897 _not_send: PhantomData,
1898 }
1899 }
1900
1901 pub fn signal(self) -> Signal<Load<T>> {
1903 self.state
1904 }
1905
1906 pub fn get(self) -> Load<T>
1908 where
1909 T: Clone,
1910 {
1911 self.state.get()
1912 }
1913
1914 pub fn with<R>(self, f: impl FnOnce(&Load<T>) -> R) -> R {
1916 self.state.with(f)
1917 }
1918
1919 pub fn loading(self) -> bool {
1921 self.with(Load::is_loading)
1922 }
1923
1924 pub fn ready(self) -> bool {
1926 self.with(Load::is_ready)
1927 }
1928
1929 pub fn refetch(self) {
1931 self.refetch_count.update(|c| *c = c.wrapping_add(1));
1932 }
1933}
1934
1935#[cfg(test)]
1940mod tests {
1941 use super::*;
1942 use std::cell::Cell as StdCell;
1943 use std::rc::Rc;
1944
1945 fn counter() -> (Rc<StdCell<u32>>, impl Fn()) {
1946 let c = Rc::new(StdCell::new(0));
1947 let c2 = c.clone();
1948 (c, move || c2.set(c2.get() + 1))
1949 }
1950
1951 #[test]
1952 fn signal_get_set() {
1953 let s = Signal::new(1);
1954 assert_eq!(s.get(), 1);
1955 s.set(5);
1956 assert_eq!(s.get(), 5);
1957 s.update(|v| *v += 1);
1958 assert_eq!(s.get(), 6);
1959 }
1960
1961 #[test]
1962 fn signal_teardown_does_not_write_after_scope_disposal() {
1963 let scope = Scope::child();
1964 let warned = with_rt(|rt| rt.warned_writes.len());
1965 scope.enter(|| {
1966 let signal = Signal::new(String::new());
1967 signal.write_preview("Fixture final edit".into());
1968 assert_eq!(signal.peek(), "Fixture final edit");
1969 Scope::current().on_cleanup(move || {
1970 signal.write_teardown("Fixture final edit".into());
1971 });
1972 });
1973 scope.dispose();
1974 assert_eq!(with_rt(|rt| rt.warned_writes.len()), warned);
1975 }
1976
1977 #[test]
1978 fn persistent_binding_teardown_seals_preview() {
1979 #[derive(Clone)]
1980 struct FixtureBinding(Rc<RefCell<Vec<String>>>);
1981 impl Binding<String> for FixtureBinding {
1982 fn read(&self) -> String {
1983 String::new()
1984 }
1985 fn peek(&self) -> String {
1986 self.read()
1987 }
1988 fn write(&self, value: String) {
1989 self.0.borrow_mut().push(value);
1990 }
1991 fn write_preview(&self, _value: String) {}
1992 }
1993 let committed = Rc::new(RefCell::new(Vec::new()));
1994 let binding = FixtureBinding(committed.clone());
1995 let scope = Scope::child();
1996 scope.enter(|| {
1997 binding.write_preview("Fixture edit".into());
1998 Scope::current().on_cleanup(move || binding.write_teardown("Fixture edit".into()));
1999 });
2000 assert!(committed.borrow().is_empty());
2001 scope.dispose();
2002 assert_eq!(*committed.borrow(), ["Fixture edit"]);
2003 }
2004
2005 #[test]
2006 fn effect_reruns_on_change() {
2007 let s = Signal::new(1);
2008 let (count, bump) = counter();
2009 Effect::new(move || {
2010 s.track();
2011 bump();
2012 });
2013 assert_eq!(count.get(), 1); batch(|| s.set(2));
2015 assert_eq!(count.get(), 2);
2016 batch(|| s.set(3));
2017 assert_eq!(count.get(), 3);
2018 }
2019
2020 #[test]
2021 fn batch_coalesces() {
2022 let s = Signal::new(0);
2023 let (count, bump) = counter();
2024 Effect::new(move || {
2025 s.track();
2026 bump();
2027 });
2028 batch(|| {
2029 s.set(1);
2030 s.set(2);
2031 s.set(3);
2032 });
2033 assert_eq!(count.get(), 2); assert_eq!(s.get(), 3);
2035 }
2036
2037 #[test]
2038 fn set_if_changed_no_op() {
2039 let s = Signal::new(7);
2040 let (count, bump) = counter();
2041 Effect::new(move || {
2042 s.track();
2043 bump();
2044 });
2045 batch(|| s.set_if_changed(7));
2046 assert_eq!(count.get(), 1); }
2048
2049 #[test]
2050 fn memo_caches_and_diffs() {
2051 let s = Signal::new(1);
2052 let computes = Rc::new(StdCell::new(0));
2053 let c2 = computes.clone();
2054 let doubled = Memo::new(move || {
2055 c2.set(c2.get() + 1);
2056 s.get() * 2
2057 });
2058 assert_eq!(doubled.get(), 2);
2059 assert_eq!(doubled.get(), 2);
2060 assert_eq!(computes.get(), 1); let (effect_runs, bump) = counter();
2062 Effect::new(move || {
2063 let _ = doubled.get();
2064 bump();
2065 });
2066 assert_eq!(effect_runs.get(), 1);
2067 batch(|| s.set(1)); assert_eq!(effect_runs.get(), 1); batch(|| s.set(5));
2071 assert_eq!(doubled.get(), 10);
2072 assert_eq!(effect_runs.get(), 2);
2073 }
2074
2075 #[test]
2076 fn bind_applies_on_change_only() {
2077 let s = Signal::new(1);
2078 let applied: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
2079 let a2 = applied.clone();
2080 bind(
2081 move || s.get().to_string(),
2082 move |v| a2.borrow_mut().push(v.clone()),
2083 );
2084 assert_eq!(*applied.borrow(), vec!["1"]);
2085 batch(|| s.set(2));
2086 assert_eq!(*applied.borrow(), vec!["1", "2"]);
2087 batch(|| s.update(|v| *v = 2)); assert_eq!(*applied.borrow(), vec!["1", "2"]);
2089 }
2090
2091 #[test]
2092 fn watch_skips_initial_and_passes_old() {
2093 let s = Signal::new(10);
2094 type Log = Rc<RefCell<Vec<(i32, Option<i32>)>>>;
2095 let log: Log = Rc::new(RefCell::new(Vec::new()));
2096 let l2 = log.clone();
2097 watch(
2098 move || s.get(),
2099 move |new, old| l2.borrow_mut().push((*new, old.copied())),
2100 );
2101 assert!(log.borrow().is_empty());
2102 batch(|| s.set(11));
2103 assert_eq!(*log.borrow(), vec![(11, Some(10))]);
2104 }
2105
2106 #[test]
2107 fn scope_dispose_stops_effects_and_write_is_noop() {
2108 let s = Signal::new(0);
2109 let (count, bump) = counter();
2110 let scope = Scope::child();
2111 let inner = scope.enter(|| {
2112 let inner = Signal::new(1);
2113 Effect::new(move || {
2114 s.track();
2115 bump();
2116 });
2117 inner
2118 });
2119 assert_eq!(count.get(), 1);
2120 batch(|| s.set(1));
2121 assert_eq!(count.get(), 2);
2122 scope.dispose();
2123 batch(|| s.set(2));
2124 assert_eq!(count.get(), 2); inner.set(9); assert_eq!(inner.try_get(), None);
2127 }
2128
2129 #[test]
2130 fn dispose_during_drain_skips_pending() {
2131 let s = Signal::new(0);
2132 let scope = Scope::child();
2133 let (count, bump) = counter();
2134 let scope_cell = Rc::new(StdCell::new(Some(scope)));
2136 let sc = scope_cell.clone();
2137 Effect::new(move || {
2138 if s.get() == 1
2139 && let Some(scope) = sc.take()
2140 {
2141 scope.dispose();
2142 }
2143 });
2144 scope.enter(|| {
2145 Effect::new(move || {
2146 s.track();
2147 bump();
2148 });
2149 });
2150 assert_eq!(count.get(), 1);
2151 batch(|| s.set(1));
2152 assert_eq!(count.get(), 1);
2155 }
2156
2157 #[test]
2158 fn fixpoint_extends_drain() {
2159 let a = Signal::new(0);
2160 let b = Signal::new(0);
2161 let (count, bump) = counter();
2162 Effect::new(move || {
2163 if a.get() == 1 {
2164 b.set(1); }
2166 });
2167 Effect::new(move || {
2168 b.track();
2169 bump();
2170 });
2171 assert_eq!(count.get(), 1);
2172 batch(|| a.set(1));
2173 assert_eq!(count.get(), 2);
2174 assert_eq!(b.get(), 1);
2175 }
2176
2177 #[cfg(debug_assertions)]
2180 #[test]
2181 #[should_panic(expected = "re-ran more than")]
2182 fn rerun_cap_panics_in_debug() {
2183 let s = Signal::new(0);
2184 Effect::new(move || {
2185 let v = s.get();
2186 s.set(v + 1); });
2188 batch(|| s.set(1));
2189 }
2190
2191 #[test]
2192 fn context_provides_down() {
2193 #[derive(Clone, PartialEq, Debug)]
2194 struct Theme(u32);
2195 let scope = Scope::child();
2196 scope.provide(Theme(7));
2197 let child = scope.create_child();
2198 assert_eq!(child.use_context::<Theme>(), Some(Theme(7)));
2199 scope.dispose();
2200 }
2201
2202 #[test]
2203 fn trigger_notifies() {
2204 let t = Trigger::new();
2205 let (count, bump) = counter();
2206 Effect::new(move || {
2207 t.track();
2208 bump();
2209 });
2210 batch(|| t.notify());
2211 assert_eq!(count.get(), 2);
2212 }
2213
2214 #[test]
2215 fn turn_end_runs_after_fixpoint() {
2216 let s = Signal::new(0);
2217 let order: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
2218 let o1 = order.clone();
2219 Effect::new(move || {
2220 s.track();
2221 o1.borrow_mut().push("effect");
2222 });
2223 let o2 = order.clone();
2224 on_turn_end(move || o2.borrow_mut().push("turn-end"));
2225 order.borrow_mut().clear();
2226 batch(|| s.set(1));
2227 assert_eq!(*order.borrow(), vec!["effect", "turn-end"]);
2228 }
2229
2230 #[test]
2231 fn at_turn_end_waits_for_the_turn_and_runs_once() {
2232 let s = Signal::new(0);
2233 let order: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
2234 let o = order.clone();
2236 at_turn_end(move || o.borrow_mut().push("now".into()));
2237 assert_eq!(*order.borrow(), vec!["now".to_string()]);
2238 order.borrow_mut().clear();
2239 let o1 = order.clone();
2241 Effect::new(move || {
2242 let v = s.get();
2243 o1.borrow_mut().push(format!("effect {v}"));
2244 });
2245 let o2 = order.clone();
2246 on_turn_end(move || o2.borrow_mut().push("standing".into()));
2247 order.borrow_mut().clear();
2248 let o3 = order.clone();
2249 batch(|| {
2250 at_turn_end(move || o3.borrow_mut().push("once".into()));
2251 s.set(1);
2252 });
2253 assert_eq!(*order.borrow(), vec!["effect 1", "once", "standing"]);
2254 order.borrow_mut().clear();
2256 let o4 = order.clone();
2257 batch(|| at_turn_end(move || o4.borrow_mut().push("quiet".into())));
2258 assert_eq!(*order.borrow(), vec!["quiet", "standing"]);
2259 }
2260
2261 #[test]
2262 fn bindings_run_before_effects() {
2263 let s = Signal::new(0);
2264 let order: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
2265 let o1 = order.clone();
2266 Effect::new(move || {
2268 s.track();
2269 o1.borrow_mut().push("effect");
2270 });
2271 let o2 = order.clone();
2272 bind(move || s.get(), move |_| o2.borrow_mut().push("bind"));
2273 order.borrow_mut().clear();
2274 batch(|| s.set(1));
2275 assert_eq!(*order.borrow(), vec!["bind", "effect"]);
2276 }
2277}
2278
2279#[cfg(test)]
2280mod resource_tests {
2281 use super::*;
2282 use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
2283
2284 thread_local! {
2290 static TEST_TASKS: RefCell<Vec<(u64, Option<LocalBoxFuture>)>> =
2291 const { RefCell::new(Vec::new()) };
2292 static NEXT_ID: Cell<u64> = const { Cell::new(1) };
2293 static ABORTED: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
2294 static INSTALLED: Cell<bool> = const { Cell::new(false) };
2295 }
2296
2297 fn noop_waker() -> Waker {
2298 fn raw() -> RawWaker {
2299 RawWaker::new(std::ptr::null(), &VT)
2300 }
2301 static VT: RawWakerVTable = RawWakerVTable::new(|_| raw(), |_| {}, |_| {}, |_| {});
2302 unsafe { Waker::from_raw(raw()) }
2304 }
2305
2306 fn poll_one(fut: &mut LocalBoxFuture) -> bool {
2307 let waker = noop_waker();
2308 let mut cx = Context::from_waker(&waker);
2309 fut.as_mut().poll(&mut cx).is_ready()
2310 }
2311
2312 fn install_test_spawner() {
2313 if INSTALLED.with(|c| c.replace(true)) {
2314 return;
2315 }
2316 install_spawner(|mut fut| {
2317 let id = NEXT_ID.with(|c| {
2318 let v = c.get();
2319 c.set(v + 1);
2320 v
2321 });
2322 if !poll_one(&mut fut) {
2323 TEST_TASKS.with(|t| t.borrow_mut().push((id, Some(fut))));
2324 }
2325 Box::new(move || {
2326 let removed = TEST_TASKS.with(|t| {
2327 let mut t = t.borrow_mut();
2328 let before = t.len();
2329 t.retain(|(i, _)| *i != id);
2330 before != t.len()
2331 });
2332 if removed {
2333 ABORTED.with(|a| a.borrow_mut().push(id));
2334 }
2335 })
2336 });
2337 }
2338
2339 fn aborted_count() -> usize {
2340 ABORTED.with(|a| a.borrow().len())
2341 }
2342
2343 fn pump() {
2345 let ids: Vec<u64> = TEST_TASKS.with(|t| t.borrow().iter().map(|(i, _)| *i).collect());
2346 for id in ids {
2347 let fut = TEST_TASKS.with(|t| {
2348 t.borrow_mut()
2349 .iter_mut()
2350 .find(|(i, _)| *i == id)
2351 .and_then(|(_, s)| s.take())
2352 });
2353 let Some(mut fut) = fut else { continue };
2354 if poll_one(&mut fut) {
2355 TEST_TASKS.with(|t| t.borrow_mut().retain(|(i, _)| *i != id));
2356 } else {
2357 TEST_TASKS.with(|t| {
2358 if let Some((_, s)) = t.borrow_mut().iter_mut().find(|(i, _)| *i == id) {
2359 *s = Some(fut);
2360 }
2361 });
2362 }
2363 }
2364 flush_sync();
2367 }
2368
2369 type Slot<T> = Rc<RefCell<Option<Result<T, TestErr>>>>;
2370
2371 fn manual_future<T: 'static>(slot: Slot<T>) -> impl Future<Output = Result<T, TestErr>> {
2374 std::future::poll_fn(move |_| match slot.borrow_mut().take() {
2375 Some(r) => Poll::Ready(r),
2376 None => Poll::Pending,
2377 })
2378 }
2379
2380 #[derive(Debug)]
2381 struct TestErr(&'static str);
2382 impl std::fmt::Display for TestErr {
2383 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2384 write!(f, "{}", self.0)
2385 }
2386 }
2387 impl std::error::Error for TestErr {}
2388
2389 #[test]
2390 fn resource_sync_fetcher_is_ready_immediately() {
2391 install_test_spawner();
2392 let r = Resource::new(|| (), |_| async { Ok::<_, std::convert::Infallible>(42) });
2393 assert!(r.ready());
2394 assert_eq!(r.with(|l| l.ready().copied()), Some(42));
2395 }
2396
2397 #[test]
2398 fn resource_loading_then_ready() {
2399 install_test_spawner();
2400 let slot: Slot<i32> = Rc::new(RefCell::new(None));
2401 let s2 = slot.clone();
2402 let r = Resource::new(move || (), move |_| manual_future(s2.clone()));
2403 assert!(r.loading());
2404 *slot.borrow_mut() = Some(Ok(7));
2405 pump();
2406 assert_eq!(r.with(|l| l.ready().copied()), Some(7));
2407 }
2408
2409 #[test]
2410 fn resource_failed_preserves_error() {
2411 install_test_spawner();
2412 let r = Resource::new(|| (), |_| async { Err::<i32, _>(TestErr("boom")) });
2413 assert!(!r.ready());
2414 assert_eq!(
2415 r.with(|l| l.error().map(|e| e.to_string())),
2416 Some("boom".into())
2417 );
2418 }
2419
2420 #[test]
2421 fn resource_refetches_on_source_change() {
2422 install_test_spawner();
2423 let src = Signal::new(1i32);
2424 let fetches = Rc::new(Cell::new(0));
2425 let f = fetches.clone();
2426 let r = Resource::new(
2427 move || src.get(),
2428 move |v| {
2429 f.set(f.get() + 1);
2430 async move { Ok::<_, TestErr>(v * 10) }
2431 },
2432 );
2433 assert_eq!(fetches.get(), 1);
2434 assert_eq!(r.with(|l| l.ready().copied()), Some(10));
2435 batch(|| src.set(2));
2436 assert_eq!(fetches.get(), 2);
2437 assert_eq!(r.with(|l| l.ready().copied()), Some(20));
2438 }
2439
2440 #[test]
2441 fn resource_source_equality_gates() {
2442 install_test_spawner();
2443 let a = Signal::new(1i32);
2444 let b = Signal::new(10i32);
2445 let fetches = Rc::new(Cell::new(0));
2446 let f = fetches.clone();
2447 let r = Resource::new(
2448 move || {
2449 let _ = b.get(); a.get()
2451 },
2452 move |v| {
2453 f.set(f.get() + 1);
2454 async move { Ok::<_, TestErr>(v) }
2455 },
2456 );
2457 assert_eq!(fetches.get(), 1);
2458 batch(|| b.set(20)); assert_eq!(fetches.get(), 1);
2460 assert_eq!(r.with(|l| l.ready().copied()), Some(1));
2461 batch(|| a.set(2)); assert_eq!(fetches.get(), 2);
2463 }
2464
2465 #[test]
2466 fn resource_refetch_forces() {
2467 install_test_spawner();
2468 let fetches = Rc::new(Cell::new(0));
2469 let f = fetches.clone();
2470 let r = Resource::new(
2471 || (),
2472 move |_| {
2473 f.set(f.get() + 1);
2474 async { Ok::<_, TestErr>(0) }
2475 },
2476 );
2477 assert_eq!(fetches.get(), 1);
2478 batch(|| r.refetch()); assert_eq!(fetches.get(), 2);
2480 }
2481
2482 #[test]
2483 fn resource_latest_wins() {
2484 install_test_spawner();
2485 let src = Signal::new(1i32);
2486 let slots: Rc<RefCell<Vec<Slot<i32>>>> = Rc::new(RefCell::new(Vec::new()));
2487 let sl = slots.clone();
2488 let r = Resource::new(
2489 move || src.get(),
2490 move |_| {
2491 let slot: Slot<i32> = Rc::new(RefCell::new(None));
2492 sl.borrow_mut().push(slot.clone());
2493 manual_future(slot)
2494 },
2495 );
2496 assert!(r.loading());
2497 let before = aborted_count();
2498 batch(|| src.set(2)); assert_eq!(aborted_count(), before + 1, "the stale task was aborted");
2500 *slots.borrow()[0].borrow_mut() = Some(Ok(111));
2502 pump();
2503 assert!(r.loading(), "a stale result writes nothing");
2504 *slots.borrow()[1].borrow_mut() = Some(Ok(222));
2505 pump();
2506 assert_eq!(r.with(|l| l.ready().copied()), Some(222));
2507 }
2508
2509 #[test]
2510 fn resource_scope_disposal_aborts() {
2511 install_test_spawner();
2512 let scope = Scope::child();
2513 let slot: Slot<i32> = Rc::new(RefCell::new(None));
2514 let s2 = slot.clone();
2515 let r = scope.enter(|| Resource::new(move || (), move |_| manual_future(s2.clone())));
2516 assert!(r.loading());
2517 let before = aborted_count();
2518 scope.dispose();
2519 assert_eq!(aborted_count(), before + 1, "disposal aborted the fetch");
2520 *slot.borrow_mut() = Some(Ok(1));
2522 pump();
2523 }
2524
2525 #[test]
2526 fn resource_ready_is_tracked() {
2527 install_test_spawner();
2528 let slot: Slot<i32> = Rc::new(RefCell::new(None));
2529 let s2 = slot.clone();
2530 let r = Resource::new(move || (), move |_| manual_future(s2.clone()));
2531 let runs = Rc::new(Cell::new(0));
2532 let rn = runs.clone();
2533 Effect::new(move || {
2534 let _ = r.ready();
2535 rn.set(rn.get() + 1);
2536 });
2537 assert_eq!(runs.get(), 1);
2538 *slot.borrow_mut() = Some(Ok(1));
2539 pump();
2540 assert!(runs.get() >= 2, "ready() re-ran the effect on completion");
2541 }
2542
2543 #[test]
2544 #[should_panic(expected = "no spawner installed")]
2545 fn spawner_missing_panics() {
2546 let _r = Resource::new(|| (), |_| async { Ok::<_, std::convert::Infallible>(1) });
2548 }
2549}
2550
2551#[cfg(test)]
2552mod unwind_safety_tests {
2553 use super::*;
2554
2555 fn contained(f: impl FnOnce() + std::panic::UnwindSafe) {
2557 let prev = std::panic::take_hook();
2558 std::panic::set_hook(Box::new(|_| {}));
2559 let r = std::panic::catch_unwind(f);
2560 std::panic::set_hook(prev);
2561 assert!(r.is_err(), "expected the closure to panic");
2562 }
2563
2564 #[test]
2568 fn panic_in_scope_enter_restores_current_scope() {
2569 let before = with_rt(|rt| rt.current_scope);
2570 let scope = Scope::detached();
2571 contained(|| scope.enter(|| panic!("boom in enter")));
2572 assert_eq!(with_rt(|rt| rt.current_scope), before, "scope not restored");
2573 let s = Signal::new(7u32);
2575 assert_eq!(s.get(), 7);
2576 }
2577
2578 #[test]
2585 fn panic_in_effect_body_pops_its_observer_frame() {
2586 let depth = with_rt(|rt| rt.observers.len());
2587 let boom = Signal::new(false);
2588 Effect::new(move || {
2589 if boom.get() {
2590 panic!("effect boom");
2591 }
2592 });
2593 assert_eq!(with_rt(|rt| rt.observers.len()), depth);
2594 contained(|| batch(|| boom.set(true)));
2595 assert_eq!(
2596 with_rt(|rt| rt.observers.len()),
2597 depth,
2598 "observer frame stranded by the panicking effect run"
2599 );
2600 recover_from_panic(); }
2602
2603 #[test]
2604 fn panic_in_untrack_restores_tracking() {
2605 let depth = with_rt(|rt| rt.observers.len());
2606 contained(|| untrack(|| panic!("boom in untrack")));
2607 assert_eq!(with_rt(|rt| rt.observers.len()), depth, "observer stranded");
2608
2609 let src = Signal::new(0i32);
2611 let runs = Rc::new(RefCell::new(0));
2612 let r2 = runs.clone();
2613 Effect::new(move || {
2614 src.get();
2615 *r2.borrow_mut() += 1;
2616 });
2617 flush_sync();
2618 let before = *runs.borrow();
2619 src.set(1);
2620 flush_sync();
2621 assert!(
2622 *runs.borrow() > before,
2623 "effect did not re-run — tracking is off"
2624 );
2625 }
2626
2627 #[test]
2630 fn panic_in_batch_restores_depth() {
2631 let depth = with_rt(|rt| rt.batch_depth);
2632 contained(|| batch(|| panic!("boom in batch")));
2633 assert_eq!(with_rt(|rt| rt.batch_depth), depth, "batch depth stranded");
2634 }
2635
2636 #[test]
2640 fn panic_in_with_leaves_the_value_intact() {
2641 let s = Signal::new(String::from("intact"));
2642 contained(|| s.with(|_| panic!("boom in with")));
2643 assert_eq!(s.with(|v| v.clone()), "intact");
2644 }
2645
2646 #[test]
2649 fn reentrant_read_inside_with_succeeds() {
2650 let s = Signal::new(5u32);
2651 let doubled = s.with(|outer| *outer + s.with(|inner| *inner));
2652 assert_eq!(doubled, 10);
2653 assert_eq!(
2654 s.with(|v| *v),
2655 5,
2656 "value still in place after the nested read"
2657 );
2658 }
2659
2660 #[test]
2663 fn nested_reads_of_distinct_signals_succeed() {
2664 let a = Signal::new(2u32);
2665 let b = Signal::new(3u32);
2666 assert_eq!(a.with(|x| *x * b.with(|y| *y)), 6);
2667 }
2668
2669 #[test]
2671 fn write_during_read_panics_with_a_clear_message() {
2672 let s = Signal::new(1u32);
2673 let prev = std::panic::take_hook();
2674 std::panic::set_hook(Box::new(|_| {}));
2675 let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2676 s.with(|_| s.set(2));
2677 }));
2678 std::panic::set_hook(prev);
2679 let payload = r.unwrap_err();
2680 let msg = payload
2682 .downcast_ref::<&str>()
2683 .map(|s| s.to_string())
2684 .or_else(|| payload.downcast_ref::<String>().cloned())
2685 .expect("panic payload should be a string");
2686 assert!(
2687 msg.contains("in flight") && msg.contains("Signal"),
2688 "message should name the cause, got: {msg}"
2689 );
2690 }
2691
2692 #[cfg(not(debug_assertions))]
2697 #[test]
2698 fn rerun_cap_defers_instead_of_killing_the_binding() {
2699 let s = Signal::new(0u32);
2700 let runs = std::rc::Rc::new(std::cell::Cell::new(0u32));
2701 let r2 = runs.clone();
2702 Effect::new(move || {
2703 let v = s.get();
2704 r2.set(r2.get() + 1);
2705 if v < 1_000_000 {
2706 s.set(v + 1); }
2708 });
2709 flush_sync();
2710 let after_cycle = runs.get();
2711 assert!(
2712 after_cycle <= RERUN_CAP + 1,
2713 "cap did not bound the drain: {after_cycle} runs"
2714 );
2715
2716 batch(|| s.set(2_000_000)); assert_eq!(
2719 runs.get(),
2720 after_cycle + 1,
2721 "binding stayed dead after hitting the re-run cap"
2722 );
2723 }
2724}
2725
2726#[cfg(test)]
2727mod owner_scope_tests {
2728 use super::*;
2729
2730 #[test]
2731 fn reactions_and_lazy_memos_keep_their_owner_and_restore_the_caller() {
2732 let outer = Scope::child();
2733 outer.provide("outer fixture");
2734 let first = outer.create_child();
2735 let second = outer.create_child();
2736 first.provide("first fixture");
2737 second.provide("second fixture");
2738 let source = Signal::new(0);
2739 let seen = Rc::new(RefCell::new(Vec::new()));
2740 let lazy = first.enter(|| {
2741 Memo::new(move || {
2742 (
2743 source.get(),
2744 Scope::current().use_context::<&str>().unwrap(),
2745 )
2746 })
2747 });
2748 let nested = second.enter(|| {
2749 Memo::new(move || (lazy.get(), Scope::current().use_context::<&str>().unwrap()))
2750 });
2751 second.enter(|| assert_eq!(lazy.get(), (0, "first fixture")));
2752 assert_eq!(nested.get(), ((0, "first fixture"), "second fixture"));
2753 for (scope, name) in [(first, "first fixture"), (second, "second fixture")] {
2754 let seen = seen.clone();
2755 scope.enter(|| {
2756 Effect::new(move || {
2757 seen.borrow_mut()
2758 .push((source.get(), Scope::current().use_context::<&str>()));
2759 assert_eq!(Scope::current().use_context::<&str>(), Some(name));
2760 })
2761 });
2762 }
2763 second.enter(|| {
2764 batch(|| source.set(1));
2765 assert_eq!(
2766 Scope::current().use_context::<&str>(),
2767 Some("second fixture")
2768 );
2769 });
2770 assert_eq!(nested.get(), ((1, "first fixture"), "second fixture"));
2771 assert_eq!(seen.borrow().len(), 4);
2772 outer.dispose();
2773 batch(|| source.set(2));
2774 assert_eq!(seen.borrow().len(), 4, "disposed reactions must not run");
2775 }
2776
2777 #[test]
2778 fn watches_allocate_state_and_cleanup_in_their_owner() {
2779 let owner = Scope::child();
2780 let trigger = Signal::new(0);
2781 let allocated = Rc::new(Cell::new(None::<Signal<i32>>));
2782 let cleaned = Rc::new(Cell::new(0));
2783 owner.enter(|| {
2784 let allocated = allocated.clone();
2785 let cleaned = cleaned.clone();
2786 watch(
2787 move || trigger.get(),
2788 move |value, _| {
2789 allocated.set(Some(Signal::new(*value)));
2790 let cleaned = cleaned.clone();
2791 Scope::current().on_cleanup(move || cleaned.set(cleaned.get() + 1));
2792 },
2793 );
2794 });
2795 batch(|| trigger.set(1));
2796 let state = allocated.get().unwrap();
2797 assert_eq!(state.get(), 1);
2798 owner.dispose();
2799 assert_eq!(cleaned.get(), 1);
2800 assert!(state.try_get().is_none());
2801 }
2802
2803 #[test]
2804 fn panic_in_owned_computations_restores_scope_and_tracking() {
2805 let owner = Scope::child();
2806 owner.provide("owner fixture");
2807 let caller = Scope::child();
2808 caller.provide("caller fixture");
2809 let trigger = Signal::new(false);
2810 let memo = owner.enter(|| {
2811 Memo::new(move || {
2812 assert_eq!(
2813 Scope::current().use_context::<&str>(),
2814 Some("owner fixture")
2815 );
2816 assert!(!trigger.get(), "synthetic memo failure");
2817 7
2818 })
2819 });
2820 assert_eq!(memo.get(), 7);
2821 batch(|| trigger.set(true));
2822 caller.enter(|| {
2823 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| memo.get()));
2824 assert!(result.is_err());
2825 assert_eq!(
2826 Scope::current().use_context::<&str>(),
2827 Some("caller fixture")
2828 );
2829 assert!(with_rt(|rt| rt.observers.is_empty()));
2830 });
2831 owner.dispose();
2832 caller.dispose();
2833 }
2834}