scope_context.rs 20 KB

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