scopes.rs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  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. 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: TaskQueue::new(sender),
  64. }
  65. }
  66. /// Safety:
  67. /// - Obtaining a mutable reference to any Scope is unsafe
  68. /// - Scopes use interior mutability when sharing data into components
  69. pub(crate) fn get_scope(&self, id: ScopeId) -> Option<&ScopeState> {
  70. unsafe { self.scopes.borrow().get(&id).map(|f| &**f) }
  71. }
  72. pub(crate) fn get_scope_raw(&self, id: ScopeId) -> Option<*mut ScopeState> {
  73. self.scopes.borrow().get(&id).copied()
  74. }
  75. pub(crate) fn new_with_key(
  76. &self,
  77. fc_ptr: ComponentPtr,
  78. vcomp: Box<dyn AnyProps>,
  79. parent_scope: Option<ScopeId>,
  80. container: ElementId,
  81. subtree: u32,
  82. ) -> ScopeId {
  83. // Increment the ScopeId system. ScopeIDs are never reused
  84. let new_scope_id = ScopeId(self.scope_gen.get());
  85. self.scope_gen.set(self.scope_gen.get() + 1);
  86. // Get the height of the scope
  87. let height = parent_scope
  88. .map(|id| self.get_scope(id).map(|scope| scope.height + 1))
  89. .flatten()
  90. .unwrap_or_default();
  91. let parent_scope = parent_scope.map(|f| self.get_scope_raw(f)).flatten();
  92. /*
  93. This scopearena aggressively reuses old scopes when possible.
  94. We try to minimize the new allocations for props/arenas.
  95. However, this will probably lead to some sort of fragmentation.
  96. I'm not exactly sure how to improve this today.
  97. */
  98. if let Some(old_scope) = self.free_scopes.borrow_mut().pop() {
  99. // reuse the old scope
  100. let scope = unsafe { &mut *old_scope };
  101. scope.container = container;
  102. scope.our_arena_idx = new_scope_id;
  103. scope.parent_scope = parent_scope;
  104. scope.height = height;
  105. scope.fnptr = fc_ptr;
  106. scope.props.get_mut().replace(vcomp);
  107. scope.subtree.set(subtree);
  108. scope.frames[0].reset();
  109. scope.frames[1].reset();
  110. scope.shared_contexts.get_mut().clear();
  111. scope.items.get_mut().listeners.clear();
  112. scope.items.get_mut().borrowed_props.clear();
  113. scope.hook_idx.set(0);
  114. scope.hook_vals.get_mut().clear();
  115. let any_item = self.scopes.borrow_mut().insert(new_scope_id, scope);
  116. debug_assert!(any_item.is_none());
  117. } else {
  118. // else create a new scope
  119. let (node_capacity, hook_capacity) = self
  120. .heuristics
  121. .borrow()
  122. .get(&fc_ptr)
  123. .map(|h| (h.node_arena_size, h.hook_arena_size))
  124. .unwrap_or_default();
  125. self.scopes.borrow_mut().insert(
  126. new_scope_id,
  127. self.bump.alloc(ScopeState {
  128. container,
  129. our_arena_idx: new_scope_id,
  130. parent_scope,
  131. height,
  132. fnptr: fc_ptr,
  133. props: RefCell::new(Some(vcomp)),
  134. frames: [BumpFrame::new(node_capacity), BumpFrame::new(node_capacity)],
  135. // todo: subtrees
  136. subtree: Cell::new(0),
  137. is_subtree_root: Cell::new(false),
  138. generation: 0.into(),
  139. tasks: self.tasks.clone(),
  140. shared_contexts: Default::default(),
  141. items: RefCell::new(SelfReferentialItems {
  142. listeners: Default::default(),
  143. borrowed_props: Default::default(),
  144. }),
  145. hook_arena: Bump::new(),
  146. hook_vals: RefCell::new(Vec::with_capacity(hook_capacity)),
  147. hook_idx: Default::default(),
  148. }),
  149. );
  150. }
  151. new_scope_id
  152. }
  153. // Removes a scope and its descendents from the arena
  154. pub fn try_remove(&self, id: ScopeId) -> Option<()> {
  155. log::trace!("removing scope {:?}", id);
  156. self.ensure_drop_safety(id);
  157. // Safety:
  158. // - ensure_drop_safety ensures that no references to this scope are in use
  159. // - this raw pointer is removed from the map
  160. let scope = unsafe { &mut *self.scopes.borrow_mut().remove(&id).unwrap() };
  161. scope.reset();
  162. self.free_scopes.borrow_mut().push(scope);
  163. Some(())
  164. }
  165. pub fn reserve_node<'a>(&self, node: &'a VNode<'a>) -> ElementId {
  166. let mut els = self.nodes.borrow_mut();
  167. let entry = els.vacant_entry();
  168. let key = entry.key();
  169. let id = ElementId(key);
  170. let node = unsafe { extend_vnode(node) };
  171. entry.insert(node as *const _);
  172. id
  173. }
  174. pub fn update_node<'a>(&self, node: &'a VNode<'a>, id: ElementId) {
  175. let node = unsafe { extend_vnode(node) };
  176. *self.nodes.borrow_mut().get_mut(id.0).unwrap() = node;
  177. }
  178. pub fn collect_garbage(&self, id: ElementId) {
  179. self.nodes.borrow_mut().remove(id.0);
  180. }
  181. /// This method cleans up any references to data held within our hook list. This prevents mutable aliasing from
  182. /// causing UB in our tree.
  183. ///
  184. /// This works by cleaning up our references from the bottom of the tree to the top. The directed graph of components
  185. /// essentially forms a dependency tree that we can traverse from the bottom to the top. As we traverse, we remove
  186. /// any possible references to the data in the hook list.
  187. ///
  188. /// References to hook data can only be stored in listeners and component props. During diffing, we make sure to log
  189. /// all listeners and borrowed props so we can clear them here.
  190. ///
  191. /// This also makes sure that drop order is consistent and predictable. All resources that rely on being dropped will
  192. /// be dropped.
  193. pub(crate) fn ensure_drop_safety(&self, scope_id: ScopeId) {
  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. log::trace!("running scope {:?} symbol: {:?}", id, scope.fnptr);
  220. // Safety:
  221. // - We dropped the listeners, so no more &mut T can be used while these are held
  222. // - All children nodes that rely on &mut T are replaced with a new reference
  223. scope.hook_idx.set(0);
  224. {
  225. // Safety:
  226. // - We've dropped all references to the wip bump frame with "ensure_drop_safety"
  227. unsafe { scope.reset_wip_frame() };
  228. let items = scope.items.borrow();
  229. // guarantee that we haven't screwed up - there should be no latent references anywhere
  230. debug_assert!(items.listeners.is_empty());
  231. debug_assert!(items.borrowed_props.is_empty());
  232. }
  233. /*
  234. If the component returns None, then we fill in a placeholder node. This will wipe what was there.
  235. An alternate approach is to leave the Real Dom the same, but that can lead to safety issues and a lot more checks.
  236. Instead, we just treat the `None` as a shortcut to placeholder.
  237. If the developer wants to prevent a scope from updating, they should control its memoization instead.
  238. Also, the way we implement hooks allows us to cut rendering short before the next hook is recalled.
  239. I'm not sure if React lets you abort the component early, but we let you do that.
  240. */
  241. let props = scope.props.borrow();
  242. let render = props.as_ref().unwrap();
  243. if let Some(node) = render.render(scope) {
  244. let frame = scope.wip_frame();
  245. let node = frame.bump.alloc(node);
  246. frame.node.set(unsafe { extend_vnode(node) });
  247. } else {
  248. let frame = scope.wip_frame();
  249. let node = frame
  250. .bump
  251. .alloc(VNode::Placeholder(frame.bump.alloc(VPlaceholder {
  252. id: Default::default(),
  253. })));
  254. frame.node.set(unsafe { extend_vnode(node) });
  255. }
  256. // make the "wip frame" contents the "finished frame"
  257. // any future dipping into completed nodes after "render" will go through "fin head"
  258. scope.cycle_frame();
  259. }
  260. pub fn call_listener_with_bubbling(&self, event: UserEvent, element: ElementId) {
  261. let nodes = self.nodes.borrow();
  262. let mut cur_el = Some(element);
  263. log::trace!("calling listener {:?}, {:?}", event, element);
  264. let state = Rc::new(BubbleState::new());
  265. while let Some(id) = cur_el.take() {
  266. if let Some(el) = nodes.get(id.0) {
  267. let real_el = unsafe { &**el };
  268. log::debug!("looking for listener on {:?}", real_el);
  269. if let VNode::Element(real_el) = real_el {
  270. for listener in real_el.listeners.borrow().iter() {
  271. if listener.event == event.name {
  272. log::debug!("calling listener {:?}", listener.event);
  273. if state.canceled.get() {
  274. // stop bubbling if canceled
  275. break;
  276. }
  277. let mut cb = listener.callback.borrow_mut();
  278. if let Some(cb) = cb.as_mut() {
  279. // todo: arcs are pretty heavy to clone
  280. // we really want to convert arc to rc
  281. // unfortunately, the SchedulerMsg must be send/sync to be sent across threads
  282. // we could convert arc to rc internally or something
  283. (cb)(AnyEvent {
  284. bubble_state: state.clone(),
  285. data: event.data.clone(),
  286. });
  287. }
  288. }
  289. }
  290. cur_el = real_el.parent.get();
  291. }
  292. }
  293. }
  294. }
  295. // The head of the bumpframe is the first linked NodeLink
  296. pub fn wip_head(&self, id: ScopeId) -> &VNode {
  297. let scope = self.get_scope(id).unwrap();
  298. let frame = scope.wip_frame();
  299. let node = unsafe { &*frame.node.get() };
  300. unsafe { extend_vnode(node) }
  301. }
  302. // The head of the bumpframe is the first linked NodeLink
  303. pub fn fin_head(&self, id: ScopeId) -> &VNode {
  304. let scope = self.get_scope(id).unwrap();
  305. let frame = scope.fin_frame();
  306. let node = unsafe { &*frame.node.get() };
  307. unsafe { extend_vnode(node) }
  308. }
  309. pub fn root_node(&self, id: ScopeId) -> &VNode {
  310. self.fin_head(id)
  311. }
  312. // this is totally okay since all our nodes are always in a valid state
  313. pub fn get_element(&self, id: ElementId) -> Option<&VNode> {
  314. let ptr = self.nodes.borrow().get(id.0).cloned();
  315. match ptr {
  316. Some(ptr) => {
  317. let node = unsafe { &*ptr };
  318. Some(unsafe { extend_vnode(node) })
  319. }
  320. None => None,
  321. }
  322. }
  323. }
  324. /// Components in Dioxus use the "Context" object to interact with their lifecycle.
  325. ///
  326. /// This lets components access props, schedule updates, integrate hooks, and expose shared state.
  327. ///
  328. /// For the most part, the only method you should be using regularly is `render`.
  329. ///
  330. /// ## Example
  331. ///
  332. /// ```ignore
  333. /// #[derive(Props)]
  334. /// struct ExampleProps {
  335. /// name: String
  336. /// }
  337. ///
  338. /// fn Example(cx: Scope<ExampleProps>) -> Element {
  339. /// cx.render(rsx!{ div {"Hello, {cx.props.name}"} })
  340. /// }
  341. /// ```
  342. pub struct Scope<'a, P = ()> {
  343. pub scope: &'a ScopeState,
  344. pub props: &'a P,
  345. }
  346. impl<P> Copy for Scope<'_, P> {}
  347. impl<P> Clone for Scope<'_, P> {
  348. fn clone(&self) -> Self {
  349. Self {
  350. scope: self.scope,
  351. props: self.props,
  352. }
  353. }
  354. }
  355. impl<'a, P> std::ops::Deref for Scope<'a, P> {
  356. // rust will auto deref again to the original 'a lifetime at the call site
  357. type Target = &'a ScopeState;
  358. fn deref(&self) -> &Self::Target {
  359. &self.scope
  360. }
  361. }
  362. /// A component's unique identifier.
  363. ///
  364. /// `ScopeId` is a `usize` that is unique across the entire VirtualDOM and across time. ScopeIDs will never be reused
  365. /// once a component has been unmounted.
  366. #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
  367. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
  368. pub struct ScopeId(pub usize);
  369. /// A task's unique identifier.
  370. ///
  371. /// `TaskId` is a `usize` that is unique across the entire VirtualDOM and across time. TaskIDs will never be reused
  372. /// once a Task has been completed.
  373. #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
  374. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
  375. pub struct TaskId(pub usize);
  376. /// Every component in Dioxus is represented by a `ScopeState`.
  377. ///
  378. /// Scopes contain the state for hooks, the component's props, and other lifecycle information.
  379. ///
  380. /// Scopes are allocated in a generational arena. As components are mounted/unmounted, they will replace slots of dead components.
  381. /// The actual contents of the hooks, though, will be allocated with the standard allocator. These should not allocate as frequently.
  382. ///
  383. /// We expose the `Scope` type so downstream users can traverse the Dioxus VirtualDOM for whatever
  384. /// use case they might have.
  385. pub struct ScopeState {
  386. pub(crate) parent_scope: Option<*mut ScopeState>,
  387. pub(crate) container: ElementId,
  388. pub(crate) our_arena_idx: ScopeId,
  389. pub(crate) height: u32,
  390. pub(crate) fnptr: ComponentPtr,
  391. // todo: subtrees
  392. pub(crate) is_subtree_root: Cell<bool>,
  393. pub(crate) subtree: Cell<u32>,
  394. pub(crate) props: RefCell<Option<Box<dyn AnyProps>>>,
  395. // nodes, items
  396. pub(crate) frames: [BumpFrame; 2],
  397. pub(crate) generation: Cell<u32>,
  398. pub(crate) items: RefCell<SelfReferentialItems<'static>>,
  399. // hooks
  400. pub(crate) hook_arena: Bump,
  401. pub(crate) hook_vals: RefCell<Vec<*mut dyn Any>>,
  402. pub(crate) hook_idx: Cell<usize>,
  403. // shared state -> todo: move this out of scopestate
  404. pub(crate) shared_contexts: RefCell<HashMap<TypeId, Rc<dyn Any>>>,
  405. pub(crate) tasks: Rc<TaskQueue>,
  406. }
  407. pub struct SelfReferentialItems<'a> {
  408. pub(crate) listeners: Vec<&'a Listener<'a>>,
  409. pub(crate) borrowed_props: Vec<&'a VComponent<'a>>,
  410. }
  411. // Public methods exposed to libraries and components
  412. impl ScopeState {
  413. /// Get the subtree ID that this scope belongs to.
  414. ///
  415. /// Each component has its own subtree ID - the root subtree has an ID of 0. This ID is used by the renderer to route
  416. /// the mutations to the correct window/portal/subtree.
  417. ///
  418. ///
  419. /// # Example
  420. ///
  421. /// ```rust, ignore
  422. /// let mut dom = VirtualDom::new(|cx| cx.render(rsx!{ div {} }));
  423. /// dom.rebuild();
  424. ///
  425. /// let base = dom.base_scope();
  426. ///
  427. /// assert_eq!(base.subtree(), 0);
  428. /// ```
  429. ///
  430. /// todo: enable
  431. pub(crate) fn _subtree(&self) -> u32 {
  432. self.subtree.get()
  433. }
  434. /// Create a new subtree with this scope as the root of the subtree.
  435. ///
  436. /// Each component has its own subtree ID - the root subtree has an ID of 0. This ID is used by the renderer to route
  437. /// the mutations to the correct window/portal/subtree.
  438. ///
  439. /// This method
  440. ///
  441. /// # Example
  442. ///
  443. /// ```rust, ignore
  444. /// fn App(cx: Scope) -> Element {
  445. /// rsx!(cx, div { "Subtree {id}"})
  446. /// };
  447. /// ```
  448. ///
  449. /// todo: enable subtree
  450. pub(crate) fn _create_subtree(&self) -> Option<u32> {
  451. if self.is_subtree_root.get() {
  452. None
  453. } else {
  454. todo!()
  455. }
  456. }
  457. /// Get the height of this Scope - IE the number of scopes above it.
  458. ///
  459. /// A Scope with a height of `0` is the root scope - there are no other scopes above it.
  460. ///
  461. /// # Example
  462. ///
  463. /// ```rust, ignore
  464. /// let mut dom = VirtualDom::new(|cx| cx.render(rsx!{ div {} }));
  465. /// dom.rebuild();
  466. ///
  467. /// let base = dom.base_scope();
  468. ///
  469. /// assert_eq!(base.height(), 0);
  470. /// ```
  471. pub fn height(&self) -> u32 {
  472. self.height
  473. }
  474. /// Get the Parent of this Scope within this Dioxus VirtualDOM.
  475. ///
  476. /// This ID is not unique across Dioxus VirtualDOMs or across time. IDs will be reused when components are unmounted.
  477. ///
  478. /// The base component will not have a parent, and will return `None`.
  479. ///
  480. /// # Example
  481. ///
  482. /// ```rust, ignore
  483. /// let mut dom = VirtualDom::new(|cx| cx.render(rsx!{ div {} }));
  484. /// dom.rebuild();
  485. ///
  486. /// let base = dom.base_scope();
  487. ///
  488. /// assert_eq!(base.parent(), None);
  489. /// ```
  490. pub fn parent(&self) -> Option<ScopeId> {
  491. // safety: the pointer to our parent is *always* valid thanks to the bump arena
  492. self.parent_scope.map(|p| unsafe { &*p }.our_arena_idx)
  493. }
  494. /// Get the ID of this Scope within this Dioxus VirtualDOM.
  495. ///
  496. /// This ID is not unique across Dioxus VirtualDOMs or across time. IDs will be reused when components are unmounted.
  497. ///
  498. /// # Example
  499. ///
  500. /// ```rust, ignore
  501. /// let mut dom = VirtualDom::new(|cx| cx.render(rsx!{ div {} }));
  502. /// dom.rebuild();
  503. /// let base = dom.base_scope();
  504. ///
  505. /// assert_eq!(base.scope_id(), 0);
  506. /// ```
  507. pub fn scope_id(&self) -> ScopeId {
  508. self.our_arena_idx
  509. }
  510. /// Get a handle to the raw update scheduler channel
  511. pub fn scheduler_channel(&self) -> UnboundedSender<SchedulerMsg> {
  512. self.tasks.sender.clone()
  513. }
  514. /// Create a subscription that schedules a future render for the reference component
  515. ///
  516. /// ## Notice: you should prefer using prepare_update and get_scope_id
  517. pub fn schedule_update(&self) -> Arc<dyn Fn() + Send + Sync + 'static> {
  518. let (chan, id) = (self.tasks.sender.clone(), self.scope_id());
  519. Arc::new(move || {
  520. let _ = chan.unbounded_send(SchedulerMsg::Immediate(id));
  521. })
  522. }
  523. /// Schedule an update for any component given its ScopeId.
  524. ///
  525. /// A component's ScopeId can be obtained from `use_hook` or the [`ScopeState::scope_id`] method.
  526. ///
  527. /// This method should be used when you want to schedule an update for a component
  528. pub fn schedule_update_any(&self) -> Arc<dyn Fn(ScopeId) + Send + Sync> {
  529. let chan = self.tasks.sender.clone();
  530. Arc::new(move |id| {
  531. let _ = chan.unbounded_send(SchedulerMsg::Immediate(id));
  532. })
  533. }
  534. /// Get the [`ScopeId`] of a mounted component.
  535. ///
  536. /// `ScopeId` is not unique for the lifetime of the VirtualDom - a ScopeId will be reused if a component is unmounted.
  537. pub fn needs_update(&self) {
  538. self.needs_update_any(self.scope_id())
  539. }
  540. /// Get the [`ScopeId`] of a mounted component.
  541. ///
  542. /// `ScopeId` is not unique for the lifetime of the VirtualDom - a ScopeId will be reused if a component is unmounted.
  543. pub fn needs_update_any(&self, id: ScopeId) {
  544. let _ = self
  545. .tasks
  546. .sender
  547. .unbounded_send(SchedulerMsg::Immediate(id));
  548. }
  549. /// Get the Root Node of this scope
  550. pub fn root_node(&self) -> &VNode {
  551. let node = unsafe { &*self.fin_frame().node.get() };
  552. unsafe { std::mem::transmute(node) }
  553. }
  554. /// This method enables the ability to expose state to children further down the VirtualDOM Tree.
  555. ///
  556. /// This is a "fundamental" operation and should only be called during initialization of a hook.
  557. ///
  558. /// For a hook that provides the same functionality, use `use_provide_context` and `use_consume_context` instead.
  559. ///
  560. /// When the component is dropped, so is the context. Be aware of this behavior when consuming
  561. /// the context via Rc/Weak.
  562. ///
  563. /// # Example
  564. ///
  565. /// ```rust, ignore
  566. /// struct SharedState(&'static str);
  567. ///
  568. /// static App: Component = |cx| {
  569. /// cx.use_hook(|_| cx.provide_context(SharedState("world")));
  570. /// rsx!(cx, Child {})
  571. /// }
  572. ///
  573. /// static Child: Component = |cx| {
  574. /// let state = cx.consume_state::<SharedState>();
  575. /// rsx!(cx, div { "hello {state.0}" })
  576. /// }
  577. /// ```
  578. pub fn provide_context<T: 'static>(&self, value: T) -> Rc<T> {
  579. let value = Rc::new(value);
  580. self.shared_contexts
  581. .borrow_mut()
  582. .insert(TypeId::of::<T>(), value.clone())
  583. .map(|f| f.downcast::<T>().ok())
  584. .flatten();
  585. value
  586. }
  587. /// Provide a context for the root component from anywhere in your app.
  588. ///
  589. ///
  590. /// # Example
  591. ///
  592. /// ```rust, ignore
  593. /// struct SharedState(&'static str);
  594. ///
  595. /// static App: Component = |cx| {
  596. /// cx.use_hook(|_| cx.provide_root_context(SharedState("world")));
  597. /// rsx!(cx, Child {})
  598. /// }
  599. ///
  600. /// static Child: Component = |cx| {
  601. /// let state = cx.consume_state::<SharedState>();
  602. /// rsx!(cx, div { "hello {state.0}" })
  603. /// }
  604. /// ```
  605. pub fn provide_root_context<T: 'static>(&self, value: T) -> Rc<T> {
  606. let value = Rc::new(value);
  607. // if we *are* the root component, then we can just provide the context directly
  608. if self.scope_id() == ScopeId(0) {
  609. self.shared_contexts
  610. .borrow_mut()
  611. .insert(TypeId::of::<T>(), value.clone())
  612. .map(|f| f.downcast::<T>().ok())
  613. .flatten();
  614. return value;
  615. }
  616. let mut search_parent = self.parent_scope;
  617. while let Some(parent) = search_parent.take() {
  618. let parent = unsafe { &*parent };
  619. if parent.scope_id() == ScopeId(0) {
  620. let exists = parent
  621. .shared_contexts
  622. .borrow_mut()
  623. .insert(TypeId::of::<T>(), value.clone());
  624. if exists.is_some() {
  625. log::warn!("Context already provided to parent scope - replacing it");
  626. }
  627. return value;
  628. }
  629. search_parent = parent.parent_scope;
  630. }
  631. unreachable!("all apps have a root scope")
  632. }
  633. /// Try to retrieve a SharedState with type T from the any parent Scope.
  634. pub fn consume_context<T: 'static>(&self) -> Option<Rc<T>> {
  635. if let Some(shared) = self.shared_contexts.borrow().get(&TypeId::of::<T>()) {
  636. Some(shared.clone().downcast::<T>().unwrap())
  637. } else {
  638. let mut search_parent = self.parent_scope;
  639. while let Some(parent_ptr) = search_parent {
  640. // safety: all parent pointers are valid thanks to the bump arena
  641. let parent = unsafe { &*parent_ptr };
  642. if let Some(shared) = parent.shared_contexts.borrow().get(&TypeId::of::<T>()) {
  643. return Some(shared.clone().downcast::<T>().unwrap());
  644. }
  645. search_parent = parent.parent_scope;
  646. }
  647. None
  648. }
  649. }
  650. /// Pushes the future onto the poll queue to be polled after the component renders.
  651. pub fn push_future(&self, fut: impl Future<Output = ()> + 'static) -> TaskId {
  652. // wake up the scheduler if it is sleeping
  653. self.tasks
  654. .sender
  655. .unbounded_send(SchedulerMsg::NewTask(self.our_arena_idx))
  656. .unwrap();
  657. self.tasks.push_fut(fut)
  658. }
  659. /// Spawns the future but does not return the TaskId
  660. pub fn spawn(&self, fut: impl Future<Output = ()> + 'static) {
  661. self.push_future(fut);
  662. }
  663. // todo: attach some state to the future to know if we should poll it
  664. pub fn remove_future(&self, id: TaskId) {
  665. self.tasks.remove_fut(id);
  666. }
  667. /// Take a lazy VNode structure and actually build it with the context of the VDom's efficient VNode allocator.
  668. ///
  669. /// This function consumes the context and absorb the lifetime, so these VNodes *must* be returned.
  670. ///
  671. /// ## Example
  672. ///
  673. /// ```ignore
  674. /// fn Component(cx: Scope<Props>) -> Element {
  675. /// // Lazy assemble the VNode tree
  676. /// let lazy_nodes = rsx!("hello world");
  677. ///
  678. /// // Actually build the tree and allocate it
  679. /// cx.render(lazy_tree)
  680. /// }
  681. ///```
  682. pub fn render<'src>(&'src self, rsx: LazyNodes<'src, '_>) -> Option<VNode<'src>> {
  683. Some(rsx.call(NodeFactory {
  684. scope: self,
  685. bump: &self.wip_frame().bump,
  686. }))
  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 {
  781. borrowed_props,
  782. listeners,
  783. } = self.items.get_mut();
  784. borrowed_props.clear();
  785. listeners.clear();
  786. self.frames[0].reset();
  787. self.frames[1].reset();
  788. // Free up the hook values
  789. self.hook_vals.get_mut().drain(..).for_each(|state| {
  790. let as_mut = unsafe { &mut *state };
  791. let boxed = unsafe { bumpalo::boxed::Box::from_raw(as_mut) };
  792. drop(boxed);
  793. });
  794. // Finally, clear the hook arena
  795. self.hook_arena.reset();
  796. }
  797. }
  798. pub(crate) struct BumpFrame {
  799. pub bump: Bump,
  800. pub node: Cell<*const VNode<'static>>,
  801. }
  802. impl BumpFrame {
  803. pub(crate) fn new(capacity: usize) -> Self {
  804. let bump = Bump::with_capacity(capacity);
  805. let node = &*bump.alloc(VText {
  806. text: "placeholdertext",
  807. id: Default::default(),
  808. is_static: false,
  809. });
  810. let node = bump.alloc(VNode::Text(unsafe { std::mem::transmute(node) }));
  811. let nodes = Cell::new(node as *const _);
  812. Self { bump, node: nodes }
  813. }
  814. pub(crate) fn reset(&mut self) {
  815. self.bump.reset();
  816. let node = self.bump.alloc(VText {
  817. text: "placeholdertext",
  818. id: Default::default(),
  819. is_static: false,
  820. });
  821. let node = self
  822. .bump
  823. .alloc(VNode::Text(unsafe { std::mem::transmute(node) }));
  824. self.node.set(node as *const _);
  825. }
  826. }
  827. pub(crate) struct TaskQueue {
  828. pub(crate) tasks: RefCell<FxHashMap<TaskId, InnerTask>>,
  829. gen: Cell<usize>,
  830. sender: UnboundedSender<SchedulerMsg>,
  831. }
  832. pub(crate) type InnerTask = Pin<Box<dyn Future<Output = ()>>>;
  833. impl TaskQueue {
  834. fn new(sender: UnboundedSender<SchedulerMsg>) -> Rc<Self> {
  835. Rc::new(Self {
  836. tasks: RefCell::new(FxHashMap::default()),
  837. gen: Cell::new(0),
  838. sender,
  839. })
  840. }
  841. fn push_fut(&self, task: impl Future<Output = ()> + 'static) -> TaskId {
  842. let pinned = Box::pin(task);
  843. let id = self.gen.get();
  844. self.gen.set(id + 1);
  845. let tid = TaskId(id);
  846. self.tasks.borrow_mut().insert(tid, pinned);
  847. tid
  848. }
  849. fn remove_fut(&self, id: TaskId) {
  850. if let Ok(mut tasks) = self.tasks.try_borrow_mut() {
  851. let _ = tasks.remove(&id);
  852. } else {
  853. // todo: it should be okay to remote a fut while the queue is being polled
  854. // However, it's not currently possible to do that.
  855. log::trace!("Unable to remove task from task queue. This is probably a bug.");
  856. }
  857. }
  858. pub(crate) fn has_tasks(&self) -> bool {
  859. !self.tasks.borrow().is_empty()
  860. }
  861. }
  862. #[test]
  863. fn sizeof() {
  864. dbg!(std::mem::size_of::<ScopeState>());
  865. }