lib.rs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. //! Dioxus WebSys
  2. //!
  3. //! ## Overview
  4. //! ------------
  5. //! This crate implements a renderer of the Dioxus Virtual DOM for the web browser using WebSys. This web render for
  6. //! Dioxus is one of the more advanced renderers, supporting:
  7. //! - idle work
  8. //! - animations
  9. //! - jank-free rendering
  10. //! - noderefs
  11. //! - controlled components
  12. //! - re-hydration
  13. //! - and more.
  14. //!
  15. //! The actual implementation is farily thin, with the heavy lifting happening inside the Dioxus Core crate.
  16. //!
  17. //! To purview the examples, check of the root Dioxus crate - the examples in this crate are mostly meant to provide
  18. //! validation of websys-specific features and not the general use of Dioxus.
  19. // ## RequestAnimationFrame and RequestIdleCallback
  20. // ------------------------------------------------
  21. // React implements "jank free rendering" by deliberately not blocking the browser's main thread. For large diffs, long
  22. // running work, and integration with things like React-Three-Fiber, it's extremeley important to avoid blocking the
  23. // main thread.
  24. //
  25. // React solves this problem by breaking up the rendering process into a "diff" phase and a "render" phase. In Dioxus,
  26. // the diff phase is non-blocking, using "yield_now" to allow the browser to process other events. When the diff phase
  27. // is finally complete, the VirtualDOM will return a set of "Mutations" for this crate to apply.
  28. //
  29. // Here, we schedule the "diff" phase during the browser's idle period, achieved by calling RequestIdleCallback and then
  30. // setting a timeout from the that completes when the idleperiod is over. Then, we call requestAnimationFrame
  31. //
  32. // From Google's guide on rAF and rIC:
  33. // -----------------------------------
  34. //
  35. // If the callback is fired at the end of the frame, it will be scheduled to go after the current frame has been committed,
  36. // which means that style changes will have been applied, and, importantly, layout calculated. If we make DOM changes inside
  37. // of the idle callback, those layout calculations will be invalidated. If there are any kind of layout reads in the next
  38. // frame, e.g. getBoundingClientRect, clientWidth, etc, the browser will have to perform a Forced Synchronous Layout,
  39. // which is a potential performance bottleneck.
  40. //
  41. // Another reason not trigger DOM changes in the idle callback is that the time impact of changing the DOM is unpredictable,
  42. // and as such we could easily go past the deadline the browser provided.
  43. //
  44. // The best practice is to only make DOM changes inside of a requestAnimationFrame callback, since it is scheduled by the
  45. // browser with that type of work in mind. That means that our code will need to use a document fragment, which can then
  46. // be appended in the next requestAnimationFrame callback. If you are using a VDOM library, you would use requestIdleCallback
  47. // to make changes, but you would apply the DOM patches in the next requestAnimationFrame callback, not the idle callback.
  48. //
  49. // Essentially:
  50. // ------------
  51. // - Do the VDOM work during the idlecallback
  52. // - Do DOM work in the next requestAnimationFrame callback
  53. use std::rc::Rc;
  54. pub use crate::cfg::WebConfig;
  55. use dioxus::SchedulerMsg;
  56. use dioxus::VirtualDom;
  57. pub use dioxus_core as dioxus;
  58. use dioxus_core::prelude::Component;
  59. use futures_util::FutureExt;
  60. pub(crate) mod bindings;
  61. mod cache;
  62. mod cfg;
  63. mod dom;
  64. mod rehydrate;
  65. mod ric_raf;
  66. /// Launch the VirtualDOM given a root component and a configuration.
  67. ///
  68. /// This function expects the root component to not have root props. To launch the root component with root props, use
  69. /// `launch_with_props` instead.
  70. ///
  71. /// This method will block the thread with `spawn_local` from wasm_bindgen_futures.
  72. ///
  73. /// If you need to run the VirtualDOM in its own thread, use `run_with_props` instead and await the future.
  74. ///
  75. /// # Example
  76. ///
  77. /// ```rust, ignore
  78. /// fn main() {
  79. /// dioxus_web::launch(App);
  80. /// }
  81. ///
  82. /// static App: Component = |cx| {
  83. /// rsx!(cx, div {"hello world"})
  84. /// }
  85. /// ```
  86. pub fn launch(root_component: Component) {
  87. launch_with_props(root_component, (), |c| c);
  88. }
  89. /// Launch your app and run the event loop, with configuration.
  90. ///
  91. /// This function will start your web app on the main web thread.
  92. ///
  93. /// You can configure the WebView window with a configuration closure
  94. ///
  95. /// ```rust
  96. /// use dioxus::prelude::*;
  97. ///
  98. /// fn main() {
  99. /// dioxus_web::launch_with_props(App, |config| config.pre_render(true));
  100. /// }
  101. ///
  102. /// fn app(cx: Scope) -> Element {
  103. /// cx.render(rsx!{
  104. /// h1 {"hello world!"}
  105. /// })
  106. /// }
  107. /// ```
  108. pub fn launch_cfg(root: Component, config_builder: impl FnOnce(&mut WebConfig) -> &mut WebConfig) {
  109. launch_with_props(root, (), config_builder)
  110. }
  111. /// Launches the VirtualDOM from the specified component function and props.
  112. ///
  113. /// This method will block the thread with `spawn_local`
  114. ///
  115. /// # Example
  116. ///
  117. /// ```rust, ignore
  118. /// fn main() {
  119. /// dioxus_web::launch_with_props(
  120. /// App,
  121. /// RootProps { name: String::from("joe") },
  122. /// |config| config
  123. /// );
  124. /// }
  125. ///
  126. /// #[derive(ParitalEq, Props)]
  127. /// struct RootProps {
  128. /// name: String
  129. /// }
  130. ///
  131. /// static App: Component<RootProps> = |cx| {
  132. /// rsx!(cx, div {"hello {cx.props.name}"})
  133. /// }
  134. /// ```
  135. pub fn launch_with_props<T>(
  136. root_component: Component<T>,
  137. root_properties: T,
  138. configuration_builder: impl FnOnce(&mut WebConfig) -> &mut WebConfig,
  139. ) where
  140. T: Send + 'static,
  141. {
  142. if cfg!(feature = "panic_hook") {
  143. console_error_panic_hook::set_once();
  144. }
  145. let mut config = WebConfig::default();
  146. configuration_builder(&mut config);
  147. wasm_bindgen_futures::spawn_local(run_with_props(root_component, root_properties, config));
  148. }
  149. /// Runs the app as a future that can be scheduled around the main thread.
  150. ///
  151. /// Polls futures internal to the VirtualDOM, hence the async nature of this function.
  152. ///
  153. /// # Example
  154. ///
  155. /// ```ignore
  156. /// fn main() {
  157. /// let app_fut = dioxus_web::run_with_props(App, RootProps { name: String::from("joe") });
  158. /// wasm_bindgen_futures::spawn_local(app_fut);
  159. /// }
  160. /// ```
  161. pub async fn run_with_props<T: 'static + Send>(root: Component<T>, root_props: T, cfg: WebConfig) {
  162. let mut dom = VirtualDom::new_with_props(root, root_props);
  163. for s in crate::cache::BUILTIN_INTERNED_STRINGS {
  164. wasm_bindgen::intern(s);
  165. }
  166. for s in &cfg.cached_strings {
  167. wasm_bindgen::intern(s);
  168. }
  169. let tasks = dom.get_scheduler_channel();
  170. let sender_callback: Rc<dyn Fn(SchedulerMsg)> =
  171. Rc::new(move |event| tasks.unbounded_send(event).unwrap());
  172. let should_hydrate = cfg.hydrate;
  173. let mut websys_dom = dom::WebsysDom::new(cfg, sender_callback);
  174. log::trace!("rebuilding app");
  175. if should_hydrate {
  176. // todo: we need to split rebuild and initialize into two phases
  177. // it's a waste to produce edits just to get the vdom loaded
  178. let _ = dom.rebuild();
  179. if let Err(err) = websys_dom.rehydrate(&dom) {
  180. log::error!(
  181. "Rehydration failed {:?}. Rebuild DOM into element from scratch",
  182. &err
  183. );
  184. websys_dom.root.set_text_content(None);
  185. // errrrr we should split rebuild into two phases
  186. // one that initializes things and one that produces edits
  187. let edits = dom.rebuild();
  188. websys_dom.apply_edits(edits.edits);
  189. }
  190. } else {
  191. let edits = dom.rebuild();
  192. websys_dom.apply_edits(edits.edits);
  193. }
  194. let work_loop = ric_raf::RafLoop::new();
  195. loop {
  196. log::trace!("waiting for work");
  197. // if virtualdom has nothing, wait for it to have something before requesting idle time
  198. // if there is work then this future resolves immediately.
  199. dom.wait_for_work().await;
  200. log::trace!("working..");
  201. // wait for the mainthread to schedule us in
  202. let mut deadline = work_loop.wait_for_idle_time().await;
  203. // run the virtualdom work phase until the frame deadline is reached
  204. let mutations = dom.work_with_deadline(|| (&mut deadline).now_or_never().is_some());
  205. // wait for the animation frame to fire so we can apply our changes
  206. work_loop.wait_for_raf().await;
  207. for edit in mutations {
  208. // actually apply our changes during the animation frame
  209. websys_dom.apply_edits(edit.edits);
  210. }
  211. }
  212. }