virtual_dom.rs 28 KB

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