lib.rs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. #![deny(missing_docs)]
  2. //! Dioxus WebSys
  3. //!
  4. //! ## Overview
  5. //! ------------
  6. //! This crate implements a renderer of the Dioxus Virtual DOM for the web browser using WebSys. This web render for
  7. //! Dioxus is one of the more advanced renderers, supporting:
  8. //! - idle work
  9. //! - animations
  10. //! - jank-free rendering
  11. //! - controlled components
  12. //! - 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 "work_with_deadline" 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. pub use crate::cfg::Config;
  54. pub use crate::util::{use_eval, EvalResult};
  55. use dioxus_core::{Element, Scope, VirtualDom};
  56. use futures_util::{pin_mut, FutureExt, StreamExt};
  57. mod cache;
  58. mod cfg;
  59. mod dom;
  60. mod hot_reload;
  61. mod util;
  62. // Currently disabled since it actually slows down immediate rendering
  63. // todo: only schedule non-immediate renders through ric/raf
  64. // mod ric_raf;
  65. // mod rehydrate;
  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. /// render!(div {"hello world"})
  84. /// }
  85. /// ```
  86. pub fn launch(root_component: fn(Scope) -> Element) {
  87. launch_with_props(root_component, (), Config::default());
  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, ignore
  96. /// use dioxus::prelude::*;
  97. ///
  98. /// fn main() {
  99. /// dioxus_web::launch_with_props(App, Config::new().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: fn(Scope) -> Element, config: Config) {
  109. launch_with_props(root, (), config)
  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::new()
  123. /// );
  124. /// }
  125. ///
  126. /// #[derive(ParitalEq, Props)]
  127. /// struct RootProps {
  128. /// name: String
  129. /// }
  130. ///
  131. /// static App: Component<RootProps> = |cx| {
  132. /// render!(div {"hello {cx.props.name}"})
  133. /// }
  134. /// ```
  135. pub fn launch_with_props<T: 'static>(
  136. root_component: fn(Scope<T>) -> Element,
  137. root_properties: T,
  138. config: Config,
  139. ) {
  140. wasm_bindgen_futures::spawn_local(run_with_props(root_component, root_properties, config));
  141. }
  142. /// Runs the app as a future that can be scheduled around the main thread.
  143. ///
  144. /// Polls futures internal to the VirtualDOM, hence the async nature of this function.
  145. ///
  146. /// # Example
  147. ///
  148. /// ```ignore
  149. /// fn main() {
  150. /// let app_fut = dioxus_web::run_with_props(App, RootProps { name: String::from("joe") });
  151. /// wasm_bindgen_futures::spawn_local(app_fut);
  152. /// }
  153. /// ```
  154. pub async fn run_with_props<T: 'static>(root: fn(Scope<T>) -> Element, root_props: T, cfg: Config) {
  155. log::info!("Starting up");
  156. let mut dom = VirtualDom::new_with_props(root, root_props);
  157. #[cfg(feature = "panic_hook")]
  158. if cfg.default_panic_hook {
  159. console_error_panic_hook::set_once();
  160. }
  161. let mut hotreload_rx = hot_reload::init();
  162. for s in crate::cache::BUILTIN_INTERNED_STRINGS {
  163. wasm_bindgen::intern(s);
  164. }
  165. for s in &cfg.cached_strings {
  166. wasm_bindgen::intern(s);
  167. }
  168. let _should_hydrate = cfg.hydrate;
  169. let (tx, mut rx) = futures_channel::mpsc::unbounded();
  170. let mut websys_dom = dom::WebsysDom::new(cfg, tx);
  171. log::info!("rebuilding app");
  172. // if should_hydrate {
  173. // } else {
  174. let edits = dom.rebuild();
  175. websys_dom.load_templates(&edits.templates);
  176. websys_dom.apply_edits(edits.edits);
  177. // the mutations come back with nothing - we need to actually mount them
  178. websys_dom.mount();
  179. loop {
  180. log::debug!("waiting for work");
  181. // if virtualdom has nothing, wait for it to have something before requesting idle time
  182. // if there is work then this future resolves immediately.
  183. let (mut res, template) = {
  184. let work = dom.wait_for_work().fuse();
  185. pin_mut!(work);
  186. futures_util::select! {
  187. _ = work => (None, None),
  188. new_template = hotreload_rx.next() => {
  189. (None, new_template)
  190. }
  191. evt = rx.next() => (evt, None)
  192. }
  193. };
  194. if let Some(template) = template {
  195. dom.replace_template(template);
  196. }
  197. // Dequeue all of the events from the channel in send order
  198. // todo: we should re-order these if possible
  199. while let Some(evt) = res {
  200. dom.handle_event(evt.name.as_str(), evt.data, evt.element, evt.bubbles);
  201. res = rx.try_next().transpose().unwrap().ok();
  202. }
  203. // Todo: This is currently disabled because it has a negative impact on responce times for events but it could be re-enabled for tasks
  204. // Jank free rendering
  205. //
  206. // 1. wait for the browser to give us "idle" time
  207. // 2. During idle time, diff the dom
  208. // 3. Stop diffing if the deadline is exceded
  209. // 4. Wait for the animation frame to patch the dom
  210. // wait for the mainthread to schedule us in
  211. // let deadline = work_loop.wait_for_idle_time().await;
  212. // run the virtualdom work phase until the frame deadline is reached
  213. let edits = dom.render_immediate();
  214. // wait for the animation frame to fire so we can apply our changes
  215. // work_loop.wait_for_raf().await;
  216. websys_dom.load_templates(&edits.templates);
  217. websys_dom.apply_edits(edits.edits);
  218. }
  219. }
  220. // if should_hydrate {
  221. // // todo: we need to split rebuild and initialize into two phases
  222. // // it's a waste to produce edits just to get the vdom loaded
  223. // let _ = dom.rebuild();
  224. // #[cfg(feature = "hydrate")]
  225. // #[allow(unused_variables)]
  226. // if let Err(err) = websys_dom.rehydrate(&dom) {
  227. // log::error!(
  228. // "Rehydration failed {:?}. Rebuild DOM into element from scratch",
  229. // &err
  230. // );
  231. // websys_dom.root.set_text_content(None);
  232. // // errrrr we should split rebuild into two phases
  233. // // one that initializes things and one that produces edits
  234. // let edits = dom.rebuild();
  235. // websys_dom.apply_edits(edits.edits);
  236. // }
  237. // } else {
  238. // let edits = dom.rebuild();
  239. // websys_dom.apply_edits(edits.template_mutations);
  240. // websys_dom.apply_edits(edits.edits);
  241. // }