Skip to main content

repose_core/
scope.rs

1use std::any::Any;
2use std::cell::{Cell, RefCell};
3use std::rc::{Rc, Weak};
4
5use rustc_hash::FxHashMap;
6
7use crate::effects::Dispose;
8
9thread_local! {
10    static CURRENT_SCOPE: RefCell<Option<Weak<ScopeInner>>> = const { RefCell::new(None) };
11}
12
13pub struct Scope {
14    inner: Rc<ScopeInner>,
15}
16
17struct ScopeInner {
18    disposers: RefCell<Vec<Box<dyn FnOnce()>>>,
19    children: RefCell<Vec<Scope>>,
20    memo_cache: RefCell<FxHashMap<String, Box<dyn Any>>>,
21    disposed: Cell<bool>,
22}
23
24impl Default for Scope {
25    fn default() -> Self {
26        Self::new()
27    }
28}
29
30impl Scope {
31    pub fn new() -> Self {
32        Self {
33            inner: Rc::new(ScopeInner {
34                disposers: RefCell::new(Vec::new()),
35                children: RefCell::new(Vec::new()),
36                memo_cache: RefCell::new(FxHashMap::default()),
37                disposed: Cell::new(false),
38            }),
39        }
40    }
41
42    pub fn run<R>(&self, f: impl FnOnce() -> R) -> R {
43        CURRENT_SCOPE.with(|current| {
44            let prev = current.borrow().clone();
45            *current.borrow_mut() = Some(Rc::downgrade(&self.inner));
46            let result = f();
47            *current.borrow_mut() = prev;
48            result
49        })
50    }
51
52    pub fn add_disposer(&self, disposer: impl FnOnce() + 'static) {
53        self.inner.disposers.borrow_mut().push(Box::new(disposer));
54    }
55
56    /// Returns a cached value from this scope's memo cache, or creates it with
57    /// `init` and stores it. The value persists for the lifetime of this scope
58    /// (i.e., until the scope key is no longer composed or the root is replaced).
59    pub fn memo<T: 'static>(&self, key: &str, init: impl FnOnce() -> T) -> Rc<T> {
60        let mut cache = self.inner.memo_cache.borrow_mut();
61        if let Some(existing) = cache.get(key)
62            && let Some(v) = existing.downcast_ref::<Rc<T>>()
63        {
64            return v.clone();
65        }
66        let val: Rc<T> = Rc::new(init());
67        cache.insert(key.to_string(), Box::new(val.clone()));
68        val
69    }
70
71    pub fn child(&self) -> Scope {
72        let child = Scope::new();
73        self.inner.children.borrow_mut().push(child.clone());
74        child
75    }
76
77    pub fn dispose(self) {
78        if self.inner.disposed.replace(true) {
79            return; // already disposed (or being dropped)
80        }
81        // Dispose children first
82        let children = std::mem::take(&mut *self.inner.children.borrow_mut());
83        for child in children {
84            child.dispose();
85        }
86
87        // Run disposers
88        let disposers = std::mem::take(&mut *self.inner.disposers.borrow_mut());
89        for disposer in disposers {
90            disposer();
91        }
92    }
93}
94
95impl Clone for Scope {
96    fn clone(&self) -> Self {
97        Self {
98            inner: self.inner.clone(),
99        }
100    }
101}
102
103pub fn current_scope() -> Option<Scope> {
104    CURRENT_SCOPE.with(|current| {
105        current
106            .borrow()
107            .as_ref()
108            .and_then(|weak| weak.upgrade().map(|inner| Scope { inner }))
109    })
110}
111
112/// Access this scope's memo cache from anywhere inside a `scope!` body.
113/// Returns the cached value for `key`, or creates it with `init` and stores it.
114/// The value persists until the scope is disposed.
115///
116/// Unlike `remember_with_key`, this is scoped to the current composition scope
117/// and is automatically cleaned up when the scope is no longer composed.
118pub fn scope_memo<T: 'static>(key: &str, init: impl FnOnce() -> T) -> Rc<T> {
119    match current_scope() {
120        Some(scope) => scope.memo(key, init),
121        None => Rc::new(init()),
122    }
123}
124
125/// Scoped effect that auto-cleans up.
126///
127/// Runs `f()` immediately and registers the returned `Dispose` to run when the
128/// current scope is disposed.
129pub fn scoped_effect<F>(f: F)
130where
131    F: FnOnce() -> Dispose + 'static,
132{
133    if let Some(scope) = current_scope() {
134        let cleanup = f();
135        scope.add_disposer(move || cleanup.run());
136    } else {
137        // No scope, run setup now, but drop cleanup (legacy "leak" behavior).
138        let _cleanup = f();
139    }
140}
141
142impl Drop for ScopeInner {
143    fn drop(&mut self) {
144        if self.disposed.replace(true) {
145            return; // already disposed via explicit dispose() call
146        }
147        let children = std::mem::take(&mut *self.children.borrow_mut());
148        for child in children {
149            drop(child);
150        }
151
152        let disposers = std::mem::take(&mut *self.disposers.borrow_mut());
153        for disposer in disposers {
154            disposer();
155        }
156    }
157}