global_context.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. use crate::prelude::SuspenseContext;
  2. use crate::runtime::RuntimeError;
  3. use crate::{innerlude::SuspendedFuture, runtime::Runtime, CapturedError, Element, ScopeId, Task};
  4. use std::future::Future;
  5. use std::sync::Arc;
  6. /// Get the current scope id
  7. pub fn current_scope_id() -> Result<ScopeId, RuntimeError> {
  8. Runtime::with(|rt| rt.current_scope_id().ok())
  9. .ok()
  10. .flatten()
  11. .ok_or(RuntimeError::new())
  12. }
  13. #[doc(hidden)]
  14. /// Check if the virtual dom is currently inside of the body of a component
  15. pub fn vdom_is_rendering() -> bool {
  16. Runtime::with(|rt| rt.rendering.get()).unwrap_or_default()
  17. }
  18. /// Throw a [`CapturedError`] into the current scope. The error will bubble up to the nearest [`crate::prelude::ErrorBoundary()`] or the root of the app.
  19. ///
  20. /// # Examples
  21. /// ```rust, no_run
  22. /// # use dioxus::prelude::*;
  23. /// fn Component() -> Element {
  24. /// let request = spawn(async move {
  25. /// match reqwest::get("https://api.example.com").await {
  26. /// Ok(_) => unimplemented!(),
  27. /// // You can explicitly throw an error into a scope with throw_error
  28. /// Err(err) => ScopeId::APP.throw_error(err)
  29. /// }
  30. /// });
  31. ///
  32. /// unimplemented!()
  33. /// }
  34. /// ```
  35. pub fn throw_error(error: impl Into<CapturedError> + 'static) {
  36. current_scope_id()
  37. .unwrap_or_else(|e| panic!("{}", e))
  38. .throw_error(error)
  39. }
  40. /// Get the suspense context the current scope is in
  41. pub fn suspense_context() -> Option<SuspenseContext> {
  42. current_scope_id()
  43. .unwrap_or_else(|e| panic!("{}", e))
  44. .suspense_context()
  45. }
  46. /// Consume context from the current scope
  47. pub fn try_consume_context<T: 'static + Clone>() -> Option<T> {
  48. Runtime::with_current_scope(|cx| cx.consume_context::<T>())
  49. .ok()
  50. .flatten()
  51. }
  52. /// Consume context from the current scope
  53. pub fn consume_context<T: 'static + Clone>() -> T {
  54. Runtime::with_current_scope(|cx| cx.consume_context::<T>())
  55. .ok()
  56. .flatten()
  57. .unwrap_or_else(|| panic!("Could not find context {}", std::any::type_name::<T>()))
  58. }
  59. /// Consume context from the current scope
  60. pub fn consume_context_from_scope<T: 'static + Clone>(scope_id: ScopeId) -> Option<T> {
  61. Runtime::with(|rt| {
  62. rt.get_state(scope_id)
  63. .and_then(|cx| cx.consume_context::<T>())
  64. })
  65. .ok()
  66. .flatten()
  67. }
  68. /// Check if the current scope has a context
  69. pub fn has_context<T: 'static + Clone>() -> Option<T> {
  70. Runtime::with_current_scope(|cx| cx.has_context::<T>())
  71. .ok()
  72. .flatten()
  73. }
  74. /// Provide context to the current scope
  75. pub fn provide_context<T: 'static + Clone>(value: T) -> T {
  76. Runtime::with_current_scope(|cx| cx.provide_context(value)).unwrap()
  77. }
  78. /// Provide a context to the root scope
  79. pub fn provide_root_context<T: 'static + Clone>(value: T) -> T {
  80. Runtime::with_current_scope(|cx| cx.provide_root_context(value)).unwrap()
  81. }
  82. /// Suspended the current component on a specific task and then return None
  83. pub fn suspend(task: Task) -> Element {
  84. Err(crate::innerlude::RenderError::Suspended(
  85. SuspendedFuture::new(task),
  86. ))
  87. }
  88. /// Start a new future on the same thread as the rest of the VirtualDom.
  89. ///
  90. /// **You should generally use `spawn` instead of this method unless you specifically need to run a task during suspense**
  91. ///
  92. /// This future will not contribute to suspense resolving but it will run during suspense.
  93. ///
  94. /// 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.
  95. ///
  96. /// ```rust, no_run
  97. /// # use dioxus::prelude::*;
  98. /// // ❌ Do not do requests in isomorphic tasks. It may resolve at a different time on the server and client, causing hydration issues.
  99. /// let mut state = use_signal(|| None);
  100. /// spawn_isomorphic(async move {
  101. /// state.set(Some(reqwest::get("https://api.example.com").await));
  102. /// });
  103. ///
  104. /// // ✅ You may wait for a signal to change and then log it
  105. /// let mut state = use_signal(|| 0);
  106. /// spawn_isomorphic(async move {
  107. /// loop {
  108. /// tokio::time::sleep(std::time::Duration::from_secs(1)).await;
  109. /// println!("State is {state}");
  110. /// }
  111. /// });
  112. /// ```
  113. ///
  114. #[doc = include_str!("../docs/common_spawn_errors.md")]
  115. pub fn spawn_isomorphic(fut: impl Future<Output = ()> + 'static) -> Task {
  116. Runtime::with_current_scope(|cx| cx.spawn_isomorphic(fut)).unwrap()
  117. }
  118. /// Spawns the future and returns the [`Task`]. This task will automatically be canceled when the component is dropped.
  119. ///
  120. /// # Example
  121. /// ```rust
  122. /// use dioxus::prelude::*;
  123. ///
  124. /// fn App() -> Element {
  125. /// rsx! {
  126. /// button {
  127. /// onclick: move |_| {
  128. /// spawn(async move {
  129. /// tokio::time::sleep(std::time::Duration::from_secs(1)).await;
  130. /// println!("Hello World");
  131. /// });
  132. /// },
  133. /// "Print hello in one second"
  134. /// }
  135. /// }
  136. /// }
  137. /// ```
  138. ///
  139. #[doc = include_str!("../docs/common_spawn_errors.md")]
  140. pub fn spawn(fut: impl Future<Output = ()> + 'static) -> Task {
  141. Runtime::with_current_scope(|cx| cx.spawn(fut)).unwrap()
  142. }
  143. /// Queue an effect to run after the next render. You generally shouldn't need to interact with this function directly. [use_effect](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_effect.html) will call this function for you.
  144. pub fn queue_effect(f: impl FnOnce() + 'static) {
  145. Runtime::with_current_scope(|cx| cx.queue_effect(f)).unwrap()
  146. }
  147. /// Spawn a future that Dioxus won't clean up when this component is unmounted
  148. ///
  149. /// This is good for tasks that need to be run after the component has been dropped.
  150. ///
  151. /// **This will run the task in the root scope. Any calls to global methods inside the future (including `context`) will be run in the root scope.**
  152. ///
  153. /// # Example
  154. ///
  155. /// ```rust
  156. /// use dioxus::prelude::*;
  157. ///
  158. /// // The parent component can create and destroy children dynamically
  159. /// fn App() -> Element {
  160. /// let mut count = use_signal(|| 0);
  161. ///
  162. /// rsx! {
  163. /// button {
  164. /// onclick: move |_| count += 1,
  165. /// "Increment"
  166. /// }
  167. /// button {
  168. /// onclick: move |_| count -= 1,
  169. /// "Decrement"
  170. /// }
  171. ///
  172. /// for id in 0..10 {
  173. /// Child { id }
  174. /// }
  175. /// }
  176. /// }
  177. ///
  178. /// #[component]
  179. /// fn Child(id: i32) -> Element {
  180. /// rsx! {
  181. /// button {
  182. /// onclick: move |_| {
  183. /// // This will spawn a task in the root scope that will run forever
  184. /// // It will keep running even if you drop the child component by decreasing the count
  185. /// spawn_forever(async move {
  186. /// loop {
  187. /// tokio::time::sleep(std::time::Duration::from_secs(1)).await;
  188. /// println!("Running task spawned in child component {id}");
  189. /// }
  190. /// });
  191. /// },
  192. /// "Spawn background task"
  193. /// }
  194. /// }
  195. /// }
  196. /// ```
  197. ///
  198. #[doc = include_str!("../docs/common_spawn_errors.md")]
  199. pub fn spawn_forever(fut: impl Future<Output = ()> + 'static) -> Option<Task> {
  200. Runtime::with_scope(ScopeId::ROOT, |cx| cx.spawn(fut)).ok()
  201. }
  202. /// Informs the scheduler that this task is no longer needed and should be removed.
  203. ///
  204. /// This drops the task immediately.
  205. pub fn remove_future(id: Task) {
  206. Runtime::with(|rt| rt.remove_task(id)).expect("Runtime to exist");
  207. }
  208. /// Store a value between renders. The foundational hook for all other hooks.
  209. ///
  210. /// Accepts an `initializer` closure, which is run on the first use of the hook (typically the initial render).
  211. /// `use_hook` will return a clone of the value on every render.
  212. ///
  213. /// 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),
  214. /// as these only drop their inner value once all references have been dropped, which only happens when the component is dropped.
  215. ///
  216. /// <div class="warning">
  217. ///
  218. /// `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.
  219. ///
  220. /// ❌ Don't use `use_hook` with `Rc<RefCell<T>>` for state. It will not update the UI and other hooks when the state changes.
  221. /// ```rust
  222. /// use dioxus::prelude::*;
  223. /// use std::rc::Rc;
  224. /// use std::cell::RefCell;
  225. ///
  226. /// pub fn Comp() -> Element {
  227. /// let count = use_hook(|| Rc::new(RefCell::new(0)));
  228. ///
  229. /// rsx! {
  230. /// button {
  231. /// onclick: move |_| *count.borrow_mut() += 1,
  232. /// "{count.borrow()}"
  233. /// }
  234. /// }
  235. /// }
  236. /// ```
  237. ///
  238. /// ✅ Use `use_signal` instead.
  239. /// ```rust
  240. /// use dioxus::prelude::*;
  241. ///
  242. /// pub fn Comp() -> Element {
  243. /// let mut count = use_signal(|| 0);
  244. ///
  245. /// rsx! {
  246. /// button {
  247. /// onclick: move |_| count += 1,
  248. /// "{count}"
  249. /// }
  250. /// }
  251. /// }
  252. /// ```
  253. ///
  254. /// </div>
  255. ///
  256. /// # Example
  257. ///
  258. /// ```rust, no_run
  259. /// use dioxus::prelude::*;
  260. ///
  261. /// // prints a greeting on the initial render
  262. /// pub fn use_hello_world() {
  263. /// use_hook(|| println!("Hello, world!"));
  264. /// }
  265. /// ```
  266. ///
  267. /// # Custom Hook Example
  268. ///
  269. /// ```rust, no_run
  270. /// use dioxus::prelude::*;
  271. ///
  272. /// pub struct InnerCustomState(usize);
  273. ///
  274. /// impl Drop for InnerCustomState {
  275. /// fn drop(&mut self){
  276. /// println!("Component has been dropped.");
  277. /// }
  278. /// }
  279. ///
  280. /// #[derive(Clone, Copy)]
  281. /// pub struct CustomState {
  282. /// inner: Signal<InnerCustomState>
  283. /// }
  284. ///
  285. /// pub fn use_custom_state() -> CustomState {
  286. /// use_hook(|| CustomState {
  287. /// inner: Signal::new(InnerCustomState(0))
  288. /// })
  289. /// }
  290. /// ```
  291. #[track_caller]
  292. pub fn use_hook<State: Clone + 'static>(initializer: impl FnOnce() -> State) -> State {
  293. Runtime::with_current_scope(|cx| cx.use_hook(initializer)).unwrap()
  294. }
  295. /// Get the current render since the inception of this component
  296. ///
  297. /// This can be used as a helpful diagnostic when debugging hooks/renders, etc
  298. pub fn generation() -> usize {
  299. Runtime::with_current_scope(|cx| cx.generation()).unwrap()
  300. }
  301. /// Get the parent of the current scope if it exists
  302. pub fn parent_scope() -> Option<ScopeId> {
  303. Runtime::with_current_scope(|cx| cx.parent_id())
  304. .ok()
  305. .flatten()
  306. }
  307. /// Mark the current scope as dirty, causing it to re-render
  308. pub fn needs_update() {
  309. let _ = Runtime::with_current_scope(|cx| cx.needs_update());
  310. }
  311. /// Mark the current scope as dirty, causing it to re-render
  312. pub fn needs_update_any(id: ScopeId) {
  313. let _ = Runtime::with_current_scope(|cx| cx.needs_update_any(id));
  314. }
  315. /// Schedule an update for the current component
  316. ///
  317. /// Note: Unlike [`needs_update`], the function returned by this method will work outside of the dioxus runtime.
  318. ///
  319. /// You should prefer [`schedule_update_any`] if you need to update multiple components.
  320. #[track_caller]
  321. pub fn schedule_update() -> Arc<dyn Fn() + Send + Sync> {
  322. Runtime::with_current_scope(|cx| cx.schedule_update()).unwrap_or_else(|e| panic!("{}", e))
  323. }
  324. /// Schedule an update for any component given its [`ScopeId`].
  325. ///
  326. /// A component's [`ScopeId`] can be obtained from the [`current_scope_id`] method.
  327. ///
  328. /// Note: Unlike [`needs_update`], the function returned by this method will work outside of the dioxus runtime.
  329. #[track_caller]
  330. pub fn schedule_update_any() -> Arc<dyn Fn(ScopeId) + Send + Sync> {
  331. Runtime::with_current_scope(|cx| cx.schedule_update_any()).unwrap_or_else(|e| panic!("{}", e))
  332. }
  333. /// Creates a callback that will be run before the component is removed.
  334. /// This can be used to clean up side effects from the component
  335. /// (created with [`use_effect`](dioxus::prelude::use_effect)).
  336. ///
  337. /// Note:
  338. /// Effects do not run on the server, but use_drop **DOES**. It runs any time the component is dropped including during SSR rendering on the server. If your clean up logic targets web, the logic has to be gated by a feature, see the below example for details.
  339. ///
  340. /// Example:
  341. /// ```rust
  342. /// use dioxus::prelude::*;
  343. ///
  344. /// fn app() -> Element {
  345. /// let mut state = use_signal(|| true);
  346. /// rsx! {
  347. /// for _ in 0..100 {
  348. /// h1 {
  349. /// "spacer"
  350. /// }
  351. /// }
  352. /// if state() {
  353. /// child_component {}
  354. /// }
  355. /// button {
  356. /// onclick: move |_| {
  357. /// state.toggle()
  358. /// },
  359. /// "Unmount element"
  360. /// }
  361. /// }
  362. /// }
  363. ///
  364. /// fn child_component() -> Element {
  365. /// let mut original_scroll_position = use_signal(|| 0.0);
  366. ///
  367. /// use_effect(move || {
  368. /// let window = web_sys::window().unwrap();
  369. /// let document = window.document().unwrap();
  370. /// let element = document.get_element_by_id("my_element").unwrap();
  371. /// element.scroll_into_view();
  372. /// original_scroll_position.set(window.scroll_y().unwrap());
  373. /// });
  374. ///
  375. /// use_drop(move || {
  376. /// // This only make sense to web and hence the `web!` macro
  377. /// web! {
  378. /// /// restore scroll to the top of the page
  379. /// let window = web_sys::window().unwrap();
  380. /// window.scroll_with_x_and_y(original_scroll_position(), 0.0);
  381. /// }
  382. /// });
  383. ///
  384. /// rsx! {
  385. /// div {
  386. /// id: "my_element",
  387. /// "hello"
  388. /// }
  389. /// }
  390. /// }
  391. /// ```
  392. #[doc(alias = "use_on_unmount")]
  393. pub fn use_drop<D: FnOnce() + 'static>(destroy: D) {
  394. struct LifeCycle<D: FnOnce()> {
  395. /// Wrap the closure in an option so that we can take it out on drop.
  396. ondestroy: Option<D>,
  397. }
  398. /// On drop, we want to run the closure.
  399. impl<D: FnOnce()> Drop for LifeCycle<D> {
  400. fn drop(&mut self) {
  401. if let Some(f) = self.ondestroy.take() {
  402. f();
  403. }
  404. }
  405. }
  406. // We need to impl clone for the lifecycle, but we don't want the drop handler for the closure to be called twice.
  407. impl<D: FnOnce()> Clone for LifeCycle<D> {
  408. fn clone(&self) -> Self {
  409. Self { ondestroy: None }
  410. }
  411. }
  412. use_hook(|| LifeCycle {
  413. ondestroy: Some(destroy),
  414. });
  415. }
  416. /// A hook that allows you to insert a "before render" function.
  417. ///
  418. /// This function will always be called before dioxus tries to render your component. This should be used for safely handling
  419. /// early returns
  420. pub fn use_before_render(f: impl FnMut() + 'static) {
  421. use_hook(|| before_render(f));
  422. }
  423. /// Push this function to be run after the next render
  424. ///
  425. /// This function will always be called before dioxus tries to render your component. This should be used for safely handling
  426. /// early returns
  427. pub fn use_after_render(f: impl FnMut() + 'static) {
  428. use_hook(|| after_render(f));
  429. }
  430. /// Push a function to be run before the next render
  431. /// This is a hook and will always run, so you can't unschedule it
  432. /// Will run for every progression of suspense, though this might change in the future
  433. pub fn before_render(f: impl FnMut() + 'static) {
  434. let _ = Runtime::with_current_scope(|cx| cx.push_before_render(f));
  435. }
  436. /// Push a function to be run after the render is complete, even if it didn't complete successfully
  437. pub fn after_render(f: impl FnMut() + 'static) {
  438. let _ = Runtime::with_current_scope(|cx| cx.push_after_render(f));
  439. }
  440. /// Use a hook with a cleanup function
  441. pub fn use_hook_with_cleanup<T: Clone + 'static>(
  442. hook: impl FnOnce() -> T,
  443. cleanup: impl FnOnce(T) + 'static,
  444. ) -> T {
  445. let value = use_hook(hook);
  446. let _value = value.clone();
  447. use_drop(move || cleanup(_value));
  448. value
  449. }
  450. /// Force every component to be dirty and require a re-render. Used by hot-reloading.
  451. ///
  452. /// This might need to change to a different flag in the event hooks order changes within components.
  453. /// What we really need is a way to mark components as needing a complete rebuild if they were hit by changes.
  454. pub fn force_all_dirty() {
  455. Runtime::with(|rt| {
  456. rt.scope_states.borrow_mut().iter().for_each(|state| {
  457. if let Some(scope) = state.as_ref() {
  458. scope.needs_update();
  459. }
  460. });
  461. })
  462. .expect("Runtime to exist");
  463. }