virtual_dom.rs 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  1. //! # VirtualDOM Implementation for Rust
  2. //! This module provides the primary mechanics to create a hook-based, concurrent VDOM for Rust.
  3. //!
  4. //! In this file, multiple items are defined. This file is big, but should be documented well to
  5. //! navigate the innerworkings of the Dom. We try to keep these main mechanics in this file to limit
  6. //! the possible exposed API surface (keep fields private). This particular implementation of VDOM
  7. //! is extremely efficient, but relies on some unsafety under the hood to do things like manage
  8. //! micro-heaps for components. We are currently working on refactoring the safety out into safe(r)
  9. //! abstractions, but current tests (MIRI and otherwise) show no issues with the current implementation.
  10. //!
  11. //! Included is:
  12. //! - The [`VirtualDom`] itself
  13. //! - The [`Scope`] object for mangning component lifecycle
  14. //! - The [`ActiveFrame`] object for managing the Scope`s microheap
  15. //! - The [`Context`] object for exposing VirtualDOM API to components
  16. //! - The [`NodeFactory`] object for lazyily exposing the `Context` API to the nodebuilder API
  17. //! - The [`Hook`] object for exposing state management in components.
  18. //!
  19. //! This module includes just the barebones for a complete VirtualDOM API.
  20. //! Additional functionality is defined in the respective files.
  21. use crate::{arena::ScopeArena, innerlude::*};
  22. use bumpalo::Bump;
  23. use futures::FutureExt;
  24. use slotmap::DefaultKey;
  25. use slotmap::SlotMap;
  26. use std::{
  27. any::{Any, TypeId},
  28. cell::{Cell, RefCell},
  29. collections::{HashMap, HashSet, VecDeque},
  30. fmt::Debug,
  31. future::Future,
  32. ops::Deref,
  33. pin::Pin,
  34. rc::{Rc, Weak},
  35. };
  36. pub type ScopeIdx = DefaultKey;
  37. // pub type ScopeIdx = generational_arena::Index;
  38. /// An integrated virtual node system that progresses events and diffs UI trees.
  39. /// Differences are converted into patches which a renderer can use to draw the UI.
  40. pub struct VirtualDom {
  41. /// All mounted components are arena allocated to make additions, removals, and references easy to work with
  42. /// A generational arena is used to re-use slots of deleted scopes without having to resize the underlying arena.
  43. ///
  44. /// This is wrapped in an UnsafeCell because we will need to get mutable access to unique values in unique bump arenas
  45. /// and rusts's guartnees cannot prove that this is safe. We will need to maintain the safety guarantees manually.
  46. pub components: ScopeArena,
  47. /// The index of the root component
  48. /// Should always be the first (gen=0, id=0)
  49. pub base_scope: ScopeIdx,
  50. /// All components dump their updates into a queue to be processed
  51. pub(crate) event_queue: EventQueue,
  52. /// a strong allocation to the "caller" for the original component and its props
  53. #[doc(hidden)]
  54. _root_caller: Rc<OpaqueComponent>,
  55. // _root_caller: Rc<OpaqueComponent<'static>>,
  56. /// Type of the original cx. This is stored as TypeId so VirtualDom does not need to be generic.
  57. ///
  58. /// Whenver props need to be updated, an Error will be thrown if the new props do not
  59. /// match the props used to create the VirtualDom.
  60. #[doc(hidden)]
  61. _root_prop_type: std::any::TypeId,
  62. }
  63. /// The `RealDomNode` is an ID handle that corresponds to a foreign DOM node.
  64. ///
  65. /// "u64" was chosen for two reasons
  66. /// - 0 cost hashing
  67. /// - use with slotmap and other versioned slot arenas
  68. #[derive(Clone, Copy, Debug, PartialEq)]
  69. pub struct RealDomNode(pub u64);
  70. impl RealDomNode {
  71. pub fn new(id: u64) -> Self {
  72. Self(id)
  73. }
  74. pub fn empty() -> Self {
  75. Self(u64::MIN)
  76. }
  77. }
  78. // ======================================
  79. // Public Methods for the VirtualDom
  80. // ======================================
  81. impl VirtualDom {
  82. /// Create a new instance of the Dioxus Virtual Dom with no properties for the root component.
  83. ///
  84. /// This means that the root component must either consumes its own context, or statics are used to generate the page.
  85. /// The root component can access things like routing in its context.
  86. ///
  87. /// As an end-user, you'll want to use the Renderer's "new" method instead of this method.
  88. /// Directly creating the VirtualDOM is only useful when implementing a new renderer.
  89. ///
  90. ///
  91. /// ```ignore
  92. /// // Directly from a closure
  93. ///
  94. /// let dom = VirtualDom::new(|cx| cx.render(rsx!{ div {"hello world"} }));
  95. ///
  96. /// // or pass in...
  97. ///
  98. /// let root = |cx| {
  99. /// cx.render(rsx!{
  100. /// div {"hello world"}
  101. /// })
  102. /// }
  103. /// let dom = VirtualDom::new(root);
  104. ///
  105. /// // or directly from a fn
  106. ///
  107. /// fn Example(cx: Context<()>) -> VNode {
  108. /// cx.render(rsx!{ div{"hello world"} })
  109. /// }
  110. ///
  111. /// let dom = VirtualDom::new(Example);
  112. /// ```
  113. pub fn new(root: FC<()>) -> Self {
  114. Self::new_with_props(root, ())
  115. }
  116. /// Start a new VirtualDom instance with a dependent cx.
  117. /// Later, the props can be updated by calling "update" with a new set of props, causing a set of re-renders.
  118. ///
  119. /// This is useful when a component tree can be driven by external state (IE SSR) but it would be too expensive
  120. /// to toss out the entire tree.
  121. ///
  122. /// ```ignore
  123. /// // Directly from a closure
  124. ///
  125. /// let dom = VirtualDom::new(|cx| cx.render(rsx!{ div {"hello world"} }));
  126. ///
  127. /// // or pass in...
  128. ///
  129. /// let root = |cx| {
  130. /// cx.render(rsx!{
  131. /// div {"hello world"}
  132. /// })
  133. /// }
  134. /// let dom = VirtualDom::new(root);
  135. ///
  136. /// // or directly from a fn
  137. ///
  138. /// fn Example(cx: Context, props: &SomeProps) -> VNode {
  139. /// cx.render(rsx!{ div{"hello world"} })
  140. /// }
  141. ///
  142. /// let dom = VirtualDom::new(Example);
  143. /// ```
  144. pub fn new_with_props<P: Properties + 'static>(root: FC<P>, root_props: P) -> Self {
  145. let components = ScopeArena::new(SlotMap::new());
  146. // Normally, a component would be passed as a child in the RSX macro which automatically produces OpaqueComponents
  147. // Here, we need to make it manually, using an RC to force the Weak reference to stick around for the main scope.
  148. let _root_caller: Rc<OpaqueComponent> = Rc::new(move |scope| {
  149. // let _root_caller: Rc<OpaqueComponent<'static>> = Rc::new(move |scope| {
  150. // the lifetime of this closure is just as long as the lifetime on the scope reference
  151. // this closure moves root props (which is static) into this closure
  152. let props = unsafe { &*(&root_props as *const _) };
  153. root(Context { props, scope })
  154. });
  155. // Create a weak reference to the OpaqueComponent for the root scope to use as its render function
  156. let caller_ref = Rc::downgrade(&_root_caller);
  157. // Build a funnel for hooks to send their updates into. The `use_hook` method will call into the update funnel.
  158. let event_queue = EventQueue::default();
  159. let _event_queue = event_queue.clone();
  160. // Make the first scope
  161. // We don't run the component though, so renderers will need to call "rebuild" when they initialize their DOM
  162. let link = components.clone();
  163. let base_scope = components
  164. .with(|arena| {
  165. arena.insert_with_key(move |myidx| {
  166. let event_channel = _event_queue.new_channel(0, myidx);
  167. Scope::new(caller_ref, myidx, None, 0, event_channel, link, &[])
  168. })
  169. })
  170. .unwrap();
  171. Self {
  172. _root_caller,
  173. base_scope,
  174. event_queue,
  175. components,
  176. _root_prop_type: TypeId::of::<P>(),
  177. }
  178. }
  179. }
  180. // ======================================
  181. // Private Methods for the VirtualDom
  182. // ======================================
  183. impl VirtualDom {
  184. /// Performs a *full* rebuild of the virtual dom, returning every edit required to generate the actual dom rom scratch
  185. /// Currently this doesn't do what we want it to do
  186. pub fn rebuild<'s, Dom: RealDom<'s>>(&'s mut self, realdom: &mut Dom) -> Result<()> {
  187. let mut diff_machine = DiffMachine::new(
  188. realdom,
  189. &self.components,
  190. self.base_scope,
  191. self.event_queue.clone(),
  192. );
  193. // Schedule an update and then immediately call it on the root component
  194. // This is akin to a hook being called from a listener and requring a re-render
  195. // Instead, this is done on top-level component
  196. let base = self.components.try_get(self.base_scope)?;
  197. let update = &base.event_channel;
  198. update();
  199. self.progress_completely(&mut diff_machine)?;
  200. Ok(())
  201. }
  202. /// This method is the most sophisticated way of updating the virtual dom after an external event has been triggered.
  203. ///
  204. /// Given a synthetic event, the component that triggered the event, and the index of the callback, this runs the virtual
  205. /// dom to completion, tagging components that need updates, compressing events together, and finally emitting a single
  206. /// change list.
  207. ///
  208. /// If implementing an external renderer, this is the perfect method to combine with an async event loop that waits on
  209. /// listeners, something like this:
  210. ///
  211. /// ```ignore
  212. /// while let Ok(event) = receiver.recv().await {
  213. /// let edits = self.internal_dom.progress_with_event(event)?;
  214. /// for edit in &edits {
  215. /// patch_machine.handle_edit(edit);
  216. /// }
  217. /// }
  218. /// ```
  219. ///
  220. /// Note: this method is not async and does not provide suspense-like functionality. It is up to the renderer to provide the
  221. /// executor and handlers for suspense as show in the example.
  222. ///
  223. /// ```ignore
  224. /// let (sender, receiver) = channel::new();
  225. /// sender.send(EventTrigger::start());
  226. ///
  227. /// let mut dom = VirtualDom::new();
  228. /// dom.suspense_handler(|event| sender.send(event));
  229. ///
  230. /// while let Ok(diffs) = dom.progress_with_event(receiver.recv().await) {
  231. /// render(diffs);
  232. /// }
  233. ///
  234. /// ```
  235. //
  236. // Developer notes:
  237. // ----
  238. // This method has some pretty complex safety guarantees to uphold.
  239. // We interact with bump arenas, raw pointers, and use UnsafeCell to get a partial borrow of the arena.
  240. // The final EditList has edits that pull directly from the Bump Arenas which add significant complexity
  241. // in crafting a 100% safe solution with traditional lifetimes. Consider this method to be internally unsafe
  242. // but the guarantees provide a safe, fast, and efficient abstraction for the VirtualDOM updating framework.
  243. //
  244. // A good project would be to remove all unsafe from this crate and move the unsafety into safer abstractions.
  245. pub fn progress_with_event<'s, Dom: RealDom<'s>>(
  246. &'s mut self,
  247. realdom: &'_ mut Dom,
  248. trigger: EventTrigger,
  249. ) -> Result<()> {
  250. let id = trigger.component_id.clone();
  251. self.components.try_get_mut(id)?.call_listener(trigger)?;
  252. let mut diff_machine =
  253. DiffMachine::new(realdom, &self.components, id, self.event_queue.clone());
  254. self.progress_completely(&mut diff_machine)?;
  255. Ok(())
  256. }
  257. /// Consume the event queue, descending depth-first.
  258. /// Only ever run each component once.
  259. ///
  260. /// The DiffMachine logs its progress as it goes which might be useful for certain types of renderers.
  261. pub(crate) fn progress_completely<'a, 'bump, Dom: RealDom<'bump>>(
  262. &'bump self,
  263. diff_machine: &'_ mut DiffMachine<'a, 'bump, Dom>,
  264. ) -> Result<()> {
  265. // Add this component to the list of components that need to be difed
  266. // #[allow(unused_assignments)]
  267. // let mut cur_height: u32 = 0;
  268. // Now, there are events in the queue
  269. let mut updates = self.event_queue.0.as_ref().borrow_mut();
  270. // Order the nodes by their height, we want the nodes with the smallest depth on top
  271. // This prevents us from running the same component multiple times
  272. updates.sort_unstable();
  273. log::debug!("There are: {:#?} updates to be processed", updates.len());
  274. // Iterate through the triggered nodes (sorted by height) and begin to diff them
  275. for update in updates.drain(..) {
  276. log::debug!("Running updates for: {:#?}", update);
  277. // Make sure this isn't a node we've already seen, we don't want to double-render anything
  278. // If we double-renderer something, this would cause memory safety issues
  279. if diff_machine.seen_nodes.contains(&update.idx) {
  280. continue;
  281. }
  282. // Now, all the "seen nodes" are nodes that got notified by running this listener
  283. diff_machine.seen_nodes.insert(update.idx.clone());
  284. // Start a new mutable borrow to components
  285. // We are guaranteeed that this scope is unique because we are tracking which nodes have modified
  286. let cur_component = self.components.try_get_mut(update.idx).unwrap();
  287. // let inner: &'s mut _ = unsafe { &mut *self.components.0.borrow().arena.get() };
  288. // let cur_component = inner.get_mut(update.idx).unwrap();
  289. cur_component.run_scope()?;
  290. // diff_machine.change_list.load_known_root(1);
  291. let (old, new) = (cur_component.old_frame(), cur_component.next_frame());
  292. // let (old, new) = cur_component.get_frames_mut();
  293. diff_machine.diff_node(old, new);
  294. // cur_height = cur_component.height;
  295. // log::debug!(
  296. // "Processing update: {:#?} with height {}",
  297. // &update.idx,
  298. // cur_height
  299. // );
  300. }
  301. Ok(())
  302. }
  303. pub fn base_scope(&self) -> &Scope {
  304. let idx = self.base_scope;
  305. self.components.try_get(idx).unwrap()
  306. }
  307. }
  308. // TODO!
  309. // These impls are actually wrong. The DOM needs to have a mutex implemented.
  310. unsafe impl Sync for VirtualDom {}
  311. unsafe impl Send for VirtualDom {}
  312. /// Every component in Dioxus is represented by a `Scope`.
  313. ///
  314. /// Scopes contain the state for hooks, the component's props, and other lifecycle information.
  315. ///
  316. /// Scopes are allocated in a generational arena. As components are mounted/unmounted, they will replace slots of dead components.
  317. /// The actual contents of the hooks, though, will be allocated with the standard allocator. These should not allocate as frequently.
  318. pub struct Scope {
  319. // The parent's scope ID
  320. pub parent: Option<ScopeIdx>,
  321. // IDs of children that this scope has created
  322. // This enables us to drop the children and their children when this scope is destroyed
  323. pub(crate) descendents: RefCell<HashSet<ScopeIdx>>,
  324. child_nodes: &'static [VNode<'static>],
  325. // A reference to the list of components.
  326. // This lets us traverse the component list whenever we need to access our parent or children.
  327. arena_link: ScopeArena,
  328. pub shared_contexts: RefCell<HashMap<TypeId, Rc<dyn Any>>>,
  329. // Our own ID accessible from the component map
  330. pub arena_idx: ScopeIdx,
  331. pub height: u32,
  332. pub event_channel: Rc<dyn Fn() + 'static>,
  333. pub caller: Weak<OpaqueComponent>,
  334. pub hookidx: Cell<usize>,
  335. // ==========================
  336. // slightly unsafe stuff
  337. // ==========================
  338. // an internal, highly efficient storage of vnodes
  339. pub frames: ActiveFrame,
  340. // These hooks are actually references into the hook arena
  341. // These two could be combined with "OwningRef" to remove unsafe usage
  342. // or we could dedicate a tiny bump arena just for them
  343. // could also use ourborous
  344. hooks: RefCell<Vec<Hook>>,
  345. pub(crate) listener_idx: Cell<usize>,
  346. // Unsafety:
  347. // - is self-refenrential and therefore needs to point into the bump
  348. // Stores references into the listeners attached to the vnodes
  349. // NEEDS TO BE PRIVATE
  350. pub(crate) listeners: RefCell<Vec<(*const Cell<RealDomNode>, *const dyn Fn(VirtualEvent))>>,
  351. pub(crate) suspended_tasks: Vec<Box<dyn Future<Output = VNode<'static>>>>,
  352. // pub(crate) listeners: RefCell<nohash_hasher::IntMap<u32, *const dyn Fn(VirtualEvent)>>,
  353. // pub(crate) listeners: RefCell<Vec<*const dyn Fn(VirtualEvent)>>,
  354. // pub(crate) listeners: RefCell<Vec<*const dyn Fn(VirtualEvent)>>,
  355. // NoHashMap<RealDomNode, <*const dyn Fn(VirtualEvent)>
  356. // pub(crate) listeners: RefCell<Vec<*const dyn Fn(VirtualEvent)>>
  357. }
  358. // We need to pin the hook so it doesn't move as we initialize the list of hooks
  359. type Hook = Pin<Box<dyn std::any::Any>>;
  360. type EventChannel = Rc<dyn Fn()>;
  361. impl Scope {
  362. // we are being created in the scope of an existing component (where the creator_node lifetime comes into play)
  363. // we are going to break this lifetime by force in order to save it on ourselves.
  364. // To make sure that the lifetime isn't truly broken, we receive a Weak RC so we can't keep it around after the parent dies.
  365. // This should never happen, but is a good check to keep around
  366. //
  367. // Scopes cannot be made anywhere else except for this file
  368. // Therefore, their lifetimes are connected exclusively to the virtual dom
  369. pub fn new<'creator_node>(
  370. caller: Weak<OpaqueComponent>,
  371. arena_idx: ScopeIdx,
  372. parent: Option<ScopeIdx>,
  373. height: u32,
  374. event_channel: EventChannel,
  375. arena_link: ScopeArena,
  376. child_nodes: &'creator_node [VNode<'creator_node>],
  377. ) -> Self {
  378. log::debug!(
  379. "New scope created, height is {}, idx is {:?}",
  380. height,
  381. arena_idx
  382. );
  383. // The function to run this scope is actually located in the parent's bump arena.
  384. // Every time the parent is updated, that function is invalidated via double-buffering wiping the old frame.
  385. // If children try to run this invalid caller, it *will* result in UB.
  386. //
  387. // During the lifecycle progression process, this caller will need to be updated. Right now,
  388. // until formal safety abstractions are implemented, we will just use unsafe to "detach" the caller
  389. // lifetime from the bump arena, exposing ourselves to this potential for invalidation. Truthfully,
  390. // this is a bit of a hack, but will remain this way until we've figured out a cleaner solution.
  391. //
  392. // Not the best solution, so TODO on removing this in favor of a dedicated resource abstraction.
  393. let caller = unsafe {
  394. std::mem::transmute::<
  395. Weak<OpaqueComponent>,
  396. Weak<OpaqueComponent>,
  397. // Weak<OpaqueComponent<'creator_node>>,
  398. // Weak<OpaqueComponent<'static>>,
  399. >(caller)
  400. };
  401. let child_nodes = unsafe { std::mem::transmute(child_nodes) };
  402. Self {
  403. child_nodes,
  404. caller,
  405. parent,
  406. arena_idx,
  407. height,
  408. event_channel,
  409. arena_link,
  410. listener_idx: Default::default(),
  411. frames: ActiveFrame::new(),
  412. hooks: Default::default(),
  413. shared_contexts: Default::default(),
  414. listeners: Default::default(),
  415. hookidx: Default::default(),
  416. descendents: Default::default(),
  417. suspended_tasks: Default::default(),
  418. }
  419. }
  420. pub fn update_caller<'creator_node>(&mut self, caller: Weak<OpaqueComponent>) {
  421. // pub fn update_caller<'creator_node>(&mut self, caller: Weak<OpaqueComponent<'creator_node>>) {
  422. let broken_caller = unsafe {
  423. std::mem::transmute::<
  424. Weak<OpaqueComponent>,
  425. Weak<OpaqueComponent>,
  426. // Weak<OpaqueComponent<'creator_node>>,
  427. // Weak<OpaqueComponent<'static>>,
  428. >(caller)
  429. };
  430. self.caller = broken_caller;
  431. }
  432. pub fn update_children<'creator_node>(
  433. &mut self,
  434. child_nodes: &'creator_node [VNode<'creator_node>],
  435. ) {
  436. let child_nodes = unsafe { std::mem::transmute(child_nodes) };
  437. self.child_nodes = child_nodes;
  438. }
  439. /// Create a new context and run the component with references from the Virtual Dom
  440. /// This function downcasts the function pointer based on the stored props_type
  441. ///
  442. /// Props is ?Sized because we borrow the props and don't need to know the size. P (sized) is used as a marker (unsized)
  443. pub fn run_scope<'sel>(&'sel mut self) -> Result<()> {
  444. // Cycle to the next frame and then reset it
  445. // This breaks any latent references, invalidating every pointer referencing into it.
  446. self.frames.next().bump.reset();
  447. // Remove all the outdated listeners
  448. self.listeners.borrow_mut().clear();
  449. self.hookidx.set(0);
  450. self.listener_idx.set(0);
  451. let caller = self
  452. .caller
  453. .upgrade()
  454. .ok_or(Error::FatalInternal("Failed to get caller"))?;
  455. // Cast the caller ptr from static to one with our own reference
  456. let c2: &OpaqueComponent = caller.as_ref();
  457. let c3: &OpaqueComponent = unsafe { std::mem::transmute(c2) };
  458. self.frames.cur_frame_mut().head_node = unsafe { self.own_vnodes(c3) };
  459. Ok(())
  460. }
  461. // this is its own function so we can preciesly control how lifetimes flow
  462. unsafe fn own_vnodes<'a>(&'a self, f: &OpaqueComponent) -> VNode<'static> {
  463. let new_head: VNode<'a> = f(self);
  464. let out: VNode<'static> = std::mem::transmute(new_head);
  465. out
  466. }
  467. // A safe wrapper around calling listeners
  468. // calling listeners will invalidate the list of listeners
  469. // The listener list will be completely drained because the next frame will write over previous listeners
  470. pub fn call_listener(&mut self, trigger: EventTrigger) -> Result<()> {
  471. let EventTrigger {
  472. real_node_id,
  473. event,
  474. ..
  475. } = trigger;
  476. // todo: implement scanning for outdated events
  477. // Convert the raw ptr into an actual object
  478. // This operation is assumed to be safe
  479. log::debug!("Calling listeners! {:?}", self.listeners.borrow().len());
  480. let listners = self.listeners.borrow();
  481. let (_, listener) = listners
  482. .iter()
  483. .find(|(domptr, _)| {
  484. let p = unsafe { &**domptr };
  485. p.get() == real_node_id
  486. })
  487. .expect(&format!(
  488. "Failed to find real node with ID {:?}",
  489. real_node_id
  490. ));
  491. // TODO: Don'tdo a linear scan! Do a hashmap lookup! It'll be faster!
  492. unsafe {
  493. let listener_fn = &**listener;
  494. listener_fn(event);
  495. }
  496. Ok(())
  497. }
  498. pub fn next_frame<'bump>(&'bump self) -> &'bump VNode<'bump> {
  499. self.frames.current_head_node()
  500. }
  501. pub fn old_frame<'bump>(&'bump self) -> &'bump VNode<'bump> {
  502. self.frames.prev_head_node()
  503. }
  504. pub fn cur_frame(&self) -> &BumpFrame {
  505. self.frames.cur_frame()
  506. }
  507. pub fn root<'a>(&'a self) -> &'a VNode<'a> {
  508. &self.frames.cur_frame().head_node
  509. }
  510. }
  511. /// Components in Dioxus use the "Context" object to interact with their lifecycle.
  512. /// This lets components schedule updates, integrate hooks, and expose their context via the context api.
  513. ///
  514. /// Properties passed down from the parent component are also directly accessible via the exposed "props" field.
  515. ///
  516. /// ```ignore
  517. /// #[derive(Properties)]
  518. /// struct Props {
  519. /// name: String
  520. ///
  521. /// }
  522. ///
  523. /// fn example(cx: Context<Props>) -> VNode {
  524. /// html! {
  525. /// <div> "Hello, {cx.name}" </div>
  526. /// }
  527. /// }
  528. /// ```
  529. // todo: force lifetime of source into T as a valid lifetime too
  530. // it's definitely possible, just needs some more messing around
  531. pub struct Context<'src, T> {
  532. pub props: &'src T,
  533. pub scope: &'src Scope,
  534. }
  535. impl<'src, T> Copy for Context<'src, T> {}
  536. impl<'src, T> Clone for Context<'src, T> {
  537. fn clone(&self) -> Self {
  538. Self {
  539. props: self.props,
  540. scope: self.scope,
  541. }
  542. }
  543. }
  544. impl<'a, T> Deref for Context<'a, T> {
  545. type Target = &'a T;
  546. fn deref(&self) -> &Self::Target {
  547. &self.props
  548. }
  549. }
  550. impl<'src, T> Scoped<'src> for Context<'src, T> {
  551. fn get_scope(&self) -> &'src Scope {
  552. self.scope
  553. }
  554. }
  555. pub trait Scoped<'src>: Sized {
  556. fn get_scope(&self) -> &'src Scope;
  557. /// Access the children elements passed into the component
  558. fn children(&self) -> &'src [VNode<'src>] {
  559. // We're re-casting the nodes back out
  560. // They don't really have a static lifetime
  561. unsafe {
  562. let scope = self.get_scope();
  563. let nodes = scope.child_nodes;
  564. nodes
  565. }
  566. }
  567. /// Create a subscription that schedules a future render for the reference component
  568. fn schedule_update(&self) -> Rc<dyn Fn() + 'static> {
  569. self.get_scope().event_channel.clone()
  570. }
  571. fn schedule_effect(&self) -> Rc<dyn Fn() + 'static> {
  572. todo!()
  573. }
  574. fn schedule_layout_effect(&self) {
  575. todo!()
  576. }
  577. /// Take a lazy VNode structure and actually build it with the context of the VDom's efficient VNode allocator.
  578. ///
  579. /// This function consumes the context and absorb the lifetime, so these VNodes *must* be returned.
  580. ///
  581. /// ## Example
  582. ///
  583. /// ```ignore
  584. /// fn Component(cx: Context<()>) -> VNode {
  585. /// // Lazy assemble the VNode tree
  586. /// let lazy_tree = html! {<div> "Hello World" </div>};
  587. ///
  588. /// // Actually build the tree and allocate it
  589. /// cx.render(lazy_tree)
  590. /// }
  591. ///```
  592. fn render<F: FnOnce(NodeFactory<'src>) -> VNode<'src>>(
  593. self,
  594. lazy_nodes: LazyNodes<'src, F>,
  595. ) -> VNode<'src> {
  596. let scope_ref = self.get_scope();
  597. let listener_id = &scope_ref.listener_idx;
  598. lazy_nodes.into_vnode(NodeFactory {
  599. scope_ref,
  600. listener_id,
  601. })
  602. }
  603. // impl<'scope> Context<'scope> {
  604. /// Store a value between renders
  605. ///
  606. /// - Initializer: closure used to create the initial hook state
  607. /// - Runner: closure used to output a value every time the hook is used
  608. /// - Cleanup: closure used to teardown the hook once the dom is cleaned up
  609. ///
  610. /// ```ignore
  611. /// // use_ref is the simplest way of storing a value between renders
  612. /// pub fn use_ref<T: 'static>(initial_value: impl FnOnce() -> T + 'static) -> Rc<RefCell<T>> {
  613. /// use_hook(
  614. /// || Rc::new(RefCell::new(initial_value())),
  615. /// |state| state.clone(),
  616. /// |_| {},
  617. /// )
  618. /// }
  619. /// ```
  620. fn use_hook<InternalHookState: 'static, Output: 'src>(
  621. &self,
  622. // The closure that builds the hook state
  623. initializer: impl FnOnce() -> InternalHookState,
  624. // The closure that takes the hookstate and returns some value
  625. runner: impl FnOnce(&'src mut InternalHookState) -> Output,
  626. // The closure that cleans up whatever mess is left when the component gets torn down
  627. // TODO: add this to the "clean up" group for when the component is dropped
  628. _cleanup: impl FnOnce(InternalHookState),
  629. ) -> Output {
  630. let scope = self.get_scope();
  631. let idx = scope.hookidx.get();
  632. // Grab out the hook list
  633. let mut hooks = scope.hooks.borrow_mut();
  634. // If the idx is the same as the hook length, then we need to add the current hook
  635. if idx >= hooks.len() {
  636. let new_state = initializer();
  637. hooks.push(Box::pin(new_state));
  638. }
  639. scope.hookidx.set(idx + 1);
  640. let stable_ref = hooks
  641. .get_mut(idx)
  642. .expect("Should not fail, idx is validated")
  643. .as_mut();
  644. let pinned_state = unsafe { Pin::get_unchecked_mut(stable_ref) };
  645. let internal_state = pinned_state.downcast_mut::<InternalHookState>().expect(
  646. r###"
  647. Unable to retrive the hook that was initialized in this index.
  648. Consult the `rules of hooks` to understand how to use hooks properly.
  649. You likely used the hook in a conditional. Hooks rely on consistent ordering between renders.
  650. Any function prefixed with "use" should not be called conditionally.
  651. "###,
  652. );
  653. // We extend the lifetime of the internal state
  654. runner(unsafe { &mut *(internal_state as *mut _) })
  655. }
  656. /// This hook enables the ability to expose state to children further down the VirtualDOM Tree.
  657. ///
  658. /// This is a hook, so it may not be called conditionally!
  659. ///
  660. /// The init method is ran *only* on first use, otherwise it is ignored. However, it uses hooks (ie `use`)
  661. /// so don't put it in a conditional.
  662. ///
  663. /// When the component is dropped, so is the context. Be aware of this behavior when consuming
  664. /// the context via Rc/Weak.
  665. ///
  666. ///
  667. ///
  668. fn use_create_context<T: 'static>(&self, init: impl Fn() -> T) {
  669. let scope = self.get_scope();
  670. let mut cxs = scope.shared_contexts.borrow_mut();
  671. let ty = TypeId::of::<T>();
  672. let is_initialized = self.use_hook(
  673. || false,
  674. |s| {
  675. let i = s.clone();
  676. *s = true;
  677. i
  678. },
  679. |_| {},
  680. );
  681. match (is_initialized, cxs.contains_key(&ty)) {
  682. // Do nothing, already initialized and already exists
  683. (true, true) => {}
  684. // Needs to be initialized
  685. (false, false) => {
  686. log::debug!("Initializing context...");
  687. cxs.insert(ty, Rc::new(init()));
  688. }
  689. _ => debug_assert!(false, "Cannot initialize two contexts of the same type"),
  690. }
  691. }
  692. /// There are hooks going on here!
  693. fn use_context<T: 'static>(&self) -> &'src Rc<T> {
  694. self.try_use_context().unwrap()
  695. }
  696. /// Uses a context, storing the cached value around
  697. fn try_use_context<T: 'static>(&self) -> Result<&'src Rc<T>> {
  698. struct UseContextHook<C> {
  699. par: Option<Rc<C>>,
  700. we: Option<Weak<C>>,
  701. }
  702. self.use_hook(
  703. move || UseContextHook {
  704. par: None as Option<Rc<T>>,
  705. we: None as Option<Weak<T>>,
  706. },
  707. move |hook| {
  708. let scope = self.get_scope();
  709. let mut scope = Some(scope);
  710. if let Some(we) = &hook.we {
  711. if let Some(re) = we.upgrade() {
  712. hook.par = Some(re);
  713. return Ok(hook.par.as_ref().unwrap());
  714. }
  715. }
  716. let ty = TypeId::of::<T>();
  717. while let Some(inner) = scope {
  718. log::debug!("Searching {:#?} for valid shared_context", inner.arena_idx);
  719. let shared_contexts = inner.shared_contexts.borrow();
  720. if let Some(shared_cx) = shared_contexts.get(&ty) {
  721. log::debug!("found matching cx");
  722. let rc = shared_cx
  723. .clone()
  724. .downcast::<T>()
  725. .expect("Should not fail, already validated the type from the hashmap");
  726. hook.we = Some(Rc::downgrade(&rc));
  727. hook.par = Some(rc);
  728. return Ok(hook.par.as_ref().unwrap());
  729. } else {
  730. match inner.parent {
  731. Some(parent_id) => {
  732. let parent = inner
  733. .arena_link
  734. .try_get(parent_id)
  735. .map_err(|_| Error::FatalInternal("Failed to find parent"))?;
  736. scope = Some(parent);
  737. }
  738. None => return Err(Error::MissingSharedContext),
  739. }
  740. }
  741. }
  742. Err(Error::MissingSharedContext)
  743. },
  744. |_| {},
  745. )
  746. }
  747. fn suspend<Output: 'src, Fut: FnOnce(SuspendedContext, Output) -> VNode<'src> + 'src>(
  748. &self,
  749. fut: &'src mut Pin<Box<dyn Future<Output = Output> + 'static>>,
  750. callback: Fut,
  751. ) -> VNode<'src> {
  752. match fut.now_or_never() {
  753. Some(out) => {
  754. let suspended_cx = SuspendedContext {};
  755. let nodes = callback(suspended_cx, out);
  756. return nodes;
  757. }
  758. None => {
  759. // we need to register this task
  760. VNode::Suspended {
  761. real: Cell::new(RealDomNode::empty()),
  762. }
  763. }
  764. }
  765. }
  766. }
  767. #[derive(Clone)]
  768. pub struct SuspendedContext {}
  769. // impl SuspendedContext {
  770. // pub fn render<'a, F: for<'b, 'src> FnOnce(&'b NodeFactory<'src>) -> VNode<'src>>(
  771. // &self,
  772. // lazy_nodes: LazyNodes<F>,
  773. // ) -> VNode {
  774. // todo!()
  775. // }
  776. // }
  777. // ==================================================================================
  778. // Supporting structs for the above abstractions
  779. // ==================================================================================
  780. // We actually allocate the properties for components in their parent's properties
  781. // We then expose a handle to use those props for render in the form of "OpaqueComponent"
  782. pub type OpaqueComponent = dyn for<'b> Fn(&'b Scope) -> VNode<'b>;
  783. #[derive(PartialEq, Debug, Clone, Default)]
  784. pub struct EventQueue(pub Rc<RefCell<Vec<HeightMarker>>>);
  785. impl EventQueue {
  786. pub fn new_channel(&self, height: u32, idx: ScopeIdx) -> Rc<dyn Fn()> {
  787. let inner = self.clone();
  788. let marker = HeightMarker { height, idx };
  789. Rc::new(move || {
  790. log::debug!("channel updated {:#?}", marker);
  791. inner.0.as_ref().borrow_mut().push(marker)
  792. })
  793. }
  794. }
  795. /// A helper type that lets scopes be ordered by their height
  796. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  797. pub struct HeightMarker {
  798. pub idx: ScopeIdx,
  799. pub height: u32,
  800. }
  801. impl Ord for HeightMarker {
  802. fn cmp(&self, other: &Self) -> std::cmp::Ordering {
  803. self.height.cmp(&other.height)
  804. }
  805. }
  806. impl PartialOrd for HeightMarker {
  807. fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
  808. Some(self.cmp(other))
  809. }
  810. }
  811. #[derive(Debug, PartialEq, Hash)]
  812. pub struct ContextId {
  813. // Which component is the scope in
  814. original: ScopeIdx,
  815. // What's the height of the scope
  816. height: u32,
  817. // Which scope is it (in order)
  818. id: u32,
  819. }
  820. pub struct ActiveFrame {
  821. // We use a "generation" for users of contents in the bump frames to ensure their data isn't broken
  822. pub generation: RefCell<usize>,
  823. // The double-buffering situation that we will use
  824. pub frames: [BumpFrame; 2],
  825. }
  826. pub struct BumpFrame {
  827. pub bump: Bump,
  828. pub head_node: VNode<'static>,
  829. }
  830. impl ActiveFrame {
  831. pub fn new() -> Self {
  832. Self::from_frames(
  833. BumpFrame {
  834. bump: Bump::new(),
  835. head_node: VNode::text(""),
  836. },
  837. BumpFrame {
  838. bump: Bump::new(),
  839. head_node: VNode::text(""),
  840. },
  841. )
  842. }
  843. pub fn from_frames(a: BumpFrame, b: BumpFrame) -> Self {
  844. Self {
  845. generation: 0.into(),
  846. frames: [a, b],
  847. }
  848. }
  849. pub fn cur_frame(&self) -> &BumpFrame {
  850. match *self.generation.borrow() & 1 == 0 {
  851. true => &self.frames[0],
  852. false => &self.frames[1],
  853. }
  854. }
  855. pub fn cur_frame_mut(&mut self) -> &mut BumpFrame {
  856. match *self.generation.borrow() & 1 == 0 {
  857. true => &mut self.frames[0],
  858. false => &mut self.frames[1],
  859. }
  860. }
  861. pub fn current_head_node<'b>(&'b self) -> &'b VNode<'b> {
  862. let raw_node = match *self.generation.borrow() & 1 == 0 {
  863. true => &self.frames[0],
  864. false => &self.frames[1],
  865. };
  866. // Give out our self-referential item with our own borrowed lifetime
  867. unsafe {
  868. let unsafe_head = &raw_node.head_node;
  869. let safe_node = std::mem::transmute::<&VNode<'static>, &VNode<'b>>(unsafe_head);
  870. safe_node
  871. }
  872. }
  873. pub fn prev_head_node<'b>(&'b self) -> &'b VNode<'b> {
  874. let raw_node = match *self.generation.borrow() & 1 != 0 {
  875. true => &self.frames[0],
  876. false => &self.frames[1],
  877. };
  878. // Give out our self-referential item with our own borrowed lifetime
  879. unsafe {
  880. let unsafe_head = &raw_node.head_node;
  881. let safe_node = std::mem::transmute::<&VNode<'static>, &VNode<'b>>(unsafe_head);
  882. safe_node
  883. }
  884. }
  885. pub fn next(&mut self) -> &mut BumpFrame {
  886. *self.generation.borrow_mut() += 1;
  887. if *self.generation.borrow() % 2 == 0 {
  888. &mut self.frames[0]
  889. } else {
  890. &mut self.frames[1]
  891. }
  892. }
  893. }