1
0

lib.rs 10 KB

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