scope.rs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. use crate::innerlude::*;
  2. use futures_channel::mpsc::UnboundedSender;
  3. use fxhash::FxHashMap;
  4. use std::{
  5. any::{Any, TypeId},
  6. cell::{Cell, RefCell},
  7. collections::HashMap,
  8. future::Future,
  9. rc::Rc,
  10. };
  11. use bumpalo::{boxed::Box as BumpBox, Bump};
  12. /// Components in Dioxus use the "Context" object to interact with their lifecycle.
  13. ///
  14. /// This lets components access props, schedule updates, integrate hooks, and expose shared state.
  15. ///
  16. /// For the most part, the only method you should be using regularly is `render`.
  17. ///
  18. /// ## Example
  19. ///
  20. /// ```ignore
  21. /// #[derive(Props)]
  22. /// struct ExampleProps {
  23. /// name: String
  24. /// }
  25. ///
  26. /// fn Example((cx, props): Scope<Props>) -> Element {
  27. /// cx.render(rsx!{ div {"Hello, {props.name}"} })
  28. /// }
  29. /// ```
  30. pub type Context<'a> = &'a ScopeInner;
  31. /// Every component in Dioxus is represented by a `Scope`.
  32. ///
  33. /// Scopes contain the state for hooks, the component's props, and other lifecycle information.
  34. ///
  35. /// Scopes are allocated in a generational arena. As components are mounted/unmounted, they will replace slots of dead components.
  36. /// The actual contents of the hooks, though, will be allocated with the standard allocator. These should not allocate as frequently.
  37. ///
  38. /// We expose the `Scope` type so downstream users can traverse the Dioxus VirtualDOM for whatever
  39. /// use case they might have.
  40. pub struct ScopeInner {
  41. // Book-keeping about our spot in the arena
  42. // yes, a raw pointer
  43. // it's bump allocated so it's stable
  44. // the safety of parent pointers is guaranteed by the logic in this crate
  45. pub(crate) parent_scope: Option<*mut ScopeInner>,
  46. pub(crate) our_arena_idx: ScopeId,
  47. pub(crate) height: u32,
  48. pub(crate) subtree: Cell<u32>,
  49. pub(crate) is_subtree_root: Cell<bool>,
  50. // Nodes
  51. pub(crate) frames: ActiveFrame,
  52. pub(crate) vcomp: *const VComponent<'static>,
  53. /*
  54. we care about:
  55. - listeners (and how to call them when an event is triggered)
  56. - borrowed props (and how to drop them when the parent is dropped)
  57. - suspended nodes (and how to call their callback when their associated tasks are complete)
  58. */
  59. pub(crate) items: RefCell<SelfReferentialItems<'static>>,
  60. // State
  61. pub(crate) hooks: HookList,
  62. // todo: move this into a centralized place - is more memory efficient
  63. pub(crate) shared_contexts: RefCell<HashMap<TypeId, Rc<dyn Any>>>,
  64. pub(crate) sender: UnboundedSender<SchedulerMsg>,
  65. }
  66. pub struct SelfReferentialItems<'a> {
  67. pub(crate) listeners: Vec<*const Listener<'a>>,
  68. pub(crate) borrowed_props: Vec<*const VComponent<'a>>,
  69. pub(crate) suspended_nodes: FxHashMap<u64, *const VSuspended<'a>>,
  70. pub(crate) tasks: Vec<BumpBox<'a, dyn Future<Output = ()>>>,
  71. pub(crate) pending_effects: Vec<BumpBox<'a, dyn FnMut()>>,
  72. }
  73. pub struct ScopeVcomp {
  74. // important things
  75. }
  76. impl ScopeInner {
  77. /// This method cleans up any references to data held within our hook list. This prevents mutable aliasing from
  78. /// causing UB in our tree.
  79. ///
  80. /// This works by cleaning up our references from the bottom of the tree to the top. The directed graph of components
  81. /// essentially forms a dependency tree that we can traverse from the bottom to the top. As we traverse, we remove
  82. /// any possible references to the data in the hook list.
  83. ///
  84. /// References to hook data can only be stored in listeners and component props. During diffing, we make sure to log
  85. /// all listeners and borrowed props so we can clear them here.
  86. ///
  87. /// This also makes sure that drop order is consistent and predictable. All resources that rely on being dropped will
  88. /// be dropped.
  89. pub(crate) fn ensure_drop_safety(&mut self) {
  90. // make sure we drop all borrowed props manually to guarantee that their drop implementation is called before we
  91. // run the hooks (which hold an &mut Reference)
  92. // right now, we don't drop
  93. self.items
  94. .get_mut()
  95. .borrowed_props
  96. .drain(..)
  97. .map(|li| unsafe { &*li })
  98. .for_each(|comp| {
  99. // First drop the component's undropped references
  100. let scope_id = comp
  101. .associated_scope
  102. .get()
  103. .expect("VComponents should be associated with a valid Scope");
  104. let scope = unsafe { &mut *scope_id };
  105. scope.ensure_drop_safety();
  106. todo!("drop the component's props");
  107. // let mut drop_props = comp.drop_props.borrow_mut().take().unwrap();
  108. // drop_props();
  109. });
  110. // Now that all the references are gone, we can safely drop our own references in our listeners.
  111. self.items
  112. .get_mut()
  113. .listeners
  114. .drain(..)
  115. .map(|li| unsafe { &*li })
  116. .for_each(|listener| drop(listener.callback.borrow_mut().take()));
  117. }
  118. /// A safe wrapper around calling listeners
  119. pub(crate) fn call_listener(&mut self, event: UserEvent, element: ElementId) {
  120. let listners = &mut self.items.get_mut().listeners;
  121. let raw_listener = listners.iter().find(|lis| {
  122. let search = unsafe { &***lis };
  123. if search.event == event.name {
  124. let search_id = search.mounted_node.get();
  125. search_id.map(|f| f == element).unwrap_or(false)
  126. } else {
  127. false
  128. }
  129. });
  130. if let Some(raw_listener) = raw_listener {
  131. let listener = unsafe { &**raw_listener };
  132. let mut cb = listener.callback.borrow_mut();
  133. if let Some(cb) = cb.as_mut() {
  134. (cb)(event.event);
  135. }
  136. } else {
  137. log::warn!("An event was triggered but there was no listener to handle it");
  138. }
  139. }
  140. // General strategy here is to load up the appropriate suspended task and then run it.
  141. // Suspended nodes cannot be called repeatedly.
  142. pub(crate) fn call_suspended_node<'a>(&'a mut self, task_id: u64) {
  143. let mut nodes = &mut self.items.get_mut().suspended_nodes;
  144. if let Some(suspended) = nodes.remove(&task_id) {
  145. let sus: &'a VSuspended<'static> = unsafe { &*suspended };
  146. let sus: &'a VSuspended<'a> = unsafe { std::mem::transmute(sus) };
  147. let mut boxed = sus.callback.borrow_mut().take().unwrap();
  148. let new_node: Element<'a> = boxed();
  149. }
  150. }
  151. // run the list of effects
  152. pub(crate) fn run_effects(&mut self) {
  153. // pub(crate) fn run_effects(&mut self, pool: &ResourcePool) {
  154. for mut effect in self.items.get_mut().pending_effects.drain(..) {
  155. effect();
  156. }
  157. }
  158. /// Render this component.
  159. ///
  160. /// Returns true if the scope completed successfully and false if running failed (IE a None error was propagated).
  161. pub(crate) fn run_scope<'sel>(&'sel mut self) -> bool {
  162. // Cycle to the next frame and then reset it
  163. // This breaks any latent references, invalidating every pointer referencing into it.
  164. // Remove all the outdated listeners
  165. self.ensure_drop_safety();
  166. // Safety:
  167. // - We dropped the listeners, so no more &mut T can be used while these are held
  168. // - All children nodes that rely on &mut T are replaced with a new reference
  169. unsafe { self.hooks.reset() };
  170. // Safety:
  171. // - We've dropped all references to the wip bump frame
  172. unsafe { self.frames.reset_wip_frame() };
  173. let items = self.items.get_mut();
  174. // just forget about our suspended nodes while we're at it
  175. items.suspended_nodes.clear();
  176. // guarantee that we haven't screwed up - there should be no latent references anywhere
  177. debug_assert!(items.listeners.is_empty());
  178. debug_assert!(items.suspended_nodes.is_empty());
  179. debug_assert!(items.borrowed_props.is_empty());
  180. log::debug!("Borrowed stuff is successfully cleared");
  181. // temporarily cast the vcomponent to the right lifetime
  182. let vcomp = self.load_vcomp();
  183. let render: &dyn for<'b> Fn(&'b ScopeInner) -> Element<'b> = todo!();
  184. // Todo: see if we can add stronger guarantees around internal bookkeeping and failed component renders.
  185. if let Some(builder) = render(self) {
  186. let new_head = builder.into_vnode(NodeFactory {
  187. bump: &self.frames.wip_frame().bump,
  188. });
  189. log::debug!("Render is successful");
  190. // the user's component succeeded. We can safely cycle to the next frame
  191. self.frames.wip_frame_mut().head_node = unsafe { std::mem::transmute(new_head) };
  192. self.frames.cycle_frame();
  193. true
  194. } else {
  195. false
  196. }
  197. }
  198. pub(crate) fn new_subtree(&self) -> Option<u32> {
  199. todo!()
  200. // if self.is_subtree_root.get() {
  201. // None
  202. // } else {
  203. // let cur = self.shared.cur_subtree.get();
  204. // self.shared.cur_subtree.set(cur + 1);
  205. // Some(cur)
  206. // }
  207. }
  208. pub(crate) fn update_vcomp(&mut self, vcomp: &VComponent) {
  209. let f: *const _ = vcomp;
  210. self.vcomp = unsafe { std::mem::transmute(f) };
  211. }
  212. pub(crate) fn load_vcomp<'a>(&'a mut self) -> &'a VComponent<'a> {
  213. unsafe { std::mem::transmute(&*self.vcomp) }
  214. }
  215. /// Get the root VNode for this Scope.
  216. ///
  217. /// This VNode is the "entrypoint" VNode. If the component renders multiple nodes, then this VNode will be a fragment.
  218. ///
  219. /// # Example
  220. /// ```rust
  221. /// let mut dom = VirtualDom::new(|(cx, props)|cx.render(rsx!{ div {} }));
  222. /// dom.rebuild();
  223. ///
  224. /// let base = dom.base_scope();
  225. ///
  226. /// if let VNode::VElement(node) = base.root_node() {
  227. /// assert_eq!(node.tag_name, "div");
  228. /// }
  229. /// ```
  230. pub fn root_node(&self) -> &VNode {
  231. self.frames.fin_head()
  232. }
  233. /// Get the subtree ID that this scope belongs to.
  234. ///
  235. /// Each component has its own subtree ID - the root subtree has an ID of 0. This ID is used by the renderer to route
  236. /// the mutations to the correct window/portal/subtree.
  237. ///
  238. ///
  239. /// # Example
  240. ///
  241. /// ```rust
  242. /// let mut dom = VirtualDom::new(|(cx, props)|cx.render(rsx!{ div {} }));
  243. /// dom.rebuild();
  244. ///
  245. /// let base = dom.base_scope();
  246. ///
  247. /// assert_eq!(base.subtree(), 0);
  248. /// ```
  249. pub fn subtree(&self) -> u32 {
  250. self.subtree.get()
  251. }
  252. /// Get the height of this Scope - IE the number of scopes above it.
  253. ///
  254. /// A Scope with a height of `0` is the root scope - there are no other scopes above it.
  255. ///
  256. /// # Example
  257. ///
  258. /// ```rust
  259. /// let mut dom = VirtualDom::new(|(cx, props)|cx.render(rsx!{ div {} }));
  260. /// dom.rebuild();
  261. ///
  262. /// let base = dom.base_scope();
  263. ///
  264. /// assert_eq!(base.height(), 0);
  265. /// ```
  266. pub fn height(&self) -> u32 {
  267. self.height
  268. }
  269. /// Get the Parent of this Scope within this Dioxus VirtualDOM.
  270. ///
  271. /// This ID is not unique across Dioxus VirtualDOMs or across time. IDs will be reused when components are unmounted.
  272. ///
  273. /// The base component will not have a parent, and will return `None`.
  274. ///
  275. /// # Example
  276. ///
  277. /// ```rust
  278. /// let mut dom = VirtualDom::new(|(cx, props)|cx.render(rsx!{ div {} }));
  279. /// dom.rebuild();
  280. ///
  281. /// let base = dom.base_scope();
  282. ///
  283. /// assert_eq!(base.parent(), None);
  284. /// ```
  285. pub fn parent(&self) -> Option<ScopeId> {
  286. match self.parent_scope {
  287. Some(p) => Some(unsafe { &*p }.our_arena_idx),
  288. None => None,
  289. }
  290. }
  291. /// Get the ID of this Scope within this Dioxus VirtualDOM.
  292. ///
  293. /// This ID is not unique across Dioxus VirtualDOMs or across time. IDs will be reused when components are unmounted.
  294. ///
  295. /// # Example
  296. ///
  297. /// ```rust
  298. /// let mut dom = VirtualDom::new(|(cx, props)|cx.render(rsx!{ div {} }));
  299. /// dom.rebuild();
  300. /// let base = dom.base_scope();
  301. ///
  302. /// assert_eq!(base.scope_id(), 0);
  303. /// ```
  304. pub fn scope_id(&self) -> ScopeId {
  305. self.our_arena_idx
  306. }
  307. /// Create a subscription that schedules a future render for the reference component
  308. ///
  309. /// ## Notice: you should prefer using prepare_update and get_scope_id
  310. pub fn schedule_update(&self) -> Rc<dyn Fn() + 'static> {
  311. // pub fn schedule_update(&self) -> Rc<dyn Fn() + 'static> {
  312. let chan = self.sender.clone();
  313. let id = self.scope_id();
  314. Rc::new(move || {
  315. chan.unbounded_send(SchedulerMsg::Immediate(id));
  316. })
  317. }
  318. /// Schedule an update for any component given its ScopeId.
  319. ///
  320. /// A component's ScopeId can be obtained from `use_hook` or the [`Context::scope_id`] method.
  321. ///
  322. /// This method should be used when you want to schedule an update for a component
  323. pub fn schedule_update_any(&self) -> Rc<dyn Fn(ScopeId)> {
  324. let chan = self.sender.clone();
  325. Rc::new(move |id| {
  326. chan.unbounded_send(SchedulerMsg::Immediate(id));
  327. })
  328. }
  329. /// Get the [`ScopeId`] of a mounted component.
  330. ///
  331. /// `ScopeId` is not unique for the lifetime of the VirtualDom - a ScopeId will be reused if a component is unmounted.
  332. pub fn needs_update(&self) {
  333. self.needs_update_any(self.scope_id())
  334. }
  335. /// Get the [`ScopeId`] of a mounted component.
  336. ///
  337. /// `ScopeId` is not unique for the lifetime of the VirtualDom - a ScopeId will be reused if a component is unmounted.
  338. pub fn needs_update_any(&self, id: ScopeId) {
  339. self.sender
  340. .unbounded_send(SchedulerMsg::Immediate(id))
  341. .unwrap();
  342. }
  343. /// Get the [`ScopeId`] of a mounted component.
  344. ///
  345. /// `ScopeId` is not unique for the lifetime of the VirtualDom - a ScopeId will be reused if a component is unmounted.
  346. pub fn bump(&self) -> &Bump {
  347. let bump = &self.frames.wip_frame().bump;
  348. bump
  349. }
  350. /// Take a lazy VNode structure and actually build it with the context of the VDom's efficient VNode allocator.
  351. ///
  352. /// This function consumes the context and absorb the lifetime, so these VNodes *must* be returned.
  353. ///
  354. /// ## Example
  355. ///
  356. /// ```ignore
  357. /// fn Component(cx: Context<()>) -> VNode {
  358. /// // Lazy assemble the VNode tree
  359. /// let lazy_tree = html! {<div> "Hello World" </div>};
  360. ///
  361. /// // Actually build the tree and allocate it
  362. /// cx.render(lazy_tree)
  363. /// }
  364. ///```
  365. pub fn render<'src>(
  366. &'src self,
  367. lazy_nodes: Option<LazyNodes<'src, '_>>,
  368. ) -> Option<VNode<'src>> {
  369. let bump = &self.frames.wip_frame().bump;
  370. let factory = NodeFactory { bump };
  371. lazy_nodes.map(|f| f.call(factory))
  372. }
  373. /// Push an effect to be ran after the component has been successfully mounted to the dom
  374. /// Returns the effect's position in the stack
  375. pub fn push_effect<'src>(&'src self, effect: impl FnOnce() + 'src) -> usize {
  376. // this is some tricker to get around not being able to actually call fnonces
  377. let mut slot = Some(effect);
  378. let fut: &mut dyn FnMut() = self.bump().alloc(move || slot.take().unwrap()());
  379. // wrap it in a type that will actually drop the contents
  380. let boxed_fut = unsafe { BumpBox::from_raw(fut) };
  381. // erase the 'src lifetime for self-referential storage
  382. let self_ref_fut = unsafe { std::mem::transmute(boxed_fut) };
  383. let mut items = self.items.borrow_mut();
  384. items.pending_effects.push(self_ref_fut);
  385. items.pending_effects.len() - 1
  386. }
  387. /// Pushes the future onto the poll queue to be polled
  388. /// The future is forcibly dropped if the component is not ready by the next render
  389. pub fn push_task<'src>(&'src self, fut: impl Future<Output = ()> + 'src) -> usize {
  390. // allocate the future
  391. let fut: &mut dyn Future<Output = ()> = self.bump().alloc(fut);
  392. // wrap it in a type that will actually drop the contents
  393. let boxed_fut: BumpBox<dyn Future<Output = ()>> = unsafe { BumpBox::from_raw(fut) };
  394. // erase the 'src lifetime for self-referential storage
  395. let self_ref_fut = unsafe { std::mem::transmute(boxed_fut) };
  396. let mut items = self.items.borrow_mut();
  397. items.tasks.push(self_ref_fut);
  398. items.tasks.len() - 1
  399. }
  400. /// This method enables the ability to expose state to children further down the VirtualDOM Tree.
  401. ///
  402. /// This is a "fundamental" operation and should only be called during initialization of a hook.
  403. ///
  404. /// For a hook that provides the same functionality, use `use_provide_state` and `use_consume_state` instead.
  405. ///
  406. /// When the component is dropped, so is the context. Be aware of this behavior when consuming
  407. /// the context via Rc/Weak.
  408. ///
  409. /// # Example
  410. ///
  411. /// ```
  412. /// struct SharedState(&'static str);
  413. ///
  414. /// static App: FC<()> = |(cx, props)|{
  415. /// cx.use_hook(|_| cx.provide_state(SharedState("world")), |_| {}, |_| {});
  416. /// rsx!(cx, Child {})
  417. /// }
  418. ///
  419. /// static Child: FC<()> = |(cx, props)|{
  420. /// let state = cx.consume_state::<SharedState>();
  421. /// rsx!(cx, div { "hello {state.0}" })
  422. /// }
  423. /// ```
  424. pub fn provide_state<T>(&self, value: T)
  425. where
  426. T: 'static,
  427. {
  428. self.shared_contexts
  429. .borrow_mut()
  430. .insert(TypeId::of::<T>(), Rc::new(value))
  431. .map(|f| f.downcast::<T>().ok())
  432. .flatten();
  433. }
  434. /// Try to retrieve a SharedState with type T from the any parent Scope.
  435. pub fn consume_state<T: 'static>(&self) -> Option<Rc<T>> {
  436. if let Some(shared) = self.shared_contexts.borrow().get(&TypeId::of::<T>()) {
  437. Some(shared.clone().downcast::<T>().unwrap())
  438. } else {
  439. let mut search_parent = self.parent_scope;
  440. while let Some(parent_ptr) = search_parent {
  441. let parent = unsafe { &*parent_ptr };
  442. if let Some(shared) = parent.shared_contexts.borrow().get(&TypeId::of::<T>()) {
  443. return Some(shared.clone().downcast::<T>().unwrap());
  444. }
  445. search_parent = parent.parent_scope;
  446. }
  447. None
  448. }
  449. }
  450. /// Create a new subtree with this scope as the root of the subtree.
  451. ///
  452. /// Each component has its own subtree ID - the root subtree has an ID of 0. This ID is used by the renderer to route
  453. /// the mutations to the correct window/portal/subtree.
  454. ///
  455. /// This method
  456. ///
  457. /// # Example
  458. ///
  459. /// ```rust
  460. /// static App: FC<()> = |(cx, props)| {
  461. /// todo!();
  462. /// rsx!(cx, div { "Subtree {id}"})
  463. /// };
  464. /// ```
  465. pub fn create_subtree(&self) -> Option<u32> {
  466. self.new_subtree()
  467. }
  468. /// Get the subtree ID that this scope belongs to.
  469. ///
  470. /// Each component has its own subtree ID - the root subtree has an ID of 0. This ID is used by the renderer to route
  471. /// the mutations to the correct window/portal/subtree.
  472. ///
  473. /// # Example
  474. ///
  475. /// ```rust
  476. /// static App: FC<()> = |(cx, props)| {
  477. /// let id = cx.get_current_subtree();
  478. /// rsx!(cx, div { "Subtree {id}"})
  479. /// };
  480. /// ```
  481. pub fn get_current_subtree(&self) -> u32 {
  482. self.subtree()
  483. }
  484. /// Store a value between renders
  485. ///
  486. /// This is *the* foundational hook for all other hooks.
  487. ///
  488. /// - Initializer: closure used to create the initial hook state
  489. /// - Runner: closure used to output a value every time the hook is used
  490. ///
  491. /// To "cleanup" the hook, implement `Drop` on the stored hook value. Whenever the component is dropped, the hook
  492. /// will be dropped as well.
  493. ///
  494. /// # Example
  495. ///
  496. /// ```ignore
  497. /// // use_ref is the simplest way of storing a value between renders
  498. /// fn use_ref<T: 'static>(initial_value: impl FnOnce() -> T) -> &RefCell<T> {
  499. /// use_hook(
  500. /// || Rc::new(RefCell::new(initial_value())),
  501. /// |state| state,
  502. /// )
  503. /// }
  504. /// ```
  505. pub fn use_hook<'src, State: 'static, Output: 'src>(
  506. &'src self,
  507. initializer: impl FnOnce(usize) -> State,
  508. runner: impl FnOnce(&'src mut State) -> Output,
  509. ) -> Output {
  510. if self.hooks.at_end() {
  511. self.hooks.push_hook(initializer(self.hooks.len()));
  512. }
  513. runner(self.hooks.next::<State>().expect(HOOK_ERR_MSG))
  514. }
  515. }
  516. const HOOK_ERR_MSG: &str = r###"
  517. Unable to retrieve the hook that was initialized at this index.
  518. Consult the `rules of hooks` to understand how to use hooks properly.
  519. You likely used the hook in a conditional. Hooks rely on consistent ordering between renders.
  520. Functions prefixed with "use" should never be called conditionally.
  521. "###;