dioxus_core/
scope_context.rs

1use crate::{
2    innerlude::{throw_into, CapturedError, SchedulerMsg, SuspenseContext},
3    runtime::RuntimeError,
4    Runtime, ScopeId, Task,
5};
6use generational_box::{AnyStorage, Owner};
7use rustc_hash::FxHashSet;
8use std::{
9    any::Any,
10    cell::{Cell, RefCell},
11    future::Future,
12    sync::Arc,
13};
14
15pub(crate) enum ScopeStatus {
16    Mounted,
17    Unmounted {
18        // Before the component is mounted, we need to keep track of effects that need to be run once the scope is mounted
19        effects_queued: Vec<Box<dyn FnOnce() + 'static>>,
20    },
21}
22
23#[derive(Debug, Clone, Default)]
24pub(crate) enum SuspenseLocation {
25    #[default]
26    NotSuspended,
27    SuspenseBoundary(SuspenseContext),
28    UnderSuspense(SuspenseContext),
29    InSuspensePlaceholder(SuspenseContext),
30}
31
32impl SuspenseLocation {
33    pub(crate) fn suspense_context(&self) -> Option<&SuspenseContext> {
34        match self {
35            SuspenseLocation::InSuspensePlaceholder(context) => Some(context),
36            SuspenseLocation::UnderSuspense(context) => Some(context),
37            SuspenseLocation::SuspenseBoundary(context) => Some(context),
38            _ => None,
39        }
40    }
41}
42
43/// A component's state separate from its props.
44///
45/// This struct exists to provide a common interface for all scopes without relying on generics.
46pub(crate) struct Scope {
47    pub(crate) name: &'static str,
48    pub(crate) id: ScopeId,
49    pub(crate) parent_id: Option<ScopeId>,
50    pub(crate) height: u32,
51    pub(crate) render_count: Cell<usize>,
52
53    // Note: the order of the hook and context fields is important. The hooks field must be dropped before the contexts field in case a hook drop implementation tries to access a context.
54    pub(crate) hooks: RefCell<Vec<Box<dyn Any>>>,
55    pub(crate) hook_index: Cell<usize>,
56    pub(crate) shared_contexts: RefCell<Vec<Box<dyn Any>>>,
57    pub(crate) spawned_tasks: RefCell<FxHashSet<Task>>,
58    pub(crate) before_render: RefCell<Vec<Box<dyn FnMut()>>>,
59    pub(crate) after_render: RefCell<Vec<Box<dyn FnMut()>>>,
60
61    /// The suspense boundary that this scope is currently in (if any)
62    suspense_boundary: SuspenseLocation,
63
64    pub(crate) status: RefCell<ScopeStatus>,
65}
66
67impl Scope {
68    pub(crate) fn new(
69        name: &'static str,
70        id: ScopeId,
71        parent_id: Option<ScopeId>,
72        height: u32,
73        suspense_boundary: SuspenseLocation,
74    ) -> Self {
75        Self {
76            name,
77            id,
78            parent_id,
79            height,
80            render_count: Cell::new(0),
81            shared_contexts: RefCell::new(vec![]),
82            spawned_tasks: RefCell::new(FxHashSet::default()),
83            hooks: RefCell::new(vec![]),
84            hook_index: Cell::new(0),
85            before_render: RefCell::new(vec![]),
86            after_render: RefCell::new(vec![]),
87            status: RefCell::new(ScopeStatus::Unmounted {
88                effects_queued: Vec::new(),
89            }),
90            suspense_boundary,
91        }
92    }
93
94    pub fn parent_id(&self) -> Option<ScopeId> {
95        self.parent_id
96    }
97
98    fn sender(&self) -> futures_channel::mpsc::UnboundedSender<SchedulerMsg> {
99        Runtime::with(|rt| rt.sender.clone()).unwrap_or_else(|e| panic!("{}", e))
100    }
101
102    /// Mount the scope and queue any pending effects if it is not already mounted
103    pub(crate) fn mount(&self, runtime: &Runtime) {
104        let mut status = self.status.borrow_mut();
105        if let ScopeStatus::Unmounted { effects_queued } = &mut *status {
106            for f in effects_queued.drain(..) {
107                runtime.queue_effect_on_mounted_scope(self.id, f);
108            }
109            *status = ScopeStatus::Mounted;
110        }
111    }
112
113    /// Get the suspense location of this scope
114    pub(crate) fn suspense_location(&self) -> SuspenseLocation {
115        self.suspense_boundary.clone()
116    }
117
118    /// If this scope is a suspense boundary, return the suspense context
119    pub(crate) fn suspense_boundary(&self) -> Option<SuspenseContext> {
120        match self.suspense_location() {
121            SuspenseLocation::SuspenseBoundary(context) => Some(context),
122            _ => None,
123        }
124    }
125
126    /// Check if a node should run during suspense
127    pub(crate) fn should_run_during_suspense(&self) -> bool {
128        let Some(context) = self.suspense_boundary.suspense_context() else {
129            return false;
130        };
131
132        !context.frozen()
133    }
134
135    /// Mark this scope as dirty, and schedule a render for it.
136    pub fn needs_update(&self) {
137        self.needs_update_any(self.id)
138    }
139
140    /// Mark this scope as dirty, and schedule a render for it.
141    pub fn needs_update_any(&self, id: ScopeId) {
142        self.sender()
143            .unbounded_send(SchedulerMsg::Immediate(id))
144            .expect("Scheduler to exist if scope exists");
145    }
146
147    /// Create a subscription that schedules a future render for the referenced component.
148    ///
149    /// Note: you should prefer using [`Self::schedule_update_any`] and [`Self::id`].
150    ///
151    /// Note: The function returned by this method will schedule an update for the current component even if it has already updated between when `schedule_update` was called and when the returned function is called.
152    /// If the desired behavior is to invalidate the current rendering of the current component (and no-op if already invalidated)
153    /// [`subscribe`](crate::reactive_context::ReactiveContext::subscribe) to the [`current`](crate::reactive_context::ReactiveContext::current) [`ReactiveContext`](crate::reactive_context::ReactiveContext) instead.
154    pub fn schedule_update(&self) -> Arc<dyn Fn() + Send + Sync + 'static> {
155        let (chan, id) = (self.sender(), self.id);
156        Arc::new(move || drop(chan.unbounded_send(SchedulerMsg::Immediate(id))))
157    }
158
159    /// Schedule an update for any component given its [`ScopeId`].
160    ///
161    /// A component's [`ScopeId`] can be obtained from `use_hook` or the [`current_scope_id`](crate::current_scope_id) method.
162    ///
163    /// This method should be used when you want to schedule an update for a component.
164    ///
165    /// Note: It does not matter when `schedule_update_any` is called: the returned function will invalidate what ever generation of the specified component is current when returned function is called.
166    /// If the desired behavior is to schedule invalidation of the current rendering of a component, use [`ReactiveContext`](crate::reactive_context::ReactiveContext) instead.
167    pub fn schedule_update_any(&self) -> Arc<dyn Fn(ScopeId) + Send + Sync> {
168        let chan = self.sender();
169        Arc::new(move |id| {
170            chan.unbounded_send(SchedulerMsg::Immediate(id)).unwrap();
171        })
172    }
173
174    /// Get the owner for the current scope.
175    pub fn owner<S: AnyStorage>(&self) -> Owner<S> {
176        match self.has_context() {
177            Some(rt) => rt,
178            None => {
179                let owner = S::owner();
180                self.provide_context(owner)
181            }
182        }
183    }
184
185    /// Return any context of type T if it exists on this scope
186    pub fn has_context<T: 'static + Clone>(&self) -> Option<T> {
187        self.shared_contexts
188            .borrow()
189            .iter()
190            .find_map(|any| any.downcast_ref::<T>())
191            .cloned()
192    }
193
194    /// Try to retrieve a shared state with type `T` from any parent scope.
195    ///
196    /// Clones the state if it exists.
197    pub fn consume_context<T: 'static + Clone>(&self) -> Option<T> {
198        tracing::trace!(
199            "looking for context {} ({:?}) in {:?}",
200            std::any::type_name::<T>(),
201            std::any::TypeId::of::<T>(),
202            self.id
203        );
204        if let Some(this_ctx) = self.has_context() {
205            return Some(this_ctx);
206        }
207
208        let mut search_parent = self.parent_id;
209        let cur_runtime = Runtime::with(|runtime| {
210            while let Some(parent_id) = search_parent {
211                let Some(parent) = runtime.get_state(parent_id) else {
212                    tracing::error!("Parent scope {:?} not found", parent_id);
213                    return None;
214                };
215                tracing::trace!(
216                    "looking for context {} ({:?}) in {:?}",
217                    std::any::type_name::<T>(),
218                    std::any::TypeId::of::<T>(),
219                    parent.id
220                );
221                if let Some(shared) = parent.has_context() {
222                    return Some(shared);
223                }
224                search_parent = parent.parent_id;
225            }
226            None
227        });
228
229        match cur_runtime.ok().flatten() {
230            Some(ctx) => Some(ctx),
231            None => {
232                tracing::trace!(
233                    "context {} ({:?}) not found",
234                    std::any::type_name::<T>(),
235                    std::any::TypeId::of::<T>()
236                );
237                None
238            }
239        }
240    }
241
242    /// Inject a `Box<dyn Any>` into the context of this scope
243    pub(crate) fn provide_any_context(&self, mut value: Box<dyn Any>) {
244        let mut contexts = self.shared_contexts.borrow_mut();
245
246        // If the context exists, swap it out for the new value
247        for ctx in contexts.iter_mut() {
248            // Swap the ptr directly
249            if ctx.as_ref().type_id() == value.as_ref().type_id() {
250                std::mem::swap(ctx, &mut value);
251                return;
252            }
253        }
254
255        // Else, just push it
256        contexts.push(value);
257    }
258
259    /// Expose state to children further down the [`crate::VirtualDom`] Tree. Requires `Clone` on the context to allow getting values down the tree.
260    ///
261    /// This is a "fundamental" operation and should only be called during initialization of a hook.
262    ///
263    /// For a hook that provides the same functionality, use `use_provide_context` and `use_context` instead.
264    ///
265    /// # Example
266    ///
267    /// ```rust
268    /// # use dioxus::prelude::*;
269    /// #[derive(Clone)]
270    /// struct SharedState(&'static str);
271    ///
272    /// // The parent provides context that is available in all children
273    /// fn app() -> Element {
274    ///     use_hook(|| provide_context(SharedState("world")));
275    ///     rsx!(Child {})
276    /// }
277    ///
278    /// // Any child elements can access the context with the `consume_context` function
279    /// fn Child() -> Element {
280    ///     let state = use_context::<SharedState>();
281    ///     rsx!(div { "hello {state.0}" })
282    /// }
283    /// ```
284    pub fn provide_context<T: 'static + Clone>(&self, value: T) -> T {
285        tracing::trace!(
286            "providing context {} ({:?}) in {:?}",
287            std::any::type_name::<T>(),
288            std::any::TypeId::of::<T>(),
289            self.id
290        );
291        let mut contexts = self.shared_contexts.borrow_mut();
292
293        // If the context exists, swap it out for the new value
294        for ctx in contexts.iter_mut() {
295            // Swap the ptr directly
296            if let Some(ctx) = ctx.downcast_mut::<T>() {
297                std::mem::swap(ctx, &mut value.clone());
298                return value;
299            }
300        }
301
302        // Else, just push it
303        contexts.push(Box::new(value.clone()));
304
305        value
306    }
307
308    /// Provide a context to the root and then consume it
309    ///
310    /// This is intended for "global" state management solutions that would rather be implicit for the entire app.
311    /// Things like signal runtimes and routers are examples of "singletons" that would benefit from lazy initialization.
312    ///
313    /// Note that you should be checking if the context existed before trying to provide a new one. Providing a context
314    /// when a context already exists will swap the context out for the new one, which may not be what you want.
315    pub fn provide_root_context<T: 'static + Clone>(&self, context: T) -> T {
316        Runtime::with(|runtime| {
317            runtime
318                .get_state(ScopeId::ROOT)
319                .unwrap()
320                .provide_context(context)
321        })
322        .expect("Runtime to exist")
323    }
324
325    /// Start a new future on the same thread as the rest of the VirtualDom.
326    ///
327    /// **You should generally use `spawn` instead of this method unless you specifically need to need to run a task during suspense**
328    ///
329    /// This future will not contribute to suspense resolving but it will run during suspense.
330    ///
331    /// Because this future runs during suspense, you need to be careful to work with hydration. It is not recommended to do any async IO work in this future, as it can easily cause hydration issues. However, you can use isomorphic tasks to do work that can be consistently replicated on the server and client like logging or responding to state changes.
332    ///
333    /// ```rust, no_run
334    /// # use dioxus::prelude::*;
335    /// // ❌ Do not do requests in isomorphic tasks. It may resolve at a different time on the server and client, causing hydration issues.
336    /// let mut state = use_signal(|| None);
337    /// spawn_isomorphic(async move {
338    ///     state.set(Some(reqwest::get("https://api.example.com").await));
339    /// });
340    ///
341    /// // ✅ You may wait for a signal to change and then log it
342    /// let mut state = use_signal(|| 0);
343    /// spawn_isomorphic(async move {
344    ///     loop {
345    ///         tokio::time::sleep(std::time::Duration::from_secs(1)).await;
346    ///         println!("State is {state}");
347    ///     }
348    /// });
349    /// ```
350    pub fn spawn_isomorphic(&self, fut: impl Future<Output = ()> + 'static) -> Task {
351        let id = Runtime::with(|rt| rt.spawn_isomorphic(self.id, fut)).expect("Runtime to exist");
352        self.spawned_tasks.borrow_mut().insert(id);
353        id
354    }
355
356    /// Spawns the future and returns the [`Task`]
357    pub fn spawn(&self, fut: impl Future<Output = ()> + 'static) -> Task {
358        let id = Runtime::with(|rt| rt.spawn(self.id, fut)).expect("Runtime to exist");
359        self.spawned_tasks.borrow_mut().insert(id);
360        id
361    }
362
363    /// Queue an effect to run after the next render
364    pub fn queue_effect(&self, f: impl FnOnce() + 'static) {
365        Runtime::with(|rt| rt.queue_effect(self.id, f)).expect("Runtime to exist");
366    }
367
368    /// Store a value between renders. The foundational hook for all other hooks.
369    ///
370    /// Accepts an `initializer` closure, which is run on the first use of the hook (typically the initial render).
371    /// `use_hook` will return a clone of the value on every render.
372    ///
373    /// In order to clean up resources you would need to implement the [`Drop`] trait for an inner value stored in a RC or similar (Signals for instance),
374    /// as these only drop their inner value once all references have been dropped, which only happens when the component is dropped.
375    ///
376    /// <div class="warning">
377    ///
378    /// `use_hook` is not reactive. It just returns the value on every render. If you need state that will track changes, use [`use_signal`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_signal.html) instead.
379    ///
380    /// ❌ Don't use `use_hook` with `Rc<RefCell<T>>` for state. It will not update the UI and other hooks when the state changes.
381    /// ```rust
382    /// use dioxus::prelude::*;
383    /// use std::rc::Rc;
384    /// use std::cell::RefCell;
385    ///
386    /// pub fn Comp() -> Element {
387    ///     let count = use_hook(|| Rc::new(RefCell::new(0)));
388    ///
389    ///     rsx! {
390    ///         button {
391    ///             onclick: move |_| *count.borrow_mut() += 1,
392    ///             "{count.borrow()}"
393    ///         }
394    ///     }
395    /// }
396    /// ```
397    ///
398    /// ✅ Use `use_signal` instead.
399    /// ```rust
400    /// use dioxus::prelude::*;
401    ///
402    /// pub fn Comp() -> Element {
403    ///     let mut count = use_signal(|| 0);
404    ///
405    ///     rsx! {
406    ///         button {
407    ///             onclick: move |_| count += 1,
408    ///             "{count}"
409    ///         }
410    ///     }
411    /// }
412    /// ```
413    ///
414    /// </div>
415    ///
416    /// # Example
417    ///
418    /// ```rust
419    /// use dioxus::prelude::*;
420    ///
421    /// // prints a greeting on the initial render
422    /// pub fn use_hello_world() {
423    ///     use_hook(|| println!("Hello, world!"));
424    /// }
425    /// ```
426    ///
427    /// # Custom Hook Example
428    ///
429    /// ```rust
430    /// use dioxus::prelude::*;
431    ///
432    /// pub struct InnerCustomState(usize);
433    ///
434    /// impl Drop for InnerCustomState {
435    ///     fn drop(&mut self){
436    ///         println!("Component has been dropped.");
437    ///     }
438    /// }
439    ///
440    /// #[derive(Clone, Copy)]
441    /// pub struct CustomState {
442    ///     inner: Signal<InnerCustomState>
443    /// }
444    ///
445    /// pub fn use_custom_state() -> CustomState {
446    ///     use_hook(|| CustomState {
447    ///         inner: Signal::new(InnerCustomState(0))
448    ///     })
449    /// }
450    /// ```
451    pub fn use_hook<State: Clone + 'static>(&self, initializer: impl FnOnce() -> State) -> State {
452        let cur_hook = self.hook_index.get();
453        let mut hooks = self.hooks.try_borrow_mut().expect("The hook list is already borrowed: This error is likely caused by trying to use a hook inside a hook which violates the rules of hooks.");
454
455        if cur_hook >= hooks.len() {
456            Runtime::with(|rt| {
457                rt.while_not_rendering(|| {
458                    hooks.push(Box::new(initializer()));
459                });
460            })
461            .unwrap()
462        }
463
464        self.use_hook_inner::<State>(hooks, cur_hook)
465    }
466
467    // The interior version that gets monoorphized by the `State` type but not the `initializer` type.
468    // This helps trim down binary sizes
469    fn use_hook_inner<State: Clone + 'static>(
470        &self,
471        hooks: std::cell::RefMut<Vec<Box<dyn std::any::Any>>>,
472        cur_hook: usize,
473    ) -> State {
474        hooks
475            .get(cur_hook)
476            .and_then(|inn| {
477                self.hook_index.set(cur_hook + 1);
478                let raw_ref: &dyn Any = inn.as_ref();
479                raw_ref.downcast_ref::<State>().cloned()
480            })
481            .expect(
482                r#"
483                Unable to retrieve the hook that was initialized at this index.
484                Consult the `rules of hooks` to understand how to use hooks properly.
485
486                You likely used the hook in a conditional. Hooks rely on consistent ordering between renders.
487                Functions prefixed with "use" should never be called conditionally.
488
489                Help: Run `dx check` to look for check for some common hook errors.
490                "#,
491            )
492    }
493
494    pub fn push_before_render(&self, f: impl FnMut() + 'static) {
495        self.before_render.borrow_mut().push(Box::new(f));
496    }
497
498    pub fn push_after_render(&self, f: impl FnMut() + 'static) {
499        self.after_render.borrow_mut().push(Box::new(f));
500    }
501
502    /// Get the current render since the inception of this component
503    ///
504    /// This can be used as a helpful diagnostic when debugging hooks/renders, etc
505    pub fn generation(&self) -> usize {
506        self.render_count.get()
507    }
508
509    /// Get the height of this scope
510    pub fn height(&self) -> u32 {
511        self.height
512    }
513}
514
515impl ScopeId {
516    /// Get the current scope id
517    pub fn current_scope_id(self) -> Result<ScopeId, RuntimeError> {
518        Runtime::with(|rt| rt.current_scope_id().ok())
519            .ok()
520            .flatten()
521            .ok_or(RuntimeError::new())
522    }
523
524    /// Consume context from the current scope
525    pub fn consume_context<T: 'static + Clone>(self) -> Option<T> {
526        Runtime::with_scope(self, |cx| cx.consume_context::<T>())
527            .ok()
528            .flatten()
529    }
530
531    /// Consume context from the current scope
532    pub fn consume_context_from_scope<T: 'static + Clone>(self, scope_id: ScopeId) -> Option<T> {
533        Runtime::with(|rt| {
534            rt.get_state(scope_id)
535                .and_then(|cx| cx.consume_context::<T>())
536        })
537        .ok()
538        .flatten()
539    }
540
541    /// Check if the current scope has a context
542    pub fn has_context<T: 'static + Clone>(self) -> Option<T> {
543        Runtime::with_scope(self, |cx| cx.has_context::<T>())
544            .ok()
545            .flatten()
546    }
547
548    /// Provide context to the current scope
549    pub fn provide_context<T: 'static + Clone>(self, value: T) -> T {
550        Runtime::with_scope(self, |cx| cx.provide_context(value)).unwrap()
551    }
552
553    /// Pushes the future onto the poll queue to be polled after the component renders.
554    pub fn push_future(self, fut: impl Future<Output = ()> + 'static) -> Option<Task> {
555        Runtime::with_scope(self, |cx| cx.spawn(fut)).ok()
556    }
557
558    /// Spawns the future but does not return the [`Task`]
559    pub fn spawn(self, fut: impl Future<Output = ()> + 'static) {
560        Runtime::with_scope(self, |cx| cx.spawn(fut)).unwrap();
561    }
562
563    /// Get the current render since the inception of this component
564    ///
565    /// This can be used as a helpful diagnostic when debugging hooks/renders, etc
566    pub fn generation(self) -> Option<usize> {
567        Runtime::with_scope(self, |cx| Some(cx.generation())).unwrap()
568    }
569
570    /// Get the parent of the current scope if it exists
571    pub fn parent_scope(self) -> Option<ScopeId> {
572        Runtime::with_scope(self, |cx| cx.parent_id())
573            .ok()
574            .flatten()
575    }
576
577    /// Check if the current scope is a descendant of the given scope
578    pub fn is_descendant_of(self, other: ScopeId) -> bool {
579        let mut current = self;
580        while let Some(parent) = current.parent_scope() {
581            if parent == other {
582                return true;
583            }
584            current = parent;
585        }
586        false
587    }
588
589    /// Mark the current scope as dirty, causing it to re-render
590    pub fn needs_update(self) {
591        Runtime::with_scope(self, |cx| cx.needs_update()).unwrap();
592    }
593
594    /// Create a subscription that schedules a future render for the reference component. Unlike [`Self::needs_update`], this function will work outside of the dioxus runtime.
595    ///
596    /// ## Notice: you should prefer using [`crate::schedule_update_any`]
597    pub fn schedule_update(&self) -> Arc<dyn Fn() + Send + Sync + 'static> {
598        Runtime::with_scope(*self, |cx| cx.schedule_update()).unwrap()
599    }
600
601    /// Get the height of the current scope
602    pub fn height(self) -> u32 {
603        Runtime::with_scope(self, |cx| cx.height()).unwrap()
604    }
605
606    /// Run a closure inside of scope's runtime
607    #[track_caller]
608    pub fn in_runtime<T>(self, f: impl FnOnce() -> T) -> T {
609        Runtime::current()
610            .unwrap_or_else(|e| panic!("{}", e))
611            .on_scope(self, f)
612    }
613
614    /// Throw a [`CapturedError`] into a scope. The error will bubble up to the nearest [`ErrorBoundary`](crate::ErrorBoundary) or the root of the app.
615    ///
616    /// # Examples
617    /// ```rust, no_run
618    /// # use dioxus::prelude::*;
619    /// fn Component() -> Element {
620    ///     let request = spawn(async move {
621    ///         match reqwest::get("https://api.example.com").await {
622    ///             Ok(_) => unimplemented!(),
623    ///             // You can explicitly throw an error into a scope with throw_error
624    ///             Err(err) => ScopeId::APP.throw_error(err)
625    ///         }
626    ///     });
627    ///
628    ///     unimplemented!()
629    /// }
630    /// ```
631    pub fn throw_error(self, error: impl Into<CapturedError> + 'static) {
632        throw_into(error, self)
633    }
634
635    /// Get the suspense context the current scope is in
636    pub fn suspense_context(&self) -> Option<SuspenseContext> {
637        Runtime::with_scope(*self, |cx| cx.suspense_boundary.suspense_context().cloned()).unwrap()
638    }
639}