virtual_dom.rs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. //! # VirtualDOM Implementation for Rust
  2. //!
  3. //! This module provides the primary mechanics to create a hook-based, concurrent VDOM for Rust.
  4. use crate::innerlude::*;
  5. use futures_channel::mpsc::{UnboundedReceiver, UnboundedSender};
  6. use futures_util::{Future, StreamExt};
  7. use fxhash::FxHashSet;
  8. use indexmap::IndexSet;
  9. use std::pin::Pin;
  10. use std::rc::Rc;
  11. use std::sync::Arc;
  12. use std::task::Poll;
  13. use std::{any::Any, collections::VecDeque};
  14. /// A virtual node system that progresses user events and diffs UI trees.
  15. ///
  16. ///
  17. /// ## Guide
  18. ///
  19. /// Components are defined as simple functions that take [`Context`] and a [`Properties`] type and return an [`Element`].
  20. ///
  21. /// ```rust, ignore
  22. /// #[derive(Props, PartialEq)]
  23. /// struct AppProps {
  24. /// title: String
  25. /// }
  26. ///
  27. /// fn App(cx: Context, props: &AppProps) -> Element {
  28. /// cx.render(rsx!(
  29. /// div {"hello, {props.title}"}
  30. /// ))
  31. /// }
  32. /// ```
  33. ///
  34. /// Components may be composed to make complex apps.
  35. ///
  36. /// ```rust, ignore
  37. /// fn App(cx: Context, props: &AppProps) -> Element {
  38. /// cx.render(rsx!(
  39. /// NavBar { routes: ROUTES }
  40. /// Title { "{props.title}" }
  41. /// Footer {}
  42. /// ))
  43. /// }
  44. /// ```
  45. ///
  46. /// To start an app, create a [`VirtualDom`] and call [`VirtualDom::rebuild`] to get the list of edits required to
  47. /// draw the UI.
  48. ///
  49. /// ```rust, ignore
  50. /// let mut vdom = VirtualDom::new(App);
  51. /// let edits = vdom.rebuild();
  52. /// ```
  53. ///
  54. /// To inject UserEvents into the VirtualDom, call [`VirtualDom::get_scheduler_channel`] to get access to the scheduler.
  55. ///
  56. /// ```rust, ignore
  57. /// let channel = vdom.get_scheduler_channel();
  58. /// channel.send_unbounded(SchedulerMsg::UserEvent(UserEvent {
  59. /// // ...
  60. /// }))
  61. /// ```
  62. ///
  63. /// While waiting for UserEvents to occur, call [`VirtualDom::wait_for_work`] to poll any futures inside the VirtualDom.
  64. ///
  65. /// ```rust, ignore
  66. /// vdom.wait_for_work().await;
  67. /// ```
  68. ///
  69. /// Once work is ready, call [`VirtualDom::work_with_deadline`] to compute the differences between the previous and
  70. /// current UI trees. This will return a [`Mutations`] object that contains Edits, Effects, and NodeRefs that need to be
  71. /// handled by the renderer.
  72. ///
  73. /// ```rust, ignore
  74. /// let mutations = vdom.work_with_deadline(|| false);
  75. /// for edit in mutations {
  76. /// apply(edit);
  77. /// }
  78. /// ```
  79. ///
  80. /// ## Building an event loop around Dioxus:
  81. ///
  82. /// Putting everything together, you can build an event loop around Dioxus by using the methods outlined above.
  83. ///
  84. /// ```rust, ignore
  85. /// fn App(cx: Context, props: &()) -> Element {
  86. /// cx.render(rsx!{
  87. /// div { "Hello World" }
  88. /// })
  89. /// }
  90. ///
  91. /// async fn main() {
  92. /// let mut dom = VirtualDom::new(App);
  93. ///
  94. /// let mut inital_edits = dom.rebuild();
  95. /// apply_edits(inital_edits);
  96. ///
  97. /// loop {
  98. /// dom.wait_for_work().await;
  99. /// let frame_timeout = TimeoutFuture::new(Duration::from_millis(16));
  100. /// let deadline = || (&mut frame_timeout).now_or_never();
  101. /// let edits = dom.run_with_deadline(deadline).await;
  102. /// apply_edits(edits);
  103. /// }
  104. /// }
  105. /// ```
  106. pub struct VirtualDom {
  107. base_scope: ScopeId,
  108. _root_props: Box<dyn Any>,
  109. scopes: Box<ScopeArena>,
  110. receiver: UnboundedReceiver<SchedulerMsg>,
  111. sender: UnboundedSender<SchedulerMsg>,
  112. pending_futures: FxHashSet<ScopeId>,
  113. pending_messages: VecDeque<SchedulerMsg>,
  114. dirty_scopes: IndexSet<ScopeId>,
  115. }
  116. // Methods to create the VirtualDom
  117. impl VirtualDom {
  118. /// Create a new VirtualDOM with a component that does not have special props.
  119. ///
  120. /// # Description
  121. ///
  122. /// Later, the props can be updated by calling "update" with a new set of props, causing a set of re-renders.
  123. ///
  124. /// This is useful when a component tree can be driven by external state (IE SSR) but it would be too expensive
  125. /// to toss out the entire tree.
  126. ///
  127. ///
  128. /// # Example
  129. /// ```rust, ignore
  130. /// fn Example(cx: Context, props: &()) -> Element {
  131. /// cx.render(rsx!( div { "hello world" } ))
  132. /// }
  133. ///
  134. /// let dom = VirtualDom::new(Example);
  135. /// ```
  136. ///
  137. /// Note: the VirtualDOM is not progressed, you must either "run_with_deadline" or use "rebuild" to progress it.
  138. pub fn new(root: FC<()>) -> Self {
  139. Self::new_with_props(root, ())
  140. }
  141. /// Create a new VirtualDOM with the given properties for the root component.
  142. ///
  143. /// # Description
  144. ///
  145. /// Later, the props can be updated by calling "update" with a new set of props, causing a set of re-renders.
  146. ///
  147. /// This is useful when a component tree can be driven by external state (IE SSR) but it would be too expensive
  148. /// to toss out the entire tree.
  149. ///
  150. ///
  151. /// # Example
  152. /// ```rust, ignore
  153. /// #[derive(PartialEq, Props)]
  154. /// struct SomeProps {
  155. /// name: &'static str
  156. /// }
  157. ///
  158. /// fn Example(cx: Context, props: &SomeProps) -> Element {
  159. /// cx.render(rsx!{ div{ "hello {cx.name}" } })
  160. /// }
  161. ///
  162. /// let dom = VirtualDom::new(Example);
  163. /// ```
  164. ///
  165. /// Note: the VirtualDOM is not progressed on creation. You must either "run_with_deadline" or use "rebuild" to progress it.
  166. ///
  167. /// ```rust, ignore
  168. /// let mut dom = VirtualDom::new_with_props(Example, SomeProps { name: "jane" });
  169. /// let mutations = dom.rebuild();
  170. /// ```
  171. pub fn new_with_props<P: 'static>(root: FC<P>, root_props: P) -> Self {
  172. let (sender, receiver) = futures_channel::mpsc::unbounded::<SchedulerMsg>();
  173. Self::new_with_props_and_scheduler(root, root_props, sender, receiver)
  174. }
  175. /// Launch the VirtualDom, but provide your own channel for receiving and sending messages into the scheduler
  176. ///
  177. /// This is useful when the VirtualDom must be driven from outside a thread and it doesn't make sense to wait for the
  178. /// VirtualDom to be created just to retrieve its channel receiver.
  179. pub fn new_with_props_and_scheduler<P: 'static>(
  180. root: FC<P>,
  181. root_props: P,
  182. sender: UnboundedSender<SchedulerMsg>,
  183. receiver: UnboundedReceiver<SchedulerMsg>,
  184. ) -> Self {
  185. let scopes = ScopeArena::new(sender.clone());
  186. let mut caller = Box::new(move |scp: &Scope| -> Element { root(scp, &root_props) });
  187. let caller_ref: *mut dyn Fn(&Scope) -> Element = caller.as_mut() as *mut _;
  188. let base_scope = scopes.new_with_key(root as _, caller_ref, None, ElementId(0), 0, 0);
  189. let pending_messages = VecDeque::new();
  190. let mut dirty_scopes = IndexSet::new();
  191. dirty_scopes.insert(base_scope);
  192. Self {
  193. scopes: Box::new(scopes),
  194. base_scope,
  195. receiver,
  196. _root_props: caller,
  197. pending_messages,
  198. pending_futures: Default::default(),
  199. dirty_scopes,
  200. sender,
  201. }
  202. }
  203. /// Get the [`Scope`] for the root component.
  204. ///
  205. /// This is useful for traversing the tree from the root for heuristics or alternsative renderers that use Dioxus
  206. /// directly.
  207. ///
  208. /// # Example
  209. pub fn base_scope(&self) -> &Scope {
  210. self.get_scope(&self.base_scope).unwrap()
  211. }
  212. /// Get the [`Scope`] for a component given its [`ScopeId`]
  213. ///
  214. /// # Example
  215. ///
  216. ///
  217. ///
  218. pub fn get_scope<'a>(&'a self, id: &ScopeId) -> Option<&'a Scope> {
  219. self.scopes.get_scope(id)
  220. }
  221. /// Get an [`UnboundedSender`] handle to the channel used by the scheduler.
  222. ///
  223. /// # Example
  224. ///
  225. /// ```rust, ignore
  226. ///
  227. ///
  228. /// ```
  229. pub fn get_scheduler_channel(&self) -> futures_channel::mpsc::UnboundedSender<SchedulerMsg> {
  230. self.sender.clone()
  231. }
  232. /// Check if the [`VirtualDom`] has any pending updates or work to be done.
  233. ///
  234. /// # Example
  235. ///
  236. /// ```rust, ignore
  237. ///
  238. ///
  239. /// ```
  240. pub fn has_any_work(&self) -> bool {
  241. !(self.dirty_scopes.is_empty() && self.pending_messages.is_empty())
  242. }
  243. /// Waits for the scheduler to have work
  244. /// This lets us poll async tasks during idle periods without blocking the main thread.
  245. pub async fn wait_for_work(&mut self) {
  246. // todo: poll the events once even if there is work to do to prevent starvation
  247. // if there's no futures in the virtualdom, just wait for a scheduler message and put it into the queue to be processed
  248. if self.pending_futures.is_empty() {
  249. self.pending_messages
  250. .push_front(self.receiver.next().await.unwrap());
  251. } else {
  252. struct PollTasks<'a> {
  253. pending_futures: &'a FxHashSet<ScopeId>,
  254. scopes: &'a ScopeArena,
  255. }
  256. impl<'a> Future for PollTasks<'a> {
  257. type Output = ();
  258. fn poll(
  259. self: Pin<&mut Self>,
  260. cx: &mut std::task::Context<'_>,
  261. ) -> Poll<Self::Output> {
  262. let mut all_pending = true;
  263. // Poll every scope manually
  264. for fut in self.pending_futures.iter() {
  265. let scope = self
  266. .scopes
  267. .get_scope(fut)
  268. .expect("Scope should never be moved");
  269. let mut items = scope.items.borrow_mut();
  270. for task in items.tasks.iter_mut() {
  271. let task = task.as_mut();
  272. // todo: does this make sense?
  273. // I don't usually write futures by hand
  274. // I think the futures neeed to be pinned using bumpbox or something
  275. // right now, they're bump allocated so this shouldn't matter anyway - they're not going to move
  276. let unpinned = unsafe { Pin::new_unchecked(task) };
  277. if unpinned.poll(cx).is_ready() {
  278. all_pending = false
  279. }
  280. }
  281. }
  282. // Resolve the future if any singular task is ready
  283. match all_pending {
  284. true => Poll::Pending,
  285. false => Poll::Ready(()),
  286. }
  287. }
  288. }
  289. // Poll both the futures and the scheduler message queue simulataneously
  290. use futures_util::future::{select, Either};
  291. let scheduler_fut = self.receiver.next();
  292. let tasks_fut = PollTasks {
  293. pending_futures: &self.pending_futures,
  294. scopes: &self.scopes,
  295. };
  296. match select(tasks_fut, scheduler_fut).await {
  297. // Futures don't generate work
  298. Either::Left((_, _)) => {}
  299. // Save these messages in FIFO to be processed later
  300. Either::Right((msg, _)) => self.pending_messages.push_front(msg.unwrap()),
  301. }
  302. }
  303. }
  304. /// Run the virtualdom with a deadline.
  305. ///
  306. /// This method will progress async tasks until the deadline is reached. If tasks are completed before the deadline,
  307. /// and no tasks are pending, this method will return immediately. If tasks are still pending, then this method will
  308. /// exhaust the deadline working on them.
  309. ///
  310. /// This method is useful when needing to schedule the virtualdom around other tasks on the main thread to prevent
  311. /// "jank". It will try to finish whatever work it has by the deadline to free up time for other work.
  312. ///
  313. /// Due to platform differences in how time is handled, this method accepts a future that resolves when the deadline
  314. /// is exceeded. However, the deadline won't be met precisely, so you might want to build some wiggle room into the
  315. /// deadline closure manually.
  316. ///
  317. /// The deadline is polled before starting to diff components. This strikes a balance between the overhead of checking
  318. /// the deadline and just completing the work. However, if an individual component takes more than 16ms to render, then
  319. /// the screen will "jank" up. In debug, this will trigger an alert.
  320. ///
  321. /// If there are no in-flight fibers when this method is called, it will await any possible tasks, aborting early if
  322. /// the provided deadline future resolves.
  323. ///
  324. /// For use in the web, it is expected that this method will be called to be executed during "idle times" and the
  325. /// mutations to be applied during the "paint times" IE "animation frames". With this strategy, it is possible to craft
  326. /// entirely jank-free applications that perform a ton of work.
  327. ///
  328. /// # Example
  329. ///
  330. /// ```rust, ignore
  331. /// fn App(cx: Context, props: &()) -> Element {
  332. /// cx.render(rsx!( div {"hello"} ))
  333. /// }
  334. ///
  335. /// let mut dom = VirtualDom::new(App);
  336. ///
  337. /// loop {
  338. /// let mut timeout = TimeoutFuture::from_ms(16);
  339. /// let deadline = move || (&mut timeout).now_or_never();
  340. ///
  341. /// let mutations = dom.run_with_deadline(deadline).await;
  342. ///
  343. /// apply_mutations(mutations);
  344. /// }
  345. /// ```
  346. ///
  347. /// ## Mutations
  348. ///
  349. /// This method returns "mutations" - IE the necessary changes to get the RealDOM to match the VirtualDOM. It also
  350. /// includes a list of NodeRefs that need to be applied and effects that need to be triggered after the RealDOM has
  351. /// applied the edits.
  352. ///
  353. /// Mutations are the only link between the RealDOM and the VirtualDOM.
  354. ///
  355. pub fn work_with_deadline(&mut self, mut deadline: impl FnMut() -> bool) -> Vec<Mutations> {
  356. let mut committed_mutations = vec![];
  357. while self.has_any_work() {
  358. while let Ok(Some(msg)) = self.receiver.try_next() {
  359. self.pending_messages.push_front(msg);
  360. }
  361. while let Some(msg) = self.pending_messages.pop_back() {
  362. match msg {
  363. // TODO: Suspsense
  364. SchedulerMsg::Immediate(id) => {
  365. self.dirty_scopes.insert(id);
  366. }
  367. SchedulerMsg::UiEvent(event) => {
  368. if let Some(element) = event.mounted_dom_id {
  369. log::info!("Calling listener {:?}, {:?}", event.scope_id, element);
  370. if let Some(scope) = self.scopes.get_scope(&event.scope_id) {
  371. self.scopes.call_listener_with_bubbling(event, element);
  372. while let Ok(Some(dirty_scope)) = self.receiver.try_next() {
  373. self.pending_messages.push_front(dirty_scope);
  374. }
  375. }
  376. } else {
  377. log::debug!("User event without a targetted ElementId. Not currently supported.\nUnsure how to proceed. {:?}", event);
  378. }
  379. }
  380. }
  381. }
  382. let scopes = &self.scopes;
  383. let mut diff_state = DiffState::new(scopes);
  384. let mut ran_scopes = FxHashSet::default();
  385. // todo: the 2021 version of rust will let us not have to force the borrow
  386. // let scopes = &self.scopes;
  387. // Sort the scopes by height. Theoretically, we'll de-duplicate scopes by height
  388. self.dirty_scopes
  389. .retain(|id| scopes.get_scope(id).is_some());
  390. self.dirty_scopes.sort_by(|a, b| {
  391. let h1 = scopes.get_scope(a).unwrap().height;
  392. let h2 = scopes.get_scope(b).unwrap().height;
  393. h1.cmp(&h2).reverse()
  394. });
  395. if let Some(scopeid) = self.dirty_scopes.pop() {
  396. log::info!("handling dirty scope {:?}", scopeid);
  397. if !ran_scopes.contains(&scopeid) {
  398. ran_scopes.insert(scopeid);
  399. log::debug!("about to run scope {:?}", scopeid);
  400. if self.scopes.run_scope(&scopeid) {
  401. let (old, new) = (
  402. self.scopes.wip_head(&scopeid),
  403. self.scopes.fin_head(&scopeid),
  404. );
  405. diff_state.stack.push(DiffInstruction::Diff { new, old });
  406. diff_state.stack.scope_stack.push(scopeid);
  407. let scope = scopes.get_scope(&scopeid).unwrap();
  408. diff_state.stack.element_stack.push(scope.container);
  409. }
  410. }
  411. }
  412. let work_completed = diff_state.work(&mut deadline);
  413. if work_completed {
  414. let DiffState {
  415. mutations,
  416. seen_scopes,
  417. ..
  418. } = diff_state;
  419. for scope in seen_scopes {
  420. self.dirty_scopes.remove(&scope);
  421. }
  422. // // I think the stack should be empty at the end of diffing?
  423. // debug_assert_eq!(stack.scope_stack.len(), 1);
  424. committed_mutations.push(mutations);
  425. } else {
  426. // leave the work in an incomplete state
  427. log::debug!("don't have a mechanism to pause work (yet)");
  428. return committed_mutations;
  429. }
  430. }
  431. committed_mutations
  432. }
  433. /// Performs a *full* rebuild of the virtual dom, returning every edit required to generate the actual dom from scratch
  434. ///
  435. /// The diff machine expects the RealDom's stack to be the root of the application.
  436. ///
  437. /// Tasks will not be polled with this method, nor will any events be processed from the event queue. Instead, the
  438. /// root component will be ran once and then diffed. All updates will flow out as mutations.
  439. ///
  440. /// All state stored in components will be completely wiped away.
  441. ///
  442. /// # Example
  443. /// ```rust, ignore
  444. /// static App: FC<()> = |cx, props| cx.render(rsx!{ "hello world" });
  445. /// let mut dom = VirtualDom::new();
  446. /// let edits = dom.rebuild();
  447. ///
  448. /// apply_edits(edits);
  449. /// ```
  450. pub fn rebuild(&mut self) -> Mutations {
  451. let mut diff_state = DiffState::new(&self.scopes);
  452. let scope_id = self.base_scope;
  453. if self.scopes.run_scope(&scope_id) {
  454. diff_state
  455. .stack
  456. .create_node(self.scopes.fin_head(&scope_id), MountType::Append);
  457. diff_state.stack.element_stack.push(ElementId(0));
  458. diff_state.stack.scope_stack.push(scope_id);
  459. diff_state.work(|| false);
  460. }
  461. diff_state.mutations
  462. }
  463. /// Compute a manual diff of the VirtualDOM between states.
  464. ///
  465. /// This can be useful when state inside the DOM is remotely changed from the outside, but not propagated as an event.
  466. ///
  467. /// In this case, every component will be diffed, even if their props are memoized. This method is intended to be used
  468. /// to force an update of the DOM when the state of the app is changed outside of the app.
  469. ///
  470. ///
  471. /// # Example
  472. /// ```rust, ignore
  473. /// #[derive(PartialEq, Props)]
  474. /// struct AppProps {
  475. /// value: Shared<&'static str>,
  476. /// }
  477. ///
  478. /// static App: FC<AppProps> = |cx, props|{
  479. /// let val = cx.value.borrow();
  480. /// cx.render(rsx! { div { "{val}" } })
  481. /// };
  482. ///
  483. /// let value = Rc::new(RefCell::new("Hello"));
  484. /// let mut dom = VirtualDom::new_with_props(
  485. /// App,
  486. /// AppProps {
  487. /// value: value.clone(),
  488. /// },
  489. /// );
  490. ///
  491. /// let _ = dom.rebuild();
  492. ///
  493. /// *value.borrow_mut() = "goodbye";
  494. ///
  495. /// let edits = dom.diff();
  496. /// ```
  497. pub fn hard_diff<'a>(&'a mut self, scope_id: &ScopeId) -> Option<Mutations<'a>> {
  498. let mut diff_machine = DiffState::new(&self.scopes);
  499. if self.scopes.run_scope(scope_id) {
  500. diff_machine.force_diff = true;
  501. diff_machine.diff_scope(scope_id);
  502. }
  503. Some(diff_machine.mutations)
  504. }
  505. /// Renders an `rsx` call into the Base Scope's allocator.
  506. ///
  507. /// Useful when needing to render nodes from outside the VirtualDom, such as in a test.
  508. pub fn render_vnodes<'a>(&'a self, lazy_nodes: Option<LazyNodes<'a, '_>>) -> &'a VNode<'a> {
  509. let scope = self.scopes.get_scope(&self.base_scope).unwrap();
  510. let frame = scope.wip_frame();
  511. let factory = NodeFactory { bump: &frame.bump };
  512. let node = lazy_nodes.unwrap().call(factory);
  513. frame.bump.alloc(node)
  514. }
  515. /// Renders an `rsx` call into the Base Scope's allocator.
  516. ///
  517. /// Useful when needing to render nodes from outside the VirtualDom, such as in a test.
  518. pub fn diff_vnodes<'a>(&'a self, old: &'a VNode<'a>, new: &'a VNode<'a>) -> Mutations<'a> {
  519. let mut machine = DiffState::new(&self.scopes);
  520. machine.stack.push(DiffInstruction::Diff { new, old });
  521. machine.stack.element_stack.push(ElementId(0));
  522. machine.stack.scope_stack.push(self.base_scope);
  523. machine.work(|| false);
  524. machine.mutations
  525. }
  526. /// Renders an `rsx` call into the Base Scope's allocator.
  527. ///
  528. /// Useful when needing to render nodes from outside the VirtualDom, such as in a test.
  529. pub fn create_vnodes<'a>(&'a self, left: Option<LazyNodes<'a, '_>>) -> Mutations<'a> {
  530. let nodes = self.render_vnodes(left);
  531. let mut machine = DiffState::new(&self.scopes);
  532. machine.stack.element_stack.push(ElementId(0));
  533. machine.stack.create_node(nodes, MountType::Append);
  534. machine.work(|| false);
  535. machine.mutations
  536. }
  537. /// Renders an `rsx` call into the Base Scope's allocator.
  538. ///
  539. /// Useful when needing to render nodes from outside the VirtualDom, such as in a test.
  540. pub fn diff_lazynodes<'a>(
  541. &'a self,
  542. left: Option<LazyNodes<'a, '_>>,
  543. right: Option<LazyNodes<'a, '_>>,
  544. ) -> (Mutations<'a>, Mutations<'a>) {
  545. let (old, new) = (self.render_vnodes(left), self.render_vnodes(right));
  546. let mut create = DiffState::new(&self.scopes);
  547. create.stack.scope_stack.push(self.base_scope);
  548. create.stack.element_stack.push(ElementId(0));
  549. create.stack.create_node(old, MountType::Append);
  550. create.work(|| false);
  551. let mut edit = DiffState::new(&self.scopes);
  552. edit.stack.scope_stack.push(self.base_scope);
  553. edit.stack.element_stack.push(ElementId(0));
  554. edit.stack.push(DiffInstruction::Diff { old, new });
  555. edit.work(&mut || false);
  556. (create.mutations, edit.mutations)
  557. }
  558. }
  559. pub enum SchedulerMsg {
  560. // events from the host
  561. UiEvent(UserEvent),
  562. // setstate
  563. Immediate(ScopeId),
  564. }
  565. #[derive(Debug)]
  566. pub struct UserEvent {
  567. /// The originator of the event trigger
  568. pub scope_id: ScopeId,
  569. pub priority: EventPriority,
  570. /// The optional real node associated with the trigger
  571. pub mounted_dom_id: Option<ElementId>,
  572. /// The event type IE "onclick" or "onmouseover"
  573. ///
  574. /// The name that the renderer will use to mount the listener.
  575. pub name: &'static str,
  576. /// Event Data
  577. pub event: Arc<dyn Any + Send + Sync>,
  578. }
  579. /// Priority of Event Triggers.
  580. ///
  581. /// Internally, Dioxus will abort work that's taking too long if new, more important work arrives. Unlike React, Dioxus
  582. /// won't be afraid to pause work or flush changes to the RealDOM. This is called "cooperative scheduling". Some Renderers
  583. /// implement this form of scheduling internally, however Dioxus will perform its own scheduling as well.
  584. ///
  585. /// The ultimate goal of the scheduler is to manage latency of changes, prioritizing "flashier" changes over "subtler" changes.
  586. ///
  587. /// React has a 5-tier priority system. However, they break things into "Continuous" and "Discrete" priority. For now,
  588. /// we keep it simple, and just use a 3-tier priority system.
  589. ///
  590. /// - NoPriority = 0
  591. /// - LowPriority = 1
  592. /// - NormalPriority = 2
  593. /// - UserBlocking = 3
  594. /// - HighPriority = 4
  595. /// - ImmediatePriority = 5
  596. ///
  597. /// We still have a concept of discrete vs continuous though - discrete events won't be batched, but continuous events will.
  598. /// This means that multiple "scroll" events will be processed in a single frame, but multiple "click" events will be
  599. /// flushed before proceeding. Multiple discrete events is highly unlikely, though.
  600. #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, PartialOrd, Ord)]
  601. pub enum EventPriority {
  602. /// Work that must be completed during the EventHandler phase.
  603. ///
  604. /// Currently this is reserved for controlled inputs.
  605. Immediate = 3,
  606. /// "High Priority" work will not interrupt other high priority work, but will interrupt medium and low priority work.
  607. ///
  608. /// This is typically reserved for things like user interaction.
  609. ///
  610. /// React calls these "discrete" events, but with an extra category of "user-blocking" (Immediate).
  611. High = 2,
  612. /// "Medium priority" work is generated by page events not triggered by the user. These types of events are less important
  613. /// than "High Priority" events and will take precedence over low priority events.
  614. ///
  615. /// This is typically reserved for VirtualEvents that are not related to keyboard or mouse input.
  616. ///
  617. /// React calls these "continuous" events (e.g. mouse move, mouse wheel, touch move, etc).
  618. Medium = 1,
  619. /// "Low Priority" work will always be preempted unless the work is significantly delayed, in which case it will be
  620. /// advanced to the front of the work queue until completed.
  621. ///
  622. /// The primary user of Low Priority work is the asynchronous work system (Suspense).
  623. ///
  624. /// This is considered "idle" work or "background" work.
  625. Low = 0,
  626. }