lib.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. #![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")]
  2. #![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")]
  3. #![deny(missing_docs)]
  4. //! Dioxus WebSys
  5. //!
  6. //! ## Overview
  7. //! ------------
  8. //! This crate implements a renderer of the Dioxus Virtual DOM for the web browser using WebSys. This web render for
  9. //! Dioxus is one of the more advanced renderers, supporting:
  10. //! - idle work
  11. //! - animations
  12. //! - jank-free rendering
  13. //! - controlled components
  14. //! - hydration
  15. //! - and more.
  16. //!
  17. //! The actual implementation is farily thin, with the heavy lifting happening inside the Dioxus Core crate.
  18. //!
  19. //! To purview the examples, check of the root Dioxus crate - the examples in this crate are mostly meant to provide
  20. //! validation of websys-specific features and not the general use of Dioxus.
  21. // ## RequestAnimationFrame and RequestIdleCallback
  22. // ------------------------------------------------
  23. // React implements "jank free rendering" by deliberately not blocking the browser's main thread. For large diffs, long
  24. // running work, and integration with things like React-Three-Fiber, it's extremeley important to avoid blocking the
  25. // main thread.
  26. //
  27. // React solves this problem by breaking up the rendering process into a "diff" phase and a "render" phase. In Dioxus,
  28. // the diff phase is non-blocking, using "work_with_deadline" to allow the browser to process other events. When the diff phase
  29. // is finally complete, the VirtualDOM will return a set of "Mutations" for this crate to apply.
  30. //
  31. // Here, we schedule the "diff" phase during the browser's idle period, achieved by calling RequestIdleCallback and then
  32. // setting a timeout from the that completes when the idleperiod is over. Then, we call requestAnimationFrame
  33. //
  34. // From Google's guide on rAF and rIC:
  35. // -----------------------------------
  36. //
  37. // If the callback is fired at the end of the frame, it will be scheduled to go after the current frame has been committed,
  38. // which means that style changes will have been applied, and, importantly, layout calculated. If we make DOM changes inside
  39. // of the idle callback, those layout calculations will be invalidated. If there are any kind of layout reads in the next
  40. // frame, e.g. getBoundingClientRect, clientWidth, etc, the browser will have to perform a Forced Synchronous Layout,
  41. // which is a potential performance bottleneck.
  42. //
  43. // Another reason not trigger DOM changes in the idle callback is that the time impact of changing the DOM is unpredictable,
  44. // and as such we could easily go past the deadline the browser provided.
  45. //
  46. // The best practice is to only make DOM changes inside of a requestAnimationFrame callback, since it is scheduled by the
  47. // browser with that type of work in mind. That means that our code will need to use a document fragment, which can then
  48. // be appended in the next requestAnimationFrame callback. If you are using a VDOM library, you would use requestIdleCallback
  49. // to make changes, but you would apply the DOM patches in the next requestAnimationFrame callback, not the idle callback.
  50. //
  51. // Essentially:
  52. // ------------
  53. // - Do the VDOM work during the idlecallback
  54. // - Do DOM work in the next requestAnimationFrame callback
  55. pub use crate::cfg::Config;
  56. pub use crate::file_engine::WebFileEngineExt;
  57. use dioxus_core::{Element, Scope, VirtualDom};
  58. use futures_util::{
  59. future::{select, Either},
  60. pin_mut, FutureExt, StreamExt,
  61. };
  62. mod cache;
  63. mod cfg;
  64. mod dom;
  65. #[cfg(feature = "eval")]
  66. mod eval;
  67. #[cfg(feature = "file_engine")]
  68. mod file_engine;
  69. #[cfg(all(feature = "hot_reload", debug_assertions))]
  70. mod hot_reload;
  71. #[cfg(feature = "hydrate")]
  72. mod rehydrate;
  73. // Currently disabled since it actually slows down immediate rendering
  74. // todo: only schedule non-immediate renders through ric/raf
  75. // mod ric_raf;
  76. // mod rehydrate;
  77. /// Launch the VirtualDOM given a root component and a configuration.
  78. ///
  79. /// This function expects the root component to not have root props. To launch the root component with root props, use
  80. /// `launch_with_props` instead.
  81. ///
  82. /// This method will block the thread with `spawn_local` from wasm_bindgen_futures.
  83. ///
  84. /// If you need to run the VirtualDOM in its own thread, use `run_with_props` instead and await the future.
  85. ///
  86. /// # Example
  87. ///
  88. /// ```rust, ignore
  89. /// fn main() {
  90. /// dioxus_web::launch(App);
  91. /// }
  92. ///
  93. /// static App: Component = |cx| {
  94. /// render!(div {"hello world"})
  95. /// }
  96. /// ```
  97. pub fn launch(root_component: fn(Scope) -> Element) {
  98. launch_with_props(root_component, (), Config::default());
  99. }
  100. /// Launch your app and run the event loop, with configuration.
  101. ///
  102. /// This function will start your web app on the main web thread.
  103. ///
  104. /// You can configure the WebView window with a configuration closure
  105. ///
  106. /// ```rust, ignore
  107. /// use dioxus::prelude::*;
  108. ///
  109. /// fn main() {
  110. /// dioxus_web::launch_with_props(App, Config::new().pre_render(true));
  111. /// }
  112. ///
  113. /// fn app(cx: Scope) -> Element {
  114. /// cx.render(rsx!{
  115. /// h1 {"hello world!"}
  116. /// })
  117. /// }
  118. /// ```
  119. pub fn launch_cfg(root: fn(Scope) -> Element, config: Config) {
  120. launch_with_props(root, (), config)
  121. }
  122. /// Launches the VirtualDOM from the specified component function and props.
  123. ///
  124. /// This method will block the thread with `spawn_local`
  125. ///
  126. /// # Example
  127. ///
  128. /// ```rust, ignore
  129. /// fn main() {
  130. /// dioxus_web::launch_with_props(
  131. /// App,
  132. /// RootProps { name: String::from("joe") },
  133. /// Config::new()
  134. /// );
  135. /// }
  136. ///
  137. /// #[derive(ParitalEq, Props)]
  138. /// struct RootProps {
  139. /// name: String
  140. /// }
  141. ///
  142. /// static App: Component<RootProps> = |cx| {
  143. /// render!(div {"hello {cx.props.name}"})
  144. /// }
  145. /// ```
  146. pub fn launch_with_props<T: 'static>(
  147. root_component: fn(Scope<T>) -> Element,
  148. root_properties: T,
  149. config: Config,
  150. ) {
  151. wasm_bindgen_futures::spawn_local(run_with_props(root_component, root_properties, config));
  152. }
  153. /// Runs the app as a future that can be scheduled around the main thread.
  154. ///
  155. /// Polls futures internal to the VirtualDOM, hence the async nature of this function.
  156. ///
  157. /// # Example
  158. ///
  159. /// ```ignore
  160. /// fn main() {
  161. /// let app_fut = dioxus_web::run_with_props(App, RootProps { name: String::from("joe") });
  162. /// wasm_bindgen_futures::spawn_local(app_fut);
  163. /// }
  164. /// ```
  165. pub async fn run_with_props<T: 'static>(root: fn(Scope<T>) -> Element, root_props: T, cfg: Config) {
  166. tracing::info!("Starting up");
  167. let mut dom = VirtualDom::new_with_props(root, root_props);
  168. #[cfg(feature = "eval")]
  169. {
  170. // Eval
  171. let cx = dom.base_scope();
  172. eval::init_eval(cx);
  173. }
  174. #[cfg(feature = "panic_hook")]
  175. if cfg.default_panic_hook {
  176. console_error_panic_hook::set_once();
  177. }
  178. #[cfg(all(feature = "hot_reload", debug_assertions))]
  179. let mut hotreload_rx = hot_reload::init();
  180. for s in crate::cache::BUILTIN_INTERNED_STRINGS {
  181. wasm_bindgen::intern(s);
  182. }
  183. for s in &cfg.cached_strings {
  184. wasm_bindgen::intern(s);
  185. }
  186. let (tx, mut rx) = futures_channel::mpsc::unbounded();
  187. #[cfg(feature = "hydrate")]
  188. let should_hydrate = cfg.hydrate;
  189. #[cfg(not(feature = "hydrate"))]
  190. let should_hydrate = false;
  191. let mut websys_dom = dom::WebsysDom::new(cfg, tx);
  192. tracing::info!("rebuilding app");
  193. if should_hydrate {
  194. #[cfg(feature = "hydrate")]
  195. {
  196. // todo: we need to split rebuild and initialize into two phases
  197. // it's a waste to produce edits just to get the vdom loaded
  198. let templates = dom.rebuild().templates;
  199. websys_dom.load_templates(&templates);
  200. if let Err(err) = websys_dom.rehydrate(&dom) {
  201. tracing::error!(
  202. "Rehydration failed {:?}. Rebuild DOM into element from scratch",
  203. &err
  204. );
  205. websys_dom.root.set_text_content(None);
  206. let edits = dom.rebuild();
  207. websys_dom.load_templates(&edits.templates);
  208. websys_dom.apply_edits(edits.edits);
  209. }
  210. }
  211. } else {
  212. let edits = dom.rebuild();
  213. websys_dom.load_templates(&edits.templates);
  214. websys_dom.apply_edits(edits.edits);
  215. }
  216. // the mutations come back with nothing - we need to actually mount them
  217. websys_dom.mount();
  218. loop {
  219. tracing::trace!("waiting for work");
  220. // if virtualdom has nothing, wait for it to have something before requesting idle time
  221. // if there is work then this future resolves immediately.
  222. let (mut res, template) = {
  223. let work = dom.wait_for_work().fuse();
  224. pin_mut!(work);
  225. #[cfg(all(feature = "hot_reload", debug_assertions))]
  226. // futures_util::select! {
  227. // _ = work => (None, None),
  228. // new_template = hotreload_rx.next() => {
  229. // (None, new_template)
  230. // }
  231. // evt = rx.next() =>
  232. // }
  233. match select(work, select(hotreload_rx.next(), rx.next())).await {
  234. Either::Left((_, _)) => (None, None),
  235. Either::Right((Either::Left((new_template, _)), _)) => (None, new_template),
  236. Either::Right((Either::Right((evt, _)), _)) => (evt, None),
  237. }
  238. #[cfg(not(all(feature = "hot_reload", debug_assertions)))]
  239. match select(work, rx.next()).await {
  240. Either::Left((_, _)) => (None, None),
  241. Either::Right((evt, _)) => (evt, None),
  242. }
  243. };
  244. if let Some(template) = template {
  245. dom.replace_template(template);
  246. }
  247. // Dequeue all of the events from the channel in send order
  248. // todo: we should re-order these if possible
  249. while let Some(evt) = res {
  250. dom.handle_event(evt.name.as_str(), evt.data, evt.element, evt.bubbles);
  251. res = rx.try_next().transpose().unwrap().ok();
  252. }
  253. // Todo: This is currently disabled because it has a negative impact on response times for events but it could be re-enabled for tasks
  254. // Jank free rendering
  255. //
  256. // 1. wait for the browser to give us "idle" time
  257. // 2. During idle time, diff the dom
  258. // 3. Stop diffing if the deadline is exceded
  259. // 4. Wait for the animation frame to patch the dom
  260. // wait for the mainthread to schedule us in
  261. // let deadline = work_loop.wait_for_idle_time().await;
  262. // run the virtualdom work phase until the frame deadline is reached
  263. let edits = dom.render_immediate();
  264. // wait for the animation frame to fire so we can apply our changes
  265. // work_loop.wait_for_raf().await;
  266. websys_dom.load_templates(&edits.templates);
  267. websys_dom.apply_edits(edits.edits);
  268. }
  269. }