scopes.rs 35 KB

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