scopes.rs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  1. use crate::{innerlude::*, unsafe_utils::extend_vnode};
  2. use bumpalo::Bump;
  3. use futures_channel::mpsc::UnboundedSender;
  4. use fxhash::FxHashMap;
  5. use slab::Slab;
  6. use std::{
  7. any::{Any, TypeId},
  8. borrow::Borrow,
  9. cell::{Cell, RefCell},
  10. collections::HashMap,
  11. future::Future,
  12. pin::Pin,
  13. rc::Rc,
  14. };
  15. /// for traceability, we use the raw fn pointer to identify the function
  16. /// we can use this with the traceback crate to resolve funciton names
  17. pub(crate) type FcSlot = *mut std::os::raw::c_void;
  18. pub(crate) struct Heuristic {
  19. hook_arena_size: usize,
  20. node_arena_size: usize,
  21. }
  22. // a slab-like arena with stable references even when new scopes are allocated
  23. // uses a bump arena as a backing
  24. //
  25. // has an internal heuristics engine to pre-allocate arenas to the right size
  26. pub(crate) struct ScopeArena {
  27. pub scope_gen: Cell<usize>,
  28. pub bump: Bump,
  29. pub scopes: RefCell<FxHashMap<ScopeId, *mut ScopeState>>,
  30. pub heuristics: RefCell<FxHashMap<FcSlot, Heuristic>>,
  31. pub free_scopes: RefCell<Vec<*mut ScopeState>>,
  32. pub nodes: RefCell<Slab<*const VNode<'static>>>,
  33. pub tasks: Rc<TaskQueue>,
  34. }
  35. impl ScopeArena {
  36. pub(crate) fn new(sender: UnboundedSender<SchedulerMsg>) -> Self {
  37. let bump = Bump::new();
  38. // allocate a container for the root element
  39. // this will *never* show up in the diffing process
  40. // todo: figure out why this is necessary. i forgot. whoops.
  41. let el = bump.alloc(VElement {
  42. tag: "root",
  43. namespace: None,
  44. key: None,
  45. id: Cell::new(Some(ElementId(0))),
  46. parent: Default::default(),
  47. listeners: &[],
  48. attributes: &[],
  49. children: &[],
  50. });
  51. let node = bump.alloc(VNode::Element(el));
  52. let mut nodes = Slab::new();
  53. let root_id = nodes.insert(unsafe { std::mem::transmute(node as *const _) });
  54. debug_assert_eq!(root_id, 0);
  55. Self {
  56. scope_gen: Cell::new(0),
  57. bump,
  58. scopes: RefCell::new(FxHashMap::default()),
  59. heuristics: RefCell::new(FxHashMap::default()),
  60. free_scopes: RefCell::new(Vec::new()),
  61. nodes: RefCell::new(nodes),
  62. tasks: TaskQueue::new(sender),
  63. }
  64. }
  65. /// Safety:
  66. /// - Obtaining a mutable reference to any Scope is unsafe
  67. /// - Scopes use interior mutability when sharing data into components
  68. pub(crate) fn get_scope(&self, id: ScopeId) -> Option<&ScopeState> {
  69. unsafe { self.scopes.borrow().get(&id).map(|f| &**f) }
  70. }
  71. pub(crate) fn get_scope_raw(&self, id: ScopeId) -> Option<*mut ScopeState> {
  72. self.scopes.borrow().get(&id).copied()
  73. }
  74. pub(crate) fn new_with_key(
  75. &self,
  76. fc_ptr: FcSlot,
  77. vcomp: Box<dyn AnyProps>,
  78. parent_scope: Option<ScopeId>,
  79. container: ElementId,
  80. subtree: u32,
  81. ) -> ScopeId {
  82. // Increment the ScopeId system. ScopeIDs are never reused
  83. let new_scope_id = ScopeId(self.scope_gen.get());
  84. self.scope_gen.set(self.scope_gen.get() + 1);
  85. // Get the height of the scope
  86. let height = parent_scope
  87. .map(|id| self.get_scope(id).map(|scope| scope.height))
  88. .flatten()
  89. .unwrap_or_default();
  90. let parent_scope = parent_scope.map(|f| self.get_scope_raw(f)).flatten();
  91. /*
  92. This scopearena aggressively reuses old scopes when possible.
  93. We try to minimize the new allocations for props/arenas.
  94. However, this will probably lead to some sort of fragmentation.
  95. I'm not exactly sure how to improve this today.
  96. */
  97. if let Some(old_scope) = self.free_scopes.borrow_mut().pop() {
  98. // reuse the old scope
  99. let scope = unsafe { &mut *old_scope };
  100. scope.props.get_mut().replace(vcomp);
  101. scope.parent_scope = parent_scope;
  102. scope.height = height;
  103. scope.subtree.set(subtree);
  104. scope.our_arena_idx = new_scope_id;
  105. scope.container = container;
  106. scope.fnptr = fc_ptr;
  107. let any_item = self.scopes.borrow_mut().insert(new_scope_id, scope);
  108. debug_assert!(any_item.is_none());
  109. } else {
  110. // else create a new scope
  111. let (node_capacity, hook_capacity) = self
  112. .heuristics
  113. .borrow()
  114. .get(&fc_ptr)
  115. .map(|h| (h.node_arena_size, h.hook_arena_size))
  116. .unwrap_or_default();
  117. self.scopes.borrow_mut().insert(
  118. new_scope_id,
  119. self.bump.alloc(ScopeState {
  120. container,
  121. our_arena_idx: new_scope_id,
  122. parent_scope,
  123. height,
  124. fnptr: fc_ptr,
  125. props: RefCell::new(Some(vcomp)),
  126. frames: [BumpFrame::new(node_capacity), BumpFrame::new(node_capacity)],
  127. // todo: subtrees
  128. subtree: Cell::new(0),
  129. is_subtree_root: Cell::new(false),
  130. generation: 0.into(),
  131. tasks: self.tasks.clone(),
  132. shared_contexts: Default::default(),
  133. items: RefCell::new(SelfReferentialItems {
  134. listeners: Default::default(),
  135. borrowed_props: Default::default(),
  136. }),
  137. hook_arena: Bump::new(),
  138. hook_vals: RefCell::new(Vec::with_capacity(hook_capacity)),
  139. hook_idx: Default::default(),
  140. }),
  141. );
  142. }
  143. new_scope_id
  144. }
  145. // Removes a scope and its descendents from the arena
  146. pub fn try_remove(&self, id: ScopeId) -> Option<()> {
  147. log::trace!("removing scope {:?}", id);
  148. self.ensure_drop_safety(id);
  149. // Safety:
  150. // - ensure_drop_safety ensures that no references to this scope are in use
  151. // - this raw pointer is removed from the map
  152. let scope = unsafe { &mut *self.scopes.borrow_mut().remove(&id).unwrap() };
  153. scope.reset();
  154. self.free_scopes.borrow_mut().push(scope);
  155. Some(())
  156. }
  157. pub fn reserve_node<'a>(&self, node: &'a VNode<'a>) -> ElementId {
  158. let mut els = self.nodes.borrow_mut();
  159. let entry = els.vacant_entry();
  160. let key = entry.key();
  161. let id = ElementId(key);
  162. let node = unsafe { extend_vnode(node) };
  163. entry.insert(node as *const _);
  164. id
  165. }
  166. pub fn update_node<'a>(&self, node: &'a VNode<'a>, id: ElementId) {
  167. let node = unsafe { extend_vnode(node) };
  168. let mut nodes = self.nodes.borrow_mut();
  169. let entry = nodes.get_mut(id.0);
  170. match entry {
  171. Some(_node) => *_node = node,
  172. None => panic!("cannot update node {}", id),
  173. }
  174. }
  175. pub fn collect_garbage(&self, id: ElementId) {
  176. // println!("collecting garbage for {:?}", id);
  177. // log::debug!("collecting garbage for {:?}", id);
  178. self.nodes.borrow_mut().remove(id.0);
  179. }
  180. /// This method cleans up any references to data held within our hook list. This prevents mutable aliasing from
  181. /// causing UB in our tree.
  182. ///
  183. /// This works by cleaning up our references from the bottom of the tree to the top. The directed graph of components
  184. /// essentially forms a dependency tree that we can traverse from the bottom to the top. As we traverse, we remove
  185. /// any possible references to the data in the hook list.
  186. ///
  187. /// References to hook data can only be stored in listeners and component props. During diffing, we make sure to log
  188. /// all listeners and borrowed props so we can clear them here.
  189. ///
  190. /// This also makes sure that drop order is consistent and predictable. All resources that rely on being dropped will
  191. /// be dropped.
  192. pub(crate) fn ensure_drop_safety(&self, scope_id: ScopeId) {
  193. // log::trace!("Ensuring drop safety for scope {:?}", scope_id);
  194. if let Some(scope) = self.get_scope(scope_id) {
  195. let mut items = scope.items.borrow_mut();
  196. // make sure we drop all borrowed props manually to guarantee that their drop implementation is called before we
  197. // run the hooks (which hold an &mut Reference)
  198. // recursively call ensure_drop_safety on all children
  199. items.borrowed_props.drain(..).for_each(|comp| {
  200. if let Some(scope_id) = comp.scope.get() {
  201. self.ensure_drop_safety(scope_id);
  202. }
  203. drop(comp.props.take());
  204. });
  205. // Now that all the references are gone, we can safely drop our own references in our listeners.
  206. items
  207. .listeners
  208. .drain(..)
  209. .for_each(|listener| drop(listener.callback.borrow_mut().take()));
  210. }
  211. }
  212. pub(crate) fn run_scope(&self, id: ScopeId) {
  213. // Cycle to the next frame and then reset it
  214. // This breaks any latent references, invalidating every pointer referencing into it.
  215. // Remove all the outdated listeners
  216. self.ensure_drop_safety(id);
  217. // todo: we *know* that this is aliased by the contents of the scope itself
  218. let scope = unsafe { &mut *self.get_scope_raw(id).expect("could not find scope") };
  219. // if cfg!(debug_assertions) {
  220. log::debug!("running scope {:?} symbol: {:?}", id, scope.fnptr);
  221. // todo: resolve frames properly
  222. backtrace::resolve(scope.fnptr, |symbol| {
  223. // backtrace::resolve(scope.fnptr as *mut std::os::raw::c_void, |symbol| {
  224. // panic!("asd");
  225. // log::trace!("Running scope {:?}, ptr {:?}", id, scope.fnptr);
  226. log::debug!("running scope {:?} symbol: {:?}", id, symbol.name());
  227. });
  228. // }
  229. // Safety:
  230. // - We dropped the listeners, so no more &mut T can be used while these are held
  231. // - All children nodes that rely on &mut T are replaced with a new reference
  232. scope.hook_idx.set(0);
  233. // book keeping to ensure safety around the borrowed data
  234. {
  235. // Safety:
  236. // - We've dropped all references to the wip bump frame with "ensure_drop_safety"
  237. unsafe { scope.reset_wip_frame() };
  238. let items = scope.items.borrow();
  239. // guarantee that we haven't screwed up - there should be no latent references anywhere
  240. debug_assert!(items.listeners.is_empty());
  241. debug_assert!(items.borrowed_props.is_empty());
  242. }
  243. // safety: this is definitely not dropped
  244. /*
  245. If the component returns None, then we fill in a placeholder node. This will wipe what was there.
  246. An alternate approach is to leave the Real Dom the same, but that can lead to safety issues and a lot more checks.
  247. Instead, we just treat the `None` as a shortcut to placeholder.
  248. If the developer wants to prevent a scope from updating, they should control its memoization instead.
  249. Also, the way we implement hooks allows us to cut rendering short before the next hook is recalled.
  250. I'm not sure if React lets you abort the component early, but we let you do that.
  251. */
  252. let props = scope.props.borrow();
  253. let render = props.as_ref().unwrap();
  254. if let Some(node) = render.render(scope) {
  255. let frame = scope.wip_frame();
  256. let node = frame.bump.alloc(node);
  257. frame.node.set(unsafe { extend_vnode(node) });
  258. } else {
  259. let frame = scope.wip_frame();
  260. let node = frame.bump.alloc(VNode::Placeholder(
  261. frame.bump.alloc(VPlaceholder { id: Default::default() }),
  262. ));
  263. frame.node.set(unsafe { extend_vnode(node) });
  264. }
  265. // make the "wip frame" contents the "finished frame"
  266. // any future dipping into completed nodes after "render" will go through "fin head"
  267. scope.cycle_frame();
  268. }
  269. pub fn call_listener_with_bubbling(&self, event: UserEvent, element: ElementId) {
  270. let nodes = self.nodes.borrow();
  271. let mut cur_el = Some(element);
  272. log::trace!("calling listener {:?}, {:?}", event, element);
  273. let state = Rc::new(BubbleState::new());
  274. while let Some(id) = cur_el.take() {
  275. if let Some(el) = nodes.get(id.0) {
  276. log::trace!("Found valid receiver element");
  277. let real_el = unsafe { &**el };
  278. if let VNode::Element(real_el) = real_el {
  279. for listener in real_el.listeners.borrow().iter() {
  280. if listener.event == event.name {
  281. log::trace!("Found valid receiver event");
  282. if state.canceled.get() {
  283. // stop bubbling if canceled
  284. break;
  285. }
  286. let mut cb = listener.callback.borrow_mut();
  287. if let Some(cb) = cb.as_mut() {
  288. // todo: arcs are pretty heavy to clone
  289. // we really want to convert arc to rc
  290. // unfortunately, the SchedulerMsg must be send/sync to be sent across threads
  291. // we could convert arc to rc internally or something
  292. (cb)(AnyEvent {
  293. bubble_state: state.clone(),
  294. data: event.data.clone(),
  295. });
  296. }
  297. }
  298. }
  299. cur_el = real_el.parent.get();
  300. }
  301. }
  302. }
  303. }
  304. // The head of the bumpframe is the first linked NodeLink
  305. pub fn wip_head(&self, id: ScopeId) -> &VNode {
  306. let scope = self.get_scope(id).unwrap();
  307. let frame = scope.wip_frame();
  308. let node = unsafe { &*frame.node.get() };
  309. unsafe { extend_vnode(node) }
  310. }
  311. // The head of the bumpframe is the first linked NodeLink
  312. pub fn fin_head(&self, id: ScopeId) -> &VNode {
  313. let scope = self.get_scope(id).unwrap();
  314. let frame = scope.fin_frame();
  315. let node = unsafe { &*frame.node.get() };
  316. unsafe { extend_vnode(node) }
  317. }
  318. pub fn root_node(&self, id: ScopeId) -> &VNode {
  319. self.fin_head(id)
  320. }
  321. // this is totally okay since all our nodes are always in a valid state
  322. pub fn get_element(&self, id: ElementId) -> Option<&VNode> {
  323. let ptr = self.nodes.borrow().get(id.0).cloned();
  324. match ptr {
  325. Some(ptr) => {
  326. let node = unsafe { &*ptr };
  327. Some(unsafe { extend_vnode(node) })
  328. }
  329. None => None,
  330. }
  331. }
  332. }
  333. /// Components in Dioxus use the "Context" object to interact with their lifecycle.
  334. ///
  335. /// This lets components access props, schedule updates, integrate hooks, and expose shared state.
  336. ///
  337. /// For the most part, the only method you should be using regularly is `render`.
  338. ///
  339. /// ## Example
  340. ///
  341. /// ```ignore
  342. /// #[derive(Props)]
  343. /// struct ExampleProps {
  344. /// name: String
  345. /// }
  346. ///
  347. /// fn Example(cx: Scope<ExampleProps>) -> Element {
  348. /// cx.render(rsx!{ div {"Hello, {cx.props.name}"} })
  349. /// }
  350. /// ```
  351. pub struct Scope<'a, P = ()> {
  352. pub scope: &'a ScopeState,
  353. pub props: &'a P,
  354. }
  355. impl<P> Copy for Scope<'_, P> {}
  356. impl<P> Clone for Scope<'_, P> {
  357. fn clone(&self) -> Self {
  358. Self { scope: self.scope, props: self.props }
  359. }
  360. }
  361. impl<'a, P> std::ops::Deref for Scope<'a, P> {
  362. // rust will auto deref again to the original 'a lifetime at the call site
  363. type Target = &'a ScopeState;
  364. fn deref(&self) -> &Self::Target {
  365. &self.scope
  366. }
  367. }
  368. /// A component's unique identifier.
  369. ///
  370. /// `ScopeId` is a `usize` that is unique across the entire VirtualDOM and across time. ScopeIDs will never be reused
  371. /// once a component has been unmounted.
  372. #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
  373. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
  374. pub struct ScopeId(pub usize);
  375. /// A task's unique identifier.
  376. ///
  377. /// `TaskId` is a `usize` that is unique across the entire VirtualDOM and across time. TaskIDs will never be reused
  378. /// once a Task has been completed.
  379. #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
  380. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
  381. pub struct TaskId(pub usize);
  382. /// Every component in Dioxus is represented by a `ScopeState`.
  383. ///
  384. /// Scopes contain the state for hooks, the component's props, and other lifecycle information.
  385. ///
  386. /// Scopes are allocated in a generational arena. As components are mounted/unmounted, they will replace slots of dead components.
  387. /// The actual contents of the hooks, though, will be allocated with the standard allocator. These should not allocate as frequently.
  388. ///
  389. /// We expose the `Scope` type so downstream users can traverse the Dioxus VirtualDOM for whatever
  390. /// use case they might have.
  391. pub struct ScopeState {
  392. pub(crate) parent_scope: Option<*mut ScopeState>,
  393. pub(crate) container: ElementId,
  394. pub(crate) our_arena_idx: ScopeId,
  395. pub(crate) height: u32,
  396. pub(crate) fnptr: FcSlot,
  397. // todo: subtrees
  398. pub(crate) is_subtree_root: Cell<bool>,
  399. pub(crate) subtree: Cell<u32>,
  400. pub(crate) props: RefCell<Option<Box<dyn AnyProps>>>,
  401. // nodes, items
  402. pub(crate) frames: [BumpFrame; 2],
  403. pub(crate) generation: Cell<u32>,
  404. pub(crate) items: RefCell<SelfReferentialItems<'static>>,
  405. // hooks
  406. pub(crate) hook_arena: Bump,
  407. pub(crate) hook_vals: RefCell<Vec<*mut dyn Any>>,
  408. pub(crate) hook_idx: Cell<usize>,
  409. // shared state -> todo: move this out of scopestate
  410. pub(crate) shared_contexts: RefCell<HashMap<TypeId, Rc<dyn Any>>>,
  411. pub(crate) tasks: Rc<TaskQueue>,
  412. }
  413. pub struct SelfReferentialItems<'a> {
  414. pub(crate) listeners: Vec<&'a Listener<'a>>,
  415. pub(crate) borrowed_props: Vec<&'a VComponent<'a>>,
  416. }
  417. // Public methods exposed to libraries and components
  418. impl ScopeState {
  419. /// Get the subtree ID that this scope belongs to.
  420. ///
  421. /// Each component has its own subtree ID - the root subtree has an ID of 0. This ID is used by the renderer to route
  422. /// the mutations to the correct window/portal/subtree.
  423. ///
  424. ///
  425. /// # Example
  426. ///
  427. /// ```rust, ignore
  428. /// let mut dom = VirtualDom::new(|cx| cx.render(rsx!{ div {} }));
  429. /// dom.rebuild();
  430. ///
  431. /// let base = dom.base_scope();
  432. ///
  433. /// assert_eq!(base.subtree(), 0);
  434. /// ```
  435. ///
  436. /// todo: enable
  437. pub(crate) fn _subtree(&self) -> u32 {
  438. self.subtree.get()
  439. }
  440. /// Create a new subtree with this scope as the root of the subtree.
  441. ///
  442. /// Each component has its own subtree ID - the root subtree has an ID of 0. This ID is used by the renderer to route
  443. /// the mutations to the correct window/portal/subtree.
  444. ///
  445. /// This method
  446. ///
  447. /// # Example
  448. ///
  449. /// ```rust, ignore
  450. /// fn App(cx: Scope) -> Element {
  451. /// rsx!(cx, div { "Subtree {id}"})
  452. /// };
  453. /// ```
  454. ///
  455. /// todo: enable subtree
  456. pub(crate) fn _create_subtree(&self) -> Option<u32> {
  457. if self.is_subtree_root.get() {
  458. None
  459. } else {
  460. todo!()
  461. }
  462. }
  463. /// Get the height of this Scope - IE the number of scopes above it.
  464. ///
  465. /// A Scope with a height of `0` is the root scope - there are no other scopes above it.
  466. ///
  467. /// # Example
  468. ///
  469. /// ```rust, ignore
  470. /// let mut dom = VirtualDom::new(|cx| cx.render(rsx!{ div {} }));
  471. /// dom.rebuild();
  472. ///
  473. /// let base = dom.base_scope();
  474. ///
  475. /// assert_eq!(base.height(), 0);
  476. /// ```
  477. pub fn height(&self) -> u32 {
  478. self.height
  479. }
  480. /// Get the Parent of this Scope within this Dioxus VirtualDOM.
  481. ///
  482. /// This ID is not unique across Dioxus VirtualDOMs or across time. IDs will be reused when components are unmounted.
  483. ///
  484. /// The base component will not have a parent, and will return `None`.
  485. ///
  486. /// # Example
  487. ///
  488. /// ```rust, ignore
  489. /// let mut dom = VirtualDom::new(|cx| cx.render(rsx!{ div {} }));
  490. /// dom.rebuild();
  491. ///
  492. /// let base = dom.base_scope();
  493. ///
  494. /// assert_eq!(base.parent(), None);
  495. /// ```
  496. pub fn parent(&self) -> Option<ScopeId> {
  497. // safety: the pointer to our parent is *always* valid thanks to the bump arena
  498. self.parent_scope.map(|p| unsafe { &*p }.our_arena_idx)
  499. }
  500. /// Get the ID of this Scope within this Dioxus VirtualDOM.
  501. ///
  502. /// This ID is not unique across Dioxus VirtualDOMs or across time. IDs will be reused when components are unmounted.
  503. ///
  504. /// # Example
  505. ///
  506. /// ```rust, ignore
  507. /// let mut dom = VirtualDom::new(|cx| cx.render(rsx!{ div {} }));
  508. /// dom.rebuild();
  509. /// let base = dom.base_scope();
  510. ///
  511. /// assert_eq!(base.scope_id(), 0);
  512. /// ```
  513. pub fn scope_id(&self) -> ScopeId {
  514. self.our_arena_idx
  515. }
  516. /// Create a subscription that schedules a future render for the reference component
  517. ///
  518. /// ## Notice: you should prefer using prepare_update and get_scope_id
  519. pub fn schedule_update(&self) -> Rc<dyn Fn() + 'static> {
  520. let (chan, id) = (self.tasks.sender.clone(), self.scope_id());
  521. Rc::new(move || {
  522. let _ = chan.unbounded_send(SchedulerMsg::Immediate(id));
  523. })
  524. }
  525. /// Schedule an update for any component given its ScopeId.
  526. ///
  527. /// A component's ScopeId can be obtained from `use_hook` or the [`ScopeState::scope_id`] method.
  528. ///
  529. /// This method should be used when you want to schedule an update for a component
  530. pub fn schedule_update_any(&self) -> Rc<dyn Fn(ScopeId)> {
  531. let chan = self.tasks.sender.clone();
  532. Rc::new(move |id| {
  533. let _ = chan.unbounded_send(SchedulerMsg::Immediate(id));
  534. })
  535. }
  536. /// Get the [`ScopeId`] of a mounted component.
  537. ///
  538. /// `ScopeId` is not unique for the lifetime of the VirtualDom - a ScopeId will be reused if a component is unmounted.
  539. pub fn needs_update(&self) {
  540. self.needs_update_any(self.scope_id())
  541. }
  542. /// Get the [`ScopeId`] of a mounted component.
  543. ///
  544. /// `ScopeId` is not unique for the lifetime of the VirtualDom - a ScopeId will be reused if a component is unmounted.
  545. pub fn needs_update_any(&self, id: ScopeId) {
  546. let _ = self
  547. .tasks
  548. .sender
  549. .unbounded_send(SchedulerMsg::Immediate(id));
  550. }
  551. /// Get the Root Node of this scope
  552. pub fn root_node(&self) -> &VNode {
  553. let node = unsafe { &*self.fin_frame().node.get() };
  554. unsafe { std::mem::transmute(node) }
  555. }
  556. /// This method enables the ability to expose state to children further down the VirtualDOM Tree.
  557. ///
  558. /// This is a "fundamental" operation and should only be called during initialization of a hook.
  559. ///
  560. /// For a hook that provides the same functionality, use `use_provide_context` and `use_consume_context` instead.
  561. ///
  562. /// When the component is dropped, so is the context. Be aware of this behavior when consuming
  563. /// the context via Rc/Weak.
  564. ///
  565. /// # Example
  566. ///
  567. /// ```rust, ignore
  568. /// struct SharedState(&'static str);
  569. ///
  570. /// static App: Component = |cx| {
  571. /// cx.use_hook(|_| cx.provide_context(SharedState("world")));
  572. /// rsx!(cx, Child {})
  573. /// }
  574. ///
  575. /// static Child: Component = |cx| {
  576. /// let state = cx.consume_state::<SharedState>();
  577. /// rsx!(cx, div { "hello {state.0}" })
  578. /// }
  579. /// ```
  580. pub fn provide_context<T: 'static>(&self, value: T) -> Rc<T> {
  581. let value = Rc::new(value);
  582. self.shared_contexts
  583. .borrow_mut()
  584. .insert(TypeId::of::<T>(), value.clone())
  585. .map(|f| f.downcast::<T>().ok())
  586. .flatten();
  587. value
  588. }
  589. /// Provide a context for the root component from anywhere in your app.
  590. ///
  591. ///
  592. /// # Example
  593. ///
  594. /// ```rust, ignore
  595. /// struct SharedState(&'static str);
  596. ///
  597. /// static App: Component = |cx| {
  598. /// cx.use_hook(|_| cx.provide_root_context(SharedState("world")));
  599. /// rsx!(cx, Child {})
  600. /// }
  601. ///
  602. /// static Child: Component = |cx| {
  603. /// let state = cx.consume_state::<SharedState>();
  604. /// rsx!(cx, div { "hello {state.0}" })
  605. /// }
  606. /// ```
  607. pub fn provide_root_context<T: 'static>(&self, value: T) -> Rc<T> {
  608. let value = Rc::new(value);
  609. // if we *are* the root component, then we can just provide the context directly
  610. if self.scope_id() == ScopeId(0) {
  611. self.shared_contexts
  612. .borrow_mut()
  613. .insert(TypeId::of::<T>(), value.clone())
  614. .map(|f| f.downcast::<T>().ok())
  615. .flatten();
  616. return value;
  617. }
  618. let mut search_parent = self.parent_scope;
  619. while let Some(parent) = search_parent.take() {
  620. let parent = unsafe { &*parent };
  621. if parent.scope_id() == ScopeId(0) {
  622. let exists = parent
  623. .shared_contexts
  624. .borrow_mut()
  625. .insert(TypeId::of::<T>(), value.clone());
  626. if exists.is_some() {
  627. log::warn!("Context already provided to parent scope - replacing it");
  628. }
  629. return value;
  630. }
  631. search_parent = parent.parent_scope;
  632. }
  633. unreachable!("all apps have a root scope")
  634. }
  635. /// Try to retrieve a SharedState with type T from the any parent Scope.
  636. pub fn consume_context<T: 'static>(&self) -> Option<Rc<T>> {
  637. if let Some(shared) = self.shared_contexts.borrow().get(&TypeId::of::<T>()) {
  638. Some(shared.clone().downcast::<T>().unwrap())
  639. } else {
  640. let mut search_parent = self.parent_scope;
  641. while let Some(parent_ptr) = search_parent {
  642. // safety: all parent pointers are valid thanks to the bump arena
  643. let parent = unsafe { &*parent_ptr };
  644. log::trace!("Searching parent scope {:?}", parent.scope_id());
  645. if let Some(shared) = parent.shared_contexts.borrow().get(&TypeId::of::<T>()) {
  646. return Some(shared.clone().downcast::<T>().unwrap());
  647. }
  648. search_parent = parent.parent_scope;
  649. }
  650. None
  651. }
  652. }
  653. /// Pushes the future onto the poll queue to be polled after the component renders.
  654. pub fn push_future(&self, fut: impl Future<Output = ()> + 'static) -> TaskId {
  655. // wake up the scheduler if it is sleeping
  656. self.tasks
  657. .sender
  658. .unbounded_send(SchedulerMsg::NewTask(self.our_arena_idx))
  659. .unwrap();
  660. self.tasks.push_fut(fut)
  661. }
  662. /// Spawns the future but does not return the TaskId
  663. pub fn spawn(&self, fut: impl Future<Output = ()> + 'static) {
  664. self.push_future(fut);
  665. }
  666. // todo: attach some state to the future to know if we should poll it
  667. pub fn remove_future(&self, id: TaskId) {
  668. self.tasks.remove_fut(id);
  669. }
  670. /// Take a lazy VNode structure and actually build it with the context of the VDom's efficient VNode allocator.
  671. ///
  672. /// This function consumes the context and absorb the lifetime, so these VNodes *must* be returned.
  673. ///
  674. /// ## Example
  675. ///
  676. /// ```ignore
  677. /// fn Component(cx: Scope<Props>) -> Element {
  678. /// // Lazy assemble the VNode tree
  679. /// let lazy_nodes = rsx!("hello world");
  680. ///
  681. /// // Actually build the tree and allocate it
  682. /// cx.render(lazy_tree)
  683. /// }
  684. ///```
  685. pub fn render<'src>(&'src self, rsx: LazyNodes<'src, '_>) -> Option<VNode<'src>> {
  686. Some(rsx.call(NodeFactory { scope: self, bump: &self.wip_frame().bump }))
  687. }
  688. /// Store a value between renders
  689. ///
  690. /// This is *the* foundational hook for all other hooks.
  691. ///
  692. /// - Initializer: closure used to create the initial hook state
  693. /// - Runner: closure used to output a value every time the hook is used
  694. ///
  695. /// To "cleanup" the hook, implement `Drop` on the stored hook value. Whenever the component is dropped, the hook
  696. /// will be dropped as well.
  697. ///
  698. /// # Example
  699. ///
  700. /// ```ignore
  701. /// // use_ref is the simplest way of storing a value between renders
  702. /// fn use_ref<T: 'static>(initial_value: impl FnOnce() -> T) -> &RefCell<T> {
  703. /// use_hook(|| Rc::new(RefCell::new(initial_value())))
  704. /// }
  705. /// ```
  706. #[allow(clippy::mut_from_ref)]
  707. pub fn use_hook<'src, State: 'static>(
  708. &'src self,
  709. initializer: impl FnOnce(usize) -> State,
  710. ) -> &'src mut State {
  711. let mut vals = self.hook_vals.borrow_mut();
  712. let hook_len = vals.len();
  713. let cur_idx = self.hook_idx.get();
  714. if cur_idx >= hook_len {
  715. vals.push(self.hook_arena.alloc(initializer(hook_len)));
  716. }
  717. vals
  718. .get(cur_idx)
  719. .and_then(|inn| {
  720. self.hook_idx.set(cur_idx + 1);
  721. let raw_box = unsafe { &mut **inn };
  722. raw_box.downcast_mut::<State>()
  723. })
  724. .expect(
  725. r###"
  726. Unable to retrieve the hook that was initialized at this index.
  727. Consult the `rules of hooks` to understand how to use hooks properly.
  728. You likely used the hook in a conditional. Hooks rely on consistent ordering between renders.
  729. Functions prefixed with "use" should never be called conditionally.
  730. "###,
  731. )
  732. }
  733. /// The "work in progress frame" represents the frame that is currently being worked on.
  734. pub(crate) fn wip_frame(&self) -> &BumpFrame {
  735. match self.generation.get() & 1 == 0 {
  736. true => &self.frames[0],
  737. false => &self.frames[1],
  738. }
  739. }
  740. /// Mutable access to the "work in progress frame" - used to clear it
  741. pub(crate) fn wip_frame_mut(&mut self) -> &mut BumpFrame {
  742. match self.generation.get() & 1 == 0 {
  743. true => &mut self.frames[0],
  744. false => &mut self.frames[1],
  745. }
  746. }
  747. /// Access to the frame where finalized nodes existed
  748. pub(crate) fn fin_frame(&self) -> &BumpFrame {
  749. match self.generation.get() & 1 == 1 {
  750. true => &self.frames[0],
  751. false => &self.frames[1],
  752. }
  753. }
  754. /// Reset this component's frame
  755. ///
  756. /// # Safety:
  757. ///
  758. /// This method breaks every reference of VNodes in the current frame.
  759. ///
  760. /// Calling reset itself is not usually a big deal, but we consider it important
  761. /// due to the complex safety guarantees we need to uphold.
  762. pub(crate) unsafe fn reset_wip_frame(&mut self) {
  763. self.wip_frame_mut().bump.reset();
  764. }
  765. /// Cycle to the next generation
  766. pub(crate) fn cycle_frame(&self) {
  767. self.generation.set(self.generation.get() + 1);
  768. }
  769. // todo: disable bookkeeping on drop (unncessary)
  770. pub(crate) fn reset(&mut self) {
  771. // first: book keaping
  772. self.hook_idx.set(0);
  773. self.parent_scope = None;
  774. self.generation.set(0);
  775. self.is_subtree_root.set(false);
  776. self.subtree.set(0);
  777. // next: shared context data
  778. self.shared_contexts.get_mut().clear();
  779. // next: reset the node data
  780. let SelfReferentialItems { borrowed_props, listeners } = self.items.get_mut();
  781. borrowed_props.clear();
  782. listeners.clear();
  783. self.frames[0].reset();
  784. self.frames[1].reset();
  785. // Free up the hook values
  786. self.hook_vals.get_mut().drain(..).for_each(|state| {
  787. let as_mut = unsafe { &mut *state };
  788. let boxed = unsafe { bumpalo::boxed::Box::from_raw(as_mut) };
  789. drop(boxed);
  790. });
  791. // Finally, clear the hook arena
  792. self.hook_arena.reset();
  793. }
  794. }
  795. pub(crate) struct BumpFrame {
  796. pub bump: Bump,
  797. pub node: Cell<*const VNode<'static>>,
  798. }
  799. impl BumpFrame {
  800. pub(crate) fn new(capacity: usize) -> Self {
  801. let bump = Bump::with_capacity(capacity);
  802. let node = &*bump.alloc(VText {
  803. text: "placeholdertext",
  804. id: Default::default(),
  805. is_static: false,
  806. });
  807. let node = bump.alloc(VNode::Text(unsafe { std::mem::transmute(node) }));
  808. let nodes = Cell::new(node as *const _);
  809. Self { bump, node: nodes }
  810. }
  811. pub(crate) fn reset(&mut self) {
  812. self.bump.reset();
  813. let node = self.bump.alloc(VText {
  814. text: "placeholdertext",
  815. id: Default::default(),
  816. is_static: false,
  817. });
  818. let node = self
  819. .bump
  820. .alloc(VNode::Text(unsafe { std::mem::transmute(node) }));
  821. self.node.set(node as *const _);
  822. }
  823. }
  824. pub(crate) struct TaskQueue {
  825. pub(crate) tasks: RefCell<FxHashMap<TaskId, InnerTask>>,
  826. gen: Cell<usize>,
  827. sender: UnboundedSender<SchedulerMsg>,
  828. }
  829. pub(crate) type InnerTask = Pin<Box<dyn Future<Output = ()>>>;
  830. impl TaskQueue {
  831. fn new(sender: UnboundedSender<SchedulerMsg>) -> Rc<Self> {
  832. Rc::new(Self { tasks: RefCell::new(FxHashMap::default()), gen: Cell::new(0), sender })
  833. }
  834. fn push_fut(&self, task: impl Future<Output = ()> + 'static) -> TaskId {
  835. let pinned = Box::pin(task);
  836. let id = self.gen.get();
  837. self.gen.set(id + 1);
  838. let tid = TaskId(id);
  839. self.tasks.borrow_mut().insert(tid, pinned);
  840. tid
  841. }
  842. fn remove_fut(&self, id: TaskId) {
  843. if let Ok(mut tasks) = self.tasks.try_borrow_mut() {
  844. let _ = tasks.remove(&id);
  845. } else {
  846. // todo: it should be okay to remote a fut while the queue is being polled
  847. // However, it's not currently possible to do that.
  848. log::trace!("Unable to remove task from task queue. This is probably a bug.");
  849. }
  850. }
  851. pub(crate) fn has_tasks(&self) -> bool {
  852. !self.tasks.borrow().is_empty()
  853. }
  854. }
  855. #[test]
  856. fn sizeof() {
  857. dbg!(std::mem::size_of::<ScopeState>());
  858. }