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