scope_context.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. use crate::{innerlude::SchedulerMsg, Element, Runtime, ScopeId, Task};
  2. use rustc_hash::FxHashSet;
  3. use std::{
  4. any::Any,
  5. cell::{Cell, RefCell},
  6. future::Future,
  7. sync::Arc,
  8. };
  9. /// A component's state separate from its props.
  10. ///
  11. /// This struct exists to provide a common interface for all scopes without relying on generics.
  12. pub(crate) struct Scope {
  13. pub(crate) name: &'static str,
  14. pub(crate) id: ScopeId,
  15. pub(crate) parent_id: Option<ScopeId>,
  16. pub(crate) height: u32,
  17. pub(crate) render_count: Cell<usize>,
  18. pub(crate) suspended: Cell<bool>,
  19. // 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.
  20. pub(crate) hooks: RefCell<Vec<Box<dyn Any>>>,
  21. pub(crate) hook_index: Cell<usize>,
  22. pub(crate) shared_contexts: RefCell<Vec<Box<dyn Any>>>,
  23. pub(crate) spawned_tasks: RefCell<FxHashSet<Task>>,
  24. pub(crate) before_render: RefCell<Vec<Box<dyn FnMut()>>>,
  25. pub(crate) after_render: RefCell<Vec<Box<dyn FnMut()>>>,
  26. }
  27. impl Scope {
  28. pub(crate) fn new(
  29. name: &'static str,
  30. id: ScopeId,
  31. parent_id: Option<ScopeId>,
  32. height: u32,
  33. ) -> Self {
  34. Self {
  35. name,
  36. id,
  37. parent_id,
  38. height,
  39. render_count: Cell::new(0),
  40. suspended: Cell::new(false),
  41. shared_contexts: RefCell::new(vec![]),
  42. spawned_tasks: RefCell::new(FxHashSet::default()),
  43. hooks: RefCell::new(vec![]),
  44. hook_index: Cell::new(0),
  45. before_render: RefCell::new(vec![]),
  46. after_render: RefCell::new(vec![]),
  47. }
  48. }
  49. pub fn parent_id(&self) -> Option<ScopeId> {
  50. self.parent_id
  51. }
  52. fn sender(&self) -> futures_channel::mpsc::UnboundedSender<SchedulerMsg> {
  53. Runtime::with(|rt| rt.sender.clone()).unwrap()
  54. }
  55. /// Mark this scope as dirty, and schedule a render for it.
  56. pub fn needs_update(&self) {
  57. self.needs_update_any(self.id)
  58. }
  59. /// Mark this scope as dirty, and schedule a render for it.
  60. pub fn needs_update_any(&self, id: ScopeId) {
  61. self.sender()
  62. .unbounded_send(SchedulerMsg::Immediate(id))
  63. .expect("Scheduler to exist if scope exists");
  64. }
  65. /// Create a subscription that schedules a future render for the reference component
  66. ///
  67. /// ## Notice: you should prefer using [`Self::schedule_update_any`] and [`Self::scope_id`]
  68. pub fn schedule_update(&self) -> Arc<dyn Fn() + Send + Sync + 'static> {
  69. let (chan, id) = (self.sender(), self.id);
  70. Arc::new(move || drop(chan.unbounded_send(SchedulerMsg::Immediate(id))))
  71. }
  72. /// Schedule an update for any component given its [`ScopeId`].
  73. ///
  74. /// A component's [`ScopeId`] can be obtained from `use_hook` or the [`current_scope_id`] method.
  75. ///
  76. /// This method should be used when you want to schedule an update for a component
  77. pub fn schedule_update_any(&self) -> Arc<dyn Fn(ScopeId) + Send + Sync> {
  78. let chan = self.sender();
  79. Arc::new(move |id| {
  80. chan.unbounded_send(SchedulerMsg::Immediate(id)).unwrap();
  81. })
  82. }
  83. /// Return any context of type T if it exists on this scope
  84. pub fn has_context<T: 'static + Clone>(&self) -> Option<T> {
  85. self.shared_contexts
  86. .borrow()
  87. .iter()
  88. .find_map(|any| any.downcast_ref::<T>())
  89. .cloned()
  90. }
  91. /// Try to retrieve a shared state with type `T` from any parent scope.
  92. ///
  93. /// Clones the state if it exists.
  94. pub fn consume_context<T: 'static + Clone>(&self) -> Option<T> {
  95. tracing::trace!(
  96. "looking for context {} ({:?}) in {}",
  97. std::any::type_name::<T>(),
  98. std::any::TypeId::of::<T>(),
  99. self.name
  100. );
  101. if let Some(this_ctx) = self.has_context() {
  102. return Some(this_ctx);
  103. }
  104. let mut search_parent = self.parent_id;
  105. let cur_runtime = Runtime::with(|runtime| {
  106. while let Some(parent_id) = search_parent {
  107. let parent = runtime.get_state(parent_id).unwrap();
  108. tracing::trace!(
  109. "looking for context {} ({:?}) in {}",
  110. std::any::type_name::<T>(),
  111. std::any::TypeId::of::<T>(),
  112. parent.name
  113. );
  114. if let Some(shared) = parent.shared_contexts.borrow().iter().find_map(|any| {
  115. tracing::trace!("found context {:?}", (**any).type_id());
  116. any.downcast_ref::<T>()
  117. }) {
  118. return Some(shared.clone());
  119. }
  120. search_parent = parent.parent_id;
  121. }
  122. None
  123. });
  124. match cur_runtime.flatten() {
  125. Some(ctx) => Some(ctx),
  126. None => {
  127. tracing::trace!(
  128. "context {} ({:?}) not found",
  129. std::any::type_name::<T>(),
  130. std::any::TypeId::of::<T>()
  131. );
  132. None
  133. }
  134. }
  135. }
  136. /// Inject a Box<dyn Any> into the context of this scope
  137. pub(crate) fn provide_any_context(&self, mut value: Box<dyn Any>) {
  138. let mut contexts = self.shared_contexts.borrow_mut();
  139. // If the context exists, swap it out for the new value
  140. for ctx in contexts.iter_mut() {
  141. // Swap the ptr directly
  142. if ctx.as_ref().type_id() == value.as_ref().type_id() {
  143. std::mem::swap(ctx, &mut value);
  144. return;
  145. }
  146. }
  147. // Else, just push it
  148. contexts.push(value);
  149. }
  150. /// Expose state to children further down the [`crate::VirtualDom`] Tree. Requires `Clone` on the context to allow getting values down the tree.
  151. ///
  152. /// This is a "fundamental" operation and should only be called during initialization of a hook.
  153. ///
  154. /// For a hook that provides the same functionality, use `use_provide_context` and `use_context` instead.
  155. ///
  156. /// # Example
  157. ///
  158. /// ```rust, ignore
  159. /// struct SharedState(&'static str);
  160. ///
  161. /// static app: Component = |cx| {
  162. /// cx.use_hook(|| cx.provide_context(SharedState("world")));
  163. /// rsx!(Child {})
  164. /// }
  165. ///
  166. /// static Child: Component = |cx| {
  167. /// let state = cx.consume_state::<SharedState>();
  168. /// rsx!(div { "hello {state.0}" })
  169. /// }
  170. /// ```
  171. pub fn provide_context<T: 'static + Clone>(&self, value: T) -> T {
  172. tracing::trace!(
  173. "providing context {} ({:?}) in {}",
  174. std::any::type_name::<T>(),
  175. std::any::TypeId::of::<T>(),
  176. self.name
  177. );
  178. let mut contexts = self.shared_contexts.borrow_mut();
  179. // If the context exists, swap it out for the new value
  180. for ctx in contexts.iter_mut() {
  181. // Swap the ptr directly
  182. if let Some(ctx) = ctx.downcast_mut::<T>() {
  183. std::mem::swap(ctx, &mut value.clone());
  184. return value;
  185. }
  186. }
  187. // Else, just push it
  188. contexts.push(Box::new(value.clone()));
  189. value
  190. }
  191. /// Provide a context to the root and then consume it
  192. ///
  193. /// This is intended for "global" state management solutions that would rather be implicit for the entire app.
  194. /// Things like signal runtimes and routers are examples of "singletons" that would benefit from lazy initialization.
  195. ///
  196. /// Note that you should be checking if the context existed before trying to provide a new one. Providing a context
  197. /// when a context already exists will swap the context out for the new one, which may not be what you want.
  198. pub fn provide_root_context<T: 'static + Clone>(&self, context: T) -> T {
  199. Runtime::with(|runtime| {
  200. runtime
  201. .get_state(ScopeId::ROOT)
  202. .unwrap()
  203. .provide_context(context)
  204. })
  205. .expect("Runtime to exist")
  206. }
  207. /// Spawns the future but does not return the [`TaskId`]
  208. pub fn spawn(&self, fut: impl Future<Output = ()> + 'static) -> Task {
  209. let id = Runtime::with(|rt| rt.spawn(self.id, fut)).expect("Runtime to exist");
  210. self.spawned_tasks.borrow_mut().insert(id);
  211. id
  212. }
  213. /// Spawn a future that Dioxus won't clean up when this component is unmounted
  214. ///
  215. /// This is good for tasks that need to be run after the component has been dropped.
  216. pub fn spawn_forever(&self, fut: impl Future<Output = ()> + 'static) -> Task {
  217. // The root scope will never be unmounted so we can just add the task at the top of the app
  218. Runtime::with(|rt| rt.spawn(self.id, fut)).expect("Runtime to exist")
  219. }
  220. /// Mark this component as suspended and then return None
  221. pub fn suspend(&self) -> Option<Element> {
  222. self.suspended.set(true);
  223. None
  224. }
  225. /// Store a value between renders. The foundational hook for all other hooks.
  226. ///
  227. /// Accepts an `initializer` closure, which is run on the first use of the hook (typically the initial render). The return value of this closure is stored for the lifetime of the component, and a mutable reference to it is provided on every render as the return value of `use_hook`.
  228. ///
  229. /// When the component is unmounted (removed from the UI), the value is dropped. This means you can return a custom type and provide cleanup code by implementing the [`Drop`] trait
  230. ///
  231. /// # Example
  232. ///
  233. /// ```
  234. /// # use dioxus::prelude::*;
  235. /// // prints a greeting on the initial render
  236. /// pub fn use_hello_world() {
  237. /// use_hook(|| println!("Hello, world!"));
  238. /// }
  239. /// ```
  240. pub fn use_hook<State: Clone + 'static>(&self, initializer: impl FnOnce() -> State) -> State {
  241. let cur_hook = self.hook_index.get();
  242. 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.");
  243. if cur_hook >= hooks.len() {
  244. hooks.push(Box::new(initializer()));
  245. }
  246. hooks
  247. .get(cur_hook)
  248. .and_then(|inn| {
  249. self.hook_index.set(cur_hook + 1);
  250. let raw_ref: &dyn Any = inn.as_ref();
  251. raw_ref.downcast_ref::<State>().cloned()
  252. })
  253. .expect(
  254. r#"
  255. Unable to retrieve the hook that was initialized at this index.
  256. Consult the `rules of hooks` to understand how to use hooks properly.
  257. You likely used the hook in a conditional. Hooks rely on consistent ordering between renders.
  258. Functions prefixed with "use" should never be called conditionally.
  259. "#,
  260. )
  261. }
  262. pub fn push_before_render(&self, f: impl FnMut() + 'static) {
  263. self.before_render.borrow_mut().push(Box::new(f));
  264. }
  265. pub fn push_after_render(&self, f: impl FnMut() + 'static) {
  266. self.after_render.borrow_mut().push(Box::new(f));
  267. }
  268. /// Get the current render since the inception of this component
  269. ///
  270. /// This can be used as a helpful diagnostic when debugging hooks/renders, etc
  271. pub fn generation(&self) -> usize {
  272. self.render_count.get()
  273. }
  274. /// Get the height of this scope
  275. pub fn height(&self) -> u32 {
  276. self.height
  277. }
  278. }
  279. impl ScopeId {
  280. /// Get the current scope id
  281. pub fn current_scope_id(self) -> Option<ScopeId> {
  282. Runtime::with(|rt| rt.current_scope_id()).flatten()
  283. }
  284. /// Consume context from the current scope
  285. pub fn consume_context<T: 'static + Clone>(self) -> Option<T> {
  286. Runtime::with_scope(self, |cx| cx.consume_context::<T>()).flatten()
  287. }
  288. /// Consume context from the current scope
  289. pub fn consume_context_from_scope<T: 'static + Clone>(self, scope_id: ScopeId) -> Option<T> {
  290. Runtime::with(|rt| {
  291. rt.get_state(scope_id)
  292. .and_then(|cx| cx.consume_context::<T>())
  293. })
  294. .flatten()
  295. }
  296. /// Check if the current scope has a context
  297. pub fn has_context<T: 'static + Clone>(self) -> Option<T> {
  298. Runtime::with_scope(self, |cx| cx.has_context::<T>()).flatten()
  299. }
  300. /// Provide context to the current scope
  301. pub fn provide_context<T: 'static + Clone>(self, value: T) -> T {
  302. Runtime::with_scope(self, |cx| cx.provide_context(value))
  303. .expect("to be in a dioxus runtime")
  304. }
  305. /// Suspends the current component
  306. pub fn suspend(self) -> Option<Element> {
  307. Runtime::with_scope(self, |cx| {
  308. cx.suspend();
  309. });
  310. None
  311. }
  312. /// Pushes the future onto the poll queue to be polled after the component renders.
  313. pub fn push_future(self, fut: impl Future<Output = ()> + 'static) -> Option<Task> {
  314. Runtime::with_scope(self, |cx| cx.spawn(fut))
  315. }
  316. /// Spawns the future but does not return the [`TaskId`]
  317. pub fn spawn(self, fut: impl Future<Output = ()> + 'static) {
  318. Runtime::with_scope(self, |cx| cx.spawn(fut));
  319. }
  320. /// Get the current render since the inception of this component
  321. ///
  322. /// This can be used as a helpful diagnostic when debugging hooks/renders, etc
  323. pub fn generation(self) -> Option<usize> {
  324. Runtime::with_scope(self, |cx| Some(cx.generation())).expect("to be in a dioxus runtime")
  325. }
  326. /// Get the parent of the current scope if it exists
  327. pub fn parent_scope(self) -> Option<ScopeId> {
  328. Runtime::with_scope(self, |cx| cx.parent_id()).flatten()
  329. }
  330. /// Mark the current scope as dirty, causing it to re-render
  331. pub fn needs_update(self) {
  332. Runtime::with_scope(self, |cx| cx.needs_update());
  333. }
  334. /// 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.
  335. ///
  336. /// ## Notice: you should prefer using [`dioxus_core::schedule_update_any`] and [`Self::scope_id`]
  337. pub fn schedule_update(&self) -> Arc<dyn Fn() + Send + Sync + 'static> {
  338. Runtime::with_scope(*self, |cx| cx.schedule_update()).expect("to be in a dioxus runtime")
  339. }
  340. /// Get the height of the current scope
  341. pub fn height(self) -> u32 {
  342. Runtime::with_scope(self, |cx| cx.height()).expect("to be in a dioxus runtime")
  343. }
  344. /// Run a closure inside of scope's runtime
  345. pub fn in_runtime<T>(self, f: impl FnOnce() -> T) -> T {
  346. Runtime::current()
  347. .expect("to be in a dioxus runtime")
  348. .on_scope(self, f)
  349. }
  350. }