Skip to main content

strata_dom/
reactive.rs

1//! Fine-grained reactive dependency tracking graph (SolidJS-grade, zero Virtual DOM).
2
3use std::cell::{Cell, RefCell};
4use std::collections::{BTreeMap, BTreeSet};
5use std::rc::Rc;
6
7pub type SignalId = usize;
8pub type ScopeId = usize;
9
10/// Generational subscriber identifier preventing stale-reference memory leaks and ABA hazards.
11#[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
29/// Central thread-local reactive graph coordinator.
30pub 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                // If this signal is produced by an upstream subscriber, update current subscriber's topological rank
206                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            // Evict stale subscriptions automatically only when stale subscribers are encountered
365            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/// Fine-grained reactive state container.
465#[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    /// Splits this combined signal into decoupled read-only and write-only capabilities.
514    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/// Read-only reactive signal capability.
529#[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/// Write-only reactive signal capability.
570#[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
599/// Idiomatic SolidJS/Leptos alias for write capability.
600pub type SetSignal<T> = WriteSignal<T>;
601
602/// Creates an atomic reactive cell with decoupled read and write capabilities.
603pub fn create_signal<T: Clone + 'static>(initial: T) -> (ReadSignal<T>, WriteSignal<T>) {
604    let sig = Signal::new(initial);
605    sig.split()
606}
607
608/// RAII guard tracking an actively evaluating subscriber on the thread-local call stack.
609pub 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/// Derived computed value that caches its output and only recomputes when dependencies change.
638#[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                // Halt downstream propagation if output has not changed (O(1) memoization)
705                if changed {
706                    ReactiveRuntime::notify(signal_id);
707                }
708            }
709        }));
710
711        ReactiveRuntime::register_subscriber(subscriber_id, runner.clone());
712
713        // Initial evaluation
714        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/// Reactive effect executing side-effects when subscribed signals mutate.
768#[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            // Run previous cleanup closure if any
804            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            // Run effect
811            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        // Initial run
820        {
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    /// Converts the effect into an RAII guard that disposes the effect when dropped.
846    pub fn into_guard(self) -> EffectGuard {
847        EffectGuard { effect: self }
848    }
849}
850
851/// RAII guard that automatically disposes an effect when dropped.
852pub struct EffectGuard {
853    effect: Effect,
854}
855
856impl Drop for EffectGuard {
857    fn drop(&mut self) {
858        self.effect.dispose();
859    }
860}
861
862// ============================================================================
863// Component-Scoped Hook Cursor Stack & Lifecycle Management
864// ============================================================================
865
866#[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
928/// RAII guard emitted automatically at the top of every `#[component]` function body.
929///
930/// Tracks the component's hierarchical instance identity, resets its hook cursor to `0`
931/// for the current render pass, pops component-scoped context providers on exit, and
932/// disposes unmounted child component subtrees (running their `use_effect` cleanups)
933/// when the render finishes without unwinding.
934pub struct ComponentScopeGuard {
935    _private: (),
936}
937
938impl ComponentScopeGuard {
939    /// Enters a component render scope for `component_id`.
940    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 component instances OUTSIDE any HOOK_STORE borrow so `use_effect`
1043        // cleanup callbacks can freely inspect or update signals without borrow conflicts.
1044        drop(evicted);
1045    }
1046}
1047
1048/// Assigns an explicit reconciliation key to the immediate child component rendered inside `f`,
1049/// preserving its hook state across list reorderings.
1050pub 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
1068/// Evaluates `f` inside an implicit root component scope when no `#[component]` scope is
1069/// active on the current thread.
1070///
1071/// Wrapping plain root view closures (e.g. `|| rsx! { <> <Child /> <Child /> </> }`) gives
1072/// top-level unkeyed sibling components distinct ordinals (`#0`, `#1`, ...) instead of colliding
1073/// on `#0`, and runs child unmount / `use_effect` cleanup when siblings are toggled off.
1074pub fn with_root_component_scope<R>(f: impl FnOnce() -> R) -> R {
1075    let has_active = HOOK_STORE.with(|store| !store.borrow().active_stack.is_empty());
1076    if has_active {
1077        f()
1078    } else {
1079        let _root_scope = ComponentScopeGuard::enter("__strata_root__");
1080        f()
1081    }
1082}
1083
1084/// Clears all persisted component-scoped hook state and runs pending effect cleanups on this
1085/// thread. Intended for test isolation or full application resets.
1086pub fn reset_component_hooks() {
1087    let evicted: Vec<ComponentInstance> = HOOK_STORE.with(|store| {
1088        let mut st = store.borrow_mut();
1089        st.active_stack.clear();
1090        st.pending_key = None;
1091        st.next_hook_id = 0;
1092        st.instances.drain().map(|(_, inst)| inst).collect()
1093    });
1094    CONTEXT_STACK.with(|stack| stack.borrow_mut().clear());
1095    drop(evicted);
1096}
1097
1098/// Looks up or initializes the current hook slot for the active component frame.
1099///
1100/// Returns `None` when called outside any `#[component]` scope so standalone unit tests
1101/// and top-level state builders continue working without a component frame.
1102fn use_hook_slot_cloned<T: Clone + 'static>(init: impl FnOnce() -> T) -> Option<T> {
1103    enum Lookup<T> {
1104        NoScope,
1105        Hit(T),
1106        Miss(ComponentPath, usize),
1107    }
1108
1109    let lookup = HOOK_STORE.with(|store| {
1110        let mut st = store.borrow_mut();
1111        let Some(frame) = st.active_stack.last_mut() else {
1112            return Lookup::NoScope;
1113        };
1114        let path = frame.path.clone();
1115        let idx = frame.hook_cursor;
1116        frame.hook_cursor += 1;
1117
1118        let inst = st
1119            .instances
1120            .entry(path.clone())
1121            .or_insert_with(ComponentInstance::new);
1122
1123        if idx < inst.slots.len() && !inst.slots[idx].is::<PendingHookSlot>() {
1124            let existing = inst.slots[idx]
1125                .downcast_ref::<T>()
1126                .unwrap_or_else(|| {
1127                    panic!(
1128                        "Strata Rules of Hooks violation at slot #{idx} in component `{}`: hook type mismatch across renders (avoid calling hooks conditionally).",
1129                        path.0
1130                            .last()
1131                            .map(|s| s.component_id.as_str())
1132                            .unwrap_or("<root>")
1133                    )
1134                })
1135                .clone();
1136            Lookup::Hit(existing)
1137        } else {
1138            while inst.slots.len() <= idx {
1139                inst.slots.push(Box::new(PendingHookSlot));
1140            }
1141            Lookup::Miss(path, idx)
1142        }
1143    });
1144
1145    match lookup {
1146        Lookup::NoScope => None,
1147        Lookup::Hit(val) => Some(val),
1148        Lookup::Miss(path, idx) => {
1149            // Run `init()` completely outside any HOOK_STORE borrow so closures may
1150            // read/write signals, access context, or construct reactive subscribers safely.
1151            let val = init();
1152            HOOK_STORE.with(|store| {
1153                let mut st = store.borrow_mut();
1154                if let Some(inst) = st.instances.get_mut(&path) {
1155                    if idx < inst.slots.len() {
1156                        inst.slots[idx] = Box::new(val.clone());
1157                    }
1158                }
1159            });
1160            Some(val)
1161        }
1162    }
1163}
1164
1165/// Like [`use_hook_slot_cloned`], but falls back directly to `init()` when outside a
1166/// `#[component]` scope so non-`Clone` `FnOnce` initializers are only moved once.
1167fn use_hook_slot_or_init<T: Clone + 'static>(init: impl FnOnce() -> T) -> T {
1168    enum Lookup<T> {
1169        NoScope,
1170        Hit(T),
1171        Miss(ComponentPath, usize),
1172    }
1173
1174    let lookup = HOOK_STORE.with(|store| {
1175        let mut st = store.borrow_mut();
1176        let Some(frame) = st.active_stack.last_mut() else {
1177            return Lookup::NoScope;
1178        };
1179        let path = frame.path.clone();
1180        let idx = frame.hook_cursor;
1181        frame.hook_cursor += 1;
1182
1183        let inst = st
1184            .instances
1185            .entry(path.clone())
1186            .or_insert_with(ComponentInstance::new);
1187
1188        if idx < inst.slots.len() && !inst.slots[idx].is::<PendingHookSlot>() {
1189            let existing = inst.slots[idx]
1190                .downcast_ref::<T>()
1191                .unwrap_or_else(|| {
1192                    panic!(
1193                        "Strata Rules of Hooks violation at slot #{idx} in component `{}`: hook type mismatch across renders (avoid calling hooks conditionally).",
1194                        path.0
1195                            .last()
1196                            .map(|s| s.component_id.as_str())
1197                            .unwrap_or("<root>")
1198                    )
1199                })
1200                .clone();
1201            Lookup::Hit(existing)
1202        } else {
1203            while inst.slots.len() <= idx {
1204                inst.slots.push(Box::new(PendingHookSlot));
1205            }
1206            Lookup::Miss(path, idx)
1207        }
1208    });
1209
1210    match lookup {
1211        Lookup::NoScope => init(),
1212        Lookup::Hit(val) => val,
1213        Lookup::Miss(path, idx) => {
1214            let val = init();
1215            HOOK_STORE.with(|store| {
1216                let mut st = store.borrow_mut();
1217                if let Some(inst) = st.instances.get_mut(&path) {
1218                    if idx < inst.slots.len() {
1219                        inst.slots[idx] = Box::new(val.clone());
1220                    }
1221                }
1222            });
1223            val
1224        }
1225    }
1226}
1227
1228/// Owned wrapper stored inside a component's hook slot so unmounting the component
1229/// automatically disposes its `Effect` and executes the cleanup closure.
1230#[derive(Clone)]
1231struct OwnedComponentEffect {
1232    effect: Effect,
1233    _owner: Rc<EffectDropGuard>,
1234}
1235
1236struct EffectDropGuard(Effect);
1237
1238impl Drop for EffectDropGuard {
1239    fn drop(&mut self) {
1240        self.0.dispose();
1241    }
1242}
1243
1244/// Owned wrapper for dependency-tracked `use_effect_with_deps` cleanup closures.
1245struct OwnedDepsEffect<D> {
1246    deps: Rc<RefCell<D>>,
1247    cleanup: CleanupCell,
1248    _owner: Rc<CleanupDropGuard>,
1249}
1250
1251impl<D> Clone for OwnedDepsEffect<D> {
1252    fn clone(&self) -> Self {
1253        Self {
1254            deps: Rc::clone(&self.deps),
1255            cleanup: Rc::clone(&self.cleanup),
1256            _owner: Rc::clone(&self._owner),
1257        }
1258    }
1259}
1260
1261struct CleanupDropGuard(CleanupCell);
1262
1263impl Drop for CleanupDropGuard {
1264    fn drop(&mut self) {
1265        if let Ok(mut cell) = self.0.try_borrow_mut() {
1266            if let Some(clean) = cell.take() {
1267                clean();
1268            }
1269        }
1270    }
1271}
1272
1273/// Trait allowing [`use_state`] to accept either a direct initial value (`use_state(0)`)
1274/// or a lazy initializer closure (`use_state(|| expensive())`), matching React's `useState`.
1275pub trait IntoInitialState<T, Marker = ()> {
1276    fn into_initial_state(self) -> T;
1277}
1278
1279impl<T> IntoInitialState<T, ()> for T {
1280    #[inline]
1281    fn into_initial_state(self) -> T {
1282        self
1283    }
1284}
1285
1286impl<T, F: FnOnce() -> T> IntoInitialState<T, ((),)> for F {
1287    #[inline]
1288    fn into_initial_state(self) -> T {
1289        self()
1290    }
1291}
1292
1293// ============================================================================
1294// Ergonomic Component Hooks
1295// ============================================================================
1296
1297/// Creates or retrieves a component-scoped reactive [`Signal`].
1298///
1299/// Inside a `#[component]`, the signal persists across re-renders at this hook cursor slot;
1300/// outside any component scope, allocates a fresh standalone `Signal`.
1301pub fn use_signal<T: Clone + 'static>(initial: T) -> Signal<T> {
1302    use_hook_slot_or_init(|| Signal::new(initial))
1303}
1304
1305thread_local! {
1306    static PERSISTENT_SIGNALS: RefCell<std::collections::HashMap<String, Box<dyn std::any::Any>>> =
1307        RefCell::new(std::collections::HashMap::new());
1308}
1309
1310/// Returns a signal that survives root re-invocation, identified by an explicit `key`.
1311///
1312/// Useful when sharing keyed state across disconnected subtrees or outside `#[component]`.
1313/// Asking for the same key with a different type panics, since that is a key clash.
1314pub fn use_persistent_signal<T: Clone + 'static>(key: &str, init: impl FnOnce() -> T) -> Signal<T> {
1315    PERSISTENT_SIGNALS.with(|store| {
1316        let mut store = store.borrow_mut();
1317        if let Some(existing) = store.get(key) {
1318            return existing
1319                .downcast_ref::<Signal<T>>()
1320                .unwrap_or_else(|| panic!("persistent signal key `{key}` reused with another type"))
1321                .clone();
1322        }
1323        let signal = Signal::new(init());
1324        store.insert(key.to_string(), Box::new(signal.clone()));
1325        signal
1326    })
1327}
1328
1329/// Drops all persistent signals and component-scoped hooks on this thread. Intended for tests.
1330pub fn clear_persistent_signals() {
1331    PERSISTENT_SIGNALS.with(|store| store.borrow_mut().clear());
1332    reset_component_hooks();
1333}
1334
1335/// React-style component-scoped state hook returning decoupled `(ReadSignal<T>, WriteSignal<T>)`.
1336///
1337/// Accepts either a direct value (`use_state(0)`) or a lazy initializer closure
1338/// (`use_state(|| compute_initial())`). Inside a `#[component]`, the initializer runs only on
1339/// mount and the underlying signal persists across re-renders via the component hook cursor.
1340pub fn use_state<T: Clone + 'static, M>(
1341    initial: impl IntoInitialState<T, M>,
1342) -> (ReadSignal<T>, WriteSignal<T>) {
1343    let sig = use_hook_slot_or_init(|| Signal::new(initial.into_initial_state()));
1344    sig.split()
1345}
1346
1347/// Component-scoped derived [`Memo`] that persists its reactive subscription across re-renders
1348/// and unregisters automatically when the component unmounts.
1349pub fn use_memo<T: Clone + PartialEq + 'static>(compute: impl FnMut() -> T + 'static) -> Memo<T> {
1350    use_hook_slot_or_init(|| Memo::new(compute))
1351}
1352
1353/// React-style dependency-array memoization hook (`useMemo(() => compute(&deps), [deps])`).
1354///
1355/// Computes `compute(&deps)` on mount and recomputes only when `deps` changes (`PartialEq`)
1356/// across component re-renders, returning a cached clone in between.
1357pub fn use_memo_with_deps<D, T, F>(deps: D, compute: F) -> T
1358where
1359    D: PartialEq + 'static,
1360    T: Clone + 'static,
1361    F: FnOnce(&D) -> T,
1362{
1363    let mut deps_opt = Some(deps);
1364    let mut compute_opt = Some(compute);
1365
1366    if let Some(cell) = use_hook_slot_cloned(|| {
1367        let initial_deps = deps_opt.take().unwrap();
1368        let initial_val = (compute_opt.take().unwrap())(&initial_deps);
1369        Rc::new(RefCell::new((initial_deps, initial_val)))
1370    }) {
1371        if let (Some(new_deps), Some(run_fn)) = (deps_opt.take(), compute_opt.take()) {
1372            let changed = cell.borrow().0 != new_deps;
1373            if changed {
1374                let next_val = run_fn(&new_deps);
1375                let mut guard = cell.borrow_mut();
1376                guard.0 = new_deps;
1377                guard.1 = next_val;
1378            }
1379        }
1380        return cell.borrow().1.clone();
1381    }
1382
1383    let d = deps_opt.take().unwrap();
1384    (compute_opt.take().unwrap())(&d)
1385}
1386
1387/// Component-scoped reactive [`Effect`] that tracks read signals, runs cleanup before each
1388/// re-execution, avoids duplicate registrations across re-renders, and automatically runs its
1389/// cleanup closure when the owning component unmounts.
1390pub fn use_effect<F>(effect_fn: F) -> Effect
1391where
1392    F: FnMut() -> Option<Box<dyn FnOnce()>> + 'static,
1393{
1394    let mut effect_opt = Some(effect_fn);
1395    if let Some(owned) = use_hook_slot_cloned(|| {
1396        let eff = Effect::new(effect_opt.take().unwrap());
1397        OwnedComponentEffect {
1398            effect: eff.clone(),
1399            _owner: Rc::new(EffectDropGuard(eff)),
1400        }
1401    }) {
1402        owned.effect
1403    } else {
1404        Effect::new(effect_opt.take().unwrap())
1405    }
1406}
1407
1408/// React-style dependency-array effect hook.
1409///
1410/// Runs `effect_fn(&deps)` on mount and whenever `deps` changes (`PartialEq`) across component
1411/// re-renders, invoking the prior cleanup closure before re-running and again on unmount.
1412pub fn use_effect_with_deps<D, F>(deps: D, effect_fn: F)
1413where
1414    D: PartialEq + 'static,
1415    F: FnOnce(&D) -> Option<Box<dyn FnOnce()>>,
1416{
1417    let mut effect_opt = Some(effect_fn);
1418    let mut deps_opt = Some(deps);
1419
1420    if let Some(slot) = use_hook_slot_cloned(|| {
1421        let initial_deps = deps_opt.take().unwrap();
1422        let initial_clean = (effect_opt.take().unwrap())(&initial_deps);
1423        let cleanup: CleanupCell = Rc::new(RefCell::new(initial_clean));
1424        OwnedDepsEffect {
1425            deps: Rc::new(RefCell::new(initial_deps)),
1426            cleanup: cleanup.clone(),
1427            _owner: Rc::new(CleanupDropGuard(cleanup)),
1428        }
1429    }) {
1430        // If `effect_opt` is still `Some`, this is a re-render (slot already existed on mount).
1431        if let (Some(new_deps), Some(run_fn)) = (deps_opt.take(), effect_opt.take()) {
1432            let changed = *slot.deps.borrow() != new_deps;
1433            if changed {
1434                let prev_clean = slot.cleanup.borrow_mut().take();
1435                if let Some(clean) = prev_clean {
1436                    clean();
1437                }
1438                let next_clean = run_fn(&new_deps);
1439                *slot.deps.borrow_mut() = new_deps;
1440                *slot.cleanup.borrow_mut() = next_clean;
1441            }
1442        }
1443    } else if let (Some(d), Some(run_fn)) = (deps_opt.take(), effect_opt.take()) {
1444        // Standalone execution outside any component scope: run immediately.
1445        let _ = run_fn(&d);
1446    }
1447}
1448
1449struct ReducerSlot<S: Clone + 'static, A: 'static, R: 'static> {
1450    state: Signal<S>,
1451    reducer: Rc<RefCell<R>>,
1452    dispatch: Rc<dyn Fn(A)>,
1453}
1454
1455impl<S: Clone + 'static, A: 'static, R: 'static> Clone for ReducerSlot<S, A, R> {
1456    fn clone(&self) -> Self {
1457        Self {
1458            state: self.state.clone(),
1459            reducer: Rc::clone(&self.reducer),
1460            dispatch: Rc::clone(&self.dispatch),
1461        }
1462    }
1463}
1464
1465/// React-style `useReducer` hook returning `(ReadSignal<S>, Rc<dyn Fn(A)>)`.
1466///
1467/// Persists state, reducer closure, and `dispatch` handle in the component hook slot so
1468/// `dispatch` preserves pointer identity (`Rc::ptr_eq`) across re-renders.
1469pub fn use_reducer<S, A, R>(reducer: R, initial_state: S) -> (ReadSignal<S>, Rc<dyn Fn(A)>)
1470where
1471    S: Clone + 'static,
1472    A: 'static,
1473    R: FnMut(&S, A) -> S + 'static,
1474{
1475    use_reducer_init(reducer, initial_state, |s| s)
1476}
1477
1478/// React-style 3-argument `useReducer` hook with lazy state initialization (`init(initial_arg)`).
1479///
1480/// Preserves the `dispatch` `Rc` identity across component re-renders while refreshing the active
1481/// reducer closure so inline reducers always see up-to-date prop captures.
1482pub fn use_reducer_init<S, A, I, R, F>(
1483    reducer: R,
1484    initial_arg: I,
1485    init: F,
1486) -> (ReadSignal<S>, Rc<dyn Fn(A)>)
1487where
1488    S: Clone + 'static,
1489    A: 'static,
1490    R: FnMut(&S, A) -> S + 'static,
1491    F: FnOnce(I) -> S,
1492{
1493    let mut reducer_opt = Some(reducer);
1494    let mut init_opt = Some((initial_arg, init));
1495
1496    let slot = use_hook_slot_or_init(|| {
1497        let (arg, init_fn) = init_opt.take().unwrap();
1498        let state = Signal::new(init_fn(arg));
1499        let reducer_cell = Rc::new(RefCell::new(reducer_opt.take().unwrap()));
1500        let dispatch_sig = state.clone();
1501        let dispatch_reducer = Rc::clone(&reducer_cell);
1502        let dispatch: Rc<dyn Fn(A)> = Rc::new(move |action: A| {
1503            let current = dispatch_sig.untracked_get();
1504            let next = {
1505                let mut r = dispatch_reducer.borrow_mut();
1506                r(&current, action)
1507            };
1508            dispatch_sig.set(next);
1509        });
1510        ReducerSlot {
1511            state,
1512            reducer: reducer_cell,
1513            dispatch,
1514        }
1515    });
1516
1517    if let Some(latest_reducer) = reducer_opt.take() {
1518        *slot.reducer.borrow_mut() = latest_reducer;
1519    }
1520
1521    (slot.state.split().0, slot.dispatch)
1522}
1523
1524/// Mutable, non-reactive reference container persisted across component re-renders (React `useRef`).
1525///
1526/// Mutating a [`Ref`] never marks the reactive graph dirty or triggers a re-render.
1527pub struct Ref<T> {
1528    inner: Rc<RefCell<T>>,
1529}
1530
1531impl<T> Clone for Ref<T> {
1532    fn clone(&self) -> Self {
1533        Self {
1534            inner: Rc::clone(&self.inner),
1535        }
1536    }
1537}
1538
1539impl<T: std::fmt::Debug> std::fmt::Debug for Ref<T> {
1540    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1541        f.debug_struct("Ref")
1542            .field("current", &*self.inner.borrow())
1543            .finish()
1544    }
1545}
1546
1547impl<T: 'static> Ref<T> {
1548    pub fn new(initial: T) -> Self {
1549        Self {
1550            inner: Rc::new(RefCell::new(initial)),
1551        }
1552    }
1553
1554    pub fn get(&self) -> T
1555    where
1556        T: Clone,
1557    {
1558        self.inner.borrow().clone()
1559    }
1560
1561    pub fn set(&self, value: T) {
1562        *self.inner.borrow_mut() = value;
1563    }
1564
1565    pub fn replace(&self, value: T) -> T {
1566        std::mem::replace(&mut *self.inner.borrow_mut(), value)
1567    }
1568
1569    pub fn borrow(&self) -> std::cell::Ref<'_, T> {
1570        self.inner.borrow()
1571    }
1572
1573    pub fn borrow_mut(&self) -> std::cell::RefMut<'_, T> {
1574        self.inner.borrow_mut()
1575    }
1576
1577    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
1578        f(&*self.inner.borrow())
1579    }
1580
1581    pub fn with_mut<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
1582        f(&mut *self.inner.borrow_mut())
1583    }
1584}
1585
1586/// React-style `useRef` hook returning a mutable [`Ref<T>`] that persists across re-renders
1587/// without triggering reactive updates.
1588pub fn use_ref<T: 'static>(initial: T) -> Ref<T> {
1589    use_hook_slot_or_init(|| Ref::new(initial))
1590}
1591
1592/// React-style `useCallback` hook that memoizes a closure `Rc<F>` across re-renders while
1593/// `deps` remains equal (`PartialEq`).
1594///
1595/// When `deps` is unchanged, the returned `Rc<F>` preserves exact pointer identity (`Rc::ptr_eq`).
1596pub fn use_callback<D, F>(deps: D, callback: F) -> Rc<F>
1597where
1598    D: PartialEq + 'static,
1599    F: 'static,
1600{
1601    let mut deps_opt = Some(deps);
1602    let mut cb_opt = Some(callback);
1603
1604    if let Some(cell) = use_hook_slot_cloned(|| {
1605        Rc::new(RefCell::new((
1606            deps_opt.take().unwrap(),
1607            Rc::new(cb_opt.take().unwrap()),
1608        )))
1609    }) {
1610        if let (Some(new_deps), Some(new_cb)) = (deps_opt.take(), cb_opt.take()) {
1611            let mut guard = cell.borrow_mut();
1612            if guard.0 != new_deps {
1613                guard.0 = new_deps;
1614                guard.1 = Rc::new(new_cb);
1615            }
1616            return Rc::clone(&guard.1);
1617        }
1618        return Rc::clone(&cell.borrow().1);
1619    }
1620
1621    Rc::new(cb_opt.take().unwrap())
1622}
1623
1624/// React-style `useId` hook generating a stable unique identifier (e.g. `":r0:"`) that persists
1625/// across re-renders of the same component instance and is unique across sibling instances.
1626pub fn use_id() -> String {
1627    let alloc = || {
1628        HOOK_STORE.with(|store| {
1629            let mut st = store.borrow_mut();
1630            let id = st.next_hook_id;
1631            st.next_hook_id += 1;
1632            format!(":r{id}:")
1633        })
1634    };
1635    use_hook_slot_cloned(alloc).unwrap_or_else(alloc)
1636}
1637
1638// ============================================================================
1639// React-Style Context API (`create_context` / `provide_context` / `use_context`)
1640// ============================================================================
1641
1642/// Typed context handle created by [`create_context`].
1643///
1644/// Provide values to descendant components either via [`provide_context`] (scoped to the
1645/// enclosing `#[component]`) or [`Context::provide`] (scoped to an explicit closure).
1646pub struct Context<T: Clone + 'static> {
1647    id: u64,
1648    default_value: Rc<T>,
1649}
1650
1651impl<T: Clone + 'static> Clone for Context<T> {
1652    fn clone(&self) -> Self {
1653        Self {
1654            id: self.id,
1655            default_value: Rc::clone(&self.default_value),
1656        }
1657    }
1658}
1659
1660impl<T: Clone + std::fmt::Debug + 'static> std::fmt::Debug for Context<T> {
1661    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1662        f.debug_struct("Context")
1663            .field("id", &self.id)
1664            .field("default_value", &*self.default_value)
1665            .finish()
1666    }
1667}
1668
1669impl<T: Clone + 'static> Context<T> {
1670    /// Returns this context's unique identifier.
1671    pub fn id(&self) -> u64 {
1672        self.id
1673    }
1674
1675    /// Returns a clone of the default fallback value supplied at creation time.
1676    pub fn default_value(&self) -> T {
1677        (*self.default_value).clone()
1678    }
1679
1680    /// Provides `value` to all components evaluated within `f`, restoring the previous
1681    /// context value automatically even if `f` unwinds.
1682    pub fn provide<R>(&self, value: T, f: impl FnOnce() -> R) -> R {
1683        struct ContextPopGuard;
1684        impl Drop for ContextPopGuard {
1685            fn drop(&mut self) {
1686                let _ = CONTEXT_STACK.try_with(|stack| {
1687                    if let Ok(mut st) = stack.try_borrow_mut() {
1688                        st.pop();
1689                    }
1690                });
1691            }
1692        }
1693
1694        CONTEXT_STACK.with(|stack| {
1695            stack.borrow_mut().push(ContextEntry {
1696                context_id: self.id,
1697                value: Box::new(value),
1698            });
1699        });
1700        let _guard = ContextPopGuard;
1701        f()
1702    }
1703}
1704
1705/// Creates a new typed [`Context<T>`] with a fallback `default_value`.
1706pub fn create_context<T: Clone + 'static>(default_value: T) -> Context<T> {
1707    let id = NEXT_CONTEXT_ID.with(|next| {
1708        let id = next.get();
1709        next.set(id + 1);
1710        id
1711    });
1712    Context {
1713        id,
1714        default_value: Rc::new(default_value),
1715    }
1716}
1717
1718/// Provides `value` for `context` to all child components rendered in the remainder of the
1719/// current `#[component]` scope.
1720///
1721/// The provided entry is automatically popped when the enclosing `#[component]` finishes
1722/// rendering. Outside a `#[component]` scope, prefer [`Context::provide`].
1723pub fn provide_context<T: Clone + 'static>(context: &Context<T>, value: T) {
1724    CONTEXT_STACK.with(|stack| {
1725        stack.borrow_mut().push(ContextEntry {
1726            context_id: context.id,
1727            value: Box::new(value),
1728        });
1729    });
1730    HOOK_STORE.with(|store| {
1731        let mut st = store.borrow_mut();
1732        if let Some(frame) = st.active_stack.last_mut() {
1733            frame.provided_context_count += 1;
1734        }
1735    });
1736}
1737
1738/// Reads the nearest ancestor value provided for `context`, or its default value when no
1739/// ancestor provider is active.
1740pub fn use_context<T: Clone + 'static>(context: &Context<T>) -> T {
1741    CONTEXT_STACK.with(|stack| {
1742        let stack = stack.borrow();
1743        for entry in stack.iter().rev() {
1744            if entry.context_id == context.id {
1745                if let Some(val) = entry.value.downcast_ref::<T>() {
1746                    return val.clone();
1747                }
1748            }
1749        }
1750        context.default_value()
1751    })
1752}
1753
1754pub fn batch<R>(f: impl FnOnce() -> R) -> R {
1755    ReactiveRuntime::batch(f)
1756}
1757
1758pub fn untrack<R>(f: impl FnOnce() -> R) -> R {
1759    ReactiveRuntime::untrack(f)
1760}
1761
1762pub fn has_dirty_signals() -> bool {
1763    ReactiveRuntime::has_dirty_signals()
1764}
1765
1766pub fn take_dirty_signals() -> bool {
1767    ReactiveRuntime::take_dirty_signals()
1768}
1769
1770pub fn mark_dirty() {
1771    ReactiveRuntime::mark_dirty()
1772}