virtual_dom.rs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  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::diff::DiffState;
  5. use crate::innerlude::*;
  6. use futures_channel::mpsc::{UnboundedReceiver, UnboundedSender};
  7. use futures_util::{future::poll_fn, StreamExt};
  8. use fxhash::FxHashSet;
  9. use indexmap::IndexSet;
  10. use std::{collections::VecDeque, iter::FromIterator, task::Poll};
  11. /// A virtual node system that progresses user events and diffs UI trees.
  12. ///
  13. ///
  14. /// ## Guide
  15. ///
  16. /// Components are defined as simple functions that take [`Scope`] 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: ScopeArena,
  105. pending_messages: VecDeque<SchedulerMsg>,
  106. dirty_scopes: IndexSet<ScopeId>,
  107. channel: (
  108. UnboundedSender<SchedulerMsg>,
  109. UnboundedReceiver<SchedulerMsg>,
  110. ),
  111. }
  112. /// The type of message that can be sent to the scheduler.
  113. ///
  114. /// These messages control how the scheduler will process updates to the UI.
  115. #[derive(Debug)]
  116. pub enum SchedulerMsg {
  117. /// Events from the Renderer
  118. Event(UserEvent),
  119. /// Immediate updates from Components that mark them as dirty
  120. Immediate(ScopeId),
  121. /// New tasks from components that should be polled when the next poll is ready
  122. NewTask(ScopeId),
  123. }
  124. // Methods to create the VirtualDom
  125. impl VirtualDom {
  126. /// Create a new VirtualDom with a component that does not have special props.
  127. ///
  128. /// # Description
  129. ///
  130. /// Later, the props can be updated by calling "update" with a new set of props, causing a set of re-renders.
  131. ///
  132. /// This is useful when a component tree can be driven by external state (IE SSR) but it would be too expensive
  133. /// to toss out the entire tree.
  134. ///
  135. ///
  136. /// # Example
  137. /// ```rust, ignore
  138. /// fn Example(cx: Scope) -> Element {
  139. /// cx.render(rsx!( div { "hello world" } ))
  140. /// }
  141. ///
  142. /// let dom = VirtualDom::new(Example);
  143. /// ```
  144. ///
  145. /// Note: the VirtualDom is not progressed, you must either "run_with_deadline" or use "rebuild" to progress it.
  146. pub fn new(root: Component) -> Self {
  147. Self::new_with_props(root, ())
  148. }
  149. /// Create a new VirtualDom with the given properties for the root component.
  150. ///
  151. /// # Description
  152. ///
  153. /// Later, the props can be updated by calling "update" with a new set of props, causing a set of re-renders.
  154. ///
  155. /// This is useful when a component tree can be driven by external state (IE SSR) but it would be too expensive
  156. /// to toss out the entire tree.
  157. ///
  158. ///
  159. /// # Example
  160. /// ```rust, ignore
  161. /// #[derive(PartialEq, Props)]
  162. /// struct SomeProps {
  163. /// name: &'static str
  164. /// }
  165. ///
  166. /// fn Example(cx: Scope<SomeProps>) -> Element {
  167. /// cx.render(rsx!{ div{ "hello {cx.props.name}" } })
  168. /// }
  169. ///
  170. /// let dom = VirtualDom::new(Example);
  171. /// ```
  172. ///
  173. /// Note: the VirtualDom is not progressed on creation. You must either "run_with_deadline" or use "rebuild" to progress it.
  174. ///
  175. /// ```rust, ignore
  176. /// let mut dom = VirtualDom::new_with_props(Example, SomeProps { name: "jane" });
  177. /// let mutations = dom.rebuild();
  178. /// ```
  179. pub fn new_with_props<P>(root: Component<P>, root_props: P) -> Self
  180. where
  181. P: 'static,
  182. {
  183. Self::new_with_props_and_scheduler(
  184. root,
  185. root_props,
  186. futures_channel::mpsc::unbounded::<SchedulerMsg>(),
  187. )
  188. }
  189. /// Launch the VirtualDom, but provide your own channel for receiving and sending messages into the scheduler
  190. ///
  191. /// This is useful when the VirtualDom must be driven from outside a thread and it doesn't make sense to wait for the
  192. /// VirtualDom to be created just to retrieve its channel receiver.
  193. ///
  194. /// ```rust, ignore
  195. /// let channel = futures_channel::mpsc::unbounded();
  196. /// let dom = VirtualDom::new_with_scheduler(Example, (), channel);
  197. /// ```
  198. pub fn new_with_props_and_scheduler<P: 'static>(
  199. root: Component<P>,
  200. root_props: P,
  201. channel: (
  202. UnboundedSender<SchedulerMsg>,
  203. UnboundedReceiver<SchedulerMsg>,
  204. ),
  205. ) -> Self {
  206. let scopes = ScopeArena::new(channel.0.clone());
  207. scopes.new_with_key(
  208. root as ComponentPtr,
  209. Box::new(VComponentProps {
  210. props: root_props,
  211. memo: |_a, _b| unreachable!("memo on root will neve be run"),
  212. render_fn: root,
  213. }),
  214. None,
  215. ElementId(0),
  216. 0,
  217. );
  218. Self {
  219. scopes,
  220. channel,
  221. dirty_scopes: IndexSet::from_iter([ScopeId(0)]),
  222. pending_messages: VecDeque::new(),
  223. }
  224. }
  225. /// Get the [`Scope`] for the root component.
  226. ///
  227. /// This is useful for traversing the tree from the root for heuristics or alternative renderers that use Dioxus
  228. /// directly.
  229. ///
  230. /// This method is equivalent to calling `get_scope(ScopeId(0))`
  231. ///
  232. /// # Example
  233. ///
  234. /// ```rust, ignore
  235. /// let mut dom = VirtualDom::new(example);
  236. /// dom.rebuild();
  237. ///
  238. ///
  239. /// ```
  240. pub fn base_scope(&self) -> &ScopeState {
  241. self.get_scope(ScopeId(0)).unwrap()
  242. }
  243. /// Get the [`ScopeState`] for a component given its [`ScopeId`]
  244. ///
  245. /// # Example
  246. ///
  247. ///
  248. ///
  249. pub fn get_scope(&self, id: ScopeId) -> Option<&ScopeState> {
  250. self.scopes.get_scope(id)
  251. }
  252. /// Get an [`UnboundedSender`] handle to the channel used by the scheduler.
  253. ///
  254. /// # Example
  255. ///
  256. /// ```rust, ignore
  257. /// let dom = VirtualDom::new(App);
  258. /// let sender = dom.get_scheduler_channel();
  259. /// ```
  260. pub fn get_scheduler_channel(&self) -> UnboundedSender<SchedulerMsg> {
  261. self.channel.0.clone()
  262. }
  263. /// Try to get an element from its ElementId
  264. pub fn get_element(&self, id: ElementId) -> Option<&VNode> {
  265. self.scopes.get_element(id)
  266. }
  267. /// Add a new message to the scheduler queue directly.
  268. ///
  269. ///
  270. /// This method makes it possible to send messages to the scheduler from outside the VirtualDom without having to
  271. /// call `get_schedule_channel` and then `send`.
  272. ///
  273. /// # Example
  274. /// ```rust, ignore
  275. /// let dom = VirtualDom::new(App);
  276. /// dom.handle_message(SchedulerMsg::Immediate(ScopeId(0)));
  277. /// ```
  278. pub fn handle_message(&mut self, msg: SchedulerMsg) {
  279. if self.channel.0.unbounded_send(msg).is_ok() {
  280. self.process_all_messages();
  281. }
  282. }
  283. /// Check if the [`VirtualDom`] has any pending updates or work to be done.
  284. ///
  285. /// # Example
  286. ///
  287. /// ```rust, ignore
  288. /// let dom = VirtualDom::new(App);
  289. ///
  290. /// // the dom is "dirty" when it is started and must be rebuilt to get the first render
  291. /// assert!(dom.has_any_work());
  292. /// ```
  293. pub fn has_work(&self) -> bool {
  294. !(self.dirty_scopes.is_empty() && self.pending_messages.is_empty())
  295. }
  296. /// Wait for the scheduler to have any work.
  297. ///
  298. /// This method polls the internal future queue *and* the scheduler channel.
  299. /// To add work to the VirtualDom, insert a message via the scheduler channel.
  300. ///
  301. /// This lets us poll async tasks during idle periods without blocking the main thread.
  302. ///
  303. /// # Example
  304. ///
  305. /// ```rust, ignore
  306. /// let dom = VirtualDom::new(App);
  307. /// let sender = dom.get_scheduler_channel();
  308. /// ```
  309. pub async fn wait_for_work(&mut self) {
  310. loop {
  311. if !self.dirty_scopes.is_empty() && self.pending_messages.is_empty() {
  312. break;
  313. }
  314. if self.pending_messages.is_empty() {
  315. if self.scopes.tasks.has_tasks() {
  316. use futures_util::future::{select, Either};
  317. let scopes = &mut self.scopes;
  318. let task_poll = poll_fn(|cx| {
  319. //
  320. let mut any_pending = false;
  321. let mut tasks = scopes.tasks.tasks.borrow_mut();
  322. let mut to_remove = vec![];
  323. // this would be better served by retain
  324. for (id, task) in tasks.iter_mut() {
  325. if task.as_mut().poll(cx).is_ready() {
  326. to_remove.push(*id);
  327. } else {
  328. any_pending = true;
  329. }
  330. }
  331. for id in to_remove {
  332. tasks.remove(&id);
  333. }
  334. // Resolve the future if any singular task is ready
  335. match any_pending {
  336. true => Poll::Pending,
  337. false => Poll::Ready(()),
  338. }
  339. });
  340. match select(task_poll, self.channel.1.next()).await {
  341. Either::Left((_, _)) => {}
  342. Either::Right((msg, _)) => self.pending_messages.push_front(msg.unwrap()),
  343. }
  344. } else {
  345. self.pending_messages
  346. .push_front(self.channel.1.next().await.unwrap());
  347. }
  348. }
  349. // Move all the messages into the queue
  350. self.process_all_messages();
  351. }
  352. }
  353. /// Manually kick the VirtualDom to process any
  354. pub fn process_all_messages(&mut self) {
  355. // clear out the scheduler queue
  356. while let Ok(Some(msg)) = self.channel.1.try_next() {
  357. self.pending_messages.push_front(msg);
  358. }
  359. // process all the messages pulled from the queue
  360. while let Some(msg) = self.pending_messages.pop_back() {
  361. self.process_message(msg);
  362. }
  363. }
  364. /// Handle an individual message for the scheduler.
  365. ///
  366. /// This will either call an event listener or mark a component as dirty.
  367. pub fn process_message(&mut self, msg: SchedulerMsg) {
  368. match msg {
  369. SchedulerMsg::NewTask(_id) => {
  370. // uh, not sure? I think end up re-polling it anyways
  371. }
  372. SchedulerMsg::Event(event) => {
  373. if let Some(element) = event.element {
  374. self.scopes.call_listener_with_bubbling(event, element);
  375. }
  376. }
  377. SchedulerMsg::Immediate(s) => {
  378. self.dirty_scopes.insert(s);
  379. }
  380. }
  381. }
  382. /// Run the virtualdom with a deadline.
  383. ///
  384. /// This method will perform any outstanding diffing work and try to return as many mutations as possible before the
  385. /// deadline is reached. This method accepts a closure that returns `true` if the deadline has been reached. To wrap
  386. /// your future into a deadline, consider the `now_or_never` method from `future_utils`.
  387. ///
  388. /// ```rust, ignore
  389. /// let mut vdom = VirtualDom::new(App);
  390. ///
  391. /// let timeout = TimeoutFuture::from_ms(16);
  392. /// let deadline = || (&mut timeout).now_or_never();
  393. ///
  394. /// let mutations = vdom.work_with_deadline(deadline);
  395. /// ```
  396. ///
  397. /// This method is useful when needing to schedule the virtualdom around other tasks on the main thread to prevent
  398. /// "jank". It will try to finish whatever work it has by the deadline to free up time for other work.
  399. ///
  400. /// If the work is not finished by the deadline, Dioxus will store it for later and return when work_with_deadline
  401. /// is called again. This means you can ensure some level of free time on the VirtualDom's thread during the work phase.
  402. ///
  403. /// For use in the web, it is expected that this method will be called to be executed during "idle times" and the
  404. /// mutations to be applied during the "paint times" IE "animation frames". With this strategy, it is possible to craft
  405. /// entirely jank-free applications that perform a ton of work.
  406. ///
  407. /// In general use, Dioxus is plenty fast enough to not need to worry about this.
  408. ///
  409. /// # Example
  410. ///
  411. /// ```rust, ignore
  412. /// fn App(cx: Scope) -> Element {
  413. /// cx.render(rsx!( div {"hello"} ))
  414. /// }
  415. ///
  416. /// let mut dom = VirtualDom::new(App);
  417. ///
  418. /// loop {
  419. /// let mut timeout = TimeoutFuture::from_ms(16);
  420. /// let deadline = move || (&mut timeout).now_or_never();
  421. ///
  422. /// let mutations = dom.run_with_deadline(deadline).await;
  423. ///
  424. /// apply_mutations(mutations);
  425. /// }
  426. /// ```
  427. #[allow(unused)]
  428. pub fn work_with_deadline(&mut self, mut deadline: impl FnMut() -> bool) -> Vec<Mutations> {
  429. let mut committed_mutations = vec![];
  430. while !self.dirty_scopes.is_empty() {
  431. let scopes = &self.scopes;
  432. let mut diff_state = DiffState::new(scopes);
  433. let mut ran_scopes = FxHashSet::default();
  434. // Sort the scopes by height. Theoretically, we'll de-duplicate scopes by height
  435. self.dirty_scopes
  436. .retain(|id| scopes.get_scope(*id).is_some());
  437. self.dirty_scopes.sort_by(|a, b| {
  438. let h1 = scopes.get_scope(*a).unwrap().height;
  439. let h2 = scopes.get_scope(*b).unwrap().height;
  440. h1.cmp(&h2).reverse()
  441. });
  442. log::trace!("dirty_scopes: {:?}", self.dirty_scopes);
  443. if let Some(scopeid) = self.dirty_scopes.pop() {
  444. if !ran_scopes.contains(&scopeid) {
  445. ran_scopes.insert(scopeid);
  446. self.scopes.run_scope(scopeid);
  447. diff_state.diff_scope(scopeid);
  448. let DiffState { mutations, .. } = diff_state;
  449. log::trace!("succesffuly resolved scopes {:?}", mutations.dirty_scopes);
  450. for scope in &mutations.dirty_scopes {
  451. self.dirty_scopes.remove(scope);
  452. }
  453. if !mutations.edits.is_empty() {
  454. committed_mutations.push(mutations);
  455. }
  456. // todo: pause the diff machine
  457. // if diff_state.work(&mut deadline) {
  458. // let DiffState { mutations, .. } = diff_state;
  459. // for scope in &mutations.dirty_scopes {
  460. // self.dirty_scopes.remove(scope);
  461. // }
  462. // committed_mutations.push(mutations);
  463. // } else {
  464. // // leave the work in an incomplete state
  465. // //
  466. // // todo: we should store the edits and re-apply them later
  467. // // for now, we just dump the work completely (threadsafe)
  468. // return committed_mutations;
  469. // }
  470. }
  471. }
  472. }
  473. println!("committed_mutations: {:?}", committed_mutations);
  474. committed_mutations
  475. }
  476. /// Performs a *full* rebuild of the virtual dom, returning every edit required to generate the actual dom from scratch.
  477. ///
  478. /// The diff machine expects the RealDom's stack to be the root of the application.
  479. ///
  480. /// Tasks will not be polled with this method, nor will any events be processed from the event queue. Instead, the
  481. /// root component will be ran once and then diffed. All updates will flow out as mutations.
  482. ///
  483. /// All state stored in components will be completely wiped away.
  484. ///
  485. /// # Example
  486. /// ```rust, ignore
  487. /// static App: Component = |cx| cx.render(rsx!{ "hello world" });
  488. /// let mut dom = VirtualDom::new();
  489. /// let edits = dom.rebuild();
  490. ///
  491. /// apply_edits(edits);
  492. /// ```
  493. pub fn rebuild(&mut self) -> Mutations {
  494. let scope_id = ScopeId(0);
  495. let mut diff_state = DiffState::new(&self.scopes);
  496. self.scopes.run_scope(scope_id);
  497. diff_state.element_stack.push(ElementId(0));
  498. diff_state.scope_stack.push(scope_id);
  499. let node = self.scopes.fin_head(scope_id);
  500. let created = diff_state.create_node(node);
  501. diff_state.mutations.append_children(created as u32);
  502. self.dirty_scopes.clear();
  503. assert!(self.dirty_scopes.is_empty());
  504. diff_state.mutations
  505. }
  506. /// Compute a manual diff of the VirtualDom between states.
  507. ///
  508. /// This can be useful when state inside the DOM is remotely changed from the outside, but not propagated as an event.
  509. ///
  510. /// In this case, every component will be diffed, even if their props are memoized. This method is intended to be used
  511. /// to force an update of the DOM when the state of the app is changed outside of the app.
  512. ///
  513. /// To force a reflow of the entire VirtualDom, use `ScopeId(0)` as the scope_id.
  514. ///
  515. /// # Example
  516. /// ```rust, ignore
  517. /// #[derive(PartialEq, Props)]
  518. /// struct AppProps {
  519. /// value: Shared<&'static str>,
  520. /// }
  521. ///
  522. /// static App: Component<AppProps> = |cx| {
  523. /// let val = cx.value.borrow();
  524. /// cx.render(rsx! { div { "{val}" } })
  525. /// };
  526. ///
  527. /// let value = Rc::new(RefCell::new("Hello"));
  528. /// let mut dom = VirtualDom::new_with_props(App, AppProps { value: value.clone(), });
  529. ///
  530. /// let _ = dom.rebuild();
  531. ///
  532. /// *value.borrow_mut() = "goodbye";
  533. ///
  534. /// let edits = dom.diff();
  535. /// ```
  536. pub fn hard_diff(&mut self, scope_id: ScopeId) -> Mutations {
  537. let mut diff_machine = DiffState::new(&self.scopes);
  538. self.scopes.run_scope(scope_id);
  539. let (old, new) = (
  540. diff_machine.scopes.wip_head(scope_id),
  541. diff_machine.scopes.fin_head(scope_id),
  542. );
  543. diff_machine.force_diff = true;
  544. diff_machine.scope_stack.push(scope_id);
  545. let scope = diff_machine.scopes.get_scope(scope_id).unwrap();
  546. diff_machine.element_stack.push(scope.container);
  547. diff_machine.diff_node(old, new);
  548. diff_machine.mutations
  549. }
  550. /// Renders an `rsx` call into the Base Scope's allocator.
  551. ///
  552. /// Useful when needing to render nodes from outside the VirtualDom, such as in a test.
  553. ///
  554. /// ```rust, ignore
  555. /// fn Base(cx: Scope) -> Element {
  556. /// rsx!(cx, div {})
  557. /// }
  558. ///
  559. /// let dom = VirtualDom::new(Base);
  560. /// let nodes = dom.render_nodes(rsx!("div"));
  561. /// ```
  562. pub fn render_vnodes<'a>(&'a self, lazy_nodes: LazyNodes<'a, '_>) -> &'a VNode<'a> {
  563. let scope = self.scopes.get_scope(ScopeId(0)).unwrap();
  564. let frame = scope.wip_frame();
  565. let factory = NodeFactory::new(scope);
  566. let node = lazy_nodes.call(factory);
  567. frame.bump.alloc(node)
  568. }
  569. /// Renders an `rsx` call into the Base Scope's allocator.
  570. ///
  571. /// Useful when needing to render nodes from outside the VirtualDom, such as in a test.
  572. ///
  573. /// ```rust, ignore
  574. /// fn Base(cx: Scope) -> Element {
  575. /// rsx!(cx, div {})
  576. /// }
  577. ///
  578. /// let dom = VirtualDom::new(Base);
  579. /// let nodes = dom.render_nodes(rsx!("div"));
  580. /// ```
  581. pub fn diff_vnodes<'a>(&'a self, old: &'a VNode<'a>, new: &'a VNode<'a>) -> Mutations<'a> {
  582. let mut machine = DiffState::new(&self.scopes);
  583. machine.element_stack.push(ElementId(0));
  584. machine.scope_stack.push(ScopeId(0));
  585. machine.diff_node(old, new);
  586. machine.mutations
  587. }
  588. /// Renders an `rsx` call into the Base Scope's allocator.
  589. ///
  590. /// Useful when needing to render nodes from outside the VirtualDom, such as in a test.
  591. ///
  592. ///
  593. /// ```rust, ignore
  594. /// fn Base(cx: Scope) -> Element {
  595. /// rsx!(cx, div {})
  596. /// }
  597. ///
  598. /// let dom = VirtualDom::new(Base);
  599. /// let nodes = dom.render_nodes(rsx!("div"));
  600. /// ```
  601. pub fn create_vnodes<'a>(&'a self, nodes: LazyNodes<'a, '_>) -> Mutations<'a> {
  602. let mut machine = DiffState::new(&self.scopes);
  603. machine.scope_stack.push(ScopeId(0));
  604. machine.element_stack.push(ElementId(0));
  605. let node = self.render_vnodes(nodes);
  606. let created = machine.create_node(node);
  607. machine.mutations.append_children(created as u32);
  608. machine.mutations
  609. }
  610. /// Renders an `rsx` call into the Base Scopes's arena.
  611. ///
  612. /// Useful when needing to diff two rsx! calls from outside the VirtualDom, such as in a test.
  613. ///
  614. ///
  615. /// ```rust, ignore
  616. /// fn Base(cx: Scope) -> Element {
  617. /// rsx!(cx, div {})
  618. /// }
  619. ///
  620. /// let dom = VirtualDom::new(Base);
  621. /// let nodes = dom.render_nodes(rsx!("div"));
  622. /// ```
  623. pub fn diff_lazynodes<'a>(
  624. &'a self,
  625. left: LazyNodes<'a, '_>,
  626. right: LazyNodes<'a, '_>,
  627. ) -> (Mutations<'a>, Mutations<'a>) {
  628. let (old, new) = (self.render_vnodes(left), self.render_vnodes(right));
  629. let mut create = DiffState::new(&self.scopes);
  630. create.scope_stack.push(ScopeId(0));
  631. create.element_stack.push(ElementId(0));
  632. let created = create.create_node(old);
  633. create.mutations.append_children(created as u32);
  634. let mut edit = DiffState::new(&self.scopes);
  635. edit.scope_stack.push(ScopeId(0));
  636. edit.element_stack.push(ElementId(0));
  637. edit.diff_node(old, new);
  638. (create.mutations, edit.mutations)
  639. }
  640. }
  641. /*
  642. Scopes and ScopeArenas are never dropped internally.
  643. An app will always occupy as much memory as its biggest form.
  644. This means we need to handle all specifics of drop *here*. It's easier
  645. to reason about centralizing all the drop logic in one spot rather than scattered in each module.
  646. Broadly speaking, we want to use the remove_nodes method to clean up *everything*
  647. This will drop listeners, borrowed props, and hooks for all components.
  648. We need to do this in the correct order - nodes at the very bottom must be dropped first to release
  649. the borrow chain.
  650. Once the contents of the tree have been cleaned up, we can finally clean up the
  651. memory used by ScopeState itself.
  652. questions:
  653. should we build a vcomponent for the root?
  654. - probably - yes?
  655. - store the vcomponent in the root dom
  656. - 1: Use remove_nodes to use the ensure_drop_safety pathway to safely drop the tree
  657. - 2: Drop the ScopeState itself
  658. */
  659. impl Drop for VirtualDom {
  660. fn drop(&mut self) {
  661. // the best way to drop the dom is to replace the root scope with a dud
  662. // the diff infrastructure will then finish the rest
  663. let scope = self.scopes.get_scope(ScopeId(0)).unwrap();
  664. // todo: move the remove nodes method onto scopearena
  665. // this will clear *all* scopes *except* the root scope
  666. let mut machine = DiffState::new(&self.scopes);
  667. machine.remove_nodes([scope.root_node()], false);
  668. // Now, clean up the root scope
  669. // safety: there are no more references to the root scope
  670. let scope = unsafe { &mut *self.scopes.get_scope_raw(ScopeId(0)).unwrap() };
  671. scope.reset();
  672. // make sure there are no "live" components
  673. for (_, scopeptr) in self.scopes.scopes.get_mut().drain() {
  674. // safety: all scopes were made in the bump's allocator
  675. // They are never dropped until now. The only way to drop is through Box.
  676. let scope = unsafe { bumpalo::boxed::Box::from_raw(scopeptr) };
  677. drop(scope);
  678. }
  679. for scopeptr in self.scopes.free_scopes.get_mut().drain(..) {
  680. // safety: all scopes were made in the bump's allocator
  681. // They are never dropped until now. The only way to drop is through Box.
  682. let mut scope = unsafe { bumpalo::boxed::Box::from_raw(scopeptr) };
  683. scope.reset();
  684. drop(scope);
  685. }
  686. }
  687. }