scope.rs 18 KB

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