virtual_dom.rs 35 KB

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