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/// Per-signal read/write/subscriber telemetry entry for DevTools and rebuild attribution.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct SignalTelemetryEntry {
32    pub signal_id: SignalId,
33    pub name: String,
34    pub read_count: u64,
35    pub write_count: u64,
36    pub subscriber_count: usize,
37    pub is_dirty: bool,
38}
39
40/// Live snapshot of the thread-local reactive signal graph and read/write activity.
41#[derive(Debug, Clone, Default, PartialEq, Eq)]
42pub struct ReactiveTelemetrySnapshot {
43    pub active_signals: usize,
44    pub active_subscribers: usize,
45    pub total_reads: u64,
46    pub total_writes: u64,
47    pub total_flushes: u64,
48    pub cycle_guard_trips: u64,
49    pub dirty_signal_names: Vec<String>,
50    pub signals: Vec<SignalTelemetryEntry>,
51    pub edges: Vec<(SignalId, SubscriberId)>,
52}
53
54/// Central thread-local reactive graph coordinator.
55pub struct ReactiveRuntime {
56    current_subscriber: Cell<Option<SubscriberId>>,
57    evaluating_subscribers: RefCell<Vec<SubscriberId>>,
58    signal_subscribers: RefCell<BTreeMap<SignalId, BTreeSet<SubscriberId>>>,
59    subscriber_signals: RefCell<BTreeMap<SubscriberId, BTreeSet<SignalId>>>,
60    signal_producer: RefCell<BTreeMap<SignalId, SubscriberId>>,
61    subscriber_ranks: RefCell<BTreeMap<SubscriberId, usize>>,
62    subscribers: RefCell<BTreeMap<SubscriberId, SubscriberCallback>>,
63    pending_subscribers: RefCell<BTreeSet<(usize, SubscriberId)>>,
64    subscriber_generations: RefCell<Vec<u32>>,
65    free_subscriber_indices: RefCell<Vec<u32>>,
66    batch_depth: Cell<usize>,
67    dirty_signals: Cell<bool>,
68    dirty_signal_ids: RefCell<Vec<SignalId>>,
69    signal_names: RefCell<BTreeMap<SignalId, String>>,
70    signal_read_counts: RefCell<BTreeMap<SignalId, u64>>,
71    signal_write_counts: RefCell<BTreeMap<SignalId, u64>>,
72    total_reads: Cell<u64>,
73    total_writes: Cell<u64>,
74    total_flushes: Cell<u64>,
75    cycle_guard_trips: Cell<u64>,
76    next_signal_id: Cell<SignalId>,
77    next_scope_id: Cell<ScopeId>,
78}
79
80impl ReactiveRuntime {
81    fn new() -> Self {
82        Self {
83            current_subscriber: Cell::new(None),
84            evaluating_subscribers: RefCell::new(Vec::new()),
85            signal_subscribers: RefCell::new(BTreeMap::new()),
86            subscriber_signals: RefCell::new(BTreeMap::new()),
87            signal_producer: RefCell::new(BTreeMap::new()),
88            subscriber_ranks: RefCell::new(BTreeMap::new()),
89            subscribers: RefCell::new(BTreeMap::new()),
90            pending_subscribers: RefCell::new(BTreeSet::new()),
91            subscriber_generations: RefCell::new(Vec::new()),
92            free_subscriber_indices: RefCell::new(Vec::new()),
93            batch_depth: Cell::new(0),
94            dirty_signals: Cell::new(false),
95            dirty_signal_ids: RefCell::new(Vec::new()),
96            signal_names: RefCell::new(BTreeMap::new()),
97            signal_read_counts: RefCell::new(BTreeMap::new()),
98            signal_write_counts: RefCell::new(BTreeMap::new()),
99            total_reads: Cell::new(0),
100            total_writes: Cell::new(0),
101            total_flushes: Cell::new(0),
102            cycle_guard_trips: Cell::new(0),
103            next_signal_id: Cell::new(1),
104            next_scope_id: Cell::new(1),
105        }
106    }
107
108    pub fn alloc_signal_id() -> SignalId {
109        RUNTIME.with(|rt| {
110            let id = rt.next_signal_id.get();
111            rt.next_signal_id.set(id + 1);
112            id
113        })
114    }
115
116    pub fn alloc_subscriber_id() -> SubscriberId {
117        RUNTIME.with(|rt| {
118            let mut free = rt.free_subscriber_indices.borrow_mut();
119            let mut gens = rt.subscriber_generations.borrow_mut();
120            if let Some(idx) = free.pop() {
121                let gen = gens[idx as usize];
122                SubscriberId {
123                    index: idx,
124                    generation: gen,
125                }
126            } else {
127                let idx = gens.len() as u32;
128                gens.push(1);
129                SubscriberId {
130                    index: idx,
131                    generation: 1,
132                }
133            }
134        })
135    }
136
137    pub fn is_subscriber_alive(sub_id: SubscriberId) -> bool {
138        RUNTIME
139            .try_with(|rt| {
140                if let Ok(gens) = rt.subscriber_generations.try_borrow() {
141                    if let Some(&gen) = gens.get(sub_id.index as usize) {
142                        return gen == sub_id.generation;
143                    }
144                }
145                false
146            })
147            .unwrap_or(false)
148    }
149
150    pub fn active_subscriber_count() -> usize {
151        RUNTIME
152            .try_with(|rt| rt.subscribers.try_borrow().map(|s| s.len()).unwrap_or(0))
153            .unwrap_or(0)
154    }
155
156    pub fn signal_subscription_count(signal_id: SignalId) -> usize {
157        RUNTIME
158            .try_with(|rt| {
159                rt.signal_subscribers
160                    .try_borrow()
161                    .ok()
162                    .and_then(|ss| ss.get(&signal_id).map(|s| s.len()))
163                    .unwrap_or(0)
164            })
165            .unwrap_or(0)
166    }
167
168    pub fn alloc_scope_id() -> ScopeId {
169        RUNTIME.with(|rt| {
170            let id = rt.next_scope_id.get();
171            rt.next_scope_id.set(id + 1);
172            id
173        })
174    }
175
176    pub fn has_dirty_signals() -> bool {
177        RUNTIME
178            .try_with(|rt| rt.dirty_signals.get())
179            .unwrap_or(false)
180    }
181
182    pub fn take_dirty_signals() -> bool {
183        RUNTIME
184            .try_with(|rt| {
185                if let Ok(mut dirty_ids) = rt.dirty_signal_ids.try_borrow_mut() {
186                    dirty_ids.clear();
187                }
188                rt.dirty_signals.replace(false)
189            })
190            .unwrap_or(false)
191    }
192
193    pub fn set_signal_name(signal_id: SignalId, name: impl Into<String>) {
194        let name = name.into();
195        let _ = RUNTIME.try_with(|rt| {
196            if let Ok(mut names) = rt.signal_names.try_borrow_mut() {
197                names.insert(signal_id, name);
198            }
199        });
200    }
201
202    pub fn signal_name(signal_id: SignalId) -> String {
203        RUNTIME
204            .try_with(|rt| {
205                rt.signal_names
206                    .try_borrow()
207                    .ok()
208                    .and_then(|names| names.get(&signal_id).cloned())
209            })
210            .ok()
211            .flatten()
212            .unwrap_or_else(|| format!("signal_{signal_id}"))
213    }
214
215    pub fn peek_dirty_signal_names() -> Vec<String> {
216        RUNTIME
217            .try_with(|rt| {
218                let ids = rt
219                    .dirty_signal_ids
220                    .try_borrow()
221                    .map(|v| v.clone())
222                    .unwrap_or_default();
223                let names = rt.signal_names.try_borrow().ok();
224                ids.into_iter()
225                    .map(|id| {
226                        names
227                            .as_ref()
228                            .and_then(|m| m.get(&id).cloned())
229                            .unwrap_or_else(|| format!("signal_{id}"))
230                    })
231                    .collect()
232            })
233            .unwrap_or_default()
234    }
235
236    pub fn take_dirty_signal_names() -> Vec<String> {
237        RUNTIME
238            .try_with(|rt| {
239                rt.dirty_signals.set(false);
240                let ids = if let Ok(mut dirty_ids) = rt.dirty_signal_ids.try_borrow_mut() {
241                    std::mem::take(&mut *dirty_ids)
242                } else {
243                    Vec::new()
244                };
245                let names = rt.signal_names.try_borrow().ok();
246                ids.into_iter()
247                    .map(|id| {
248                        names
249                            .as_ref()
250                            .and_then(|m| m.get(&id).cloned())
251                            .unwrap_or_else(|| format!("signal_{id}"))
252                    })
253                    .collect()
254            })
255            .unwrap_or_default()
256    }
257
258    pub fn telemetry_snapshot() -> ReactiveTelemetrySnapshot {
259        RUNTIME
260            .try_with(|rt| {
261                let names = rt.signal_names.try_borrow().ok();
262                let reads = rt.signal_read_counts.try_borrow().ok();
263                let writes = rt.signal_write_counts.try_borrow().ok();
264                let sig_subs = rt.signal_subscribers.try_borrow().ok();
265                let dirty_ids: BTreeSet<SignalId> = rt
266                    .dirty_signal_ids
267                    .try_borrow()
268                    .map(|v| v.iter().copied().collect())
269                    .unwrap_or_default();
270
271                let mut known_ids: BTreeSet<SignalId> = BTreeSet::new();
272                if let Some(ref m) = names {
273                    known_ids.extend(m.keys().copied());
274                }
275                if let Some(ref m) = reads {
276                    known_ids.extend(m.keys().copied());
277                }
278                if let Some(ref m) = writes {
279                    known_ids.extend(m.keys().copied());
280                }
281                if let Some(ref m) = sig_subs {
282                    known_ids.extend(m.keys().copied());
283                }
284
285                let mut signals = Vec::with_capacity(known_ids.len());
286                for id in known_ids {
287                    let name = names
288                        .as_ref()
289                        .and_then(|m| m.get(&id).cloned())
290                        .unwrap_or_else(|| format!("signal_{id}"));
291                    let read_count = reads
292                        .as_ref()
293                        .and_then(|m| m.get(&id).copied())
294                        .unwrap_or(0);
295                    let write_count = writes
296                        .as_ref()
297                        .and_then(|m| m.get(&id).copied())
298                        .unwrap_or(0);
299                    let subscriber_count = sig_subs
300                        .as_ref()
301                        .and_then(|m| m.get(&id).map(|s| s.len()))
302                        .unwrap_or(0);
303                    signals.push(SignalTelemetryEntry {
304                        signal_id: id,
305                        name,
306                        read_count,
307                        write_count,
308                        subscriber_count,
309                        is_dirty: dirty_ids.contains(&id),
310                    });
311                }
312                signals.sort_by(|a, b| {
313                    b.write_count
314                        .cmp(&a.write_count)
315                        .then_with(|| b.read_count.cmp(&a.read_count))
316                        .then_with(|| a.signal_id.cmp(&b.signal_id))
317                });
318
319                let mut edges = Vec::new();
320                if let Some(ref m) = sig_subs {
321                    for (&sig_id, subs) in m.iter() {
322                        for &sub in subs {
323                            edges.push((sig_id, sub));
324                        }
325                    }
326                }
327
328                let dirty_signal_names = dirty_ids
329                    .iter()
330                    .map(|id| {
331                        names
332                            .as_ref()
333                            .and_then(|m| m.get(id).cloned())
334                            .unwrap_or_else(|| format!("signal_{id}"))
335                    })
336                    .collect();
337
338                let active_subscribers = rt
339                    .subscribers
340                    .try_borrow()
341                    .map(|s| s.len())
342                    .unwrap_or(0);
343
344                ReactiveTelemetrySnapshot {
345                    active_signals: signals.len(),
346                    active_subscribers,
347                    total_reads: rt.total_reads.get(),
348                    total_writes: rt.total_writes.get(),
349                    total_flushes: rt.total_flushes.get(),
350                    cycle_guard_trips: rt.cycle_guard_trips.get(),
351                    dirty_signal_names,
352                    signals,
353                    edges,
354                }
355            })
356            .unwrap_or_default()
357    }
358
359    pub fn mark_dirty() {
360        let _ = RUNTIME.try_with(|rt| rt.dirty_signals.set(true));
361    }
362
363    pub fn push_evaluating(sub_id: SubscriberId) -> bool {
364        RUNTIME.with(|rt| {
365            if let Ok(mut stack) = rt.evaluating_subscribers.try_borrow_mut() {
366                if stack.contains(&sub_id) {
367                    false
368                } else {
369                    stack.push(sub_id);
370                    true
371                }
372            } else {
373                false
374            }
375        })
376    }
377
378    pub fn pop_evaluating(sub_id: SubscriberId) {
379        let _ = RUNTIME.try_with(|rt| {
380            if let Ok(mut stack) = rt.evaluating_subscribers.try_borrow_mut() {
381                if let Some(pos) = stack.iter().rposition(|&id| id == sub_id) {
382                    stack.remove(pos);
383                }
384            }
385        });
386    }
387
388    pub fn is_evaluating(sub_id: SubscriberId) -> bool {
389        RUNTIME
390            .try_with(|rt| {
391                rt.evaluating_subscribers
392                    .try_borrow()
393                    .map(|stack| stack.contains(&sub_id))
394                    .unwrap_or(false)
395            })
396            .unwrap_or(false)
397    }
398
399    pub fn register_signal_producer(signal_id: SignalId, sub_id: SubscriberId) {
400        RUNTIME.with(|rt| {
401            if let Ok(mut map) = rt.signal_producer.try_borrow_mut() {
402                map.insert(signal_id, sub_id);
403            }
404        });
405    }
406
407    pub fn track(signal_id: SignalId) {
408        RUNTIME.with(|rt| {
409            rt.total_reads.set(rt.total_reads.get().wrapping_add(1));
410            if let Ok(mut reads) = rt.signal_read_counts.try_borrow_mut() {
411                let c = reads.entry(signal_id).or_insert(0);
412                *c = c.wrapping_add(1);
413            }
414            if let Some(sub_id) = rt.current_subscriber.get() {
415                if let Ok(mut sig_subs) = rt.signal_subscribers.try_borrow_mut() {
416                    sig_subs.entry(signal_id).or_default().insert(sub_id);
417                }
418                if let Ok(mut sub_sigs) = rt.subscriber_signals.try_borrow_mut() {
419                    sub_sigs.entry(sub_id).or_default().insert(signal_id);
420                }
421
422                // If this signal is produced by an upstream subscriber, update current subscriber's topological rank
423                let producer_id = if let Ok(producers) = rt.signal_producer.try_borrow() {
424                    producers.get(&signal_id).copied()
425                } else {
426                    None
427                };
428
429                if let Some(producer) = producer_id {
430                    let producer_rank = if let Ok(ranks) = rt.subscriber_ranks.try_borrow() {
431                        ranks.get(&producer).copied().unwrap_or(0)
432                    } else {
433                        0
434                    };
435                    if let Ok(mut ranks) = rt.subscriber_ranks.try_borrow_mut() {
436                        let current_rank = ranks.entry(sub_id).or_insert(0);
437                        if *current_rank <= producer_rank {
438                            *current_rank = producer_rank + 1;
439                        }
440                    }
441                }
442            }
443        });
444    }
445
446    pub fn untrack<R>(f: impl FnOnce() -> R) -> R {
447        RUNTIME.with(|rt| {
448            let prev = rt.current_subscriber.replace(None);
449            let res = f();
450            rt.current_subscriber.set(prev);
451            res
452        })
453    }
454
455    pub fn register_subscriber(sub_id: SubscriberId, runner: Rc<RefCell<dyn FnMut()>>) {
456        RUNTIME.with(|rt| {
457            if let Ok(mut subs) = rt.subscribers.try_borrow_mut() {
458                subs.insert(sub_id, runner);
459            }
460        });
461    }
462
463    pub fn clear_subscriber_dependencies(sub_id: SubscriberId) {
464        let _ = RUNTIME.try_with(|rt| {
465            let signals = if let Ok(mut sub_signals) = rt.subscriber_signals.try_borrow_mut() {
466                sub_signals.remove(&sub_id)
467            } else {
468                None
469            };
470            if let Some(signals) = signals {
471                if let Ok(mut sig_subs) = rt.signal_subscribers.try_borrow_mut() {
472                    let mut empty_signals = Vec::new();
473                    for sig in signals {
474                        if let Some(subs) = sig_subs.get_mut(&sig) {
475                            subs.remove(&sub_id);
476                            if subs.is_empty() {
477                                empty_signals.push(sig);
478                            }
479                        }
480                    }
481                    for sig in empty_signals {
482                        sig_subs.remove(&sig);
483                    }
484                }
485            }
486        });
487    }
488
489    pub fn unregister_subscriber(sub_id: SubscriberId) {
490        let was_valid = RUNTIME
491            .try_with(|rt| {
492                if let Ok(gens) = rt.subscriber_generations.try_borrow() {
493                    if let Some(&gen) = gens.get(sub_id.index as usize) {
494                        gen == sub_id.generation
495                    } else {
496                        false
497                    }
498                } else {
499                    false
500                }
501            })
502            .unwrap_or(false);
503
504        if !was_valid {
505            return;
506        }
507
508        Self::clear_subscriber_dependencies(sub_id);
509
510        let removed = RUNTIME
511            .try_with(|rt| {
512                if let Ok(mut ranks) = rt.subscriber_ranks.try_borrow_mut() {
513                    if let Some(rank) = ranks.remove(&sub_id) {
514                        if let Ok(mut pending) = rt.pending_subscribers.try_borrow_mut() {
515                            pending.remove(&(rank, sub_id));
516                        }
517                    }
518                }
519                if let Ok(mut producers) = rt.signal_producer.try_borrow_mut() {
520                    producers.retain(|_, &mut prod_sub| prod_sub != sub_id);
521                }
522                if let Ok(mut gens) = rt.subscriber_generations.try_borrow_mut() {
523                    if let Some(gen) = gens.get_mut(sub_id.index as usize) {
524                        *gen = gen.wrapping_add(1);
525                    }
526                }
527                if let Ok(mut free) = rt.free_subscriber_indices.try_borrow_mut() {
528                    free.push(sub_id.index);
529                }
530                if let Ok(mut evaluating) = rt.evaluating_subscribers.try_borrow_mut() {
531                    evaluating.retain(|&id| id != sub_id);
532                }
533                if let Ok(mut subs) = rt.subscribers.try_borrow_mut() {
534                    subs.remove(&sub_id)
535                } else {
536                    None
537                }
538            })
539            .ok()
540            .flatten();
541        drop(removed);
542    }
543
544    pub fn notify(signal_id: SignalId) {
545        let _ = RUNTIME.try_with(|rt| {
546            rt.dirty_signals.set(true);
547            rt.total_writes.set(rt.total_writes.get().wrapping_add(1));
548            if let Ok(mut writes) = rt.signal_write_counts.try_borrow_mut() {
549                let c = writes.entry(signal_id).or_insert(0);
550                *c = c.wrapping_add(1);
551            }
552            if let Ok(mut dirty_ids) = rt.dirty_signal_ids.try_borrow_mut() {
553                if dirty_ids.len() < 64 && !dirty_ids.contains(&signal_id) {
554                    dirty_ids.push(signal_id);
555                }
556            }
557            let mut stale_subs: Option<Vec<SubscriberId>> = None;
558
559            if let Ok(sig_subs) = rt.signal_subscribers.try_borrow() {
560                if let Some(subs_set) = sig_subs.get(&signal_id) {
561                    if subs_set.is_empty() {
562                        return;
563                    }
564                    let gens = rt.subscriber_generations.try_borrow().ok();
565                    let ranks = rt.subscriber_ranks.try_borrow().ok();
566                    if let Ok(mut pending) = rt.pending_subscribers.try_borrow_mut() {
567                        for &sub in subs_set {
568                            let is_alive = if let Some(ref g) = gens {
569                                g.get(sub.index as usize).copied() == Some(sub.generation)
570                            } else {
571                                true
572                            };
573                            if is_alive {
574                                let rank = ranks
575                                    .as_ref()
576                                    .and_then(|r| r.get(&sub).copied())
577                                    .unwrap_or(0);
578                                pending.insert((rank, sub));
579                            } else {
580                                stale_subs.get_or_insert_with(Vec::new).push(sub);
581                            }
582                        }
583                    }
584                } else {
585                    return;
586                }
587            } else {
588                return;
589            }
590
591            // Evict stale subscriptions automatically only when stale subscribers are encountered
592            if let Some(stale_list) = stale_subs {
593                if let Ok(mut sig_subs) = rt.signal_subscribers.try_borrow_mut() {
594                    if let Some(subs_set) = sig_subs.get_mut(&signal_id) {
595                        for stale in stale_list {
596                            subs_set.remove(&stale);
597                        }
598                        if subs_set.is_empty() {
599                            sig_subs.remove(&signal_id);
600                        }
601                    }
602                }
603            }
604
605            if rt.batch_depth.get() == 0 {
606                Self::flush();
607            }
608        });
609    }
610
611    pub fn batch<R>(f: impl FnOnce() -> R) -> R {
612        RUNTIME.with(|rt| {
613            let depth = rt.batch_depth.get();
614            rt.batch_depth.set(depth + 1);
615
616            let res = f();
617
618            rt.batch_depth.set(depth);
619            if depth == 0 {
620                Self::flush();
621            }
622            res
623        })
624    }
625
626    pub fn flush() {
627        RUNTIME.with(|rt| {
628            let mut loop_count: usize = 0;
629            let mut ran_any = false;
630            let mut run_counts: Option<std::collections::HashMap<SubscriberId, usize>> = None;
631            const MAX_RUNS_PER_SUBSCRIBER: usize = 50;
632
633            loop {
634                let next_sub = {
635                    let mut pending = if let Ok(p) = rt.pending_subscribers.try_borrow_mut() {
636                        p
637                    } else {
638                        break;
639                    };
640                    if let Some(&(rank, sub_id)) = pending.iter().next() {
641                        pending.remove(&(rank, sub_id));
642                        Some(sub_id)
643                    } else {
644                        None
645                    }
646                };
647
648                let sub_id = match next_sub {
649                    Some(id) => id,
650                    None => break,
651                };
652
653                if !Self::is_subscriber_alive(sub_id) {
654                    continue;
655                }
656
657                loop_count += 1;
658                if loop_count > 64 {
659                    let map = run_counts.get_or_insert_with(std::collections::HashMap::new);
660                    let count = map.entry(sub_id).or_insert(0);
661                    *count += 1;
662                    if *count > MAX_RUNS_PER_SUBSCRIBER {
663                        rt.cycle_guard_trips
664                            .set(rt.cycle_guard_trips.get().wrapping_add(1));
665                        eprintln!(
666                            "Strata Reactive Guard: Subscriber {} exceeded maximum recursive executions (possible circular dependency).",
667                            sub_id
668                        );
669                        continue;
670                    }
671                }
672
673                let runner = {
674                    if let Ok(subs) = rt.subscribers.try_borrow() {
675                        subs.get(&sub_id).cloned()
676                    } else {
677                        None
678                    }
679                };
680
681                if let Some(runner) = runner {
682                    ran_any = true;
683                    Self::clear_subscriber_dependencies(sub_id);
684                    let prev = rt.current_subscriber.replace(Some(sub_id));
685                    if let Ok(mut r) = runner.try_borrow_mut() {
686                        (*r)();
687                    }
688                    rt.current_subscriber.set(prev);
689                }
690            }
691            if ran_any {
692                rt.total_flushes.set(rt.total_flushes.get().wrapping_add(1));
693            }
694        });
695    }
696}
697
698/// Fine-grained reactive state container.
699#[derive(Clone)]
700pub struct Signal<T> {
701    id: SignalId,
702    value: Rc<RefCell<T>>,
703}
704
705impl<T: Clone + 'static> Signal<T> {
706    pub fn new(initial: T) -> Self {
707        Self {
708            id: ReactiveRuntime::alloc_signal_id(),
709            value: Rc::new(RefCell::new(initial)),
710        }
711    }
712
713    /// Creates a signal with an explicit debug/telemetry name for rebuild-reason attribution.
714    pub fn named(initial: T, name: impl Into<String>) -> Self {
715        let sig = Self::new(initial);
716        ReactiveRuntime::set_signal_name(sig.id, name);
717        sig
718    }
719
720    /// Assigns a debug/telemetry name to this signal and returns it.
721    pub fn with_name(self, name: impl Into<String>) -> Self {
722        ReactiveRuntime::set_signal_name(self.id, name);
723        self
724    }
725
726    pub fn id(&self) -> SignalId {
727        self.id
728    }
729
730    pub fn get(&self) -> T {
731        ReactiveRuntime::track(self.id);
732        self.value.borrow().clone()
733    }
734
735    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
736        ReactiveRuntime::track(self.id);
737        f(&*self.value.borrow())
738    }
739
740    pub fn untracked_get(&self) -> T {
741        self.value.borrow().clone()
742    }
743
744    /// Updates the inner signal value without marking reactive subscribers dirty (used for HMR hydration).
745    pub fn set_untracked(&self, new_val: T) {
746        *self.value.borrow_mut() = new_val;
747    }
748
749    pub fn set(&self, new_val: T) {
750        *self.value.borrow_mut() = new_val;
751        ReactiveRuntime::notify(self.id);
752    }
753
754    pub fn update<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
755        let res = f(&mut *self.value.borrow_mut());
756        ReactiveRuntime::notify(self.id);
757        res
758    }
759
760    pub fn read(&self) -> std::cell::Ref<'_, T> {
761        ReactiveRuntime::track(self.id);
762        self.value.borrow()
763    }
764
765    /// Splits this combined signal into decoupled read-only and write-only capabilities.
766    pub fn split(&self) -> (ReadSignal<T>, WriteSignal<T>) {
767        (
768            ReadSignal {
769                id: self.id,
770                value: self.value.clone(),
771            },
772            WriteSignal {
773                id: self.id,
774                value: self.value.clone(),
775            },
776        )
777    }
778}
779
780/// Read-only reactive signal capability.
781#[derive(Clone)]
782pub struct ReadSignal<T> {
783    id: SignalId,
784    value: Rc<RefCell<T>>,
785}
786
787impl<T: Clone + 'static> ReadSignal<T> {
788    pub fn id(&self) -> SignalId {
789        self.id
790    }
791
792    pub fn get(&self) -> T {
793        ReactiveRuntime::track(self.id);
794        self.value.borrow().clone()
795    }
796
797    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
798        ReactiveRuntime::track(self.id);
799        f(&*self.value.borrow())
800    }
801
802    pub fn untracked_get(&self) -> T {
803        self.value.borrow().clone()
804    }
805
806    pub fn read(&self) -> std::cell::Ref<'_, T> {
807        ReactiveRuntime::track(self.id);
808        self.value.borrow()
809    }
810}
811
812impl<T: std::fmt::Debug> std::fmt::Debug for ReadSignal<T> {
813    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
814        f.debug_struct("ReadSignal")
815            .field("id", &self.id)
816            .field("value", &*self.value.borrow())
817            .finish()
818    }
819}
820
821/// Write-only reactive signal capability.
822#[derive(Clone)]
823pub struct WriteSignal<T> {
824    id: SignalId,
825    value: Rc<RefCell<T>>,
826}
827
828impl<T: Clone + 'static> WriteSignal<T> {
829    pub fn id(&self) -> SignalId {
830        self.id
831    }
832
833    pub fn set(&self, new_val: T) {
834        *self.value.borrow_mut() = new_val;
835        ReactiveRuntime::notify(self.id);
836    }
837
838    pub fn update<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
839        let res = f(&mut *self.value.borrow_mut());
840        ReactiveRuntime::notify(self.id);
841        res
842    }
843}
844
845impl<T: std::fmt::Debug> std::fmt::Debug for WriteSignal<T> {
846    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
847        f.debug_struct("WriteSignal").field("id", &self.id).finish()
848    }
849}
850
851/// Idiomatic SolidJS/Leptos alias for write capability.
852pub type SetSignal<T> = WriteSignal<T>;
853
854/// Creates an atomic reactive cell with decoupled read and write capabilities.
855pub fn create_signal<T: Clone + 'static>(initial: T) -> (ReadSignal<T>, WriteSignal<T>) {
856    let sig = Signal::new(initial);
857    sig.split()
858}
859
860/// RAII guard tracking an actively evaluating subscriber on the thread-local call stack.
861pub struct EvaluatingGuard(SubscriberId);
862
863impl EvaluatingGuard {
864    pub fn new(sub_id: SubscriberId) -> Option<Self> {
865        if ReactiveRuntime::push_evaluating(sub_id) {
866            Some(Self(sub_id))
867        } else {
868            None
869        }
870    }
871}
872
873impl Drop for EvaluatingGuard {
874    fn drop(&mut self) {
875        ReactiveRuntime::pop_evaluating(self.0);
876    }
877}
878
879struct MemoInner {
880    subscriber_id: SubscriberId,
881}
882
883impl Drop for MemoInner {
884    fn drop(&mut self) {
885        ReactiveRuntime::unregister_subscriber(self.subscriber_id);
886    }
887}
888
889/// Derived computed value that caches its output and only recomputes when dependencies change.
890#[derive(Clone)]
891pub struct Memo<T> {
892    id: SignalId,
893    value: Rc<RefCell<Option<T>>>,
894    _inner: Rc<MemoInner>,
895}
896
897impl<T: Clone + PartialEq + 'static> Memo<T> {
898    pub fn new(compute: impl FnMut() -> T + 'static) -> Self {
899        Self::new_with_compare(compute, |a, b| a == b)
900    }
901
902    pub fn new_with_compare(
903        compute: impl FnMut() -> T + 'static,
904        is_equal: impl Fn(&T, &T) -> bool + 'static,
905    ) -> Self {
906        let signal_id = ReactiveRuntime::alloc_signal_id();
907        let subscriber_id = ReactiveRuntime::alloc_subscriber_id();
908
909        ReactiveRuntime::register_signal_producer(signal_id, subscriber_id);
910
911        let value = Rc::new(RefCell::new(None));
912        let compute_cell = Rc::new(RefCell::new(compute));
913        let eq_cell = Rc::new(is_equal);
914
915        let value_clone = value.clone();
916        let compute_clone = compute_cell.clone();
917        let eq_clone = eq_cell.clone();
918
919        let runner = Rc::new(RefCell::new(move || {
920            let _guard = match EvaluatingGuard::new(subscriber_id) {
921                Some(guard) => guard,
922                None => {
923                    eprintln!(
924                        "Strata Reactive Guard: Circular memo dependency detected for subscriber {}. Returning cached value.",
925                        subscriber_id
926                    );
927                    return;
928                }
929            };
930
931            ReactiveRuntime::clear_subscriber_dependencies(subscriber_id);
932            let prev = RUNTIME.with(|rt| rt.current_subscriber.replace(Some(subscriber_id)));
933            let maybe_new_val = match compute_clone.try_borrow_mut() {
934                Ok(mut compute) => Some(compute()),
935                Err(_) => {
936                    eprintln!(
937                        "Strata Reactive Guard: Memo compute closure already borrowed for subscriber {}. Returning cached value.",
938                        subscriber_id
939                    );
940                    None
941                }
942            };
943            RUNTIME.with(|rt| rt.current_subscriber.set(prev));
944
945            if let Some(new_val) = maybe_new_val {
946                let changed = match value_clone.try_borrow().as_deref() {
947                    Ok(Some(old_val)) => !eq_clone(old_val, &new_val),
948                    Ok(None) => true,
949                    Err(_) => true,
950                };
951
952                if let Ok(mut val) = value_clone.try_borrow_mut() {
953                    *val = Some(new_val);
954                }
955
956                // Halt downstream propagation if output has not changed (O(1) memoization)
957                if changed {
958                    ReactiveRuntime::notify(signal_id);
959                }
960            }
961        }));
962
963        ReactiveRuntime::register_subscriber(subscriber_id, runner.clone());
964
965        // Initial evaluation
966        if let Ok(r) = runner.try_borrow_mut() {
967            (*r)();
968        }
969
970        Self {
971            id: signal_id,
972            value,
973            _inner: Rc::new(MemoInner { subscriber_id }),
974        }
975    }
976
977    pub fn id(&self) -> SignalId {
978        self.id
979    }
980
981    pub fn get(&self) -> T {
982        ReactiveRuntime::track(self.id);
983        match self.value.borrow().as_ref() {
984            Some(v) => v.clone(),
985            None => panic!(
986                "Strata Reactive Guard: Memo read before initial value could be computed (unresolvable circular dependency during initialization)."
987            ),
988        }
989    }
990
991    pub fn try_get(&self) -> Option<T> {
992        ReactiveRuntime::track(self.id);
993        self.value.borrow().as_ref().cloned()
994    }
995
996    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
997        ReactiveRuntime::track(self.id);
998        match self.value.borrow().as_ref() {
999            Some(v) => f(v),
1000            None => panic!(
1001                "Strata Reactive Guard: Memo read before initial value could be computed (unresolvable circular dependency during initialization)."
1002            ),
1003        }
1004    }
1005
1006    pub fn untracked_get(&self) -> T {
1007        match self.value.borrow().as_ref() {
1008            Some(v) => v.clone(),
1009            None => {
1010                panic!("Strata Reactive Guard: Memo read before initial value could be computed.")
1011            }
1012        }
1013    }
1014}
1015
1016pub type CleanupFn = Option<Box<dyn FnOnce()>>;
1017pub type CleanupCell = Rc<RefCell<CleanupFn>>;
1018
1019/// Reactive effect executing side-effects when subscribed signals mutate.
1020#[derive(Clone)]
1021pub struct Effect {
1022    subscriber_id: SubscriberId,
1023    disposed: Rc<Cell<bool>>,
1024    cleanup: CleanupCell,
1025}
1026
1027impl Effect {
1028    pub fn new<F, R>(mut effect_fn: F) -> Self
1029    where
1030        F: FnMut() -> R + 'static,
1031        R: IntoEffectCleanup,
1032    {
1033        let subscriber_id = ReactiveRuntime::alloc_subscriber_id();
1034        let cleanup: CleanupCell = Rc::new(RefCell::new(None));
1035        let disposed = Rc::new(Cell::new(false));
1036
1037        let cleanup_runner = cleanup.clone();
1038        let disposed_runner = disposed.clone();
1039
1040        let runner = Rc::new(RefCell::new(move || {
1041            if disposed_runner.get() {
1042                return;
1043            }
1044
1045            let _guard = match EvaluatingGuard::new(subscriber_id) {
1046                Some(guard) => guard,
1047                None => {
1048                    eprintln!(
1049                        "Strata Reactive Guard: Circular effect dependency detected for subscriber {}.",
1050                        subscriber_id
1051                    );
1052                    return;
1053                }
1054            };
1055
1056            // Run previous cleanup closure if any
1057            if let Ok(mut cleanup) = cleanup_runner.try_borrow_mut() {
1058                if let Some(prev_clean) = cleanup.take() {
1059                    prev_clean();
1060                }
1061            }
1062
1063            // Run effect
1064            let next_clean = {
1065                let _effect_guard = EffectBodyGuard::enter();
1066                effect_fn().into_effect_cleanup()
1067            };
1068            if let Ok(mut cleanup) = cleanup_runner.try_borrow_mut() {
1069                *cleanup = next_clean;
1070            }
1071        }));
1072
1073        ReactiveRuntime::register_subscriber(subscriber_id, runner.clone());
1074
1075        // Initial run
1076        {
1077            let prev = RUNTIME.with(|rt| rt.current_subscriber.replace(Some(subscriber_id)));
1078            if let Ok(mut r) = runner.try_borrow_mut() {
1079                (*r)();
1080            }
1081            RUNTIME.with(|rt| rt.current_subscriber.set(prev));
1082        }
1083
1084        Self {
1085            subscriber_id,
1086            disposed,
1087            cleanup,
1088        }
1089    }
1090
1091    pub fn dispose(&self) {
1092        if !self.disposed.replace(true) {
1093            ReactiveRuntime::unregister_subscriber(self.subscriber_id);
1094            if let Ok(mut cleanup) = self.cleanup.try_borrow_mut() {
1095                if let Some(clean) = cleanup.take() {
1096                    clean();
1097                }
1098            }
1099        }
1100    }
1101    /// Converts the effect into an RAII guard that disposes the effect when dropped.
1102    pub fn into_guard(self) -> EffectGuard {
1103        EffectGuard { effect: self }
1104    }
1105}
1106
1107/// RAII guard that automatically disposes an effect when dropped.
1108pub struct EffectGuard {
1109    effect: Effect,
1110}
1111
1112impl Drop for EffectGuard {
1113    fn drop(&mut self) {
1114        self.effect.dispose();
1115    }
1116}
1117
1118// ============================================================================
1119// Component-Scoped Hook Cursor Stack & Lifecycle Management
1120// ============================================================================
1121
1122#[derive(Clone, Debug, PartialEq, Eq, Hash)]
1123struct ComponentSegment {
1124    component_id: String,
1125    instance_key: String,
1126}
1127
1128#[derive(Clone, Debug, PartialEq, Eq, Hash)]
1129struct ComponentPath(Vec<ComponentSegment>);
1130
1131struct PendingHookSlot;
1132
1133struct ComponentInstance {
1134    slots: Vec<Box<dyn std::any::Any>>,
1135    mounted_children: std::collections::HashSet<ComponentPath>,
1136}
1137
1138impl ComponentInstance {
1139    fn new() -> Self {
1140        Self {
1141            slots: Vec::new(),
1142            mounted_children: std::collections::HashSet::new(),
1143        }
1144    }
1145}
1146
1147struct ActiveComponentFrame {
1148    path: ComponentPath,
1149    hook_cursor: usize,
1150    child_ordinals: std::collections::HashMap<String, usize>,
1151    visited_children: std::collections::HashSet<ComponentPath>,
1152    provided_context_count: usize,
1153}
1154
1155struct HookStoreState {
1156    instances: std::collections::HashMap<ComponentPath, ComponentInstance>,
1157    active_stack: Vec<ActiveComponentFrame>,
1158    pending_key: Option<String>,
1159    next_hook_id: usize,
1160}
1161
1162impl HookStoreState {
1163    fn new() -> Self {
1164        Self {
1165            instances: std::collections::HashMap::new(),
1166            active_stack: Vec::new(),
1167            pending_key: None,
1168            next_hook_id: 0,
1169        }
1170    }
1171}
1172
1173struct ContextEntry {
1174    context_id: u64,
1175    value: Box<dyn std::any::Any>,
1176}
1177
1178thread_local! {
1179    static HOOK_STORE: RefCell<HookStoreState> = RefCell::new(HookStoreState::new());
1180    static CONTEXT_STACK: RefCell<Vec<ContextEntry>> = const { RefCell::new(Vec::new()) };
1181    static NEXT_CONTEXT_ID: Cell<u64> = const { Cell::new(1) };
1182}
1183
1184/// RAII guard emitted automatically at the top of every `#[component]` function body.
1185///
1186/// Tracks the component's hierarchical instance identity, resets its hook cursor to `0`
1187/// for the current render pass, pops component-scoped context providers on exit, and
1188/// disposes unmounted child component subtrees (running their `use_effect` cleanups)
1189/// when the render finishes without unwinding.
1190pub struct ComponentScopeGuard {
1191    _private: (),
1192}
1193
1194impl ComponentScopeGuard {
1195    /// Enters a component render scope for `component_id`.
1196    pub fn enter(component_id: &'static str) -> Self {
1197        HOOK_STORE.with(|store| {
1198            let mut st = store.borrow_mut();
1199            let explicit_key = st.pending_key.take();
1200
1201            let path = if let Some(parent) = st.active_stack.last_mut() {
1202                let instance_key = match explicit_key {
1203                    Some(k) => format!("k:{k}"),
1204                    None => {
1205                        let ord = parent
1206                            .child_ordinals
1207                            .entry(component_id.to_string())
1208                            .or_insert(0);
1209                        let current = *ord;
1210                        *ord += 1;
1211                        format!("#{current}")
1212                    }
1213                };
1214                let mut segs = parent.path.0.clone();
1215                segs.push(ComponentSegment {
1216                    component_id: component_id.to_string(),
1217                    instance_key,
1218                });
1219                let child_path = ComponentPath(segs);
1220                parent.visited_children.insert(child_path.clone());
1221                child_path
1222            } else {
1223                let instance_key = match explicit_key {
1224                    Some(k) => format!("k:{k}"),
1225                    None => "#0".to_string(),
1226                };
1227                ComponentPath(vec![ComponentSegment {
1228                    component_id: component_id.to_string(),
1229                    instance_key,
1230                }])
1231            };
1232
1233            st.instances
1234                .entry(path.clone())
1235                .or_insert_with(ComponentInstance::new);
1236
1237            st.active_stack.push(ActiveComponentFrame {
1238                path,
1239                hook_cursor: 0,
1240                child_ordinals: std::collections::HashMap::new(),
1241                visited_children: std::collections::HashSet::new(),
1242                provided_context_count: 0,
1243            });
1244        });
1245
1246        Self { _private: () }
1247    }
1248}
1249
1250fn collect_unmounted_subtree(
1251    instances: &mut std::collections::HashMap<ComponentPath, ComponentInstance>,
1252    root: &ComponentPath,
1253    out: &mut Vec<ComponentInstance>,
1254) {
1255    if let Some(inst) = instances.remove(root) {
1256        let children: Vec<ComponentPath> = inst.mounted_children.iter().cloned().collect();
1257        out.push(inst);
1258        for child in children {
1259            collect_unmounted_subtree(instances, &child, out);
1260        }
1261    }
1262}
1263
1264impl Drop for ComponentScopeGuard {
1265    fn drop(&mut self) {
1266        let unwinding = std::thread::panicking();
1267        let (pop_contexts, evicted) = HOOK_STORE.with(|store| {
1268            let mut st = store.borrow_mut();
1269            let Some(frame) = st.active_stack.pop() else {
1270                return (0usize, Vec::new());
1271            };
1272            let mut evicted = Vec::new();
1273            if !unwinding {
1274                let prev_children = st
1275                    .instances
1276                    .get_mut(&frame.path)
1277                    .map(|inst| {
1278                        std::mem::replace(&mut inst.mounted_children, frame.visited_children.clone())
1279                    })
1280                    .unwrap_or_default();
1281                for stale in prev_children {
1282                    if !frame.visited_children.contains(&stale) {
1283                        collect_unmounted_subtree(&mut st.instances, &stale, &mut evicted);
1284                    }
1285                }
1286            }
1287            (frame.provided_context_count, evicted)
1288        });
1289
1290        if pop_contexts > 0 {
1291            CONTEXT_STACK.with(|stack| {
1292                let mut stack = stack.borrow_mut();
1293                let new_len = stack.len().saturating_sub(pop_contexts);
1294                stack.truncate(new_len);
1295            });
1296        }
1297
1298        // Drop evicted component instances OUTSIDE any HOOK_STORE borrow so `use_effect`
1299        // cleanup callbacks can freely inspect or update signals without borrow conflicts.
1300        drop(evicted);
1301    }
1302}
1303
1304/// Assigns an explicit reconciliation key to the immediate child component rendered inside `f`,
1305/// preserving its hook state across list reorderings.
1306pub fn with_component_key<R>(key: impl std::fmt::Display, f: impl FnOnce() -> R) -> R {
1307    struct KeyRestoreGuard(Option<String>);
1308    impl Drop for KeyRestoreGuard {
1309        fn drop(&mut self) {
1310            let prev = self.0.take();
1311            let _ = HOOK_STORE.try_with(|store| {
1312                if let Ok(mut st) = store.try_borrow_mut() {
1313                    st.pending_key = prev;
1314                }
1315            });
1316        }
1317    }
1318
1319    let prev = HOOK_STORE.with(|store| store.borrow_mut().pending_key.replace(key.to_string()));
1320    let _guard = KeyRestoreGuard(prev);
1321    f()
1322}
1323
1324/// Evaluates `f` inside an implicit root component scope when no `#[component]` scope is
1325/// active on the current thread.
1326///
1327/// Wrapping plain root view closures (e.g. `|| rsx! { <> <Child /> <Child /> </> }`) gives
1328/// top-level unkeyed sibling components distinct ordinals (`#0`, `#1`, ...) instead of colliding
1329/// on `#0`, and runs child unmount / `use_effect` cleanup when siblings are toggled off.
1330pub fn with_root_component_scope<R>(f: impl FnOnce() -> R) -> R {
1331    let has_active = HOOK_STORE.with(|store| !store.borrow().active_stack.is_empty());
1332    if has_active {
1333        f()
1334    } else {
1335        let _root_scope = ComponentScopeGuard::enter("__strata_root__");
1336        f()
1337    }
1338}
1339
1340/// Clears all persisted component-scoped hook state and runs pending effect cleanups on this
1341/// thread. Intended for test isolation or full application resets.
1342pub fn reset_component_hooks() {
1343    let evicted: Vec<ComponentInstance> = HOOK_STORE.with(|store| {
1344        let mut st = store.borrow_mut();
1345        st.active_stack.clear();
1346        st.pending_key = None;
1347        st.next_hook_id = 0;
1348        st.instances.drain().map(|(_, inst)| inst).collect()
1349    });
1350    CONTEXT_STACK.with(|stack| stack.borrow_mut().clear());
1351    drop(evicted);
1352}
1353
1354thread_local! {
1355    static EFFECT_BODY_DEPTH: Cell<usize> = const { Cell::new(0) };
1356}
1357
1358struct EffectBodyGuard;
1359
1360impl EffectBodyGuard {
1361    #[inline]
1362    fn enter() -> Self {
1363        EFFECT_BODY_DEPTH.with(|d| d.set(d.get() + 1));
1364        Self
1365    }
1366}
1367
1368impl Drop for EffectBodyGuard {
1369    #[inline]
1370    fn drop(&mut self) {
1371        let _ = EFFECT_BODY_DEPTH.try_with(|d| d.set(d.get().saturating_sub(1)));
1372    }
1373}
1374
1375/// Returns `true` when executing directly inside a `#[component]` render body (not inside an
1376/// `Effect` or `use_effect_with_deps` callback where hook slots must not be allocated).
1377#[inline]
1378pub(crate) fn in_component_hook_context() -> bool {
1379    let in_effect = EFFECT_BODY_DEPTH.with(|d| d.get() > 0);
1380    if in_effect {
1381        return false;
1382    }
1383    HOOK_STORE.with(|store| !store.borrow().active_stack.is_empty())
1384}
1385
1386/// Looks up or initializes the current hook slot for the active component frame.
1387///
1388/// Returns `None` when called outside any `#[component]` scope so standalone unit tests
1389/// and top-level state builders continue working without a component frame.
1390pub(crate) fn use_hook_slot_cloned<T: Clone + 'static>(init: impl FnOnce() -> T) -> Option<T> {
1391    enum Lookup<T> {
1392        NoScope,
1393        Hit(T),
1394        Miss(ComponentPath, usize),
1395    }
1396
1397    let lookup = HOOK_STORE.with(|store| {
1398        let mut st = store.borrow_mut();
1399        let Some(frame) = st.active_stack.last_mut() else {
1400            return Lookup::NoScope;
1401        };
1402        let path = frame.path.clone();
1403        let idx = frame.hook_cursor;
1404        frame.hook_cursor += 1;
1405
1406        let inst = st
1407            .instances
1408            .entry(path.clone())
1409            .or_insert_with(ComponentInstance::new);
1410
1411        if idx < inst.slots.len() && !inst.slots[idx].is::<PendingHookSlot>() {
1412            let existing = inst.slots[idx]
1413                .downcast_ref::<T>()
1414                .unwrap_or_else(|| {
1415                    panic!(
1416                        "Strata Rules of Hooks violation at slot #{idx} in component `{}`: hook type mismatch across renders (avoid calling hooks conditionally).",
1417                        path.0
1418                            .last()
1419                            .map(|s| s.component_id.as_str())
1420                            .unwrap_or("<root>")
1421                    )
1422                })
1423                .clone();
1424            Lookup::Hit(existing)
1425        } else {
1426            while inst.slots.len() <= idx {
1427                inst.slots.push(Box::new(PendingHookSlot));
1428            }
1429            Lookup::Miss(path, idx)
1430        }
1431    });
1432
1433    match lookup {
1434        Lookup::NoScope => None,
1435        Lookup::Hit(val) => Some(val),
1436        Lookup::Miss(path, idx) => {
1437            // Run `init()` completely outside any HOOK_STORE borrow so closures may
1438            // read/write signals, access context, or construct reactive subscribers safely.
1439            let val = init();
1440            HOOK_STORE.with(|store| {
1441                let mut st = store.borrow_mut();
1442                if let Some(inst) = st.instances.get_mut(&path) {
1443                    if idx < inst.slots.len() {
1444                        inst.slots[idx] = Box::new(val.clone());
1445                    }
1446                }
1447            });
1448            Some(val)
1449        }
1450    }
1451}
1452
1453/// Like [`use_hook_slot_cloned`], but falls back directly to `init()` when outside a
1454/// `#[component]` scope so non-`Clone` `FnOnce` initializers are only moved once.
1455fn use_hook_slot_or_init<T: Clone + 'static>(init: impl FnOnce() -> T) -> T {
1456    enum Lookup<T> {
1457        NoScope,
1458        Hit(T),
1459        Miss(ComponentPath, usize),
1460    }
1461
1462    let lookup = HOOK_STORE.with(|store| {
1463        let mut st = store.borrow_mut();
1464        let Some(frame) = st.active_stack.last_mut() else {
1465            return Lookup::NoScope;
1466        };
1467        let path = frame.path.clone();
1468        let idx = frame.hook_cursor;
1469        frame.hook_cursor += 1;
1470
1471        let inst = st
1472            .instances
1473            .entry(path.clone())
1474            .or_insert_with(ComponentInstance::new);
1475
1476        if idx < inst.slots.len() && !inst.slots[idx].is::<PendingHookSlot>() {
1477            let existing = inst.slots[idx]
1478                .downcast_ref::<T>()
1479                .unwrap_or_else(|| {
1480                    panic!(
1481                        "Strata Rules of Hooks violation at slot #{idx} in component `{}`: hook type mismatch across renders (avoid calling hooks conditionally).",
1482                        path.0
1483                            .last()
1484                            .map(|s| s.component_id.as_str())
1485                            .unwrap_or("<root>")
1486                    )
1487                })
1488                .clone();
1489            Lookup::Hit(existing)
1490        } else {
1491            while inst.slots.len() <= idx {
1492                inst.slots.push(Box::new(PendingHookSlot));
1493            }
1494            Lookup::Miss(path, idx)
1495        }
1496    });
1497
1498    match lookup {
1499        Lookup::NoScope => init(),
1500        Lookup::Hit(val) => val,
1501        Lookup::Miss(path, idx) => {
1502            let val = init();
1503            HOOK_STORE.with(|store| {
1504                let mut st = store.borrow_mut();
1505                if let Some(inst) = st.instances.get_mut(&path) {
1506                    if idx < inst.slots.len() {
1507                        inst.slots[idx] = Box::new(val.clone());
1508                    }
1509                }
1510            });
1511            val
1512        }
1513    }
1514}
1515
1516/// Owned wrapper stored inside a component's hook slot so unmounting the component
1517/// automatically disposes its `Effect` and executes the cleanup closure.
1518#[derive(Clone)]
1519struct OwnedComponentEffect {
1520    effect: Effect,
1521    _owner: Rc<EffectDropGuard>,
1522}
1523
1524struct EffectDropGuard(Effect);
1525
1526impl Drop for EffectDropGuard {
1527    fn drop(&mut self) {
1528        self.0.dispose();
1529    }
1530}
1531
1532/// Owned wrapper for dependency-tracked `use_effect_with_deps` cleanup closures.
1533struct OwnedDepsEffect<D> {
1534    deps: Rc<RefCell<D>>,
1535    cleanup: CleanupCell,
1536    _owner: Rc<CleanupDropGuard>,
1537}
1538
1539impl<D> Clone for OwnedDepsEffect<D> {
1540    fn clone(&self) -> Self {
1541        Self {
1542            deps: Rc::clone(&self.deps),
1543            cleanup: Rc::clone(&self.cleanup),
1544            _owner: Rc::clone(&self._owner),
1545        }
1546    }
1547}
1548
1549struct CleanupDropGuard(CleanupCell);
1550
1551impl Drop for CleanupDropGuard {
1552    fn drop(&mut self) {
1553        if let Ok(mut cell) = self.0.try_borrow_mut() {
1554            if let Some(clean) = cell.take() {
1555                clean();
1556            }
1557        }
1558    }
1559}
1560
1561/// Trait allowing [`use_state`] to accept either a direct initial value (`use_state(0)`)
1562/// or a lazy initializer closure (`use_state(|| expensive())`), matching React's `useState`.
1563pub trait IntoInitialState<T, Marker = ()> {
1564    fn into_initial_state(self) -> T;
1565}
1566
1567impl<T> IntoInitialState<T, ()> for T {
1568    #[inline]
1569    fn into_initial_state(self) -> T {
1570        self
1571    }
1572}
1573
1574impl<T, F: FnOnce() -> T> IntoInitialState<T, ((),)> for F {
1575    #[inline]
1576    fn into_initial_state(self) -> T {
1577        self()
1578    }
1579}
1580
1581// ============================================================================
1582// Ergonomic Component Hooks
1583// ============================================================================
1584
1585/// Creates or retrieves a component-scoped reactive [`Signal`].
1586///
1587/// Inside a `#[component]`, the signal persists across re-renders at this hook cursor slot;
1588/// outside any component scope, allocates a fresh standalone `Signal`.
1589pub fn use_signal<T: Clone + 'static>(initial: T) -> Signal<T> {
1590    use_hook_slot_or_init(|| Signal::new(initial))
1591}
1592
1593thread_local! {
1594    static PERSISTENT_SIGNALS: RefCell<std::collections::HashMap<String, Box<dyn std::any::Any>>> =
1595        RefCell::new(std::collections::HashMap::new());
1596}
1597
1598/// Returns a signal that survives root re-invocation, identified by an explicit `key`.
1599///
1600/// Useful when sharing keyed state across disconnected subtrees or outside `#[component]`.
1601/// Asking for the same key with a different type panics, since that is a key clash.
1602pub fn use_persistent_signal<T: Clone + 'static>(key: &str, init: impl FnOnce() -> T) -> Signal<T> {
1603    PERSISTENT_SIGNALS.with(|store| {
1604        let mut store = store.borrow_mut();
1605        if let Some(existing) = store.get(key) {
1606            return existing
1607                .downcast_ref::<Signal<T>>()
1608                .unwrap_or_else(|| panic!("persistent signal key `{key}` reused with another type"))
1609                .clone();
1610        }
1611        let signal = Signal::new(init());
1612        store.insert(key.to_string(), Box::new(signal.clone()));
1613        signal
1614    })
1615}
1616
1617/// Drops all persistent signals and component-scoped hooks on this thread. Intended for tests.
1618pub fn clear_persistent_signals() {
1619    PERSISTENT_SIGNALS.with(|store| store.borrow_mut().clear());
1620    reset_component_hooks();
1621}
1622
1623/// React-style component-scoped state hook returning decoupled `(ReadSignal<T>, WriteSignal<T>)`.
1624///
1625/// Accepts either a direct value (`use_state(0)`) or a lazy initializer closure
1626/// (`use_state(|| compute_initial())`). Inside a `#[component]`, the initializer runs only on
1627/// mount and the underlying signal persists across re-renders via the component hook cursor.
1628pub fn use_state<T: Clone + 'static, M>(
1629    initial: impl IntoInitialState<T, M>,
1630) -> (ReadSignal<T>, WriteSignal<T>) {
1631    let sig = use_hook_slot_or_init(|| Signal::new(initial.into_initial_state()));
1632    sig.split()
1633}
1634
1635/// Component-scoped derived [`Memo`] that persists its reactive subscription across re-renders
1636/// and unregisters automatically when the component unmounts.
1637pub fn use_memo<T: Clone + PartialEq + 'static>(compute: impl FnMut() -> T + 'static) -> Memo<T> {
1638    use_hook_slot_or_init(|| Memo::new(compute))
1639}
1640
1641/// React-style dependency-array memoization hook (`useMemo(() => compute(&deps), [deps])`).
1642///
1643/// Computes `compute(&deps)` on mount and recomputes only when `deps` changes (`PartialEq`)
1644/// across component re-renders, returning a cached clone in between.
1645pub fn use_memo_with_deps<D, T, F>(deps: D, compute: F) -> T
1646where
1647    D: PartialEq + 'static,
1648    T: Clone + 'static,
1649    F: FnOnce(&D) -> T,
1650{
1651    let mut deps_opt = Some(deps);
1652    let mut compute_opt = Some(compute);
1653
1654    if let Some(cell) = use_hook_slot_cloned(|| {
1655        let initial_deps = deps_opt.take().unwrap();
1656        let initial_val = (compute_opt.take().unwrap())(&initial_deps);
1657        Rc::new(RefCell::new((initial_deps, initial_val)))
1658    }) {
1659        if let (Some(new_deps), Some(run_fn)) = (deps_opt.take(), compute_opt.take()) {
1660            let changed = cell.borrow().0 != new_deps;
1661            if changed {
1662                let next_val = run_fn(&new_deps);
1663                let mut guard = cell.borrow_mut();
1664                guard.0 = new_deps;
1665                guard.1 = next_val;
1666            }
1667        }
1668        return cell.borrow().1.clone();
1669    }
1670
1671    let d = deps_opt.take().unwrap();
1672    (compute_opt.take().unwrap())(&d)
1673}
1674
1675/// Component-scoped reactive [`Effect`] that tracks read signals, runs cleanup before each
1676/// re-execution, avoids duplicate registrations across re-renders, and automatically runs its
1677/// cleanup closure when the owning component unmounts.
1678pub fn use_effect<F, R>(effect_fn: F) -> Effect
1679where
1680    F: FnMut() -> R + 'static,
1681    R: IntoEffectCleanup,
1682{
1683    let mut effect_opt = Some(effect_fn);
1684    if let Some(owned) = use_hook_slot_cloned(|| {
1685        let eff = Effect::new(effect_opt.take().unwrap());
1686        OwnedComponentEffect {
1687            effect: eff.clone(),
1688            _owner: Rc::new(EffectDropGuard(eff)),
1689        }
1690    }) {
1691        owned.effect
1692    } else {
1693        Effect::new(effect_opt.take().unwrap())
1694    }
1695}
1696
1697/// Converts the return value of a [`use_effect_with_deps`] callback into an optional cleanup closure.
1698///
1699/// Implemented for `()` (no cleanup, eliminating trailing `None`),
1700/// `Option<Box<dyn FnOnce()>>` (backward compatible), `Box<dyn FnOnce()>`, and `Box<F>` for any
1701/// `F: FnOnce() + 'static` without requiring manual trait-object casts.
1702pub trait IntoEffectCleanup {
1703    fn into_effect_cleanup(self) -> Option<Box<dyn FnOnce()>>;
1704}
1705
1706impl IntoEffectCleanup for () {
1707    #[inline]
1708    fn into_effect_cleanup(self) -> Option<Box<dyn FnOnce()>> {
1709        None
1710    }
1711}
1712
1713impl IntoEffectCleanup for Option<Box<dyn FnOnce()>> {
1714    #[inline]
1715    fn into_effect_cleanup(self) -> Option<Box<dyn FnOnce()>> {
1716        self
1717    }
1718}
1719
1720impl IntoEffectCleanup for Box<dyn FnOnce()> {
1721    #[inline]
1722    fn into_effect_cleanup(self) -> Option<Box<dyn FnOnce()>> {
1723        Some(self)
1724    }
1725}
1726
1727impl<F: FnOnce() + 'static> IntoEffectCleanup for Box<F> {
1728    #[inline]
1729    fn into_effect_cleanup(self) -> Option<Box<dyn FnOnce()>> {
1730        Some(self)
1731    }
1732}
1733
1734/// React-style dependency-array effect hook.
1735///
1736/// Runs `effect_fn(&deps)` on mount and whenever `deps` changes (`PartialEq`) across component
1737/// re-renders, invoking the prior cleanup closure before re-running and again on unmount.
1738/// Callbacks may return `()` (no cleanup), `Box::new(move || ...)` / `Box<dyn FnOnce()>`,
1739/// or `Option<Box<dyn FnOnce()>>`.
1740pub fn use_effect_with_deps<D, R, F>(deps: D, effect_fn: F)
1741where
1742    D: PartialEq + 'static,
1743    R: IntoEffectCleanup,
1744    F: FnOnce(&D) -> R,
1745{
1746    let mut effect_opt = Some(effect_fn);
1747    let mut deps_opt = Some(deps);
1748
1749    if let Some(slot) = use_hook_slot_cloned(|| {
1750        let initial_deps = deps_opt.take().unwrap();
1751        let initial_clean = {
1752            let _effect_guard = EffectBodyGuard::enter();
1753            (effect_opt.take().unwrap())(&initial_deps).into_effect_cleanup()
1754        };
1755        let cleanup: CleanupCell = Rc::new(RefCell::new(initial_clean));
1756        OwnedDepsEffect {
1757            deps: Rc::new(RefCell::new(initial_deps)),
1758            cleanup: cleanup.clone(),
1759            _owner: Rc::new(CleanupDropGuard(cleanup)),
1760        }
1761    }) {
1762        // If `effect_opt` is still `Some`, this is a re-render (slot already existed on mount).
1763        if let (Some(new_deps), Some(run_fn)) = (deps_opt.take(), effect_opt.take()) {
1764            let changed = *slot.deps.borrow() != new_deps;
1765            if changed {
1766                let prev_clean = slot.cleanup.borrow_mut().take();
1767                if let Some(clean) = prev_clean {
1768                    clean();
1769                }
1770                let next_clean = {
1771                    let _effect_guard = EffectBodyGuard::enter();
1772                    run_fn(&new_deps).into_effect_cleanup()
1773                };
1774                *slot.deps.borrow_mut() = new_deps;
1775                *slot.cleanup.borrow_mut() = next_clean;
1776            }
1777        }
1778    } else if let (Some(d), Some(run_fn)) = (deps_opt.take(), effect_opt.take()) {
1779        // Standalone execution outside any component scope: run immediately.
1780        let _effect_guard = EffectBodyGuard::enter();
1781        let _ = run_fn(&d).into_effect_cleanup();
1782    }
1783}
1784
1785struct ReducerSlot<S: Clone + 'static, A: 'static, R: 'static> {
1786    state: Signal<S>,
1787    reducer: Rc<RefCell<R>>,
1788    dispatch: Rc<dyn Fn(A)>,
1789}
1790
1791impl<S: Clone + 'static, A: 'static, R: 'static> Clone for ReducerSlot<S, A, R> {
1792    fn clone(&self) -> Self {
1793        Self {
1794            state: self.state.clone(),
1795            reducer: Rc::clone(&self.reducer),
1796            dispatch: Rc::clone(&self.dispatch),
1797        }
1798    }
1799}
1800
1801/// React-style `useReducer` hook returning `(ReadSignal<S>, Rc<dyn Fn(A)>)`.
1802///
1803/// Persists state, reducer closure, and `dispatch` handle in the component hook slot so
1804/// `dispatch` preserves pointer identity (`Rc::ptr_eq`) across re-renders.
1805pub fn use_reducer<S, A, R>(reducer: R, initial_state: S) -> (ReadSignal<S>, Rc<dyn Fn(A)>)
1806where
1807    S: Clone + 'static,
1808    A: 'static,
1809    R: FnMut(&S, A) -> S + 'static,
1810{
1811    use_reducer_init(reducer, initial_state, |s| s)
1812}
1813
1814/// React-style 3-argument `useReducer` hook with lazy state initialization (`init(initial_arg)`).
1815///
1816/// Preserves the `dispatch` `Rc` identity across component re-renders while refreshing the active
1817/// reducer closure so inline reducers always see up-to-date prop captures.
1818pub fn use_reducer_init<S, A, I, R, F>(
1819    reducer: R,
1820    initial_arg: I,
1821    init: F,
1822) -> (ReadSignal<S>, Rc<dyn Fn(A)>)
1823where
1824    S: Clone + 'static,
1825    A: 'static,
1826    R: FnMut(&S, A) -> S + 'static,
1827    F: FnOnce(I) -> S,
1828{
1829    let mut reducer_opt = Some(reducer);
1830    let mut init_opt = Some((initial_arg, init));
1831
1832    let slot = use_hook_slot_or_init(|| {
1833        let (arg, init_fn) = init_opt.take().unwrap();
1834        let state = Signal::new(init_fn(arg));
1835        let reducer_cell = Rc::new(RefCell::new(reducer_opt.take().unwrap()));
1836        let dispatch_sig = state.clone();
1837        let dispatch_reducer = Rc::clone(&reducer_cell);
1838        let dispatch: Rc<dyn Fn(A)> = Rc::new(move |action: A| {
1839            let current = dispatch_sig.untracked_get();
1840            let next = {
1841                let mut r = dispatch_reducer.borrow_mut();
1842                r(&current, action)
1843            };
1844            dispatch_sig.set(next);
1845        });
1846        ReducerSlot {
1847            state,
1848            reducer: reducer_cell,
1849            dispatch,
1850        }
1851    });
1852
1853    if let Some(latest_reducer) = reducer_opt.take() {
1854        *slot.reducer.borrow_mut() = latest_reducer;
1855    }
1856
1857    (slot.state.split().0, slot.dispatch)
1858}
1859
1860/// Mutable, non-reactive reference container persisted across component re-renders (React `useRef`).
1861///
1862/// Mutating a [`Ref`] never marks the reactive graph dirty or triggers a re-render.
1863pub struct Ref<T> {
1864    inner: Rc<RefCell<T>>,
1865}
1866
1867impl<T> Clone for Ref<T> {
1868    fn clone(&self) -> Self {
1869        Self {
1870            inner: Rc::clone(&self.inner),
1871        }
1872    }
1873}
1874
1875impl<T: std::fmt::Debug> std::fmt::Debug for Ref<T> {
1876    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1877        f.debug_struct("Ref")
1878            .field("current", &*self.inner.borrow())
1879            .finish()
1880    }
1881}
1882
1883impl<T: 'static> Ref<T> {
1884    pub fn new(initial: T) -> Self {
1885        Self {
1886            inner: Rc::new(RefCell::new(initial)),
1887        }
1888    }
1889
1890    pub fn get(&self) -> T
1891    where
1892        T: Clone,
1893    {
1894        self.inner.borrow().clone()
1895    }
1896
1897    pub fn set(&self, value: T) {
1898        *self.inner.borrow_mut() = value;
1899    }
1900
1901    pub fn replace(&self, value: T) -> T {
1902        std::mem::replace(&mut *self.inner.borrow_mut(), value)
1903    }
1904
1905    pub fn borrow(&self) -> std::cell::Ref<'_, T> {
1906        self.inner.borrow()
1907    }
1908
1909    pub fn borrow_mut(&self) -> std::cell::RefMut<'_, T> {
1910        self.inner.borrow_mut()
1911    }
1912
1913    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
1914        f(&*self.inner.borrow())
1915    }
1916
1917    pub fn with_mut<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
1918        f(&mut *self.inner.borrow_mut())
1919    }
1920}
1921
1922/// React-style `useRef` hook returning a mutable [`Ref<T>`] that persists across re-renders
1923/// without triggering reactive updates.
1924pub fn use_ref<T: 'static>(initial: T) -> Ref<T> {
1925    use_hook_slot_or_init(|| Ref::new(initial))
1926}
1927
1928/// React-style `useCallback` hook that memoizes a closure `Rc<F>` across re-renders while
1929/// `deps` remains equal (`PartialEq`).
1930///
1931/// When `deps` is unchanged, the returned `Rc<F>` preserves exact pointer identity (`Rc::ptr_eq`).
1932pub fn use_callback<D, F>(deps: D, callback: F) -> Rc<F>
1933where
1934    D: PartialEq + 'static,
1935    F: 'static,
1936{
1937    let mut deps_opt = Some(deps);
1938    let mut cb_opt = Some(callback);
1939
1940    if let Some(cell) = use_hook_slot_cloned(|| {
1941        Rc::new(RefCell::new((
1942            deps_opt.take().unwrap(),
1943            Rc::new(cb_opt.take().unwrap()),
1944        )))
1945    }) {
1946        if let (Some(new_deps), Some(new_cb)) = (deps_opt.take(), cb_opt.take()) {
1947            let mut guard = cell.borrow_mut();
1948            if guard.0 != new_deps {
1949                guard.0 = new_deps;
1950                guard.1 = Rc::new(new_cb);
1951            }
1952            return Rc::clone(&guard.1);
1953        }
1954        return Rc::clone(&cell.borrow().1);
1955    }
1956
1957    Rc::new(cb_opt.take().unwrap())
1958}
1959
1960/// React-style `useId` hook generating a stable unique identifier (e.g. `":r0:"`) that persists
1961/// across re-renders of the same component instance and is unique across sibling instances.
1962pub fn use_id() -> String {
1963    let alloc = || {
1964        HOOK_STORE.with(|store| {
1965            let mut st = store.borrow_mut();
1966            let id = st.next_hook_id;
1967            st.next_hook_id += 1;
1968            format!(":r{id}:")
1969        })
1970    };
1971    use_hook_slot_cloned(alloc).unwrap_or_else(alloc)
1972}
1973
1974// ============================================================================
1975// React-Style Context API (`create_context` / `provide_context` / `use_context`)
1976// ============================================================================
1977
1978/// Typed context handle created by [`create_context`].
1979///
1980/// Provide values to descendant components either via [`provide_context`] (scoped to the
1981/// enclosing `#[component]`) or [`Context::provide`] (scoped to an explicit closure).
1982pub struct Context<T: Clone + 'static> {
1983    id: u64,
1984    default_value: Rc<T>,
1985}
1986
1987impl<T: Clone + 'static> Clone for Context<T> {
1988    fn clone(&self) -> Self {
1989        Self {
1990            id: self.id,
1991            default_value: Rc::clone(&self.default_value),
1992        }
1993    }
1994}
1995
1996impl<T: Clone + std::fmt::Debug + 'static> std::fmt::Debug for Context<T> {
1997    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1998        f.debug_struct("Context")
1999            .field("id", &self.id)
2000            .field("default_value", &*self.default_value)
2001            .finish()
2002    }
2003}
2004
2005impl<T: Clone + 'static> Context<T> {
2006    /// Returns this context's unique identifier.
2007    pub fn id(&self) -> u64 {
2008        self.id
2009    }
2010
2011    /// Returns a clone of the default fallback value supplied at creation time.
2012    pub fn default_value(&self) -> T {
2013        (*self.default_value).clone()
2014    }
2015
2016    /// Provides `value` to all components evaluated within `f`, restoring the previous
2017    /// context value automatically even if `f` unwinds.
2018    pub fn provide<R>(&self, value: T, f: impl FnOnce() -> R) -> R {
2019        struct ContextPopGuard;
2020        impl Drop for ContextPopGuard {
2021            fn drop(&mut self) {
2022                let _ = CONTEXT_STACK.try_with(|stack| {
2023                    if let Ok(mut st) = stack.try_borrow_mut() {
2024                        st.pop();
2025                    }
2026                });
2027            }
2028        }
2029
2030        CONTEXT_STACK.with(|stack| {
2031            stack.borrow_mut().push(ContextEntry {
2032                context_id: self.id,
2033                value: Box::new(value),
2034            });
2035        });
2036        let _guard = ContextPopGuard;
2037        f()
2038    }
2039}
2040
2041/// Creates a new typed [`Context<T>`] with a fallback `default_value`.
2042pub fn create_context<T: Clone + 'static>(default_value: T) -> Context<T> {
2043    let id = NEXT_CONTEXT_ID.with(|next| {
2044        let id = next.get();
2045        next.set(id + 1);
2046        id
2047    });
2048    Context {
2049        id,
2050        default_value: Rc::new(default_value),
2051    }
2052}
2053
2054/// Provides `value` for `context` to all child components rendered in the remainder of the
2055/// current `#[component]` scope.
2056///
2057/// The provided entry is automatically popped when the enclosing `#[component]` finishes
2058/// rendering. Outside a `#[component]` scope, prefer [`Context::provide`].
2059pub fn provide_context<T: Clone + 'static>(context: &Context<T>, value: T) {
2060    CONTEXT_STACK.with(|stack| {
2061        stack.borrow_mut().push(ContextEntry {
2062            context_id: context.id,
2063            value: Box::new(value),
2064        });
2065    });
2066    HOOK_STORE.with(|store| {
2067        let mut st = store.borrow_mut();
2068        if let Some(frame) = st.active_stack.last_mut() {
2069            frame.provided_context_count += 1;
2070        }
2071    });
2072}
2073
2074/// Reads the nearest ancestor value provided for `context`, or its default value when no
2075/// ancestor provider is active.
2076pub fn use_context<T: Clone + 'static>(context: &Context<T>) -> T {
2077    CONTEXT_STACK.with(|stack| {
2078        let stack = stack.borrow();
2079        for entry in stack.iter().rev() {
2080            if entry.context_id == context.id {
2081                if let Some(val) = entry.value.downcast_ref::<T>() {
2082                    return val.clone();
2083                }
2084            }
2085        }
2086        context.default_value()
2087    })
2088}
2089
2090pub fn batch<R>(f: impl FnOnce() -> R) -> R {
2091    ReactiveRuntime::batch(f)
2092}
2093
2094pub fn untrack<R>(f: impl FnOnce() -> R) -> R {
2095    ReactiveRuntime::untrack(f)
2096}
2097
2098pub fn has_dirty_signals() -> bool {
2099    ReactiveRuntime::has_dirty_signals()
2100}
2101
2102pub fn take_dirty_signals() -> bool {
2103    ReactiveRuntime::take_dirty_signals()
2104}
2105
2106pub fn mark_dirty() {
2107    ReactiveRuntime::mark_dirty()
2108}
2109
2110pub fn set_signal_name(signal_id: SignalId, name: impl Into<String>) {
2111    ReactiveRuntime::set_signal_name(signal_id, name);
2112}
2113
2114pub fn signal_name(signal_id: SignalId) -> String {
2115    ReactiveRuntime::signal_name(signal_id)
2116}
2117
2118pub fn peek_dirty_signal_names() -> Vec<String> {
2119    ReactiveRuntime::peek_dirty_signal_names()
2120}
2121
2122pub fn take_dirty_signal_names() -> Vec<String> {
2123    ReactiveRuntime::take_dirty_signal_names()
2124}
2125
2126pub fn reactive_telemetry_snapshot() -> ReactiveTelemetrySnapshot {
2127    ReactiveRuntime::telemetry_snapshot()
2128}
2129
2130// ---------------------------------------------------------------------------
2131// State-Preserving Hot Module Replacement (HMR) Signal Codec & Registry
2132// ---------------------------------------------------------------------------
2133
2134/// Zero-dependency binary codec allowing reactive signal values to survive
2135/// dynamic `.so`/`.dylib`/`.dll` hot reloads cleanly across module epochs.
2136pub trait HmrCodec: Sized {
2137    /// Serializes this value into an opaque byte vector for HMR snapshotting.
2138    fn encode_hmr(&self) -> Vec<u8>;
2139    /// Restores a value from bytes captured before a hot reload.
2140    fn decode_hmr(bytes: &[u8]) -> Option<Self>;
2141}
2142
2143impl HmrCodec for bool {
2144    fn encode_hmr(&self) -> Vec<u8> {
2145        vec![if *self { 1 } else { 0 }]
2146    }
2147    fn decode_hmr(bytes: &[u8]) -> Option<Self> {
2148        bytes.first().map(|&b| b != 0)
2149    }
2150}
2151
2152macro_rules! impl_hmr_numeric {
2153    ($($ty:ty),*) => {
2154        $(
2155            impl HmrCodec for $ty {
2156                fn encode_hmr(&self) -> Vec<u8> {
2157                    self.to_le_bytes().to_vec()
2158                }
2159                fn decode_hmr(bytes: &[u8]) -> Option<Self> {
2160                    let arr: [u8; std::mem::size_of::<$ty>()] = bytes.try_into().ok()?;
2161                    Some(<$ty>::from_le_bytes(arr))
2162                }
2163            }
2164        )*
2165    };
2166}
2167
2168impl_hmr_numeric!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize, f32, f64);
2169
2170impl HmrCodec for String {
2171    fn encode_hmr(&self) -> Vec<u8> {
2172        self.as_bytes().to_vec()
2173    }
2174    fn decode_hmr(bytes: &[u8]) -> Option<Self> {
2175        String::from_utf8(bytes.to_vec()).ok()
2176    }
2177}
2178
2179impl<T: HmrCodec> HmrCodec for Option<T> {
2180    fn encode_hmr(&self) -> Vec<u8> {
2181        match self {
2182            None => vec![0u8],
2183            Some(v) => {
2184                let inner = v.encode_hmr();
2185                let mut out = Vec::with_capacity(1 + inner.len());
2186                out.push(1u8);
2187                out.extend_from_slice(&inner);
2188                out
2189            }
2190        }
2191    }
2192    fn decode_hmr(bytes: &[u8]) -> Option<Self> {
2193        let (&tag, rest) = bytes.split_first()?;
2194        if tag == 0 {
2195            Some(None)
2196        } else {
2197            Some(Some(T::decode_hmr(rest)?))
2198        }
2199    }
2200}
2201
2202impl<T: HmrCodec> HmrCodec for Vec<T> {
2203    fn encode_hmr(&self) -> Vec<u8> {
2204        let mut out = Vec::new();
2205        out.extend_from_slice(&(self.len() as u32).to_le_bytes());
2206        for item in self {
2207            let encoded = item.encode_hmr();
2208            out.extend_from_slice(&(encoded.len() as u32).to_le_bytes());
2209            out.extend_from_slice(&encoded);
2210        }
2211        out
2212    }
2213    fn decode_hmr(bytes: &[u8]) -> Option<Self> {
2214        if bytes.len() < 4 {
2215            return None;
2216        }
2217        let count = u32::from_le_bytes(bytes[0..4].try_into().ok()?) as usize;
2218        let mut pos = 4usize;
2219        let mut out = Vec::with_capacity(count.min(65_536));
2220        for _ in 0..count {
2221            if pos + 4 > bytes.len() {
2222                return None;
2223            }
2224            let len = u32::from_le_bytes(bytes[pos..pos + 4].try_into().ok()?) as usize;
2225            pos += 4;
2226            if pos + len > bytes.len() {
2227                return None;
2228            }
2229            out.push(T::decode_hmr(&bytes[pos..pos + len])?);
2230            pos += len;
2231        }
2232        Some(out)
2233    }
2234}
2235
2236struct HmrLiveSlot {
2237    type_name: String,
2238    export: Box<dyn Fn() -> Vec<u8>>,
2239    import: Box<dyn Fn(&[u8]) -> bool>,
2240}
2241
2242#[derive(Default)]
2243struct HmrStateRegistry {
2244    live_slots: BTreeMap<String, HmrLiveSlot>,
2245    hydrated_blobs: BTreeMap<String, Vec<u8>>,
2246}
2247
2248thread_local! {
2249    static HMR_STATE_REGISTRY: RefCell<HmrStateRegistry> = RefCell::new(HmrStateRegistry::default());
2250}
2251
2252/// Creates or reconnects a state-preserving HMR reactive signal keyed by `key`.
2253///
2254/// - During normal re-renders in the same binary epoch, behaves like [`use_persistent_signal`]
2255///   and returns the existing [`Signal<T>`].
2256/// - Across dynamic `.so`/`.dylib`/`.dll` hot reloads, automatically hydrates from any
2257///   snapshot imported via [`import_hmr_signals`] and registers live export/import hooks
2258///   so subsequent reloads preserve every mutation.
2259pub fn use_hmr_signal<T: HmrCodec + Clone + 'static>(
2260    key: impl Into<String>,
2261    initial: T,
2262) -> Signal<T> {
2263    let key_str = key.into();
2264    let hydrated_initial = HMR_STATE_REGISTRY.with(|reg| {
2265        reg.borrow()
2266            .hydrated_blobs
2267            .get(&key_str)
2268            .and_then(|bytes| T::decode_hmr(bytes))
2269    });
2270
2271    let sig = use_persistent_signal(&key_str, move || hydrated_initial.unwrap_or(initial));
2272
2273    // If a fresh HMR snapshot blob was imported after this signal already existed, hydrate in-place.
2274    let pending_blob = HMR_STATE_REGISTRY.with(|reg| reg.borrow_mut().hydrated_blobs.remove(&key_str));
2275    if let Some(bytes) = pending_blob {
2276        if let Some(val) = T::decode_hmr(&bytes) {
2277            sig.set_untracked(val);
2278        }
2279    }
2280
2281    let sig_for_export = sig.clone();
2282    let sig_for_import = sig.clone();
2283    HMR_STATE_REGISTRY.with(|reg| {
2284        reg.borrow_mut().live_slots.insert(
2285            key_str,
2286            HmrLiveSlot {
2287                type_name: std::any::type_name::<T>().to_string(),
2288                export: Box::new(move || sig_for_export.untracked_get().encode_hmr()),
2289                import: Box::new(move |bytes: &[u8]| {
2290                    if let Some(val) = T::decode_hmr(bytes) {
2291                        sig_for_import.set(val);
2292                        true
2293                    } else {
2294                        false
2295                    }
2296                }),
2297            },
2298        );
2299    });
2300
2301    sig
2302}
2303
2304/// Exports all registered HMR signals (plus any unconsumed hydrated blobs) as
2305/// `(key, type_name, encoded_bytes)` tuples prior to unloading/reloading a dynamic module.
2306pub fn export_hmr_signals() -> Vec<(String, String, Vec<u8>)> {
2307    HMR_STATE_REGISTRY.with(|reg| {
2308        let reg = reg.borrow();
2309        let mut out = Vec::with_capacity(reg.live_slots.len() + reg.hydrated_blobs.len());
2310        for (key, slot) in &reg.live_slots {
2311            out.push((key.clone(), slot.type_name.clone(), (slot.export)()));
2312        }
2313        for (key, bytes) in &reg.hydrated_blobs {
2314            if !reg.live_slots.contains_key(key) {
2315                out.push((key.clone(), "raw".to_string(), bytes.clone()));
2316            }
2317        }
2318        out
2319    })
2320}
2321
2322/// Imports HMR signal payloads captured before a hot reload.
2323///
2324/// Updates any currently mounted signals in-place immediately AND stages raw blobs
2325/// for components mounted during the next render pass. Returns the number of entries applied/staged.
2326pub fn import_hmr_signals(entries: &[(String, Vec<u8>)]) -> usize {
2327    HMR_STATE_REGISTRY.with(|reg| {
2328        let mut reg = reg.borrow_mut();
2329        let mut count = 0usize;
2330        for (key, bytes) in entries {
2331            let mut applied_live = false;
2332            if let Some(slot) = reg.live_slots.get(key) {
2333                if (slot.import)(bytes) {
2334                    applied_live = true;
2335                    count += 1;
2336                }
2337            }
2338            if !applied_live {
2339                reg.hydrated_blobs.insert(key.clone(), bytes.clone());
2340                count += 1;
2341            }
2342        }
2343        count
2344    })
2345}
2346
2347/// Clears all HMR signal registry entries (useful for isolated unit/integration tests).
2348pub fn clear_hmr_signals() {
2349    HMR_STATE_REGISTRY.with(|reg| {
2350        let mut reg = reg.borrow_mut();
2351        reg.live_slots.clear();
2352        reg.hydrated_blobs.clear();
2353    });
2354}
2355