virtual_dom.rs 28 KB

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