1use std::cell::{Cell, RefCell};
4use std::collections::{BTreeMap, BTreeSet};
5use std::rc::Rc;
6
7pub type SignalId = usize;
8pub type ScopeId = usize;
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
12pub struct SubscriberId {
13 pub index: u32,
14 pub generation: u32,
15}
16
17impl std::fmt::Display for SubscriberId {
18 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19 write!(f, "{}:v{}", self.index, self.generation)
20 }
21}
22
23thread_local! {
24 static RUNTIME: ReactiveRuntime = ReactiveRuntime::new();
25}
26
27pub type SubscriberCallback = Rc<RefCell<dyn FnMut()>>;
28
29pub struct ReactiveRuntime {
31 current_subscriber: Cell<Option<SubscriberId>>,
32 evaluating_subscribers: RefCell<Vec<SubscriberId>>,
33 signal_subscribers: RefCell<BTreeMap<SignalId, BTreeSet<SubscriberId>>>,
34 subscriber_signals: RefCell<BTreeMap<SubscriberId, BTreeSet<SignalId>>>,
35 signal_producer: RefCell<BTreeMap<SignalId, SubscriberId>>,
36 subscriber_ranks: RefCell<BTreeMap<SubscriberId, usize>>,
37 subscribers: RefCell<BTreeMap<SubscriberId, SubscriberCallback>>,
38 pending_subscribers: RefCell<BTreeSet<(usize, SubscriberId)>>,
39 subscriber_generations: RefCell<Vec<u32>>,
40 free_subscriber_indices: RefCell<Vec<u32>>,
41 batch_depth: Cell<usize>,
42 dirty_signals: Cell<bool>,
43 next_signal_id: Cell<SignalId>,
44 next_scope_id: Cell<ScopeId>,
45}
46
47impl ReactiveRuntime {
48 fn new() -> Self {
49 Self {
50 current_subscriber: Cell::new(None),
51 evaluating_subscribers: RefCell::new(Vec::new()),
52 signal_subscribers: RefCell::new(BTreeMap::new()),
53 subscriber_signals: RefCell::new(BTreeMap::new()),
54 signal_producer: RefCell::new(BTreeMap::new()),
55 subscriber_ranks: RefCell::new(BTreeMap::new()),
56 subscribers: RefCell::new(BTreeMap::new()),
57 pending_subscribers: RefCell::new(BTreeSet::new()),
58 subscriber_generations: RefCell::new(Vec::new()),
59 free_subscriber_indices: RefCell::new(Vec::new()),
60 batch_depth: Cell::new(0),
61 dirty_signals: Cell::new(false),
62 next_signal_id: Cell::new(1),
63 next_scope_id: Cell::new(1),
64 }
65 }
66
67 pub fn alloc_signal_id() -> SignalId {
68 RUNTIME.with(|rt| {
69 let id = rt.next_signal_id.get();
70 rt.next_signal_id.set(id + 1);
71 id
72 })
73 }
74
75 pub fn alloc_subscriber_id() -> SubscriberId {
76 RUNTIME.with(|rt| {
77 let mut free = rt.free_subscriber_indices.borrow_mut();
78 let mut gens = rt.subscriber_generations.borrow_mut();
79 if let Some(idx) = free.pop() {
80 let gen = gens[idx as usize];
81 SubscriberId {
82 index: idx,
83 generation: gen,
84 }
85 } else {
86 let idx = gens.len() as u32;
87 gens.push(1);
88 SubscriberId {
89 index: idx,
90 generation: 1,
91 }
92 }
93 })
94 }
95
96 pub fn is_subscriber_alive(sub_id: SubscriberId) -> bool {
97 RUNTIME
98 .try_with(|rt| {
99 if let Ok(gens) = rt.subscriber_generations.try_borrow() {
100 if let Some(&gen) = gens.get(sub_id.index as usize) {
101 return gen == sub_id.generation;
102 }
103 }
104 false
105 })
106 .unwrap_or(false)
107 }
108
109 pub fn active_subscriber_count() -> usize {
110 RUNTIME
111 .try_with(|rt| rt.subscribers.try_borrow().map(|s| s.len()).unwrap_or(0))
112 .unwrap_or(0)
113 }
114
115 pub fn signal_subscription_count(signal_id: SignalId) -> usize {
116 RUNTIME
117 .try_with(|rt| {
118 rt.signal_subscribers
119 .try_borrow()
120 .ok()
121 .and_then(|ss| ss.get(&signal_id).map(|s| s.len()))
122 .unwrap_or(0)
123 })
124 .unwrap_or(0)
125 }
126
127 pub fn alloc_scope_id() -> ScopeId {
128 RUNTIME.with(|rt| {
129 let id = rt.next_scope_id.get();
130 rt.next_scope_id.set(id + 1);
131 id
132 })
133 }
134
135 pub fn has_dirty_signals() -> bool {
136 RUNTIME
137 .try_with(|rt| rt.dirty_signals.get())
138 .unwrap_or(false)
139 }
140
141 pub fn take_dirty_signals() -> bool {
142 RUNTIME
143 .try_with(|rt| rt.dirty_signals.replace(false))
144 .unwrap_or(false)
145 }
146
147 pub fn mark_dirty() {
148 let _ = RUNTIME.try_with(|rt| rt.dirty_signals.set(true));
149 }
150
151 pub fn push_evaluating(sub_id: SubscriberId) -> bool {
152 RUNTIME.with(|rt| {
153 if let Ok(mut stack) = rt.evaluating_subscribers.try_borrow_mut() {
154 if stack.contains(&sub_id) {
155 false
156 } else {
157 stack.push(sub_id);
158 true
159 }
160 } else {
161 false
162 }
163 })
164 }
165
166 pub fn pop_evaluating(sub_id: SubscriberId) {
167 let _ = RUNTIME.try_with(|rt| {
168 if let Ok(mut stack) = rt.evaluating_subscribers.try_borrow_mut() {
169 if let Some(pos) = stack.iter().rposition(|&id| id == sub_id) {
170 stack.remove(pos);
171 }
172 }
173 });
174 }
175
176 pub fn is_evaluating(sub_id: SubscriberId) -> bool {
177 RUNTIME
178 .try_with(|rt| {
179 rt.evaluating_subscribers
180 .try_borrow()
181 .map(|stack| stack.contains(&sub_id))
182 .unwrap_or(false)
183 })
184 .unwrap_or(false)
185 }
186
187 pub fn register_signal_producer(signal_id: SignalId, sub_id: SubscriberId) {
188 RUNTIME.with(|rt| {
189 if let Ok(mut map) = rt.signal_producer.try_borrow_mut() {
190 map.insert(signal_id, sub_id);
191 }
192 });
193 }
194
195 pub fn track(signal_id: SignalId) {
196 RUNTIME.with(|rt| {
197 if let Some(sub_id) = rt.current_subscriber.get() {
198 if let Ok(mut sig_subs) = rt.signal_subscribers.try_borrow_mut() {
199 sig_subs.entry(signal_id).or_default().insert(sub_id);
200 }
201 if let Ok(mut sub_sigs) = rt.subscriber_signals.try_borrow_mut() {
202 sub_sigs.entry(sub_id).or_default().insert(signal_id);
203 }
204
205 let producer_id = if let Ok(producers) = rt.signal_producer.try_borrow() {
207 producers.get(&signal_id).copied()
208 } else {
209 None
210 };
211
212 if let Some(producer) = producer_id {
213 let producer_rank = if let Ok(ranks) = rt.subscriber_ranks.try_borrow() {
214 ranks.get(&producer).copied().unwrap_or(0)
215 } else {
216 0
217 };
218 if let Ok(mut ranks) = rt.subscriber_ranks.try_borrow_mut() {
219 let current_rank = ranks.entry(sub_id).or_insert(0);
220 if *current_rank <= producer_rank {
221 *current_rank = producer_rank + 1;
222 }
223 }
224 }
225 }
226 });
227 }
228
229 pub fn untrack<R>(f: impl FnOnce() -> R) -> R {
230 RUNTIME.with(|rt| {
231 let prev = rt.current_subscriber.replace(None);
232 let res = f();
233 rt.current_subscriber.set(prev);
234 res
235 })
236 }
237
238 pub fn register_subscriber(sub_id: SubscriberId, runner: Rc<RefCell<dyn FnMut()>>) {
239 RUNTIME.with(|rt| {
240 if let Ok(mut subs) = rt.subscribers.try_borrow_mut() {
241 subs.insert(sub_id, runner);
242 }
243 });
244 }
245
246 pub fn clear_subscriber_dependencies(sub_id: SubscriberId) {
247 let _ = RUNTIME.try_with(|rt| {
248 let signals = if let Ok(mut sub_signals) = rt.subscriber_signals.try_borrow_mut() {
249 sub_signals.remove(&sub_id)
250 } else {
251 None
252 };
253 if let Some(signals) = signals {
254 if let Ok(mut sig_subs) = rt.signal_subscribers.try_borrow_mut() {
255 let mut empty_signals = Vec::new();
256 for sig in signals {
257 if let Some(subs) = sig_subs.get_mut(&sig) {
258 subs.remove(&sub_id);
259 if subs.is_empty() {
260 empty_signals.push(sig);
261 }
262 }
263 }
264 for sig in empty_signals {
265 sig_subs.remove(&sig);
266 }
267 }
268 }
269 });
270 }
271
272 pub fn unregister_subscriber(sub_id: SubscriberId) {
273 let was_valid = RUNTIME
274 .try_with(|rt| {
275 if let Ok(gens) = rt.subscriber_generations.try_borrow() {
276 if let Some(&gen) = gens.get(sub_id.index as usize) {
277 gen == sub_id.generation
278 } else {
279 false
280 }
281 } else {
282 false
283 }
284 })
285 .unwrap_or(false);
286
287 if !was_valid {
288 return;
289 }
290
291 Self::clear_subscriber_dependencies(sub_id);
292
293 let removed = RUNTIME
294 .try_with(|rt| {
295 if let Ok(mut ranks) = rt.subscriber_ranks.try_borrow_mut() {
296 if let Some(rank) = ranks.remove(&sub_id) {
297 if let Ok(mut pending) = rt.pending_subscribers.try_borrow_mut() {
298 pending.remove(&(rank, sub_id));
299 }
300 }
301 }
302 if let Ok(mut producers) = rt.signal_producer.try_borrow_mut() {
303 producers.retain(|_, &mut prod_sub| prod_sub != sub_id);
304 }
305 if let Ok(mut gens) = rt.subscriber_generations.try_borrow_mut() {
306 if let Some(gen) = gens.get_mut(sub_id.index as usize) {
307 *gen = gen.wrapping_add(1);
308 }
309 }
310 if let Ok(mut free) = rt.free_subscriber_indices.try_borrow_mut() {
311 free.push(sub_id.index);
312 }
313 if let Ok(mut evaluating) = rt.evaluating_subscribers.try_borrow_mut() {
314 evaluating.retain(|&id| id != sub_id);
315 }
316 if let Ok(mut subs) = rt.subscribers.try_borrow_mut() {
317 subs.remove(&sub_id)
318 } else {
319 None
320 }
321 })
322 .ok()
323 .flatten();
324 drop(removed);
325 }
326
327 pub fn notify(signal_id: SignalId) {
328 let _ = RUNTIME.try_with(|rt| {
329 rt.dirty_signals.set(true);
330 let mut stale_subs: Option<Vec<SubscriberId>> = None;
331
332 if let Ok(sig_subs) = rt.signal_subscribers.try_borrow() {
333 if let Some(subs_set) = sig_subs.get(&signal_id) {
334 if subs_set.is_empty() {
335 return;
336 }
337 let gens = rt.subscriber_generations.try_borrow().ok();
338 let ranks = rt.subscriber_ranks.try_borrow().ok();
339 if let Ok(mut pending) = rt.pending_subscribers.try_borrow_mut() {
340 for &sub in subs_set {
341 let is_alive = if let Some(ref g) = gens {
342 g.get(sub.index as usize).copied() == Some(sub.generation)
343 } else {
344 true
345 };
346 if is_alive {
347 let rank = ranks
348 .as_ref()
349 .and_then(|r| r.get(&sub).copied())
350 .unwrap_or(0);
351 pending.insert((rank, sub));
352 } else {
353 stale_subs.get_or_insert_with(Vec::new).push(sub);
354 }
355 }
356 }
357 } else {
358 return;
359 }
360 } else {
361 return;
362 }
363
364 if let Some(stale_list) = stale_subs {
366 if let Ok(mut sig_subs) = rt.signal_subscribers.try_borrow_mut() {
367 if let Some(subs_set) = sig_subs.get_mut(&signal_id) {
368 for stale in stale_list {
369 subs_set.remove(&stale);
370 }
371 if subs_set.is_empty() {
372 sig_subs.remove(&signal_id);
373 }
374 }
375 }
376 }
377
378 if rt.batch_depth.get() == 0 {
379 Self::flush();
380 }
381 });
382 }
383
384 pub fn batch<R>(f: impl FnOnce() -> R) -> R {
385 RUNTIME.with(|rt| {
386 let depth = rt.batch_depth.get();
387 rt.batch_depth.set(depth + 1);
388
389 let res = f();
390
391 rt.batch_depth.set(depth);
392 if depth == 0 {
393 Self::flush();
394 }
395 res
396 })
397 }
398
399 pub fn flush() {
400 RUNTIME.with(|rt| {
401 let mut loop_count: usize = 0;
402 let mut run_counts: Option<std::collections::HashMap<SubscriberId, usize>> = None;
403 const MAX_RUNS_PER_SUBSCRIBER: usize = 50;
404
405 loop {
406 let next_sub = {
407 let mut pending = if let Ok(p) = rt.pending_subscribers.try_borrow_mut() {
408 p
409 } else {
410 break;
411 };
412 if let Some(&(rank, sub_id)) = pending.iter().next() {
413 pending.remove(&(rank, sub_id));
414 Some(sub_id)
415 } else {
416 None
417 }
418 };
419
420 let sub_id = match next_sub {
421 Some(id) => id,
422 None => break,
423 };
424
425 if !Self::is_subscriber_alive(sub_id) {
426 continue;
427 }
428
429 loop_count += 1;
430 if loop_count > 64 {
431 let map = run_counts.get_or_insert_with(std::collections::HashMap::new);
432 let count = map.entry(sub_id).or_insert(0);
433 *count += 1;
434 if *count > MAX_RUNS_PER_SUBSCRIBER {
435 eprintln!(
436 "Strata Reactive Guard: Subscriber {} exceeded maximum recursive executions (possible circular dependency).",
437 sub_id
438 );
439 continue;
440 }
441 }
442
443 let runner = {
444 if let Ok(subs) = rt.subscribers.try_borrow() {
445 subs.get(&sub_id).cloned()
446 } else {
447 None
448 }
449 };
450
451 if let Some(runner) = runner {
452 Self::clear_subscriber_dependencies(sub_id);
453 let prev = rt.current_subscriber.replace(Some(sub_id));
454 if let Ok(mut r) = runner.try_borrow_mut() {
455 (*r)();
456 }
457 rt.current_subscriber.set(prev);
458 }
459 }
460 });
461 }
462}
463
464#[derive(Clone)]
466pub struct Signal<T> {
467 id: SignalId,
468 value: Rc<RefCell<T>>,
469}
470
471impl<T: Clone + 'static> Signal<T> {
472 pub fn new(initial: T) -> Self {
473 Self {
474 id: ReactiveRuntime::alloc_signal_id(),
475 value: Rc::new(RefCell::new(initial)),
476 }
477 }
478
479 pub fn id(&self) -> SignalId {
480 self.id
481 }
482
483 pub fn get(&self) -> T {
484 ReactiveRuntime::track(self.id);
485 self.value.borrow().clone()
486 }
487
488 pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
489 ReactiveRuntime::track(self.id);
490 f(&*self.value.borrow())
491 }
492
493 pub fn untracked_get(&self) -> T {
494 self.value.borrow().clone()
495 }
496
497 pub fn set(&self, new_val: T) {
498 *self.value.borrow_mut() = new_val;
499 ReactiveRuntime::notify(self.id);
500 }
501
502 pub fn update<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
503 let res = f(&mut *self.value.borrow_mut());
504 ReactiveRuntime::notify(self.id);
505 res
506 }
507
508 pub fn read(&self) -> std::cell::Ref<'_, T> {
509 ReactiveRuntime::track(self.id);
510 self.value.borrow()
511 }
512
513 pub fn split(&self) -> (ReadSignal<T>, WriteSignal<T>) {
515 (
516 ReadSignal {
517 id: self.id,
518 value: self.value.clone(),
519 },
520 WriteSignal {
521 id: self.id,
522 value: self.value.clone(),
523 },
524 )
525 }
526}
527
528#[derive(Clone)]
530pub struct ReadSignal<T> {
531 id: SignalId,
532 value: Rc<RefCell<T>>,
533}
534
535impl<T: Clone + 'static> ReadSignal<T> {
536 pub fn id(&self) -> SignalId {
537 self.id
538 }
539
540 pub fn get(&self) -> T {
541 ReactiveRuntime::track(self.id);
542 self.value.borrow().clone()
543 }
544
545 pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
546 ReactiveRuntime::track(self.id);
547 f(&*self.value.borrow())
548 }
549
550 pub fn untracked_get(&self) -> T {
551 self.value.borrow().clone()
552 }
553
554 pub fn read(&self) -> std::cell::Ref<'_, T> {
555 ReactiveRuntime::track(self.id);
556 self.value.borrow()
557 }
558}
559
560impl<T: std::fmt::Debug> std::fmt::Debug for ReadSignal<T> {
561 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
562 f.debug_struct("ReadSignal")
563 .field("id", &self.id)
564 .field("value", &*self.value.borrow())
565 .finish()
566 }
567}
568
569#[derive(Clone)]
571pub struct WriteSignal<T> {
572 id: SignalId,
573 value: Rc<RefCell<T>>,
574}
575
576impl<T: Clone + 'static> WriteSignal<T> {
577 pub fn id(&self) -> SignalId {
578 self.id
579 }
580
581 pub fn set(&self, new_val: T) {
582 *self.value.borrow_mut() = new_val;
583 ReactiveRuntime::notify(self.id);
584 }
585
586 pub fn update<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
587 let res = f(&mut *self.value.borrow_mut());
588 ReactiveRuntime::notify(self.id);
589 res
590 }
591}
592
593impl<T: std::fmt::Debug> std::fmt::Debug for WriteSignal<T> {
594 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
595 f.debug_struct("WriteSignal").field("id", &self.id).finish()
596 }
597}
598
599pub type SetSignal<T> = WriteSignal<T>;
601
602pub fn create_signal<T: Clone + 'static>(initial: T) -> (ReadSignal<T>, WriteSignal<T>) {
604 let sig = Signal::new(initial);
605 sig.split()
606}
607
608pub struct EvaluatingGuard(SubscriberId);
610
611impl EvaluatingGuard {
612 pub fn new(sub_id: SubscriberId) -> Option<Self> {
613 if ReactiveRuntime::push_evaluating(sub_id) {
614 Some(Self(sub_id))
615 } else {
616 None
617 }
618 }
619}
620
621impl Drop for EvaluatingGuard {
622 fn drop(&mut self) {
623 ReactiveRuntime::pop_evaluating(self.0);
624 }
625}
626
627struct MemoInner {
628 subscriber_id: SubscriberId,
629}
630
631impl Drop for MemoInner {
632 fn drop(&mut self) {
633 ReactiveRuntime::unregister_subscriber(self.subscriber_id);
634 }
635}
636
637#[derive(Clone)]
639pub struct Memo<T> {
640 id: SignalId,
641 value: Rc<RefCell<Option<T>>>,
642 _inner: Rc<MemoInner>,
643}
644
645impl<T: Clone + PartialEq + 'static> Memo<T> {
646 pub fn new(compute: impl FnMut() -> T + 'static) -> Self {
647 Self::new_with_compare(compute, |a, b| a == b)
648 }
649
650 pub fn new_with_compare(
651 compute: impl FnMut() -> T + 'static,
652 is_equal: impl Fn(&T, &T) -> bool + 'static,
653 ) -> Self {
654 let signal_id = ReactiveRuntime::alloc_signal_id();
655 let subscriber_id = ReactiveRuntime::alloc_subscriber_id();
656
657 ReactiveRuntime::register_signal_producer(signal_id, subscriber_id);
658
659 let value = Rc::new(RefCell::new(None));
660 let compute_cell = Rc::new(RefCell::new(compute));
661 let eq_cell = Rc::new(is_equal);
662
663 let value_clone = value.clone();
664 let compute_clone = compute_cell.clone();
665 let eq_clone = eq_cell.clone();
666
667 let runner = Rc::new(RefCell::new(move || {
668 let _guard = match EvaluatingGuard::new(subscriber_id) {
669 Some(guard) => guard,
670 None => {
671 eprintln!(
672 "Strata Reactive Guard: Circular memo dependency detected for subscriber {}. Returning cached value.",
673 subscriber_id
674 );
675 return;
676 }
677 };
678
679 ReactiveRuntime::clear_subscriber_dependencies(subscriber_id);
680 let prev = RUNTIME.with(|rt| rt.current_subscriber.replace(Some(subscriber_id)));
681 let maybe_new_val = match compute_clone.try_borrow_mut() {
682 Ok(mut compute) => Some(compute()),
683 Err(_) => {
684 eprintln!(
685 "Strata Reactive Guard: Memo compute closure already borrowed for subscriber {}. Returning cached value.",
686 subscriber_id
687 );
688 None
689 }
690 };
691 RUNTIME.with(|rt| rt.current_subscriber.set(prev));
692
693 if let Some(new_val) = maybe_new_val {
694 let changed = match value_clone.try_borrow().as_deref() {
695 Ok(Some(old_val)) => !eq_clone(old_val, &new_val),
696 Ok(None) => true,
697 Err(_) => true,
698 };
699
700 if let Ok(mut val) = value_clone.try_borrow_mut() {
701 *val = Some(new_val);
702 }
703
704 if changed {
706 ReactiveRuntime::notify(signal_id);
707 }
708 }
709 }));
710
711 ReactiveRuntime::register_subscriber(subscriber_id, runner.clone());
712
713 if let Ok(r) = runner.try_borrow_mut() {
715 (*r)();
716 }
717
718 Self {
719 id: signal_id,
720 value,
721 _inner: Rc::new(MemoInner { subscriber_id }),
722 }
723 }
724
725 pub fn id(&self) -> SignalId {
726 self.id
727 }
728
729 pub fn get(&self) -> T {
730 ReactiveRuntime::track(self.id);
731 match self.value.borrow().as_ref() {
732 Some(v) => v.clone(),
733 None => panic!(
734 "Strata Reactive Guard: Memo read before initial value could be computed (unresolvable circular dependency during initialization)."
735 ),
736 }
737 }
738
739 pub fn try_get(&self) -> Option<T> {
740 ReactiveRuntime::track(self.id);
741 self.value.borrow().as_ref().cloned()
742 }
743
744 pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
745 ReactiveRuntime::track(self.id);
746 match self.value.borrow().as_ref() {
747 Some(v) => f(v),
748 None => panic!(
749 "Strata Reactive Guard: Memo read before initial value could be computed (unresolvable circular dependency during initialization)."
750 ),
751 }
752 }
753
754 pub fn untracked_get(&self) -> T {
755 match self.value.borrow().as_ref() {
756 Some(v) => v.clone(),
757 None => {
758 panic!("Strata Reactive Guard: Memo read before initial value could be computed.")
759 }
760 }
761 }
762}
763
764pub type CleanupFn = Option<Box<dyn FnOnce()>>;
765pub type CleanupCell = Rc<RefCell<CleanupFn>>;
766
767#[derive(Clone)]
769pub struct Effect {
770 subscriber_id: SubscriberId,
771 disposed: Rc<Cell<bool>>,
772 cleanup: CleanupCell,
773}
774
775impl Effect {
776 pub fn new<F>(mut effect_fn: F) -> Self
777 where
778 F: FnMut() -> Option<Box<dyn FnOnce()>> + 'static,
779 {
780 let subscriber_id = ReactiveRuntime::alloc_subscriber_id();
781 let cleanup: CleanupCell = Rc::new(RefCell::new(None));
782 let disposed = Rc::new(Cell::new(false));
783
784 let cleanup_runner = cleanup.clone();
785 let disposed_runner = disposed.clone();
786
787 let runner = Rc::new(RefCell::new(move || {
788 if disposed_runner.get() {
789 return;
790 }
791
792 let _guard = match EvaluatingGuard::new(subscriber_id) {
793 Some(guard) => guard,
794 None => {
795 eprintln!(
796 "Strata Reactive Guard: Circular effect dependency detected for subscriber {}.",
797 subscriber_id
798 );
799 return;
800 }
801 };
802
803 if let Ok(mut cleanup) = cleanup_runner.try_borrow_mut() {
805 if let Some(prev_clean) = cleanup.take() {
806 prev_clean();
807 }
808 }
809
810 let next_clean = effect_fn();
812 if let Ok(mut cleanup) = cleanup_runner.try_borrow_mut() {
813 *cleanup = next_clean;
814 }
815 }));
816
817 ReactiveRuntime::register_subscriber(subscriber_id, runner.clone());
818
819 {
821 let prev = RUNTIME.with(|rt| rt.current_subscriber.replace(Some(subscriber_id)));
822 if let Ok(mut r) = runner.try_borrow_mut() {
823 (*r)();
824 }
825 RUNTIME.with(|rt| rt.current_subscriber.set(prev));
826 }
827
828 Self {
829 subscriber_id,
830 disposed,
831 cleanup,
832 }
833 }
834
835 pub fn dispose(&self) {
836 if !self.disposed.replace(true) {
837 ReactiveRuntime::unregister_subscriber(self.subscriber_id);
838 if let Ok(mut cleanup) = self.cleanup.try_borrow_mut() {
839 if let Some(clean) = cleanup.take() {
840 clean();
841 }
842 }
843 }
844 }
845 pub fn into_guard(self) -> EffectGuard {
847 EffectGuard { effect: self }
848 }
849}
850
851pub struct EffectGuard {
853 effect: Effect,
854}
855
856impl Drop for EffectGuard {
857 fn drop(&mut self) {
858 self.effect.dispose();
859 }
860}
861
862#[derive(Clone, Debug, PartialEq, Eq, Hash)]
867struct ComponentSegment {
868 component_id: String,
869 instance_key: String,
870}
871
872#[derive(Clone, Debug, PartialEq, Eq, Hash)]
873struct ComponentPath(Vec<ComponentSegment>);
874
875struct PendingHookSlot;
876
877struct ComponentInstance {
878 slots: Vec<Box<dyn std::any::Any>>,
879 mounted_children: std::collections::HashSet<ComponentPath>,
880}
881
882impl ComponentInstance {
883 fn new() -> Self {
884 Self {
885 slots: Vec::new(),
886 mounted_children: std::collections::HashSet::new(),
887 }
888 }
889}
890
891struct ActiveComponentFrame {
892 path: ComponentPath,
893 hook_cursor: usize,
894 child_ordinals: std::collections::HashMap<String, usize>,
895 visited_children: std::collections::HashSet<ComponentPath>,
896 provided_context_count: usize,
897}
898
899struct HookStoreState {
900 instances: std::collections::HashMap<ComponentPath, ComponentInstance>,
901 active_stack: Vec<ActiveComponentFrame>,
902 pending_key: Option<String>,
903 next_hook_id: usize,
904}
905
906impl HookStoreState {
907 fn new() -> Self {
908 Self {
909 instances: std::collections::HashMap::new(),
910 active_stack: Vec::new(),
911 pending_key: None,
912 next_hook_id: 0,
913 }
914 }
915}
916
917struct ContextEntry {
918 context_id: u64,
919 value: Box<dyn std::any::Any>,
920}
921
922thread_local! {
923 static HOOK_STORE: RefCell<HookStoreState> = RefCell::new(HookStoreState::new());
924 static CONTEXT_STACK: RefCell<Vec<ContextEntry>> = const { RefCell::new(Vec::new()) };
925 static NEXT_CONTEXT_ID: Cell<u64> = const { Cell::new(1) };
926}
927
928pub struct ComponentScopeGuard {
935 _private: (),
936}
937
938impl ComponentScopeGuard {
939 pub fn enter(component_id: &'static str) -> Self {
941 HOOK_STORE.with(|store| {
942 let mut st = store.borrow_mut();
943 let explicit_key = st.pending_key.take();
944
945 let path = if let Some(parent) = st.active_stack.last_mut() {
946 let instance_key = match explicit_key {
947 Some(k) => format!("k:{k}"),
948 None => {
949 let ord = parent
950 .child_ordinals
951 .entry(component_id.to_string())
952 .or_insert(0);
953 let current = *ord;
954 *ord += 1;
955 format!("#{current}")
956 }
957 };
958 let mut segs = parent.path.0.clone();
959 segs.push(ComponentSegment {
960 component_id: component_id.to_string(),
961 instance_key,
962 });
963 let child_path = ComponentPath(segs);
964 parent.visited_children.insert(child_path.clone());
965 child_path
966 } else {
967 let instance_key = match explicit_key {
968 Some(k) => format!("k:{k}"),
969 None => "#0".to_string(),
970 };
971 ComponentPath(vec![ComponentSegment {
972 component_id: component_id.to_string(),
973 instance_key,
974 }])
975 };
976
977 st.instances
978 .entry(path.clone())
979 .or_insert_with(ComponentInstance::new);
980
981 st.active_stack.push(ActiveComponentFrame {
982 path,
983 hook_cursor: 0,
984 child_ordinals: std::collections::HashMap::new(),
985 visited_children: std::collections::HashSet::new(),
986 provided_context_count: 0,
987 });
988 });
989
990 Self { _private: () }
991 }
992}
993
994fn collect_unmounted_subtree(
995 instances: &mut std::collections::HashMap<ComponentPath, ComponentInstance>,
996 root: &ComponentPath,
997 out: &mut Vec<ComponentInstance>,
998) {
999 if let Some(inst) = instances.remove(root) {
1000 let children: Vec<ComponentPath> = inst.mounted_children.iter().cloned().collect();
1001 out.push(inst);
1002 for child in children {
1003 collect_unmounted_subtree(instances, &child, out);
1004 }
1005 }
1006}
1007
1008impl Drop for ComponentScopeGuard {
1009 fn drop(&mut self) {
1010 let unwinding = std::thread::panicking();
1011 let (pop_contexts, evicted) = HOOK_STORE.with(|store| {
1012 let mut st = store.borrow_mut();
1013 let Some(frame) = st.active_stack.pop() else {
1014 return (0usize, Vec::new());
1015 };
1016 let mut evicted = Vec::new();
1017 if !unwinding {
1018 let prev_children = st
1019 .instances
1020 .get_mut(&frame.path)
1021 .map(|inst| {
1022 std::mem::replace(&mut inst.mounted_children, frame.visited_children.clone())
1023 })
1024 .unwrap_or_default();
1025 for stale in prev_children {
1026 if !frame.visited_children.contains(&stale) {
1027 collect_unmounted_subtree(&mut st.instances, &stale, &mut evicted);
1028 }
1029 }
1030 }
1031 (frame.provided_context_count, evicted)
1032 });
1033
1034 if pop_contexts > 0 {
1035 CONTEXT_STACK.with(|stack| {
1036 let mut stack = stack.borrow_mut();
1037 let new_len = stack.len().saturating_sub(pop_contexts);
1038 stack.truncate(new_len);
1039 });
1040 }
1041
1042 drop(evicted);
1045 }
1046}
1047
1048pub fn with_component_key<R>(key: impl std::fmt::Display, f: impl FnOnce() -> R) -> R {
1051 struct KeyRestoreGuard(Option<String>);
1052 impl Drop for KeyRestoreGuard {
1053 fn drop(&mut self) {
1054 let prev = self.0.take();
1055 let _ = HOOK_STORE.try_with(|store| {
1056 if let Ok(mut st) = store.try_borrow_mut() {
1057 st.pending_key = prev;
1058 }
1059 });
1060 }
1061 }
1062
1063 let prev = HOOK_STORE.with(|store| store.borrow_mut().pending_key.replace(key.to_string()));
1064 let _guard = KeyRestoreGuard(prev);
1065 f()
1066}
1067
1068pub fn reset_component_hooks() {
1071 let evicted: Vec<ComponentInstance> = HOOK_STORE.with(|store| {
1072 let mut st = store.borrow_mut();
1073 st.active_stack.clear();
1074 st.pending_key = None;
1075 st.next_hook_id = 0;
1076 st.instances.drain().map(|(_, inst)| inst).collect()
1077 });
1078 CONTEXT_STACK.with(|stack| stack.borrow_mut().clear());
1079 drop(evicted);
1080}
1081
1082fn use_hook_slot_cloned<T: Clone + 'static>(init: impl FnOnce() -> T) -> Option<T> {
1087 enum Lookup<T> {
1088 NoScope,
1089 Hit(T),
1090 Miss(ComponentPath, usize),
1091 }
1092
1093 let lookup = HOOK_STORE.with(|store| {
1094 let mut st = store.borrow_mut();
1095 let Some(frame) = st.active_stack.last_mut() else {
1096 return Lookup::NoScope;
1097 };
1098 let path = frame.path.clone();
1099 let idx = frame.hook_cursor;
1100 frame.hook_cursor += 1;
1101
1102 let inst = st
1103 .instances
1104 .entry(path.clone())
1105 .or_insert_with(ComponentInstance::new);
1106
1107 if idx < inst.slots.len() && !inst.slots[idx].is::<PendingHookSlot>() {
1108 let existing = inst.slots[idx]
1109 .downcast_ref::<T>()
1110 .unwrap_or_else(|| {
1111 panic!(
1112 "Strata Rules of Hooks violation at slot #{idx} in component `{}`: hook type mismatch across renders (avoid calling hooks conditionally).",
1113 path.0
1114 .last()
1115 .map(|s| s.component_id.as_str())
1116 .unwrap_or("<root>")
1117 )
1118 })
1119 .clone();
1120 Lookup::Hit(existing)
1121 } else {
1122 while inst.slots.len() <= idx {
1123 inst.slots.push(Box::new(PendingHookSlot));
1124 }
1125 Lookup::Miss(path, idx)
1126 }
1127 });
1128
1129 match lookup {
1130 Lookup::NoScope => None,
1131 Lookup::Hit(val) => Some(val),
1132 Lookup::Miss(path, idx) => {
1133 let val = init();
1136 HOOK_STORE.with(|store| {
1137 let mut st = store.borrow_mut();
1138 if let Some(inst) = st.instances.get_mut(&path) {
1139 if idx < inst.slots.len() {
1140 inst.slots[idx] = Box::new(val.clone());
1141 }
1142 }
1143 });
1144 Some(val)
1145 }
1146 }
1147}
1148
1149fn use_hook_slot_or_init<T: Clone + 'static>(init: impl FnOnce() -> T) -> T {
1152 enum Lookup<T> {
1153 NoScope,
1154 Hit(T),
1155 Miss(ComponentPath, usize),
1156 }
1157
1158 let lookup = HOOK_STORE.with(|store| {
1159 let mut st = store.borrow_mut();
1160 let Some(frame) = st.active_stack.last_mut() else {
1161 return Lookup::NoScope;
1162 };
1163 let path = frame.path.clone();
1164 let idx = frame.hook_cursor;
1165 frame.hook_cursor += 1;
1166
1167 let inst = st
1168 .instances
1169 .entry(path.clone())
1170 .or_insert_with(ComponentInstance::new);
1171
1172 if idx < inst.slots.len() && !inst.slots[idx].is::<PendingHookSlot>() {
1173 let existing = inst.slots[idx]
1174 .downcast_ref::<T>()
1175 .unwrap_or_else(|| {
1176 panic!(
1177 "Strata Rules of Hooks violation at slot #{idx} in component `{}`: hook type mismatch across renders (avoid calling hooks conditionally).",
1178 path.0
1179 .last()
1180 .map(|s| s.component_id.as_str())
1181 .unwrap_or("<root>")
1182 )
1183 })
1184 .clone();
1185 Lookup::Hit(existing)
1186 } else {
1187 while inst.slots.len() <= idx {
1188 inst.slots.push(Box::new(PendingHookSlot));
1189 }
1190 Lookup::Miss(path, idx)
1191 }
1192 });
1193
1194 match lookup {
1195 Lookup::NoScope => init(),
1196 Lookup::Hit(val) => val,
1197 Lookup::Miss(path, idx) => {
1198 let val = init();
1199 HOOK_STORE.with(|store| {
1200 let mut st = store.borrow_mut();
1201 if let Some(inst) = st.instances.get_mut(&path) {
1202 if idx < inst.slots.len() {
1203 inst.slots[idx] = Box::new(val.clone());
1204 }
1205 }
1206 });
1207 val
1208 }
1209 }
1210}
1211
1212#[derive(Clone)]
1215struct OwnedComponentEffect {
1216 effect: Effect,
1217 _owner: Rc<EffectDropGuard>,
1218}
1219
1220struct EffectDropGuard(Effect);
1221
1222impl Drop for EffectDropGuard {
1223 fn drop(&mut self) {
1224 self.0.dispose();
1225 }
1226}
1227
1228struct OwnedDepsEffect<D> {
1230 deps: Rc<RefCell<D>>,
1231 cleanup: CleanupCell,
1232 _owner: Rc<CleanupDropGuard>,
1233}
1234
1235impl<D> Clone for OwnedDepsEffect<D> {
1236 fn clone(&self) -> Self {
1237 Self {
1238 deps: Rc::clone(&self.deps),
1239 cleanup: Rc::clone(&self.cleanup),
1240 _owner: Rc::clone(&self._owner),
1241 }
1242 }
1243}
1244
1245struct CleanupDropGuard(CleanupCell);
1246
1247impl Drop for CleanupDropGuard {
1248 fn drop(&mut self) {
1249 if let Ok(mut cell) = self.0.try_borrow_mut() {
1250 if let Some(clean) = cell.take() {
1251 clean();
1252 }
1253 }
1254 }
1255}
1256
1257pub trait IntoInitialState<T, Marker = ()> {
1260 fn into_initial_state(self) -> T;
1261}
1262
1263impl<T> IntoInitialState<T, ()> for T {
1264 #[inline]
1265 fn into_initial_state(self) -> T {
1266 self
1267 }
1268}
1269
1270impl<T, F: FnOnce() -> T> IntoInitialState<T, ((),)> for F {
1271 #[inline]
1272 fn into_initial_state(self) -> T {
1273 self()
1274 }
1275}
1276
1277pub fn use_signal<T: Clone + 'static>(initial: T) -> Signal<T> {
1286 use_hook_slot_or_init(|| Signal::new(initial))
1287}
1288
1289thread_local! {
1290 static PERSISTENT_SIGNALS: RefCell<std::collections::HashMap<String, Box<dyn std::any::Any>>> =
1291 RefCell::new(std::collections::HashMap::new());
1292}
1293
1294pub fn use_persistent_signal<T: Clone + 'static>(key: &str, init: impl FnOnce() -> T) -> Signal<T> {
1299 PERSISTENT_SIGNALS.with(|store| {
1300 let mut store = store.borrow_mut();
1301 if let Some(existing) = store.get(key) {
1302 return existing
1303 .downcast_ref::<Signal<T>>()
1304 .unwrap_or_else(|| panic!("persistent signal key `{key}` reused with another type"))
1305 .clone();
1306 }
1307 let signal = Signal::new(init());
1308 store.insert(key.to_string(), Box::new(signal.clone()));
1309 signal
1310 })
1311}
1312
1313pub fn clear_persistent_signals() {
1315 PERSISTENT_SIGNALS.with(|store| store.borrow_mut().clear());
1316 reset_component_hooks();
1317}
1318
1319pub fn use_state<T: Clone + 'static, M>(
1325 initial: impl IntoInitialState<T, M>,
1326) -> (ReadSignal<T>, WriteSignal<T>) {
1327 let sig = use_hook_slot_or_init(|| Signal::new(initial.into_initial_state()));
1328 sig.split()
1329}
1330
1331pub fn use_memo<T: Clone + PartialEq + 'static>(compute: impl FnMut() -> T + 'static) -> Memo<T> {
1334 use_hook_slot_or_init(|| Memo::new(compute))
1335}
1336
1337pub fn use_effect<F>(effect_fn: F) -> Effect
1341where
1342 F: FnMut() -> Option<Box<dyn FnOnce()>> + 'static,
1343{
1344 let mut effect_opt = Some(effect_fn);
1345 if let Some(owned) = use_hook_slot_cloned(|| {
1346 let eff = Effect::new(effect_opt.take().unwrap());
1347 OwnedComponentEffect {
1348 effect: eff.clone(),
1349 _owner: Rc::new(EffectDropGuard(eff)),
1350 }
1351 }) {
1352 owned.effect
1353 } else {
1354 Effect::new(effect_opt.take().unwrap())
1355 }
1356}
1357
1358pub fn use_effect_with_deps<D, F>(deps: D, effect_fn: F)
1363where
1364 D: PartialEq + 'static,
1365 F: FnOnce(&D) -> Option<Box<dyn FnOnce()>>,
1366{
1367 let mut effect_opt = Some(effect_fn);
1368 let mut deps_opt = Some(deps);
1369
1370 if let Some(slot) = use_hook_slot_cloned(|| {
1371 let initial_deps = deps_opt.take().unwrap();
1372 let initial_clean = (effect_opt.take().unwrap())(&initial_deps);
1373 let cleanup: CleanupCell = Rc::new(RefCell::new(initial_clean));
1374 OwnedDepsEffect {
1375 deps: Rc::new(RefCell::new(initial_deps)),
1376 cleanup: cleanup.clone(),
1377 _owner: Rc::new(CleanupDropGuard(cleanup)),
1378 }
1379 }) {
1380 if let (Some(new_deps), Some(run_fn)) = (deps_opt.take(), effect_opt.take()) {
1382 let changed = *slot.deps.borrow() != new_deps;
1383 if changed {
1384 let prev_clean = slot.cleanup.borrow_mut().take();
1385 if let Some(clean) = prev_clean {
1386 clean();
1387 }
1388 let next_clean = run_fn(&new_deps);
1389 *slot.deps.borrow_mut() = new_deps;
1390 *slot.cleanup.borrow_mut() = next_clean;
1391 }
1392 }
1393 } else if let (Some(d), Some(run_fn)) = (deps_opt.take(), effect_opt.take()) {
1394 let _ = run_fn(&d);
1396 }
1397}
1398
1399pub fn use_reducer<S, A, R>(reducer: R, initial_state: S) -> (ReadSignal<S>, Rc<dyn Fn(A)>)
1404where
1405 S: Clone + 'static,
1406 A: 'static,
1407 R: FnMut(&S, A) -> S + 'static,
1408{
1409 use_reducer_init(reducer, initial_state, |s| s)
1410}
1411
1412pub fn use_reducer_init<S, A, I, R, F>(
1414 reducer: R,
1415 initial_arg: I,
1416 init: F,
1417) -> (ReadSignal<S>, Rc<dyn Fn(A)>)
1418where
1419 S: Clone + 'static,
1420 A: 'static,
1421 R: FnMut(&S, A) -> S + 'static,
1422 F: FnOnce(I) -> S,
1423{
1424 let state_sig = use_hook_slot_or_init(|| Signal::new(init(initial_arg)));
1425 let reducer_cell = Rc::new(RefCell::new(reducer));
1426 let dispatch_sig = state_sig.clone();
1427 let dispatch: Rc<dyn Fn(A)> = Rc::new(move |action: A| {
1428 let current = dispatch_sig.untracked_get();
1429 let next = (reducer_cell.borrow_mut())(¤t, action);
1430 dispatch_sig.set(next);
1431 });
1432 (state_sig.split().0, dispatch)
1433}
1434
1435pub struct Ref<T> {
1439 inner: Rc<RefCell<T>>,
1440}
1441
1442impl<T> Clone for Ref<T> {
1443 fn clone(&self) -> Self {
1444 Self {
1445 inner: Rc::clone(&self.inner),
1446 }
1447 }
1448}
1449
1450impl<T: std::fmt::Debug> std::fmt::Debug for Ref<T> {
1451 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1452 f.debug_struct("Ref")
1453 .field("current", &*self.inner.borrow())
1454 .finish()
1455 }
1456}
1457
1458impl<T: 'static> Ref<T> {
1459 pub fn new(initial: T) -> Self {
1460 Self {
1461 inner: Rc::new(RefCell::new(initial)),
1462 }
1463 }
1464
1465 pub fn get(&self) -> T
1466 where
1467 T: Clone,
1468 {
1469 self.inner.borrow().clone()
1470 }
1471
1472 pub fn set(&self, value: T) {
1473 *self.inner.borrow_mut() = value;
1474 }
1475
1476 pub fn replace(&self, value: T) -> T {
1477 std::mem::replace(&mut *self.inner.borrow_mut(), value)
1478 }
1479
1480 pub fn borrow(&self) -> std::cell::Ref<'_, T> {
1481 self.inner.borrow()
1482 }
1483
1484 pub fn borrow_mut(&self) -> std::cell::RefMut<'_, T> {
1485 self.inner.borrow_mut()
1486 }
1487
1488 pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
1489 f(&*self.inner.borrow())
1490 }
1491
1492 pub fn with_mut<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
1493 f(&mut *self.inner.borrow_mut())
1494 }
1495}
1496
1497pub fn use_ref<T: 'static>(initial: T) -> Ref<T> {
1500 use_hook_slot_or_init(|| Ref::new(initial))
1501}
1502
1503pub fn use_callback<D, F>(deps: D, callback: F) -> Rc<F>
1508where
1509 D: PartialEq + 'static,
1510 F: 'static,
1511{
1512 let mut deps_opt = Some(deps);
1513 let mut cb_opt = Some(callback);
1514
1515 if let Some(cell) = use_hook_slot_cloned(|| {
1516 Rc::new(RefCell::new((
1517 deps_opt.take().unwrap(),
1518 Rc::new(cb_opt.take().unwrap()),
1519 )))
1520 }) {
1521 if let (Some(new_deps), Some(new_cb)) = (deps_opt.take(), cb_opt.take()) {
1522 let mut guard = cell.borrow_mut();
1523 if guard.0 != new_deps {
1524 guard.0 = new_deps;
1525 guard.1 = Rc::new(new_cb);
1526 }
1527 return Rc::clone(&guard.1);
1528 }
1529 return Rc::clone(&cell.borrow().1);
1530 }
1531
1532 Rc::new(cb_opt.take().unwrap())
1533}
1534
1535pub fn use_id() -> String {
1538 let alloc = || {
1539 HOOK_STORE.with(|store| {
1540 let mut st = store.borrow_mut();
1541 let id = st.next_hook_id;
1542 st.next_hook_id += 1;
1543 format!(":r{id}:")
1544 })
1545 };
1546 use_hook_slot_cloned(alloc).unwrap_or_else(alloc)
1547}
1548
1549pub struct Context<T: Clone + 'static> {
1558 id: u64,
1559 default_value: Rc<T>,
1560}
1561
1562impl<T: Clone + 'static> Clone for Context<T> {
1563 fn clone(&self) -> Self {
1564 Self {
1565 id: self.id,
1566 default_value: Rc::clone(&self.default_value),
1567 }
1568 }
1569}
1570
1571impl<T: Clone + std::fmt::Debug + 'static> std::fmt::Debug for Context<T> {
1572 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1573 f.debug_struct("Context")
1574 .field("id", &self.id)
1575 .field("default_value", &*self.default_value)
1576 .finish()
1577 }
1578}
1579
1580impl<T: Clone + 'static> Context<T> {
1581 pub fn id(&self) -> u64 {
1583 self.id
1584 }
1585
1586 pub fn default_value(&self) -> T {
1588 (*self.default_value).clone()
1589 }
1590
1591 pub fn provide<R>(&self, value: T, f: impl FnOnce() -> R) -> R {
1594 struct ContextPopGuard;
1595 impl Drop for ContextPopGuard {
1596 fn drop(&mut self) {
1597 let _ = CONTEXT_STACK.try_with(|stack| {
1598 if let Ok(mut st) = stack.try_borrow_mut() {
1599 st.pop();
1600 }
1601 });
1602 }
1603 }
1604
1605 CONTEXT_STACK.with(|stack| {
1606 stack.borrow_mut().push(ContextEntry {
1607 context_id: self.id,
1608 value: Box::new(value),
1609 });
1610 });
1611 let _guard = ContextPopGuard;
1612 f()
1613 }
1614}
1615
1616pub fn create_context<T: Clone + 'static>(default_value: T) -> Context<T> {
1618 let id = NEXT_CONTEXT_ID.with(|next| {
1619 let id = next.get();
1620 next.set(id + 1);
1621 id
1622 });
1623 Context {
1624 id,
1625 default_value: Rc::new(default_value),
1626 }
1627}
1628
1629pub fn provide_context<T: Clone + 'static>(context: &Context<T>, value: T) {
1635 CONTEXT_STACK.with(|stack| {
1636 stack.borrow_mut().push(ContextEntry {
1637 context_id: context.id,
1638 value: Box::new(value),
1639 });
1640 });
1641 HOOK_STORE.with(|store| {
1642 let mut st = store.borrow_mut();
1643 if let Some(frame) = st.active_stack.last_mut() {
1644 frame.provided_context_count += 1;
1645 }
1646 });
1647}
1648
1649pub fn use_context<T: Clone + 'static>(context: &Context<T>) -> T {
1652 CONTEXT_STACK.with(|stack| {
1653 let stack = stack.borrow();
1654 for entry in stack.iter().rev() {
1655 if entry.context_id == context.id {
1656 if let Some(val) = entry.value.downcast_ref::<T>() {
1657 return val.clone();
1658 }
1659 }
1660 }
1661 context.default_value()
1662 })
1663}
1664
1665pub fn batch<R>(f: impl FnOnce() -> R) -> R {
1666 ReactiveRuntime::batch(f)
1667}
1668
1669pub fn untrack<R>(f: impl FnOnce() -> R) -> R {
1670 ReactiveRuntime::untrack(f)
1671}
1672
1673pub fn has_dirty_signals() -> bool {
1674 ReactiveRuntime::has_dirty_signals()
1675}
1676
1677pub fn take_dirty_signals() -> bool {
1678 ReactiveRuntime::take_dirty_signals()
1679}
1680
1681pub fn mark_dirty() {
1682 ReactiveRuntime::mark_dirty()
1683}