scope.rs 20 KB

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