scopes.rs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. use crate::{
  2. any_props::AnyProps,
  3. any_props::VProps,
  4. arena::ElementId,
  5. bump_frame::BumpFrame,
  6. innerlude::{DynamicNode, EventHandler, VComponent, VText},
  7. innerlude::{Scheduler, SchedulerMsg},
  8. lazynodes::LazyNodes,
  9. nodes::{ComponentReturn, IntoAttributeValue, IntoDynNode, RenderReturn},
  10. Attribute, AttributeValue, Element, Event, Properties, TaskId,
  11. };
  12. use bumpalo::{boxed::Box as BumpBox, Bump};
  13. use rustc_hash::{FxHashMap, FxHashSet};
  14. use std::{
  15. any::{Any, TypeId},
  16. cell::{Cell, RefCell},
  17. fmt::Arguments,
  18. future::Future,
  19. rc::Rc,
  20. sync::Arc,
  21. };
  22. /// A wrapper around the [`Scoped`] object that contains a reference to the [`ScopeState`] and properties for a given
  23. /// component.
  24. ///
  25. /// The [`Scope`] is your handle to the [`crate::VirtualDom`] and the component state. Every component is given its own
  26. /// [`ScopeState`] and merged with its properties to create a [`Scoped`].
  27. ///
  28. /// The [`Scope`] handle specifically exists to provide a stable reference to these items for the lifetime of the
  29. /// component render.
  30. pub type Scope<'a, T = ()> = &'a Scoped<'a, T>;
  31. // This ScopedType exists because we want to limit the amount of monomorphization that occurs when making inner
  32. // state type generic over props. When the state is generic, it causes every method to be monomorphized for every
  33. // instance of Scope<T> in the codebase.
  34. //
  35. //
  36. /// A wrapper around a component's [`ScopeState`] and properties. The [`ScopeState`] provides the majority of methods
  37. /// for the VirtualDom and component state.
  38. pub struct Scoped<'a, T = ()> {
  39. /// The component's state and handle to the scheduler.
  40. ///
  41. /// Stores things like the custom bump arena, spawn functions, hooks, and the scheduler.
  42. pub scope: &'a ScopeState,
  43. /// The component's properties.
  44. pub props: &'a T,
  45. }
  46. impl<'a, T> std::ops::Deref for Scoped<'a, T> {
  47. type Target = &'a ScopeState;
  48. fn deref(&self) -> &Self::Target {
  49. &self.scope
  50. }
  51. }
  52. /// A component's unique identifier.
  53. ///
  54. /// `ScopeId` is a `usize` that acts a key for the internal slab of Scopes. This means that the key is not unqiue across
  55. /// time. We do try and guarantee that between calls to `wait_for_work`, no ScopeIds will be recycled in order to give
  56. /// time for any logic that relies on these IDs to properly update.
  57. #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
  58. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
  59. pub struct ScopeId(pub usize);
  60. /// A component's state separate from its props.
  61. ///
  62. /// This struct exists to provide a common interface for all scopes without relying on generics.
  63. pub struct ScopeState {
  64. pub(crate) render_cnt: Cell<usize>,
  65. pub(crate) name: &'static str,
  66. pub(crate) node_arena_1: BumpFrame,
  67. pub(crate) node_arena_2: BumpFrame,
  68. pub(crate) parent: Option<*mut ScopeState>,
  69. pub(crate) id: ScopeId,
  70. pub(crate) height: u32,
  71. pub(crate) hook_arena: Bump,
  72. pub(crate) hook_list: RefCell<Vec<*mut dyn Any>>,
  73. pub(crate) hook_idx: Cell<usize>,
  74. pub(crate) shared_contexts: RefCell<FxHashMap<TypeId, Box<dyn Any>>>,
  75. pub(crate) tasks: Rc<Scheduler>,
  76. pub(crate) spawned_tasks: FxHashSet<TaskId>,
  77. pub(crate) borrowed_props: RefCell<Vec<*const VComponent<'static>>>,
  78. pub(crate) listeners: RefCell<Vec<*const Attribute<'static>>>,
  79. pub(crate) props: Option<Box<dyn AnyProps<'static>>>,
  80. pub(crate) placeholder: Cell<Option<ElementId>>,
  81. }
  82. impl<'src> ScopeState {
  83. pub(crate) fn current_frame(&self) -> &BumpFrame {
  84. match self.render_cnt.get() % 2 {
  85. 0 => &self.node_arena_1,
  86. 1 => &self.node_arena_2,
  87. _ => unreachable!(),
  88. }
  89. }
  90. pub(crate) fn previous_frame(&self) -> &BumpFrame {
  91. match self.render_cnt.get() % 2 {
  92. 1 => &self.node_arena_1,
  93. 0 => &self.node_arena_2,
  94. _ => unreachable!(),
  95. }
  96. }
  97. pub(crate) fn previous_frame_mut(&mut self) -> &mut BumpFrame {
  98. match self.render_cnt.get() % 2 {
  99. 1 => &mut self.node_arena_1,
  100. 0 => &mut self.node_arena_2,
  101. _ => unreachable!(),
  102. }
  103. }
  104. /// Get the name of this component
  105. pub fn name(&self) -> &str {
  106. self.name
  107. }
  108. /// Get the current render since the inception of this component
  109. ///
  110. /// This can be used as a helpful diagnostic when debugging hooks/renders, etc
  111. pub fn generation(&self) -> usize {
  112. self.render_cnt.get()
  113. }
  114. /// Get a handle to the currently active bump arena for this Scope
  115. ///
  116. /// This is a bump memory allocator. Be careful using this directly since the contents will be wiped on the next render.
  117. /// It's easy to leak memory here since the drop implementation will not be called for any objects allocated in this arena.
  118. ///
  119. /// If you need to allocate items that need to be dropped, use bumpalo's box.
  120. pub fn bump(&self) -> &Bump {
  121. // note that this is actually the previous frame since we use that as scratch space while the component is rendering
  122. &self.previous_frame().bump
  123. }
  124. /// Get a handle to the currently active head node arena for this Scope
  125. ///
  126. /// This is useful for traversing the tree outside of the VirtualDom, such as in a custom renderer or in SSR.
  127. ///
  128. /// Panics if the tree has not been built yet.
  129. pub fn root_node(&self) -> &RenderReturn {
  130. self.try_root_node()
  131. .expect("The tree has not been built yet. Make sure to call rebuild on the tree before accessing its nodes.")
  132. }
  133. /// Try to get a handle to the currently active head node arena for this Scope
  134. ///
  135. /// This is useful for traversing the tree outside of the VirtualDom, such as in a custom renderer or in SSR.
  136. ///
  137. /// Returns [`None`] if the tree has not been built yet.
  138. pub fn try_root_node(&self) -> Option<&RenderReturn> {
  139. let ptr = self.current_frame().node.get();
  140. if ptr.is_null() {
  141. return None;
  142. }
  143. let r: &RenderReturn = unsafe { &*ptr };
  144. unsafe { std::mem::transmute(r) }
  145. }
  146. /// Get the height of this Scope - IE the number of scopes above it.
  147. ///
  148. /// A Scope with a height of `0` is the root scope - there are no other scopes above it.
  149. ///
  150. /// # Example
  151. ///
  152. /// ```rust, ignore
  153. /// let mut dom = VirtualDom::new(|cx| cx.render(rsx!{ div {} }));
  154. /// dom.rebuild();
  155. ///
  156. /// let base = dom.base_scope();
  157. ///
  158. /// assert_eq!(base.height(), 0);
  159. /// ```
  160. pub fn height(&self) -> u32 {
  161. self.height
  162. }
  163. /// Get the Parent of this [`Scope`] within this Dioxus [`crate::VirtualDom`].
  164. ///
  165. /// This ID is not unique across Dioxus [`crate::VirtualDom`]s or across time. IDs will be reused when components are unmounted.
  166. ///
  167. /// The base component will not have a parent, and will return `None`.
  168. ///
  169. /// # Example
  170. ///
  171. /// ```rust, ignore
  172. /// let mut dom = VirtualDom::new(|cx| cx.render(rsx!{ div {} }));
  173. /// dom.rebuild();
  174. ///
  175. /// let base = dom.base_scope();
  176. ///
  177. /// assert_eq!(base.parent(), None);
  178. /// ```
  179. pub fn parent(&self) -> Option<ScopeId> {
  180. // safety: the pointer to our parent is *always* valid thanks to the bump arena
  181. self.parent.map(|p| unsafe { &*p }.id)
  182. }
  183. /// Get the ID of this Scope within this Dioxus [`crate::VirtualDom`].
  184. ///
  185. /// This ID is not unique across Dioxus [`crate::VirtualDom`]s or across time. IDs will be reused when components are unmounted.
  186. ///
  187. /// # Example
  188. ///
  189. /// ```rust, ignore
  190. /// let mut dom = VirtualDom::new(|cx| cx.render(rsx!{ div {} }));
  191. /// dom.rebuild();
  192. /// let base = dom.base_scope();
  193. ///
  194. /// assert_eq!(base.scope_id(), 0);
  195. /// ```
  196. pub fn scope_id(&self) -> ScopeId {
  197. self.id
  198. }
  199. /// Create a subscription that schedules a future render for the reference component
  200. ///
  201. /// ## Notice: you should prefer using [`Self::schedule_update_any`] and [`Self::scope_id`]
  202. pub fn schedule_update(&self) -> Arc<dyn Fn() + Send + Sync + 'static> {
  203. let (chan, id) = (self.tasks.sender.clone(), self.scope_id());
  204. Arc::new(move || drop(chan.unbounded_send(SchedulerMsg::Immediate(id))))
  205. }
  206. /// Schedule an update for any component given its [`ScopeId`].
  207. ///
  208. /// A component's [`ScopeId`] can be obtained from `use_hook` or the [`ScopeState::scope_id`] method.
  209. ///
  210. /// This method should be used when you want to schedule an update for a component
  211. pub fn schedule_update_any(&self) -> Arc<dyn Fn(ScopeId) + Send + Sync> {
  212. let chan = self.tasks.sender.clone();
  213. Arc::new(move |id| {
  214. chan.unbounded_send(SchedulerMsg::Immediate(id)).unwrap();
  215. })
  216. }
  217. /// Mark this scope as dirty, and schedule a render for it.
  218. pub fn needs_update(&self) {
  219. self.needs_update_any(self.scope_id());
  220. }
  221. /// Get the [`ScopeId`] of a mounted component.
  222. ///
  223. /// `ScopeId` is not unique for the lifetime of the [`crate::VirtualDom`] - a [`ScopeId`] will be reused if a component is unmounted.
  224. pub fn needs_update_any(&self, id: ScopeId) {
  225. self.tasks
  226. .sender
  227. .unbounded_send(SchedulerMsg::Immediate(id))
  228. .expect("Scheduler to exist if scope exists");
  229. }
  230. /// Return any context of type T if it exists on this scope
  231. pub fn has_context<T: 'static + Clone>(&self) -> Option<T> {
  232. self.shared_contexts
  233. .borrow()
  234. .get(&TypeId::of::<T>())?
  235. .downcast_ref::<T>()
  236. .cloned()
  237. }
  238. /// Try to retrieve a shared state with type `T` from any parent scope.
  239. ///
  240. /// Clones the state if it exists.
  241. pub fn consume_context<T: 'static + Clone>(&self) -> Option<T> {
  242. if let Some(this_ctx) = self.has_context() {
  243. return Some(this_ctx);
  244. }
  245. let mut search_parent = self.parent;
  246. while let Some(parent_ptr) = search_parent {
  247. // safety: all parent pointers are valid thanks to the bump arena
  248. let parent = unsafe { &*parent_ptr };
  249. if let Some(shared) = parent.shared_contexts.borrow().get(&TypeId::of::<T>()) {
  250. return shared.downcast_ref::<T>().cloned();
  251. }
  252. search_parent = parent.parent;
  253. }
  254. None
  255. }
  256. /// Expose state to children further down the [`crate::VirtualDom`] Tree. Does not require `clone` on the context,
  257. /// though we do recommend it.
  258. ///
  259. /// This is a "fundamental" operation and should only be called during initialization of a hook.
  260. ///
  261. /// For a hook that provides the same functionality, use `use_provide_context` and `use_context` instead.
  262. ///
  263. /// If a state is provided that already exists, the new value will not be inserted. Instead, this method will
  264. /// return the existing value. This behavior is chosen so shared values do not need to be `Clone`. This particular
  265. /// behavior might change in the future.
  266. ///
  267. /// # Example
  268. ///
  269. /// ```rust, ignore
  270. /// struct SharedState(&'static str);
  271. ///
  272. /// static App: Component = |cx| {
  273. /// cx.use_hook(|| cx.provide_context(SharedState("world")));
  274. /// render!(Child {})
  275. /// }
  276. ///
  277. /// static Child: Component = |cx| {
  278. /// let state = cx.consume_state::<SharedState>();
  279. /// render!(div { "hello {state.0}" })
  280. /// }
  281. /// ```
  282. pub fn provide_context<T: 'static + Clone>(&self, value: T) -> T {
  283. let value2 = value.clone();
  284. self.shared_contexts
  285. .borrow_mut()
  286. .insert(TypeId::of::<T>(), Box::new(value));
  287. value2
  288. }
  289. /// Pushes the future onto the poll queue to be polled after the component renders.
  290. pub fn push_future(&self, fut: impl Future<Output = ()> + 'static) -> TaskId {
  291. self.tasks.spawn(self.id, fut)
  292. }
  293. /// Spawns the future but does not return the [`TaskId`]
  294. pub fn spawn(&self, fut: impl Future<Output = ()> + 'static) {
  295. self.push_future(fut);
  296. }
  297. /// Spawn a future that Dioxus won't clean up when this component is unmounted
  298. ///
  299. /// This is good for tasks that need to be run after the component has been dropped.
  300. pub fn spawn_forever(&self, fut: impl Future<Output = ()> + 'static) -> TaskId {
  301. // The root scope will never be unmounted so we can just add the task at the top of the app
  302. let id = self.tasks.spawn(ScopeId(0), fut);
  303. // wake up the scheduler if it is sleeping
  304. self.tasks
  305. .sender
  306. .unbounded_send(SchedulerMsg::TaskNotified(id))
  307. .expect("Scheduler should exist");
  308. id
  309. }
  310. /// Informs the scheduler that this task is no longer needed and should be removed.
  311. ///
  312. /// This drops the task immediately.
  313. pub fn remove_future(&self, id: TaskId) {
  314. self.tasks.remove(id);
  315. }
  316. /// Take a lazy [`crate::VNode`] structure and actually build it with the context of the efficient [`bumpalo::Bump`] allocator.
  317. ///
  318. /// ## Example
  319. ///
  320. /// ```ignore
  321. /// fn Component(cx: Scope<Props>) -> Element {
  322. /// // Lazy assemble the VNode tree
  323. /// let lazy_nodes = rsx!("hello world");
  324. ///
  325. /// // Actually build the tree and allocate it
  326. /// cx.render(lazy_tree)
  327. /// }
  328. ///```
  329. pub fn render(&'src self, rsx: LazyNodes<'src, '_>) -> Element<'src> {
  330. let element = rsx.call(self);
  331. let mut listeners = self.listeners.borrow_mut();
  332. for attr in element.dynamic_attrs {
  333. if let AttributeValue::Listener(_) = attr.value {
  334. let unbounded = unsafe { std::mem::transmute(attr as *const Attribute) };
  335. listeners.push(unbounded);
  336. }
  337. }
  338. let mut props = self.borrowed_props.borrow_mut();
  339. for node in element.dynamic_nodes {
  340. if let DynamicNode::Component(comp) = node {
  341. let unbounded = unsafe { std::mem::transmute(comp as *const VComponent) };
  342. props.push(unbounded);
  343. }
  344. }
  345. Ok(element)
  346. }
  347. /// Create a dynamic text node using [`Arguments`] and the [`ScopeState`]'s internal [`Bump`] allocator
  348. pub fn text_node(&'src self, args: Arguments) -> DynamicNode<'src> {
  349. DynamicNode::Text(VText {
  350. value: self.raw_text(args),
  351. id: Default::default(),
  352. })
  353. }
  354. /// Allocate some text inside the [`ScopeState`] from [`Arguments`]
  355. ///
  356. /// Uses the currently active [`Bump`] allocator
  357. pub fn raw_text(&'src self, args: Arguments) -> &'src str {
  358. args.as_str().unwrap_or_else(|| {
  359. use bumpalo::core_alloc::fmt::Write;
  360. let mut str_buf = bumpalo::collections::String::new_in(self.bump());
  361. str_buf.write_fmt(args).unwrap();
  362. str_buf.into_bump_str()
  363. })
  364. }
  365. /// Convert any item that implements [`IntoDynNode`] into a [`DynamicNode`] using the internal [`Bump`] allocator
  366. pub fn make_node<'c, I>(&'src self, into: impl IntoDynNode<'src, I> + 'c) -> DynamicNode {
  367. into.into_vnode(self)
  368. }
  369. /// Create a new [`Attribute`] from a name, value, namespace, and volatile bool
  370. ///
  371. /// "Volatile" referes to whether or not Dioxus should always override the value. This helps prevent the UI in
  372. /// some renderers stay in sync with the VirtualDom's understanding of the world
  373. pub fn attr(
  374. &'src self,
  375. name: &'static str,
  376. value: impl IntoAttributeValue<'src>,
  377. namespace: Option<&'static str>,
  378. volatile: bool,
  379. ) -> Attribute<'src> {
  380. Attribute {
  381. name,
  382. namespace,
  383. volatile,
  384. mounted_element: Default::default(),
  385. value: value.into_value(self.bump()),
  386. }
  387. }
  388. /// Create a new [`DynamicNode::Component`] variant
  389. ///
  390. ///
  391. /// The given component can be any of four signatures. Remember that an [`Element`] is really a [`Result<VNode>`].
  392. ///
  393. /// ```rust, ignore
  394. /// // Without explicit props
  395. /// fn(Scope) -> Element;
  396. /// async fn(Scope<'_>) -> Element;
  397. ///
  398. /// // With explicit props
  399. /// fn(Scope<Props>) -> Element;
  400. /// async fn(Scope<Props<'_>>) -> Element;
  401. /// ```
  402. pub fn component<P, A, F: ComponentReturn<'src, A>>(
  403. &'src self,
  404. component: fn(Scope<'src, P>) -> F,
  405. props: P,
  406. fn_name: &'static str,
  407. ) -> DynamicNode<'src>
  408. where
  409. P: Properties + 'src,
  410. {
  411. let vcomp = VProps::new(component, P::memoize, props);
  412. // cast off the lifetime of the render return
  413. let as_dyn: Box<dyn AnyProps<'src> + '_> = Box::new(vcomp);
  414. let extended: Box<dyn AnyProps<'src> + 'src> = unsafe { std::mem::transmute(as_dyn) };
  415. DynamicNode::Component(VComponent {
  416. name: fn_name,
  417. render_fn: component as *const (),
  418. static_props: P::IS_STATIC,
  419. props: RefCell::new(Some(extended)),
  420. scope: Cell::new(None),
  421. })
  422. }
  423. /// Create a new [`EventHandler`] from an [`FnMut`]
  424. pub fn event_handler<T>(&'src self, f: impl FnMut(T) + 'src) -> EventHandler<'src, T> {
  425. let handler: &mut dyn FnMut(T) = self.bump().alloc(f);
  426. let caller = unsafe { BumpBox::from_raw(handler as *mut dyn FnMut(T)) };
  427. let callback = RefCell::new(Some(caller));
  428. EventHandler { callback }
  429. }
  430. /// Create a new [`AttributeValue`] with the listener variant from a callback
  431. ///
  432. /// The callback must be confined to the lifetime of the ScopeState
  433. pub fn listener<T: 'static>(
  434. &'src self,
  435. mut callback: impl FnMut(Event<T>) + 'src,
  436. ) -> AttributeValue<'src> {
  437. // safety: there's no other way to create a dynamicly-dispatched bump box other than alloc + from-raw
  438. // This is the suggested way to build a bumpbox
  439. //
  440. // In theory, we could just use regular boxes
  441. let boxed: BumpBox<'src, dyn FnMut(_) + 'src> = unsafe {
  442. BumpBox::from_raw(self.bump().alloc(move |event: Event<dyn Any>| {
  443. if let Ok(data) = event.data.downcast::<T>() {
  444. callback(Event {
  445. propogates: event.propogates,
  446. data,
  447. })
  448. }
  449. }))
  450. };
  451. AttributeValue::Listener(RefCell::new(Some(boxed)))
  452. }
  453. /// Store a value between renders. The foundational hook for all other hooks.
  454. ///
  455. /// Accepts an `initializer` closure, which is run on the first use of the hook (typically the initial render). The return value of this closure is stored for the lifetime of the component, and a mutable reference to it is provided on every render as the return value of `use_hook`.
  456. ///
  457. /// When the component is unmounted (removed from the UI), the value is dropped. This means you can return a custom type and provide cleanup code by implementing the [`Drop`] trait
  458. ///
  459. /// # Example
  460. ///
  461. /// ```
  462. /// use dioxus_core::ScopeState;
  463. ///
  464. /// // prints a greeting on the initial render
  465. /// pub fn use_hello_world(cx: &ScopeState) {
  466. /// cx.use_hook(|| println!("Hello, world!"));
  467. /// }
  468. /// ```
  469. #[allow(clippy::mut_from_ref)]
  470. pub fn use_hook<State: 'static>(&self, initializer: impl FnOnce() -> State) -> &mut State {
  471. let cur_hook = self.hook_idx.get();
  472. let mut hook_list = self.hook_list.borrow_mut();
  473. if cur_hook >= hook_list.len() {
  474. hook_list.push(self.hook_arena.alloc(initializer()));
  475. }
  476. hook_list
  477. .get(cur_hook)
  478. .and_then(|inn| {
  479. self.hook_idx.set(cur_hook + 1);
  480. let raw_box = unsafe { &mut **inn };
  481. raw_box.downcast_mut::<State>()
  482. })
  483. .expect(
  484. r###"
  485. Unable to retrieve the hook that was initialized at this index.
  486. Consult the `rules of hooks` to understand how to use hooks properly.
  487. You likely used the hook in a conditional. Hooks rely on consistent ordering between renders.
  488. Functions prefixed with "use" should never be called conditionally.
  489. "###,
  490. )
  491. }
  492. }