virtual_dom.rs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  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(crate) fn next_frame<'bump>(&'bump self) -> &'bump VNode<'bump> {
  499. self.frames.current_head_node()
  500. }
  501. pub(crate) fn old_frame<'bump>(&'bump self) -> &'bump VNode<'bump> {
  502. self.frames.prev_head_node()
  503. }
  504. pub(crate) fn cur_frame(&self) -> &BumpFrame {
  505. self.frames.cur_frame()
  506. }
  507. pub(crate) fn root<'a>(&'a self) -> &'a VNode<'a> {
  508. &self.frames.cur_frame().head_node
  509. }
  510. /// Access the children elements passed into the component
  511. pub fn children(&self) -> &[VNode] {
  512. // We're re-casting the nodes back out
  513. // They don't really have a static lifetime
  514. unsafe {
  515. let scope = self;
  516. let nodes = scope.child_nodes;
  517. nodes
  518. }
  519. }
  520. /// Create a subscription that schedules a future render for the reference component
  521. pub fn schedule_update(&self) -> Rc<dyn Fn() + 'static> {
  522. self.event_channel.clone()
  523. }
  524. pub fn schedule_effect(&self) -> Rc<dyn Fn() + 'static> {
  525. todo!()
  526. }
  527. pub fn schedule_layout_effect(&self) {
  528. todo!()
  529. }
  530. /// Take a lazy VNode structure and actually build it with the context of the VDom's efficient VNode allocator.
  531. ///
  532. /// This function consumes the context and absorb the lifetime, so these VNodes *must* be returned.
  533. ///
  534. /// ## Example
  535. ///
  536. /// ```ignore
  537. /// fn Component(cx: Context<()>) -> VNode {
  538. /// // Lazy assemble the VNode tree
  539. /// let lazy_tree = html! {<div> "Hello World" </div>};
  540. ///
  541. /// // Actually build the tree and allocate it
  542. /// cx.render(lazy_tree)
  543. /// }
  544. ///```
  545. pub fn render<'src, F: FnOnce(NodeFactory<'src>) -> VNode<'src>>(
  546. &'src self,
  547. lazy_nodes: LazyNodes<'src, F>,
  548. ) -> VNode<'src> {
  549. let scope_ref = self;
  550. let listener_id = &scope_ref.listener_idx;
  551. lazy_nodes.into_vnode(NodeFactory {
  552. scope_ref,
  553. listener_id,
  554. })
  555. }
  556. /// Store a value between renders
  557. ///
  558. /// - Initializer: closure used to create the initial hook state
  559. /// - Runner: closure used to output a value every time the hook is used
  560. /// - Cleanup: closure used to teardown the hook once the dom is cleaned up
  561. ///
  562. /// ```ignore
  563. /// // use_ref is the simplest way of storing a value between renders
  564. /// pub fn use_ref<T: 'static>(initial_value: impl FnOnce() -> T + 'static) -> Rc<RefCell<T>> {
  565. /// use_hook(
  566. /// || Rc::new(RefCell::new(initial_value())),
  567. /// |state| state.clone(),
  568. /// |_| {},
  569. /// )
  570. /// }
  571. /// ```
  572. pub fn use_hook<'src, InternalHookState: 'static, Output: 'src>(
  573. &'src self,
  574. // The closure that builds the hook state
  575. initializer: impl FnOnce() -> InternalHookState,
  576. // The closure that takes the hookstate and returns some value
  577. runner: impl FnOnce(&'src mut InternalHookState) -> Output,
  578. // The closure that cleans up whatever mess is left when the component gets torn down
  579. // TODO: add this to the "clean up" group for when the component is dropped
  580. _cleanup: impl FnOnce(InternalHookState),
  581. ) -> Output {
  582. let scope = self;
  583. let idx = scope.hookidx.get();
  584. // Grab out the hook list
  585. let mut hooks = scope.hooks.borrow_mut();
  586. // If the idx is the same as the hook length, then we need to add the current hook
  587. if idx >= hooks.len() {
  588. let new_state = initializer();
  589. hooks.push(Box::pin(new_state));
  590. }
  591. scope.hookidx.set(idx + 1);
  592. let stable_ref = hooks
  593. .get_mut(idx)
  594. .expect("Should not fail, idx is validated")
  595. .as_mut();
  596. let pinned_state = unsafe { Pin::get_unchecked_mut(stable_ref) };
  597. let internal_state = pinned_state.downcast_mut::<InternalHookState>().expect(
  598. r###"
  599. Unable to retrive the hook that was initialized in this index.
  600. Consult the `rules of hooks` to understand how to use hooks properly.
  601. You likely used the hook in a conditional. Hooks rely on consistent ordering between renders.
  602. Any function prefixed with "use" should not be called conditionally.
  603. "###,
  604. );
  605. // We extend the lifetime of the internal state
  606. runner(unsafe { &mut *(internal_state as *mut _) })
  607. }
  608. /// This hook enables the ability to expose state to children further down the VirtualDOM Tree.
  609. ///
  610. /// This is a hook, so it may not be called conditionally!
  611. ///
  612. /// The init method is ran *only* on first use, otherwise it is ignored. However, it uses hooks (ie `use`)
  613. /// so don't put it in a conditional.
  614. ///
  615. /// When the component is dropped, so is the context. Be aware of this behavior when consuming
  616. /// the context via Rc/Weak.
  617. ///
  618. ///
  619. ///
  620. fn use_create_context<T: 'static>(&self, init: impl Fn() -> T) {
  621. let scope = self;
  622. let mut cxs = scope.shared_contexts.borrow_mut();
  623. let ty = TypeId::of::<T>();
  624. let is_initialized = self.use_hook(
  625. || false,
  626. |s| {
  627. let i = s.clone();
  628. *s = true;
  629. i
  630. },
  631. |_| {},
  632. );
  633. match (is_initialized, cxs.contains_key(&ty)) {
  634. // Do nothing, already initialized and already exists
  635. (true, true) => {}
  636. // Needs to be initialized
  637. (false, false) => {
  638. log::debug!("Initializing context...");
  639. cxs.insert(ty, Rc::new(init()));
  640. }
  641. _ => debug_assert!(false, "Cannot initialize two contexts of the same type"),
  642. }
  643. }
  644. /// There are hooks going on here!
  645. pub fn use_context<'src, T: 'static>(&'src self) -> &'src Rc<T> {
  646. self.try_use_context().unwrap()
  647. }
  648. /// Uses a context, storing the cached value around
  649. pub fn try_use_context<'src, T: 'static>(&'src self) -> Result<&'src Rc<T>> {
  650. struct UseContextHook<C> {
  651. par: Option<Rc<C>>,
  652. we: Option<Weak<C>>,
  653. }
  654. self.use_hook(
  655. move || UseContextHook {
  656. par: None as Option<Rc<T>>,
  657. we: None as Option<Weak<T>>,
  658. },
  659. move |hook| {
  660. let mut scope = Some(self);
  661. if let Some(we) = &hook.we {
  662. if let Some(re) = we.upgrade() {
  663. hook.par = Some(re);
  664. return Ok(hook.par.as_ref().unwrap());
  665. }
  666. }
  667. let ty = TypeId::of::<T>();
  668. while let Some(inner) = scope {
  669. log::debug!("Searching {:#?} for valid shared_context", inner.arena_idx);
  670. let shared_contexts = inner.shared_contexts.borrow();
  671. if let Some(shared_cx) = shared_contexts.get(&ty) {
  672. log::debug!("found matching cx");
  673. let rc = shared_cx
  674. .clone()
  675. .downcast::<T>()
  676. .expect("Should not fail, already validated the type from the hashmap");
  677. hook.we = Some(Rc::downgrade(&rc));
  678. hook.par = Some(rc);
  679. return Ok(hook.par.as_ref().unwrap());
  680. } else {
  681. match inner.parent {
  682. Some(parent_id) => {
  683. let parent = inner
  684. .arena_link
  685. .try_get(parent_id)
  686. .map_err(|_| Error::FatalInternal("Failed to find parent"))?;
  687. scope = Some(parent);
  688. }
  689. None => return Err(Error::MissingSharedContext),
  690. }
  691. }
  692. }
  693. Err(Error::MissingSharedContext)
  694. },
  695. |_| {},
  696. )
  697. }
  698. pub fn suspend<
  699. 'src,
  700. Output: 'src,
  701. Fut: FnOnce(SuspendedContext, Output) -> VNode<'src> + 'src,
  702. >(
  703. &'src self,
  704. fut: &'src mut Pin<Box<dyn Future<Output = Output> + 'static>>,
  705. callback: Fut,
  706. ) -> VNode<'src> {
  707. match fut.now_or_never() {
  708. Some(out) => {
  709. let suspended_cx = SuspendedContext {};
  710. let nodes = callback(suspended_cx, out);
  711. return nodes;
  712. }
  713. None => {
  714. // we need to register this task
  715. VNode::Suspended {
  716. real: Cell::new(RealDomNode::empty()),
  717. }
  718. }
  719. }
  720. }
  721. }
  722. /// Components in Dioxus use the "Context" object to interact with their lifecycle.
  723. /// This lets components schedule updates, integrate hooks, and expose their context via the context api.
  724. ///
  725. /// Properties passed down from the parent component are also directly accessible via the exposed "props" field.
  726. ///
  727. /// ```ignore
  728. /// #[derive(Properties)]
  729. /// struct Props {
  730. /// name: String
  731. ///
  732. /// }
  733. ///
  734. /// fn example(cx: Context<Props>) -> VNode {
  735. /// html! {
  736. /// <div> "Hello, {cx.name}" </div>
  737. /// }
  738. /// }
  739. /// ```
  740. // todo: force lifetime of source into T as a valid lifetime too
  741. // it's definitely possible, just needs some more messing around
  742. pub struct Context<'src, T> {
  743. pub props: &'src T,
  744. pub scope: &'src Scope,
  745. }
  746. impl<'src, T> Copy for Context<'src, T> {}
  747. impl<'src, T> Clone for Context<'src, T> {
  748. fn clone(&self) -> Self {
  749. Self {
  750. props: self.props,
  751. scope: self.scope,
  752. }
  753. }
  754. }
  755. impl<'a, T> Deref for Context<'a, T> {
  756. type Target = &'a T;
  757. fn deref(&self) -> &Self::Target {
  758. &self.props
  759. }
  760. }
  761. /// The `Scoped` trait makes it slightly less cumbersome for hooks to use the underlying `Scope` without having to make
  762. /// their hooks generic over the [`Props`] type that [`Context`] is
  763. ///
  764. /// ## Example:
  765. ///
  766. /// ```
  767. /// fn use_raw<T>(cx: impl Scoped) -> &mut T {
  768. ///
  769. /// }
  770. /// ```
  771. ///
  772. pub trait Scoped<'src>: Sized + Clone + Copy {
  773. ///
  774. ///
  775. ///
  776. ///
  777. ///
  778. ///
  779. ///
  780. fn get_scope(self) -> &'src Scope;
  781. #[inline]
  782. fn children(self) -> &'src [VNode<'src>] {
  783. self.get_scope().children()
  784. }
  785. #[inline]
  786. fn schedule_update(self) -> Rc<dyn Fn() + 'static> {
  787. self.get_scope().schedule_update()
  788. }
  789. #[inline]
  790. fn use_hook<InternalHookState: 'static, Output: 'src>(
  791. self,
  792. initializer: impl FnOnce() -> InternalHookState,
  793. runner: impl FnOnce(&'src mut InternalHookState) -> Output,
  794. _cleanup: impl FnOnce(InternalHookState),
  795. ) -> Output {
  796. self.get_scope().use_hook(initializer, runner, _cleanup)
  797. }
  798. /// Take a lazy VNode structure and actually build it with the context of the VDom's efficient VNode allocator.
  799. ///
  800. /// This function consumes the context and absorb the lifetime, so these VNodes *must* be returned.
  801. ///
  802. /// ## Example
  803. ///
  804. /// ```ignore
  805. /// fn Component(cx: Context<()>) -> VNode {
  806. /// // Lazy assemble the VNode tree
  807. /// let lazy_tree = html! {<div> "Hello World" </div>};
  808. ///
  809. /// // Actually build the tree and allocate it
  810. /// cx.render(lazy_tree)
  811. /// }
  812. ///```
  813. #[inline]
  814. fn render<F: FnOnce(NodeFactory<'src>) -> VNode<'src>>(
  815. self,
  816. lazy_nodes: LazyNodes<'src, F>,
  817. ) -> VNode<'src> {
  818. self.get_scope().render(lazy_nodes)
  819. }
  820. }
  821. impl<'src, T> Scoped<'src> for Context<'src, T> {
  822. #[inline]
  823. fn get_scope(self) -> &'src Scope {
  824. self.scope
  825. }
  826. }
  827. #[derive(Clone)]
  828. pub struct SuspendedContext {}
  829. // impl SuspendedContext {
  830. // pub fn render<'a, F: for<'b, 'src> FnOnce(&'b NodeFactory<'src>) -> VNode<'src>>(
  831. // &self,
  832. // lazy_nodes: LazyNodes<F>,
  833. // ) -> VNode {
  834. // todo!()
  835. // }
  836. // }
  837. // ==================================================================================
  838. // Supporting structs for the above abstractions
  839. // ==================================================================================
  840. // We actually allocate the properties for components in their parent's properties
  841. // We then expose a handle to use those props for render in the form of "OpaqueComponent"
  842. pub type OpaqueComponent = dyn for<'b> Fn(&'b Scope) -> VNode<'b>;
  843. #[derive(PartialEq, Debug, Clone, Default)]
  844. pub struct EventQueue(pub Rc<RefCell<Vec<HeightMarker>>>);
  845. impl EventQueue {
  846. pub fn new_channel(&self, height: u32, idx: ScopeIdx) -> Rc<dyn Fn()> {
  847. let inner = self.clone();
  848. let marker = HeightMarker { height, idx };
  849. Rc::new(move || {
  850. log::debug!("channel updated {:#?}", marker);
  851. inner.0.as_ref().borrow_mut().push(marker)
  852. })
  853. }
  854. }
  855. /// A helper type that lets scopes be ordered by their height
  856. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  857. pub struct HeightMarker {
  858. pub idx: ScopeIdx,
  859. pub height: u32,
  860. }
  861. impl Ord for HeightMarker {
  862. fn cmp(&self, other: &Self) -> std::cmp::Ordering {
  863. self.height.cmp(&other.height)
  864. }
  865. }
  866. impl PartialOrd for HeightMarker {
  867. fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
  868. Some(self.cmp(other))
  869. }
  870. }
  871. #[derive(Debug, PartialEq, Hash)]
  872. pub struct ContextId {
  873. // Which component is the scope in
  874. original: ScopeIdx,
  875. // What's the height of the scope
  876. height: u32,
  877. // Which scope is it (in order)
  878. id: u32,
  879. }
  880. pub struct ActiveFrame {
  881. // We use a "generation" for users of contents in the bump frames to ensure their data isn't broken
  882. pub generation: RefCell<usize>,
  883. // The double-buffering situation that we will use
  884. pub frames: [BumpFrame; 2],
  885. }
  886. pub struct BumpFrame {
  887. pub bump: Bump,
  888. pub head_node: VNode<'static>,
  889. }
  890. impl ActiveFrame {
  891. pub fn new() -> Self {
  892. Self::from_frames(
  893. BumpFrame {
  894. bump: Bump::new(),
  895. head_node: VNode::text(""),
  896. },
  897. BumpFrame {
  898. bump: Bump::new(),
  899. head_node: VNode::text(""),
  900. },
  901. )
  902. }
  903. pub fn from_frames(a: BumpFrame, b: BumpFrame) -> Self {
  904. Self {
  905. generation: 0.into(),
  906. frames: [a, b],
  907. }
  908. }
  909. pub fn cur_frame(&self) -> &BumpFrame {
  910. match *self.generation.borrow() & 1 == 0 {
  911. true => &self.frames[0],
  912. false => &self.frames[1],
  913. }
  914. }
  915. pub fn cur_frame_mut(&mut self) -> &mut BumpFrame {
  916. match *self.generation.borrow() & 1 == 0 {
  917. true => &mut self.frames[0],
  918. false => &mut self.frames[1],
  919. }
  920. }
  921. pub fn current_head_node<'b>(&'b self) -> &'b VNode<'b> {
  922. let raw_node = match *self.generation.borrow() & 1 == 0 {
  923. true => &self.frames[0],
  924. false => &self.frames[1],
  925. };
  926. // Give out our self-referential item with our own borrowed lifetime
  927. unsafe {
  928. let unsafe_head = &raw_node.head_node;
  929. let safe_node = std::mem::transmute::<&VNode<'static>, &VNode<'b>>(unsafe_head);
  930. safe_node
  931. }
  932. }
  933. pub fn prev_head_node<'b>(&'b self) -> &'b VNode<'b> {
  934. let raw_node = match *self.generation.borrow() & 1 != 0 {
  935. true => &self.frames[0],
  936. false => &self.frames[1],
  937. };
  938. // Give out our self-referential item with our own borrowed lifetime
  939. unsafe {
  940. let unsafe_head = &raw_node.head_node;
  941. let safe_node = std::mem::transmute::<&VNode<'static>, &VNode<'b>>(unsafe_head);
  942. safe_node
  943. }
  944. }
  945. pub fn next(&mut self) -> &mut BumpFrame {
  946. *self.generation.borrow_mut() += 1;
  947. if *self.generation.borrow() % 2 == 0 {
  948. &mut self.frames[0]
  949. } else {
  950. &mut self.frames[1]
  951. }
  952. }
  953. }