virtual_dom.rs 26 KB

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