virtual_dom.rs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  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::{
  5. any_props::AnyProps,
  6. arena::ElementId,
  7. innerlude::{
  8. DirtyScope, ElementRef, ErrorBoundary, NoOpMutations, SchedulerMsg, ScopeState, VNodeMount,
  9. VProps, WriteMutations,
  10. },
  11. nodes::RenderReturn,
  12. nodes::{Template, TemplateId},
  13. runtime::{Runtime, RuntimeGuard},
  14. scopes::ScopeId,
  15. AttributeValue, ComponentFunction, Element, Event, Mutations,
  16. };
  17. use futures_util::StreamExt;
  18. use rustc_hash::{FxHashMap, FxHashSet};
  19. use slab::Slab;
  20. use std::{any::Any, collections::BTreeSet, rc::Rc};
  21. /// A virtual node system that progresses user events and diffs UI trees.
  22. ///
  23. /// ## Guide
  24. ///
  25. /// Components are defined as simple functions that take [`crate::properties::Properties`] and return an [`Element`].
  26. ///
  27. /// ```rust
  28. /// # use dioxus::prelude::*;
  29. ///
  30. /// #[derive(Props, PartialEq, Clone)]
  31. /// struct AppProps {
  32. /// title: String
  33. /// }
  34. ///
  35. /// fn app(cx: AppProps) -> Element {
  36. /// rsx!(
  37. /// div {"hello, {cx.title}"}
  38. /// )
  39. /// }
  40. /// ```
  41. ///
  42. /// Components may be composed to make complex apps.
  43. ///
  44. /// ```rust
  45. /// # #![allow(unused)]
  46. /// # use dioxus::prelude::*;
  47. ///
  48. /// # #[derive(Props, PartialEq, Clone)]
  49. /// # struct AppProps {
  50. /// # title: String
  51. /// # }
  52. ///
  53. /// static ROUTES: &str = "";
  54. ///
  55. /// #[component]
  56. /// fn app(cx: AppProps) -> Element {
  57. /// rsx!(
  58. /// NavBar { routes: ROUTES }
  59. /// Title { "{cx.title}" }
  60. /// Footer {}
  61. /// )
  62. /// }
  63. ///
  64. /// #[component]
  65. /// fn NavBar( routes: &'static str) -> Element {
  66. /// rsx! {
  67. /// div { "Routes: {routes}" }
  68. /// }
  69. /// }
  70. ///
  71. /// #[component]
  72. /// fn Footer() -> Element {
  73. /// rsx! { div { "Footer" } }
  74. /// }
  75. ///
  76. /// #[component]
  77. /// fn Title( children: Element) -> Element {
  78. /// rsx! {
  79. /// div { id: "title", {children} }
  80. /// }
  81. /// }
  82. /// ```
  83. ///
  84. /// To start an app, create a [`VirtualDom`] and call [`VirtualDom::rebuild`] to get the list of edits required to
  85. /// draw the UI.
  86. ///
  87. /// ```rust
  88. /// # use dioxus::prelude::*;
  89. /// # fn app() -> Element { rsx! { div {} } }
  90. ///
  91. /// let mut vdom = VirtualDom::new(app);
  92. /// let edits = vdom.rebuild_to_vec();
  93. /// ```
  94. ///
  95. /// To call listeners inside the VirtualDom, call [`VirtualDom::handle_event`] with the appropriate event data.
  96. ///
  97. /// ```rust, ignore
  98. /// vdom.handle_event(event);
  99. /// ```
  100. ///
  101. /// While no events are ready, call [`VirtualDom::wait_for_work`] to poll any futures inside the VirtualDom.
  102. ///
  103. /// ```rust, ignore
  104. /// vdom.wait_for_work().await;
  105. /// ```
  106. ///
  107. /// Once work is ready, call [`VirtualDom::render_with_deadline`] to compute the differences between the previous and
  108. /// current UI trees. This will return a [`Mutations`] object that contains Edits, Effects, and NodeRefs that need to be
  109. /// handled by the renderer.
  110. ///
  111. /// ```rust, ignore
  112. /// let mutations = vdom.work_with_deadline(tokio::time::sleep(Duration::from_millis(100)));
  113. ///
  114. /// for edit in mutations.edits {
  115. /// real_dom.apply(edit);
  116. /// }
  117. /// ```
  118. ///
  119. /// To not wait for suspense while diffing the VirtualDom, call [`VirtualDom::render_immediate`] or pass an immediately
  120. /// ready future to [`VirtualDom::render_with_deadline`].
  121. ///
  122. ///
  123. /// ## Building an event loop around Dioxus:
  124. ///
  125. /// Putting everything together, you can build an event loop around Dioxus by using the methods outlined above.
  126. /// ```rust, ignore
  127. /// #[component]
  128. /// fn app() -> Element {
  129. /// rsx! {
  130. /// div { "Hello World" }
  131. /// }
  132. /// }
  133. ///
  134. /// let dom = VirtualDom::new(app);
  135. ///
  136. /// real_dom.apply(dom.rebuild());
  137. ///
  138. /// loop {
  139. /// select! {
  140. /// _ = dom.wait_for_work() => {}
  141. /// evt = real_dom.wait_for_event() => dom.handle_event(evt),
  142. /// }
  143. ///
  144. /// real_dom.apply(dom.render_immediate());
  145. /// }
  146. /// ```
  147. ///
  148. /// ## Waiting for suspense
  149. ///
  150. /// Because Dioxus supports suspense, you can use it for server-side rendering, static site generation, and other usecases
  151. /// where waiting on portions of the UI to finish rendering is important. To wait for suspense, use the
  152. /// [`VirtualDom::render_with_deadline`] method:
  153. ///
  154. /// ```rust, ignore
  155. /// let dom = VirtualDom::new(app);
  156. ///
  157. /// let deadline = tokio::time::sleep(Duration::from_millis(100));
  158. /// let edits = dom.render_with_deadline(deadline).await;
  159. /// ```
  160. ///
  161. /// ## Use with streaming
  162. ///
  163. /// If not all rendering is done by the deadline, it might be worthwhile to stream the rest later. To do this, we
  164. /// suggest rendering with a deadline, and then looping between [`VirtualDom::wait_for_work`] and render_immediate until
  165. /// no suspended work is left.
  166. ///
  167. /// ```rust, ignore
  168. /// let dom = VirtualDom::new(app);
  169. ///
  170. /// let deadline = tokio::time::sleep(Duration::from_millis(20));
  171. /// let edits = dom.render_with_deadline(deadline).await;
  172. ///
  173. /// real_dom.apply(edits);
  174. ///
  175. /// while dom.has_suspended_work() {
  176. /// dom.wait_for_work().await;
  177. /// real_dom.apply(dom.render_immediate());
  178. /// }
  179. /// ```
  180. pub struct VirtualDom {
  181. pub(crate) scopes: Slab<ScopeState>,
  182. pub(crate) dirty_scopes: BTreeSet<DirtyScope>,
  183. // Maps a template path to a map of byte indexes to templates
  184. pub(crate) templates: FxHashMap<TemplateId, FxHashMap<usize, Template>>,
  185. // Templates changes that are queued for the next render
  186. pub(crate) queued_templates: Vec<Template>,
  187. // The element ids that are used in the renderer
  188. pub(crate) elements: Slab<Option<ElementRef>>,
  189. // Once nodes are mounted, the information about where they are mounted is stored here
  190. pub(crate) mounts: Slab<VNodeMount>,
  191. pub(crate) runtime: Rc<Runtime>,
  192. // Currently suspended scopes
  193. pub(crate) suspended_scopes: FxHashSet<ScopeId>,
  194. rx: futures_channel::mpsc::UnboundedReceiver<SchedulerMsg>,
  195. }
  196. impl VirtualDom {
  197. /// Create a new VirtualDom with a component that does not have special props.
  198. ///
  199. /// # Description
  200. ///
  201. /// Later, the props can be updated by calling "update" with a new set of props, causing a set of re-renders.
  202. ///
  203. /// This is useful when a component tree can be driven by external state (IE SSR) but it would be too expensive
  204. /// to toss out the entire tree.
  205. ///
  206. ///
  207. /// # Example
  208. /// ```rust, ignore
  209. /// fn Example() -> Element {
  210. /// rsx!( div { "hello world" } )
  211. /// }
  212. ///
  213. /// let dom = VirtualDom::new(Example);
  214. /// ```
  215. ///
  216. /// Note: the VirtualDom is not progressed, you must either "run_with_deadline" or use "rebuild" to progress it.
  217. pub fn new(app: fn() -> Element) -> Self {
  218. Self::new_with_props(app, ())
  219. }
  220. /// Create a new VirtualDom with the given properties for the root component.
  221. ///
  222. /// # Description
  223. ///
  224. /// Later, the props can be updated by calling "update" with a new set of props, causing a set of re-renders.
  225. ///
  226. /// This is useful when a component tree can be driven by external state (IE SSR) but it would be too expensive
  227. /// to toss out the entire tree.
  228. ///
  229. ///
  230. /// # Example
  231. /// ```rust, ignore
  232. /// #[derive(PartialEq, Props)]
  233. /// struct SomeProps {
  234. /// name: &'static str
  235. /// }
  236. ///
  237. /// fn Example(cx: SomeProps) -> Element {
  238. /// rsx!{ div { "hello {cx.name}" } }
  239. /// }
  240. ///
  241. /// let dom = VirtualDom::new(Example);
  242. /// ```
  243. ///
  244. /// Note: the VirtualDom is not progressed on creation. You must either "run_with_deadline" or use "rebuild" to progress it.
  245. ///
  246. /// ```rust, ignore
  247. /// let mut dom = VirtualDom::new_with_props(Example, SomeProps { name: "jane" });
  248. /// let mutations = dom.rebuild();
  249. /// ```
  250. pub fn new_with_props<P: Clone + 'static, M: 'static>(
  251. root: impl ComponentFunction<P, M>,
  252. root_props: P,
  253. ) -> Self {
  254. Self::new_with_component(VProps::new(root, |_, _| true, root_props, "root"))
  255. }
  256. /// Create a new virtualdom and build it immediately
  257. pub fn prebuilt(app: fn() -> Element) -> Self {
  258. let mut dom = Self::new(app);
  259. dom.rebuild_in_place();
  260. dom
  261. }
  262. /// Create a new VirtualDom with the given properties for the root component.
  263. ///
  264. /// # Description
  265. ///
  266. /// Later, the props can be updated by calling "update" with a new set of props, causing a set of re-renders.
  267. ///
  268. /// This is useful when a component tree can be driven by external state (IE SSR) but it would be too expensive
  269. /// to toss out the entire tree.
  270. ///
  271. ///
  272. /// # Example
  273. /// ```rust, ignore
  274. /// #[derive(PartialEq, Props)]
  275. /// struct SomeProps {
  276. /// name: &'static str
  277. /// }
  278. ///
  279. /// fn Example(cx: SomeProps) -> Element {
  280. /// rsx!{ div{ "hello {cx.name}" } }
  281. /// }
  282. ///
  283. /// let dom = VirtualDom::new(Example);
  284. /// ```
  285. ///
  286. /// Note: the VirtualDom is not progressed on creation. You must either "run_with_deadline" or use "rebuild" to progress it.
  287. ///
  288. /// ```rust, ignore
  289. /// let mut dom = VirtualDom::new_from_root(VComponent::new(Example, SomeProps { name: "jane" }, "Example"));
  290. /// let mutations = dom.rebuild();
  291. /// ```
  292. pub(crate) fn new_with_component(root: impl AnyProps + 'static) -> Self {
  293. let (tx, rx) = futures_channel::mpsc::unbounded();
  294. let mut dom = Self {
  295. rx,
  296. runtime: Runtime::new(tx),
  297. scopes: Default::default(),
  298. dirty_scopes: Default::default(),
  299. templates: Default::default(),
  300. queued_templates: Default::default(),
  301. elements: Default::default(),
  302. mounts: Default::default(),
  303. suspended_scopes: Default::default(),
  304. };
  305. let root = dom.new_scope(Box::new(root), "app");
  306. // Unlike react, we provide a default error boundary that just renders the error as a string
  307. root.state()
  308. .provide_context(Rc::new(ErrorBoundary::new_in_scope(ScopeId::ROOT)));
  309. // the root element is always given element ID 0 since it's the container for the entire tree
  310. dom.elements.insert(None);
  311. dom
  312. }
  313. /// Get the state for any scope given its ID
  314. ///
  315. /// This is useful for inserting or removing contexts from a scope, or rendering out its root node
  316. pub fn get_scope(&self, id: ScopeId) -> Option<&ScopeState> {
  317. self.scopes.get(id.0)
  318. }
  319. /// Get the single scope at the top of the VirtualDom tree that will always be around
  320. ///
  321. /// This scope has a ScopeId of 0 and is the root of the tree
  322. pub fn base_scope(&self) -> &ScopeState {
  323. self.get_scope(ScopeId::ROOT).unwrap()
  324. }
  325. /// Run a closure inside the dioxus runtime
  326. pub fn in_runtime<O>(&self, f: impl FnOnce() -> O) -> O {
  327. let _runtime = RuntimeGuard::new(self.runtime.clone());
  328. f()
  329. }
  330. /// Build the virtualdom with a global context inserted into the base scope
  331. ///
  332. /// This is useful for what is essentially dependency injection when building the app
  333. pub fn with_root_context<T: Clone + 'static>(self, context: T) -> Self {
  334. self.base_scope().state().provide_context(context);
  335. self
  336. }
  337. /// Build the virtualdom with a global context inserted into the base scope
  338. ///
  339. /// This method is useful for when you want to provide a context in your app without knowing its type
  340. pub fn insert_any_root_context(&mut self, context: Box<dyn Any>) {
  341. self.base_scope().state().provide_any_context(context);
  342. }
  343. /// Manually mark a scope as requiring a re-render
  344. ///
  345. /// Whenever the Runtime "works", it will re-render this scope
  346. pub fn mark_dirty(&mut self, id: ScopeId) {
  347. let Some(scope) = self.runtime.get_state(id) else {
  348. return;
  349. };
  350. tracing::trace!("Marking scope {:?} ({}) as dirty", id, scope.name);
  351. self.dirty_scopes.insert(DirtyScope {
  352. height: scope.height(),
  353. id,
  354. });
  355. }
  356. /// Call a listener inside the VirtualDom with data from outside the VirtualDom. **The ElementId passed in must be the id of an element with a listener, not a static node or a text node.**
  357. ///
  358. /// This method will identify the appropriate element. The data must match up with the listener declared. Note that
  359. /// this method does not give any indication as to the success of the listener call. If the listener is not found,
  360. /// nothing will happen.
  361. ///
  362. /// It is up to the listeners themselves to mark nodes as dirty.
  363. ///
  364. /// If you have multiple events, you can call this method multiple times before calling "render_with_deadline"
  365. pub fn handle_event(
  366. &mut self,
  367. name: &str,
  368. data: Rc<dyn Any>,
  369. element: ElementId,
  370. bubbles: bool,
  371. ) {
  372. let _runtime = RuntimeGuard::new(self.runtime.clone());
  373. if let Some(Some(parent_path)) = self.elements.get(element.0).copied() {
  374. if bubbles {
  375. self.handle_bubbling_event(Some(parent_path), name, Event::new(data, bubbles));
  376. } else {
  377. self.handle_non_bubbling_event(parent_path, name, Event::new(data, bubbles));
  378. }
  379. }
  380. }
  381. /// Wait for the scheduler to have any work.
  382. ///
  383. /// This method polls the internal future queue, waiting for suspense nodes, tasks, or other work. This completes when
  384. /// any work is ready. If multiple scopes are marked dirty from a task or a suspense tree is finished, this method
  385. /// will exit.
  386. ///
  387. /// This method is cancel-safe, so you're fine to discard the future in a select block.
  388. ///
  389. /// This lets us poll async tasks and suspended trees during idle periods without blocking the main thread.
  390. ///
  391. /// # Example
  392. ///
  393. /// ```rust, ignore
  394. /// let dom = VirtualDom::new(app);
  395. /// ```
  396. pub async fn wait_for_work(&mut self) {
  397. // And then poll the futures
  398. self.poll_tasks().await;
  399. }
  400. ///
  401. async fn poll_tasks(&mut self) {
  402. // Release the flush lock
  403. // This will cause all the flush wakers to immediately spring to life, which we will off with process_events
  404. self.runtime.release_flush_lock();
  405. loop {
  406. // Process all events - Scopes are marked dirty, etc
  407. // Sometimes when wakers fire we get a slew of updates at once, so its important that we drain this completely
  408. self.process_events();
  409. // Now that we have collected all queued work, we should check if we have any dirty scopes. If there are not, then we can poll any queued futures
  410. if !self.dirty_scopes.is_empty() {
  411. return;
  412. }
  413. // Make sure we set the runtime since we're running user code
  414. let _runtime = RuntimeGuard::new(self.runtime.clone());
  415. // Hold a lock to the flush sync to prevent tasks from running in the event we get an immediate
  416. // When we're doing awaiting the rx, the lock will be dropped and tasks waiting on the lock will get waked
  417. // We have to own the lock since poll_tasks is cancel safe - the future that this is running in might get dropped
  418. // and if we held the lock in the scope, the lock would also get dropped prematurely
  419. self.runtime.release_flush_lock();
  420. self.runtime.acquire_flush_lock();
  421. match self.rx.next().await.expect("channel should never close") {
  422. SchedulerMsg::Immediate(id) => self.mark_dirty(id),
  423. SchedulerMsg::TaskNotified(id) => _ = self.runtime.handle_task_wakeup(id),
  424. };
  425. }
  426. }
  427. /// Process all events in the queue until there are no more left
  428. pub fn process_events(&mut self) {
  429. let _runtime = RuntimeGuard::new(self.runtime.clone());
  430. // Prevent a task from deadlocking the runtime by repeatedly queueing itself
  431. while let Ok(Some(msg)) = self.rx.try_next() {
  432. match msg {
  433. SchedulerMsg::Immediate(id) => self.mark_dirty(id),
  434. SchedulerMsg::TaskNotified(task) => _ = self.runtime.handle_task_wakeup(task),
  435. }
  436. }
  437. }
  438. /// Replace a template at runtime. This will re-render all components that use this template.
  439. /// This is the primitive that enables hot-reloading.
  440. ///
  441. /// The caller must ensure that the template references the same dynamic attributes and nodes as the original template.
  442. ///
  443. /// This will only replace the the parent template, not any nested templates.
  444. pub fn replace_template(&mut self, template: Template) {
  445. self.register_template_first_byte_index(template);
  446. // iterating a slab is very inefficient, but this is a rare operation that will only happen during development so it's fine
  447. for (_, scope) in self.scopes.iter() {
  448. if let Some(RenderReturn::Ready(sync)) = scope.try_root_node() {
  449. if sync.template.get().name.rsplit_once(':').unwrap().0
  450. == template.name.rsplit_once(':').unwrap().0
  451. {
  452. let context = scope.state();
  453. let height = context.height;
  454. self.dirty_scopes.insert(DirtyScope {
  455. height,
  456. id: context.id,
  457. });
  458. }
  459. }
  460. }
  461. }
  462. /// Rebuild the virtualdom without handling any of the mutations
  463. ///
  464. /// This is useful for testing purposes and in cases where you render the output of the virtualdom without
  465. /// handling any of its mutations.
  466. pub fn rebuild_in_place(&mut self) {
  467. self.rebuild(&mut NoOpMutations);
  468. }
  469. /// [`VirtualDom::rebuild`] to a vector of mutations for testing purposes
  470. pub fn rebuild_to_vec(&mut self) -> Mutations {
  471. let mut mutations = Mutations::default();
  472. self.rebuild(&mut mutations);
  473. mutations
  474. }
  475. /// Performs a *full* rebuild of the virtual dom, returning every edit required to generate the actual dom from scratch.
  476. ///
  477. /// The mutations item expects the RealDom's stack to be the root of the application.
  478. ///
  479. /// Tasks will not be polled with this method, nor will any events be processed from the event queue. Instead, the
  480. /// root component will be ran once and then diffed. All updates will flow out as mutations.
  481. ///
  482. /// All state stored in components will be completely wiped away.
  483. ///
  484. /// Any templates previously registered will remain.
  485. ///
  486. /// # Example
  487. /// ```rust, ignore
  488. /// static app: Component = |cx| rsx!{ "hello world" };
  489. ///
  490. /// let mut dom = VirtualDom::new();
  491. /// let edits = dom.rebuild();
  492. ///
  493. /// apply_edits(edits);
  494. /// ```
  495. pub fn rebuild(&mut self, to: &mut impl WriteMutations) {
  496. self.flush_templates(to);
  497. let _runtime = RuntimeGuard::new(self.runtime.clone());
  498. let new_nodes = self.run_scope(ScopeId::ROOT);
  499. // Rebuilding implies we append the created elements to the root
  500. let m = self.create_scope(to, ScopeId::ROOT, new_nodes, None);
  501. to.append_children(ElementId(0), m);
  502. }
  503. /// Render whatever the VirtualDom has ready as fast as possible without requiring an executor to progress
  504. /// suspended subtrees.
  505. pub fn render_immediate(&mut self, to: &mut impl WriteMutations) {
  506. self.flush_templates(to);
  507. // Process any events that might be pending in the queue
  508. // Signals marked with .write() need a chance to be handled by the effect driver
  509. // This also processes futures which might progress into immediates
  510. self.process_events();
  511. // Next, diff any dirty scopes
  512. // We choose not to poll the deadline since we complete pretty quickly anyways
  513. while let Some(dirty) = self.dirty_scopes.pop_first() {
  514. // If the scope doesn't exist for whatever reason, then we should skip it
  515. if !self.scopes.contains(dirty.id.0) {
  516. continue;
  517. }
  518. {
  519. let _runtime = RuntimeGuard::new(self.runtime.clone());
  520. // Run the scope and get the mutations
  521. let new_nodes = self.run_scope(dirty.id);
  522. self.diff_scope(to, dirty.id, new_nodes);
  523. }
  524. }
  525. }
  526. /// [`Self::render_immediate`] to a vector of mutations for testing purposes
  527. pub fn render_immediate_to_vec(&mut self) -> Mutations {
  528. let mut mutations = Mutations::default();
  529. self.render_immediate(&mut mutations);
  530. mutations
  531. }
  532. /// Render the virtual dom, waiting for all suspense to be finished
  533. ///
  534. /// The mutations will be thrown out, so it's best to use this method for things like SSR that have async content
  535. ///
  536. /// We don't call "flush_sync" here since there's no sync work to be done. Futures will be progressed like usual,
  537. /// however any futures wating on flush_sync will remain pending
  538. pub async fn wait_for_suspense(&mut self) {
  539. loop {
  540. if self.suspended_scopes.is_empty() {
  541. break;
  542. }
  543. // Wait for a work to be ready (IE new suspense leaves to pop up)
  544. self.poll_tasks().await;
  545. // Render whatever work needs to be rendered, unlocking new futures and suspense leaves
  546. self.render_immediate(&mut NoOpMutations);
  547. }
  548. }
  549. /// Get the current runtime
  550. pub fn runtime(&self) -> Rc<Runtime> {
  551. self.runtime.clone()
  552. }
  553. /// Flush any queued template changes
  554. fn flush_templates(&mut self, to: &mut impl WriteMutations) {
  555. for template in self.queued_templates.drain(..) {
  556. to.register_template(template);
  557. }
  558. }
  559. /*
  560. ------------------------
  561. The algorithm works by walking through the list of dynamic attributes, checking their paths, and breaking when
  562. we find the target path.
  563. With the target path, we try and move up to the parent until there is no parent.
  564. Due to how bubbling works, we call the listeners before walking to the parent.
  565. If we wanted to do capturing, then we would accumulate all the listeners and call them in reverse order.
  566. ----------------------
  567. For a visual demonstration, here we present a tree on the left and whether or not a listener is collected on the
  568. right.
  569. | <-- yes (is ascendant)
  570. | | | <-- no (is not direct ascendant)
  571. | | <-- yes (is ascendant)
  572. | | | | | <--- target element, break early, don't check other listeners
  573. | | | <-- no, broke early
  574. | <-- no, broke early
  575. */
  576. fn handle_bubbling_event(
  577. &mut self,
  578. mut parent: Option<ElementRef>,
  579. name: &str,
  580. uievent: Event<dyn Any>,
  581. ) {
  582. // If the event bubbles, we traverse through the tree until we find the target element.
  583. // Loop through each dynamic attribute (in a depth first order) in this template before moving up to the template's parent.
  584. while let Some(path) = parent {
  585. let mut listeners = vec![];
  586. let el_ref = &self.mounts[path.mount.0].node;
  587. let node_template = el_ref.template.get();
  588. let target_path = path.path;
  589. // Accumulate listeners into the listener list bottom to top
  590. for (idx, attrs) in el_ref.dynamic_attrs.iter().enumerate() {
  591. let this_path = node_template.attr_paths[idx];
  592. for attr in attrs.iter() {
  593. // Remove the "on" prefix if it exists, TODO, we should remove this and settle on one
  594. if attr.name.trim_start_matches("on") == name
  595. && target_path.is_decendant(&this_path)
  596. {
  597. listeners.push(&attr.value);
  598. // Break if this is the exact target element.
  599. // This means we won't call two listeners with the same name on the same element. This should be
  600. // documented, or be rejected from the rsx! macro outright
  601. if target_path == this_path {
  602. break;
  603. }
  604. }
  605. }
  606. }
  607. // Now that we've accumulated all the parent attributes for the target element, call them in reverse order
  608. // We check the bubble state between each call to see if the event has been stopped from bubbling
  609. for listener in listeners.into_iter().rev() {
  610. if let AttributeValue::Listener(listener) = listener {
  611. self.runtime.rendering.set(false);
  612. listener.call(uievent.clone());
  613. self.runtime.rendering.set(true);
  614. if !uievent.propagates.get() {
  615. return;
  616. }
  617. }
  618. }
  619. let mount = el_ref.mount.get().as_usize();
  620. parent = mount.and_then(|id| self.mounts.get(id).and_then(|el| el.parent));
  621. }
  622. }
  623. /// Call an event listener in the simplest way possible without bubbling upwards
  624. fn handle_non_bubbling_event(&mut self, node: ElementRef, name: &str, uievent: Event<dyn Any>) {
  625. let el_ref = &self.mounts[node.mount.0].node;
  626. let node_template = el_ref.template.get();
  627. let target_path = node.path;
  628. for (idx, attr) in el_ref.dynamic_attrs.iter().enumerate() {
  629. let this_path = node_template.attr_paths[idx];
  630. for attr in attr.iter() {
  631. // Remove the "on" prefix if it exists, TODO, we should remove this and settle on one
  632. // Only call the listener if this is the exact target element.
  633. if attr.name.trim_start_matches("on") == name && target_path == this_path {
  634. if let AttributeValue::Listener(listener) = &attr.value {
  635. self.runtime.rendering.set(false);
  636. listener.call(uievent.clone());
  637. self.runtime.rendering.set(true);
  638. break;
  639. }
  640. }
  641. }
  642. }
  643. }
  644. }
  645. impl Drop for VirtualDom {
  646. fn drop(&mut self) {
  647. // Drop all scopes in order of height
  648. let mut scopes = self.scopes.drain().collect::<Vec<_>>();
  649. scopes.sort_by_key(|scope| scope.state().height);
  650. for scope in scopes.into_iter().rev() {
  651. drop(scope);
  652. }
  653. }
  654. }