lib.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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::file_engine::WebFileEngineExt;
  55. use dioxus_core::{Element, Scope, VirtualDom};
  56. use futures_util::{
  57. future::{select, Either},
  58. pin_mut, FutureExt, StreamExt,
  59. };
  60. mod cache;
  61. mod cfg;
  62. mod dom;
  63. #[cfg(feature = "eval")]
  64. mod eval;
  65. #[cfg(feature = "file_engine")]
  66. mod file_engine;
  67. #[cfg(all(feature = "hot_reload", debug_assertions))]
  68. mod hot_reload;
  69. #[cfg(feature = "hydrate")]
  70. mod rehydrate;
  71. // Currently disabled since it actually slows down immediate rendering
  72. // todo: only schedule non-immediate renders through ric/raf
  73. // mod ric_raf;
  74. // mod rehydrate;
  75. /// Launch the VirtualDOM given a root component and a configuration.
  76. ///
  77. /// This function expects the root component to not have root props. To launch the root component with root props, use
  78. /// `launch_with_props` instead.
  79. ///
  80. /// This method will block the thread with `spawn_local` from wasm_bindgen_futures.
  81. ///
  82. /// If you need to run the VirtualDOM in its own thread, use `run_with_props` instead and await the future.
  83. ///
  84. /// # Example
  85. ///
  86. /// ```rust, ignore
  87. /// fn main() {
  88. /// dioxus_web::launch(App);
  89. /// }
  90. ///
  91. /// static App: Component = |cx| {
  92. /// render!(div {"hello world"})
  93. /// }
  94. /// ```
  95. pub fn launch(root_component: fn(Scope) -> Element) {
  96. launch_with_props(root_component, (), Config::default());
  97. }
  98. /// Launch your app and run the event loop, with configuration.
  99. ///
  100. /// This function will start your web app on the main web thread.
  101. ///
  102. /// You can configure the WebView window with a configuration closure
  103. ///
  104. /// ```rust, ignore
  105. /// use dioxus::prelude::*;
  106. ///
  107. /// fn main() {
  108. /// dioxus_web::launch_with_props(App, Config::new().pre_render(true));
  109. /// }
  110. ///
  111. /// fn app(cx: Scope) -> Element {
  112. /// cx.render(rsx!{
  113. /// h1 {"hello world!"}
  114. /// })
  115. /// }
  116. /// ```
  117. pub fn launch_cfg(root: fn(Scope) -> Element, config: Config) {
  118. launch_with_props(root, (), config)
  119. }
  120. /// Launches the VirtualDOM from the specified component function and props.
  121. ///
  122. /// This method will block the thread with `spawn_local`
  123. ///
  124. /// # Example
  125. ///
  126. /// ```rust, ignore
  127. /// fn main() {
  128. /// dioxus_web::launch_with_props(
  129. /// App,
  130. /// RootProps { name: String::from("joe") },
  131. /// Config::new()
  132. /// );
  133. /// }
  134. ///
  135. /// #[derive(ParitalEq, Props)]
  136. /// struct RootProps {
  137. /// name: String
  138. /// }
  139. ///
  140. /// static App: Component<RootProps> = |cx| {
  141. /// render!(div {"hello {cx.props.name}"})
  142. /// }
  143. /// ```
  144. pub fn launch_with_props<T: 'static>(
  145. root_component: fn(Scope<T>) -> Element,
  146. root_properties: T,
  147. config: Config,
  148. ) {
  149. wasm_bindgen_futures::spawn_local(run_with_props(root_component, root_properties, config));
  150. }
  151. /// Runs the app as a future that can be scheduled around the main thread.
  152. ///
  153. /// Polls futures internal to the VirtualDOM, hence the async nature of this function.
  154. ///
  155. /// # Example
  156. ///
  157. /// ```ignore
  158. /// fn main() {
  159. /// let app_fut = dioxus_web::run_with_props(App, RootProps { name: String::from("joe") });
  160. /// wasm_bindgen_futures::spawn_local(app_fut);
  161. /// }
  162. /// ```
  163. pub async fn run_with_props<T: 'static>(root: fn(Scope<T>) -> Element, root_props: T, cfg: Config) {
  164. tracing::info!("Starting up");
  165. let mut dom = VirtualDom::new_with_props(root, root_props);
  166. #[cfg(feature = "eval")]
  167. {
  168. // Eval
  169. let cx = dom.base_scope();
  170. eval::init_eval(cx);
  171. }
  172. #[cfg(feature = "panic_hook")]
  173. if cfg.default_panic_hook {
  174. console_error_panic_hook::set_once();
  175. }
  176. #[cfg(all(feature = "hot_reload", debug_assertions))]
  177. let mut hotreload_rx = hot_reload::init();
  178. for s in crate::cache::BUILTIN_INTERNED_STRINGS {
  179. wasm_bindgen::intern(s);
  180. }
  181. for s in &cfg.cached_strings {
  182. wasm_bindgen::intern(s);
  183. }
  184. let (tx, mut rx) = futures_channel::mpsc::unbounded();
  185. #[cfg(feature = "hydrate")]
  186. let should_hydrate = cfg.hydrate;
  187. #[cfg(not(feature = "hydrate"))]
  188. let should_hydrate = false;
  189. let mut websys_dom = dom::WebsysDom::new(cfg, tx);
  190. tracing::info!("rebuilding app");
  191. if should_hydrate {
  192. #[cfg(feature = "hydrate")]
  193. {
  194. // todo: we need to split rebuild and initialize into two phases
  195. // it's a waste to produce edits just to get the vdom loaded
  196. let templates = dom.rebuild().templates;
  197. websys_dom.load_templates(&templates);
  198. if let Err(err) = websys_dom.rehydrate(&dom) {
  199. tracing::error!(
  200. "Rehydration failed {:?}. Rebuild DOM into element from scratch",
  201. &err
  202. );
  203. websys_dom.root.set_text_content(None);
  204. let edits = dom.rebuild();
  205. websys_dom.load_templates(&edits.templates);
  206. websys_dom.apply_edits(edits.edits);
  207. }
  208. }
  209. } else {
  210. let edits = dom.rebuild();
  211. websys_dom.load_templates(&edits.templates);
  212. websys_dom.apply_edits(edits.edits);
  213. }
  214. // the mutations come back with nothing - we need to actually mount them
  215. websys_dom.mount();
  216. loop {
  217. tracing::trace!("waiting for work");
  218. // if virtualdom has nothing, wait for it to have something before requesting idle time
  219. // if there is work then this future resolves immediately.
  220. let (mut res, template) = {
  221. let work = dom.wait_for_work().fuse();
  222. pin_mut!(work);
  223. #[cfg(all(feature = "hot_reload", debug_assertions))]
  224. // futures_util::select! {
  225. // _ = work => (None, None),
  226. // new_template = hotreload_rx.next() => {
  227. // (None, new_template)
  228. // }
  229. // evt = rx.next() =>
  230. // }
  231. match select(work, select(hotreload_rx.next(), rx.next())).await {
  232. Either::Left((_, _)) => (None, None),
  233. Either::Right((Either::Left((new_template, _)), _)) => (None, new_template),
  234. Either::Right((Either::Right((evt, _)), _)) => (evt, None),
  235. }
  236. #[cfg(not(all(feature = "hot_reload", debug_assertions)))]
  237. match select(work, rx.next()).await {
  238. Either::Left((_, _)) => (None, None),
  239. Either::Right((evt, _)) => (evt, None),
  240. }
  241. };
  242. if let Some(template) = template {
  243. dom.replace_template(template);
  244. }
  245. // Dequeue all of the events from the channel in send order
  246. // todo: we should re-order these if possible
  247. while let Some(evt) = res {
  248. dom.handle_event(evt.name.as_str(), evt.data, evt.element, evt.bubbles);
  249. res = rx.try_next().transpose().unwrap().ok();
  250. }
  251. // Todo: This is currently disabled because it has a negative impact on response times for events but it could be re-enabled for tasks
  252. // Jank free rendering
  253. //
  254. // 1. wait for the browser to give us "idle" time
  255. // 2. During idle time, diff the dom
  256. // 3. Stop diffing if the deadline is exceded
  257. // 4. Wait for the animation frame to patch the dom
  258. // wait for the mainthread to schedule us in
  259. // let deadline = work_loop.wait_for_idle_time().await;
  260. // run the virtualdom work phase until the frame deadline is reached
  261. let edits = dom.render_immediate();
  262. // wait for the animation frame to fire so we can apply our changes
  263. // work_loop.wait_for_raf().await;
  264. websys_dom.load_templates(&edits.templates);
  265. websys_dom.apply_edits(edits.edits);
  266. }
  267. }