2021-07-15 08:09:28 +00:00
|
|
|
use crate::innerlude::*;
|
2021-11-03 23:55:02 +00:00
|
|
|
|
2021-11-05 21:15:59 +00:00
|
|
|
use futures_channel::mpsc::UnboundedSender;
|
2021-07-09 05:42:26 +00:00
|
|
|
use std::{
|
|
|
|
any::{Any, TypeId},
|
2021-10-08 20:01:13 +00:00
|
|
|
cell::{Cell, RefCell},
|
2021-09-01 04:57:04 +00:00
|
|
|
collections::HashMap,
|
2021-07-09 05:42:26 +00:00
|
|
|
future::Future,
|
2021-12-13 00:47:13 +00:00
|
|
|
pin::Pin,
|
2021-07-11 18:49:52 +00:00
|
|
|
rc::Rc,
|
2021-07-09 05:42:26 +00:00
|
|
|
};
|
|
|
|
|
2021-11-03 23:55:02 +00:00
|
|
|
use bumpalo::{boxed::Box as BumpBox, Bump};
|
|
|
|
|
|
|
|
/// Components in Dioxus use the "Context" object to interact with their lifecycle.
|
|
|
|
///
|
|
|
|
/// This lets components access props, schedule updates, integrate hooks, and expose shared state.
|
|
|
|
///
|
|
|
|
/// For the most part, the only method you should be using regularly is `render`.
|
|
|
|
///
|
|
|
|
/// ## Example
|
|
|
|
///
|
|
|
|
/// ```ignore
|
2021-11-05 20:28:08 +00:00
|
|
|
/// #[derive(Props)]
|
|
|
|
/// struct ExampleProps {
|
2021-11-03 23:55:02 +00:00
|
|
|
/// name: String
|
|
|
|
/// }
|
|
|
|
///
|
2021-12-19 04:03:59 +00:00
|
|
|
/// fn Example(cx: Scope<ExampleProps>) -> Element {
|
2021-12-15 20:56:53 +00:00
|
|
|
/// cx.render(rsx!{ div {"Hello, {cx.props.name}"} })
|
2021-11-03 23:55:02 +00:00
|
|
|
/// }
|
|
|
|
/// ```
|
2021-12-14 07:27:59 +00:00
|
|
|
pub struct Scope<'a, P> {
|
|
|
|
pub scope: &'a ScopeState,
|
2021-12-13 05:06:17 +00:00
|
|
|
pub props: &'a P,
|
|
|
|
}
|
2021-12-14 07:27:59 +00:00
|
|
|
|
2021-12-15 02:46:19 +00:00
|
|
|
impl<P> Copy for Scope<'_, P> {}
|
2021-12-14 07:27:59 +00:00
|
|
|
impl<P> Clone for Scope<'_, P> {
|
2021-12-13 05:06:17 +00:00
|
|
|
fn clone(&self) -> Self {
|
|
|
|
Self {
|
|
|
|
scope: self.scope,
|
|
|
|
props: self.props,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-12-15 02:46:19 +00:00
|
|
|
|
|
|
|
impl<'a, P> std::ops::Deref for Scope<'a, P> {
|
|
|
|
// rust will auto deref again to the original 'a lifetime at the call site
|
|
|
|
type Target = &'a ScopeState;
|
2021-12-13 05:06:17 +00:00
|
|
|
fn deref(&self) -> &Self::Target {
|
|
|
|
&self.scope
|
|
|
|
}
|
|
|
|
}
|
2021-11-03 23:55:02 +00:00
|
|
|
|
2021-12-13 00:47:13 +00:00
|
|
|
/// A component's unique identifier.
|
|
|
|
///
|
|
|
|
/// `ScopeId` is a `usize` that is unique across the entire VirtualDOM and across time. ScopeIDs will never be reused
|
|
|
|
/// once a component has been unmounted.
|
|
|
|
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
|
|
|
|
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
|
|
|
|
pub struct ScopeId(pub usize);
|
|
|
|
|
2021-12-19 04:03:59 +00:00
|
|
|
/// Every component in Dioxus is represented by a `ScopeState`.
|
2021-07-09 05:42:26 +00:00
|
|
|
///
|
|
|
|
/// Scopes contain the state for hooks, the component's props, and other lifecycle information.
|
|
|
|
///
|
|
|
|
/// Scopes are allocated in a generational arena. As components are mounted/unmounted, they will replace slots of dead components.
|
|
|
|
/// The actual contents of the hooks, though, will be allocated with the standard allocator. These should not allocate as frequently.
|
2021-07-15 08:09:28 +00:00
|
|
|
///
|
|
|
|
/// We expose the `Scope` type so downstream users can traverse the Dioxus VirtualDOM for whatever
|
2021-10-24 17:30:36 +00:00
|
|
|
/// use case they might have.
|
2021-12-14 07:27:59 +00:00
|
|
|
pub struct ScopeState {
|
|
|
|
pub(crate) parent_scope: Option<*mut ScopeState>,
|
2021-11-28 21:25:42 +00:00
|
|
|
|
2021-11-12 02:34:20 +00:00
|
|
|
pub(crate) container: ElementId,
|
2021-11-07 00:59:46 +00:00
|
|
|
|
2021-07-15 07:38:09 +00:00
|
|
|
pub(crate) our_arena_idx: ScopeId,
|
2021-11-07 00:59:46 +00:00
|
|
|
|
2021-07-15 07:38:09 +00:00
|
|
|
pub(crate) height: u32,
|
2021-11-05 21:15:59 +00:00
|
|
|
|
2021-10-08 20:01:13 +00:00
|
|
|
pub(crate) subtree: Cell<u32>,
|
2021-11-07 00:59:46 +00:00
|
|
|
|
2021-10-08 20:01:13 +00:00
|
|
|
pub(crate) is_subtree_root: Cell<bool>,
|
2021-07-09 05:42:26 +00:00
|
|
|
|
2021-11-08 03:36:57 +00:00
|
|
|
pub(crate) generation: Cell<u32>,
|
|
|
|
|
|
|
|
pub(crate) frames: [BumpFrame; 2],
|
2021-11-05 20:28:08 +00:00
|
|
|
|
2021-12-15 20:56:53 +00:00
|
|
|
pub(crate) caller: Cell<*const dyn Fn(&ScopeState) -> Element>,
|
2021-11-08 03:36:57 +00:00
|
|
|
|
2021-11-05 20:28:08 +00:00
|
|
|
pub(crate) items: RefCell<SelfReferentialItems<'static>>,
|
2021-11-03 23:55:02 +00:00
|
|
|
|
2021-11-28 21:25:42 +00:00
|
|
|
pub(crate) hook_arena: Bump,
|
2021-12-19 04:03:59 +00:00
|
|
|
|
|
|
|
pub(crate) hook_vals: RefCell<Vec<*mut dyn Any>>,
|
|
|
|
|
2021-11-28 21:25:42 +00:00
|
|
|
pub(crate) hook_idx: Cell<usize>,
|
2021-10-25 19:05:17 +00:00
|
|
|
|
2021-07-15 07:38:09 +00:00
|
|
|
pub(crate) shared_contexts: RefCell<HashMap<TypeId, Rc<dyn Any>>>,
|
2021-07-09 05:42:26 +00:00
|
|
|
|
2021-11-05 21:15:59 +00:00
|
|
|
pub(crate) sender: UnboundedSender<SchedulerMsg>,
|
2021-07-09 05:42:26 +00:00
|
|
|
}
|
|
|
|
|
2021-11-05 20:28:08 +00:00
|
|
|
pub struct SelfReferentialItems<'a> {
|
2021-11-07 06:01:22 +00:00
|
|
|
pub(crate) listeners: Vec<&'a Listener<'a>>,
|
|
|
|
pub(crate) borrowed_props: Vec<&'a VComponent<'a>>,
|
2021-12-13 00:47:13 +00:00
|
|
|
pub(crate) tasks: Vec<Pin<BumpBox<'a, dyn Future<Output = ()>>>>,
|
2021-09-13 22:55:43 +00:00
|
|
|
}
|
|
|
|
|
2021-11-07 06:01:22 +00:00
|
|
|
// Public methods exposed to libraries and components
|
2021-12-14 07:27:59 +00:00
|
|
|
impl ScopeState {
|
2021-11-05 20:28:08 +00:00
|
|
|
/// Get the subtree ID that this scope belongs to.
|
|
|
|
///
|
|
|
|
/// Each component has its own subtree ID - the root subtree has an ID of 0. This ID is used by the renderer to route
|
|
|
|
/// the mutations to the correct window/portal/subtree.
|
|
|
|
///
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
2021-11-12 02:34:20 +00:00
|
|
|
/// ```rust, ignore
|
2021-11-09 17:10:11 +00:00
|
|
|
/// let mut dom = VirtualDom::new(|cx, props|cx.render(rsx!{ div {} }));
|
2021-11-05 20:28:08 +00:00
|
|
|
/// dom.rebuild();
|
|
|
|
///
|
|
|
|
/// let base = dom.base_scope();
|
|
|
|
///
|
|
|
|
/// assert_eq!(base.subtree(), 0);
|
|
|
|
/// ```
|
2021-11-28 21:25:42 +00:00
|
|
|
///
|
|
|
|
/// todo: enable
|
|
|
|
pub(crate) fn _subtree(&self) -> u32 {
|
2021-11-05 20:28:08 +00:00
|
|
|
self.subtree.get()
|
|
|
|
}
|
|
|
|
|
2021-11-15 14:49:01 +00:00
|
|
|
/// Create a new subtree with this scope as the root of the subtree.
|
|
|
|
///
|
|
|
|
/// Each component has its own subtree ID - the root subtree has an ID of 0. This ID is used by the renderer to route
|
|
|
|
/// the mutations to the correct window/portal/subtree.
|
|
|
|
///
|
|
|
|
/// This method
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust, ignore
|
2021-12-19 04:03:59 +00:00
|
|
|
/// fn App(cx: Scope<()>) -> Element {
|
2021-11-15 14:49:01 +00:00
|
|
|
/// todo!();
|
|
|
|
/// rsx!(cx, div { "Subtree {id}"})
|
|
|
|
/// };
|
|
|
|
/// ```
|
2021-11-28 21:25:42 +00:00
|
|
|
///
|
|
|
|
/// todo: enable subtree
|
|
|
|
pub(crate) fn _create_subtree(&self) -> Option<u32> {
|
2021-11-15 14:49:01 +00:00
|
|
|
if self.is_subtree_root.get() {
|
|
|
|
None
|
|
|
|
} else {
|
|
|
|
todo!()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-05 20:28:08 +00:00
|
|
|
/// Get the height of this Scope - IE the number of scopes above it.
|
|
|
|
///
|
|
|
|
/// A Scope with a height of `0` is the root scope - there are no other scopes above it.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
2021-11-12 02:34:20 +00:00
|
|
|
/// ```rust, ignore
|
2021-12-01 03:48:05 +00:00
|
|
|
/// let mut dom = VirtualDom::new(|cx, props| cx.render(rsx!{ div {} }));
|
2021-11-05 20:28:08 +00:00
|
|
|
/// dom.rebuild();
|
|
|
|
///
|
|
|
|
/// let base = dom.base_scope();
|
|
|
|
///
|
|
|
|
/// assert_eq!(base.height(), 0);
|
|
|
|
/// ```
|
|
|
|
pub fn height(&self) -> u32 {
|
|
|
|
self.height
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Get the Parent of this Scope within this Dioxus VirtualDOM.
|
|
|
|
///
|
|
|
|
/// This ID is not unique across Dioxus VirtualDOMs or across time. IDs will be reused when components are unmounted.
|
|
|
|
///
|
|
|
|
/// The base component will not have a parent, and will return `None`.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
2021-11-12 02:34:20 +00:00
|
|
|
/// ```rust, ignore
|
2021-12-01 03:48:05 +00:00
|
|
|
/// let mut dom = VirtualDom::new(|cx, props| cx.render(rsx!{ div {} }));
|
2021-11-05 20:28:08 +00:00
|
|
|
/// dom.rebuild();
|
|
|
|
///
|
|
|
|
/// let base = dom.base_scope();
|
|
|
|
///
|
|
|
|
/// assert_eq!(base.parent(), None);
|
|
|
|
/// ```
|
|
|
|
pub fn parent(&self) -> Option<ScopeId> {
|
2021-11-28 21:25:42 +00:00
|
|
|
// safety: the pointer to our parent is *always* valid thanks to the bump arena
|
2021-11-12 02:34:20 +00:00
|
|
|
self.parent_scope.map(|p| unsafe { &*p }.our_arena_idx)
|
2021-11-05 20:28:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Get the ID of this Scope within this Dioxus VirtualDOM.
|
|
|
|
///
|
|
|
|
/// This ID is not unique across Dioxus VirtualDOMs or across time. IDs will be reused when components are unmounted.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
2021-11-12 02:34:20 +00:00
|
|
|
/// ```rust, ignore
|
2021-12-01 03:48:05 +00:00
|
|
|
/// let mut dom = VirtualDom::new(|cx, props| cx.render(rsx!{ div {} }));
|
2021-11-05 20:28:08 +00:00
|
|
|
/// dom.rebuild();
|
|
|
|
/// let base = dom.base_scope();
|
|
|
|
///
|
|
|
|
/// assert_eq!(base.scope_id(), 0);
|
|
|
|
/// ```
|
|
|
|
pub fn scope_id(&self) -> ScopeId {
|
|
|
|
self.our_arena_idx
|
|
|
|
}
|
|
|
|
|
2021-11-03 23:55:02 +00:00
|
|
|
/// Create a subscription that schedules a future render for the reference component
|
|
|
|
///
|
|
|
|
/// ## Notice: you should prefer using prepare_update and get_scope_id
|
|
|
|
pub fn schedule_update(&self) -> Rc<dyn Fn() + 'static> {
|
2021-11-28 21:25:42 +00:00
|
|
|
let (chan, id) = (self.sender.clone(), self.scope_id());
|
2021-11-05 20:28:08 +00:00
|
|
|
Rc::new(move || {
|
2021-11-07 06:01:22 +00:00
|
|
|
let _ = chan.unbounded_send(SchedulerMsg::Immediate(id));
|
2021-11-05 20:28:08 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Schedule an update for any component given its ScopeId.
|
|
|
|
///
|
|
|
|
/// A component's ScopeId can be obtained from `use_hook` or the [`Context::scope_id`] method.
|
|
|
|
///
|
|
|
|
/// This method should be used when you want to schedule an update for a component
|
|
|
|
pub fn schedule_update_any(&self) -> Rc<dyn Fn(ScopeId)> {
|
2021-11-05 21:15:59 +00:00
|
|
|
let chan = self.sender.clone();
|
2021-11-05 20:28:08 +00:00
|
|
|
Rc::new(move |id| {
|
2021-11-07 06:01:22 +00:00
|
|
|
let _ = chan.unbounded_send(SchedulerMsg::Immediate(id));
|
2021-11-05 20:28:08 +00:00
|
|
|
})
|
2021-11-03 23:55:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Get the [`ScopeId`] of a mounted component.
|
|
|
|
///
|
|
|
|
/// `ScopeId` is not unique for the lifetime of the VirtualDom - a ScopeId will be reused if a component is unmounted.
|
|
|
|
pub fn needs_update(&self) {
|
2021-11-05 20:28:08 +00:00
|
|
|
self.needs_update_any(self.scope_id())
|
2021-11-03 23:55:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Get the [`ScopeId`] of a mounted component.
|
|
|
|
///
|
|
|
|
/// `ScopeId` is not unique for the lifetime of the VirtualDom - a ScopeId will be reused if a component is unmounted.
|
|
|
|
pub fn needs_update_any(&self, id: ScopeId) {
|
2021-11-07 06:01:22 +00:00
|
|
|
let _ = self.sender.unbounded_send(SchedulerMsg::Immediate(id));
|
2021-11-03 23:55:02 +00:00
|
|
|
}
|
|
|
|
|
2021-12-13 00:47:13 +00:00
|
|
|
/// Get the Root Node of this scope
|
|
|
|
pub fn root_node(&self) -> &VNode {
|
2021-12-19 04:03:59 +00:00
|
|
|
let node = unsafe { &*self.wip_frame().node.get() };
|
|
|
|
unsafe { std::mem::transmute(node) }
|
2021-11-03 23:55:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// This method enables the ability to expose state to children further down the VirtualDOM Tree.
|
|
|
|
///
|
|
|
|
/// This is a "fundamental" operation and should only be called during initialization of a hook.
|
|
|
|
///
|
|
|
|
/// For a hook that provides the same functionality, use `use_provide_state` and `use_consume_state` instead.
|
|
|
|
///
|
|
|
|
/// When the component is dropped, so is the context. Be aware of this behavior when consuming
|
|
|
|
/// the context via Rc/Weak.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
2021-11-12 02:34:20 +00:00
|
|
|
/// ```rust, ignore
|
2021-11-03 23:55:02 +00:00
|
|
|
/// struct SharedState(&'static str);
|
|
|
|
///
|
2021-12-15 20:56:53 +00:00
|
|
|
/// static App: Component<()> = |cx, props|{
|
2021-11-03 23:55:02 +00:00
|
|
|
/// cx.use_hook(|_| cx.provide_state(SharedState("world")), |_| {}, |_| {});
|
|
|
|
/// rsx!(cx, Child {})
|
|
|
|
/// }
|
|
|
|
///
|
2021-12-15 20:56:53 +00:00
|
|
|
/// static Child: Component<()> = |cx| {
|
2021-11-03 23:55:02 +00:00
|
|
|
/// let state = cx.consume_state::<SharedState>();
|
|
|
|
/// rsx!(cx, div { "hello {state.0}" })
|
|
|
|
/// }
|
|
|
|
/// ```
|
2021-11-09 19:36:26 +00:00
|
|
|
pub fn provide_state<T: 'static>(&self, value: T) {
|
2021-11-03 23:55:02 +00:00
|
|
|
self.shared_contexts
|
|
|
|
.borrow_mut()
|
|
|
|
.insert(TypeId::of::<T>(), Rc::new(value))
|
|
|
|
.map(|f| f.downcast::<T>().ok())
|
|
|
|
.flatten();
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Try to retrieve a SharedState with type T from the any parent Scope.
|
2021-11-05 21:15:59 +00:00
|
|
|
pub fn consume_state<T: 'static>(&self) -> Option<Rc<T>> {
|
|
|
|
if let Some(shared) = self.shared_contexts.borrow().get(&TypeId::of::<T>()) {
|
|
|
|
Some(shared.clone().downcast::<T>().unwrap())
|
|
|
|
} else {
|
|
|
|
let mut search_parent = self.parent_scope;
|
|
|
|
|
|
|
|
while let Some(parent_ptr) = search_parent {
|
2021-12-10 02:19:31 +00:00
|
|
|
// safety: all parent pointers are valid thanks to the bump arena
|
2021-11-05 21:15:59 +00:00
|
|
|
let parent = unsafe { &*parent_ptr };
|
|
|
|
if let Some(shared) = parent.shared_contexts.borrow().get(&TypeId::of::<T>()) {
|
|
|
|
return Some(shared.clone().downcast::<T>().unwrap());
|
|
|
|
}
|
|
|
|
search_parent = parent.parent_scope;
|
|
|
|
}
|
|
|
|
None
|
|
|
|
}
|
2021-11-03 23:55:02 +00:00
|
|
|
}
|
|
|
|
|
2021-11-28 21:25:42 +00:00
|
|
|
/// Pushes the future onto the poll queue to be polled after the component renders.
|
|
|
|
///
|
2021-11-15 14:49:01 +00:00
|
|
|
/// The future is forcibly dropped if the component is not ready by the next render
|
2021-12-13 00:47:13 +00:00
|
|
|
pub fn push_task<'src, F>(&'src self, fut: impl FnOnce() -> F + 'src) -> usize
|
2021-11-16 06:25:38 +00:00
|
|
|
where
|
2021-12-13 00:47:13 +00:00
|
|
|
F: Future<Output = ()>,
|
2021-11-16 06:25:38 +00:00
|
|
|
F::Output: 'src,
|
|
|
|
F: 'src,
|
|
|
|
{
|
|
|
|
self.sender
|
2021-11-28 21:25:42 +00:00
|
|
|
.unbounded_send(SchedulerMsg::NewTask(self.our_arena_idx))
|
2021-11-16 06:25:38 +00:00
|
|
|
.unwrap();
|
|
|
|
|
2021-11-15 14:49:01 +00:00
|
|
|
// wrap it in a type that will actually drop the contents
|
2021-12-13 00:47:13 +00:00
|
|
|
//
|
|
|
|
// Safety: we just made the pointer above and will promise not to alias it!
|
|
|
|
// The main reason we do this through from_raw is because Bumpalo's box does
|
|
|
|
// not support unsized coercion
|
|
|
|
let fut: &mut dyn Future<Output = ()> = self.bump().alloc(fut());
|
2021-11-15 14:49:01 +00:00
|
|
|
let boxed_fut: BumpBox<dyn Future<Output = ()>> = unsafe { BumpBox::from_raw(fut) };
|
2021-12-13 00:47:13 +00:00
|
|
|
let pinned_fut: Pin<BumpBox<_>> = boxed_fut.into();
|
2021-11-15 14:49:01 +00:00
|
|
|
|
|
|
|
// erase the 'src lifetime for self-referential storage
|
2021-12-19 04:03:59 +00:00
|
|
|
// todo: provide a miri test around this
|
|
|
|
// concerned about segfaulting
|
2021-12-13 00:47:13 +00:00
|
|
|
let self_ref_fut = unsafe { std::mem::transmute(pinned_fut) };
|
2021-11-15 14:49:01 +00:00
|
|
|
|
2021-12-13 00:47:13 +00:00
|
|
|
// Push the future into the tasks
|
2021-11-15 14:49:01 +00:00
|
|
|
let mut items = self.items.borrow_mut();
|
|
|
|
items.tasks.push(self_ref_fut);
|
|
|
|
items.tasks.len() - 1
|
|
|
|
}
|
|
|
|
|
2021-12-15 02:46:19 +00:00
|
|
|
/// Take a lazy VNode structure and actually build it with the context of the VDom's efficient VNode allocator.
|
|
|
|
///
|
|
|
|
/// This function consumes the context and absorb the lifetime, so these VNodes *must* be returned.
|
|
|
|
///
|
|
|
|
/// ## Example
|
|
|
|
///
|
|
|
|
/// ```ignore
|
2021-12-15 20:56:53 +00:00
|
|
|
/// fn Component(cx: Scope<Props>) -> Element {
|
2021-12-15 02:46:19 +00:00
|
|
|
/// // Lazy assemble the VNode tree
|
|
|
|
/// let lazy_nodes = rsx!("hello world");
|
|
|
|
///
|
|
|
|
/// // Actually build the tree and allocate it
|
|
|
|
/// cx.render(lazy_tree)
|
|
|
|
/// }
|
|
|
|
///```
|
|
|
|
pub fn render<'src>(&'src self, rsx: Option<LazyNodes<'src, '_>>) -> Option<VNode<'src>> {
|
|
|
|
let fac = NodeFactory {
|
|
|
|
bump: &self.wip_frame().bump,
|
|
|
|
};
|
|
|
|
match rsx {
|
|
|
|
Some(s) => Some(s.call(fac)),
|
2021-12-19 04:03:59 +00:00
|
|
|
None => todo!("oh no no nodes"),
|
2021-12-15 02:46:19 +00:00
|
|
|
}
|
|
|
|
}
|
2021-11-03 23:55:02 +00:00
|
|
|
|
|
|
|
/// Store a value between renders
|
|
|
|
///
|
|
|
|
/// This is *the* foundational hook for all other hooks.
|
|
|
|
///
|
|
|
|
/// - Initializer: closure used to create the initial hook state
|
|
|
|
/// - Runner: closure used to output a value every time the hook is used
|
|
|
|
///
|
2021-11-05 20:28:08 +00:00
|
|
|
/// To "cleanup" the hook, implement `Drop` on the stored hook value. Whenever the component is dropped, the hook
|
|
|
|
/// will be dropped as well.
|
2021-11-03 23:55:02 +00:00
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```ignore
|
|
|
|
/// // use_ref is the simplest way of storing a value between renders
|
|
|
|
/// fn use_ref<T: 'static>(initial_value: impl FnOnce() -> T) -> &RefCell<T> {
|
|
|
|
/// use_hook(
|
|
|
|
/// || Rc::new(RefCell::new(initial_value())),
|
|
|
|
/// |state| state,
|
|
|
|
/// )
|
|
|
|
/// }
|
|
|
|
/// ```
|
2021-11-05 20:28:08 +00:00
|
|
|
pub fn use_hook<'src, State: 'static, Output: 'src>(
|
2021-11-03 23:55:02 +00:00
|
|
|
&'src self,
|
2021-11-05 20:28:08 +00:00
|
|
|
initializer: impl FnOnce(usize) -> State,
|
|
|
|
runner: impl FnOnce(&'src mut State) -> Output,
|
|
|
|
) -> Output {
|
2021-11-28 21:25:42 +00:00
|
|
|
let mut vals = self.hook_vals.borrow_mut();
|
2021-12-13 00:47:13 +00:00
|
|
|
|
2021-11-28 21:25:42 +00:00
|
|
|
let hook_len = vals.len();
|
|
|
|
let cur_idx = self.hook_idx.get();
|
|
|
|
|
|
|
|
if cur_idx >= hook_len {
|
2021-12-13 00:47:13 +00:00
|
|
|
vals.push(self.hook_arena.alloc(initializer(hook_len)));
|
2021-11-03 23:55:02 +00:00
|
|
|
}
|
|
|
|
|
2021-11-28 21:25:42 +00:00
|
|
|
let state = vals
|
|
|
|
.get(cur_idx)
|
|
|
|
.and_then(|inn| {
|
|
|
|
self.hook_idx.set(cur_idx + 1);
|
|
|
|
let raw_box = unsafe { &mut **inn };
|
|
|
|
raw_box.downcast_mut::<State>()
|
|
|
|
})
|
|
|
|
.expect(
|
|
|
|
r###"
|
|
|
|
Unable to retrieve the hook that was initialized at this index.
|
|
|
|
Consult the `rules of hooks` to understand how to use hooks properly.
|
2021-11-03 23:55:02 +00:00
|
|
|
|
2021-11-28 21:25:42 +00:00
|
|
|
You likely used the hook in a conditional. Hooks rely on consistent ordering between renders.
|
|
|
|
Functions prefixed with "use" should never be called conditionally.
|
|
|
|
"###,
|
|
|
|
);
|
2021-11-07 06:01:22 +00:00
|
|
|
|
2021-11-28 21:25:42 +00:00
|
|
|
runner(state)
|
2021-11-07 06:01:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// The "work in progress frame" represents the frame that is currently being worked on.
|
2021-11-08 03:36:57 +00:00
|
|
|
pub(crate) fn wip_frame(&self) -> &BumpFrame {
|
|
|
|
match self.generation.get() & 1 == 0 {
|
|
|
|
true => &self.frames[0],
|
|
|
|
false => &self.frames[1],
|
|
|
|
}
|
|
|
|
}
|
2021-11-10 22:09:52 +00:00
|
|
|
|
2021-12-13 00:47:13 +00:00
|
|
|
/// Mutable access to the "work in progress frame" - used to clear it
|
2021-11-12 02:34:20 +00:00
|
|
|
pub(crate) fn wip_frame_mut(&mut self) -> &mut BumpFrame {
|
|
|
|
match self.generation.get() & 1 == 0 {
|
|
|
|
true => &mut self.frames[0],
|
|
|
|
false => &mut self.frames[1],
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-13 00:47:13 +00:00
|
|
|
/// Access to the frame where finalized nodes existed
|
2021-11-08 03:36:57 +00:00
|
|
|
pub(crate) fn fin_frame(&self) -> &BumpFrame {
|
|
|
|
match self.generation.get() & 1 == 1 {
|
|
|
|
true => &self.frames[0],
|
|
|
|
false => &self.frames[1],
|
|
|
|
}
|
2021-11-07 06:01:22 +00:00
|
|
|
}
|
|
|
|
|
2021-11-12 02:34:20 +00:00
|
|
|
/// Reset this component's frame
|
|
|
|
///
|
|
|
|
/// # Safety:
|
2021-12-13 00:47:13 +00:00
|
|
|
///
|
2021-11-12 02:34:20 +00:00
|
|
|
/// This method breaks every reference of VNodes in the current frame.
|
2021-12-13 00:47:13 +00:00
|
|
|
///
|
|
|
|
/// Calling reset itself is not usually a big deal, but we consider it important
|
|
|
|
/// due to the complex safety guarantees we need to uphold.
|
2021-11-12 02:34:20 +00:00
|
|
|
pub(crate) unsafe fn reset_wip_frame(&mut self) {
|
2021-12-13 00:47:13 +00:00
|
|
|
self.wip_frame_mut().bump.reset();
|
2021-11-08 03:36:57 +00:00
|
|
|
}
|
2021-11-07 06:01:22 +00:00
|
|
|
|
2021-12-13 00:47:13 +00:00
|
|
|
/// Cycle to the next generation
|
2021-11-12 02:34:20 +00:00
|
|
|
pub(crate) fn cycle_frame(&self) {
|
2021-11-08 03:36:57 +00:00
|
|
|
self.generation.set(self.generation.get() + 1);
|
2021-11-07 06:01:22 +00:00
|
|
|
}
|
|
|
|
|
2021-12-13 00:47:13 +00:00
|
|
|
/// Get the [`Bump`] of the WIP frame.
|
|
|
|
pub(crate) fn bump(&self) -> &Bump {
|
|
|
|
&self.wip_frame().bump
|
2021-11-10 22:09:52 +00:00
|
|
|
}
|
2021-12-19 04:03:59 +00:00
|
|
|
|
|
|
|
pub(crate) fn drop_hooks(&mut self) {
|
|
|
|
self.hook_vals.get_mut().drain(..).for_each(|state| {
|
|
|
|
let as_mut = unsafe { &mut *state };
|
|
|
|
let boxed = unsafe { bumpalo::boxed::Box::from_raw(as_mut) };
|
|
|
|
drop(boxed);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
pub(crate) fn reset(&mut self) {
|
|
|
|
// we're just reusing scopes so we need to clear it out
|
|
|
|
self.drop_hooks();
|
|
|
|
|
|
|
|
self.hook_idx.set(0);
|
|
|
|
|
|
|
|
self.hook_arena.reset();
|
|
|
|
self.shared_contexts.get_mut().clear();
|
|
|
|
self.parent_scope = None;
|
|
|
|
self.generation.set(0);
|
|
|
|
self.is_subtree_root.set(false);
|
|
|
|
self.subtree.set(0);
|
|
|
|
|
|
|
|
self.frames[0].reset();
|
|
|
|
self.frames[1].reset();
|
|
|
|
|
|
|
|
let SelfReferentialItems {
|
|
|
|
borrowed_props,
|
|
|
|
listeners,
|
|
|
|
tasks,
|
|
|
|
} = self.items.get_mut();
|
|
|
|
|
|
|
|
borrowed_props.clear();
|
|
|
|
listeners.clear();
|
|
|
|
tasks.clear();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Drop for ScopeState {
|
|
|
|
fn drop(&mut self) {
|
|
|
|
self.drop_hooks();
|
|
|
|
}
|
2021-11-07 06:01:22 +00:00
|
|
|
}
|
2021-11-08 03:36:57 +00:00
|
|
|
|
2021-11-10 22:09:52 +00:00
|
|
|
pub(crate) struct BumpFrame {
|
2021-11-08 03:36:57 +00:00
|
|
|
pub bump: Bump,
|
2021-12-19 04:03:59 +00:00
|
|
|
pub node: Cell<*const VNode<'static>>,
|
2021-11-08 03:36:57 +00:00
|
|
|
}
|
|
|
|
impl BumpFrame {
|
2021-12-13 00:47:13 +00:00
|
|
|
pub(crate) fn new(capacity: usize) -> Self {
|
2021-11-10 22:09:52 +00:00
|
|
|
let bump = Bump::with_capacity(capacity);
|
2021-11-08 03:36:57 +00:00
|
|
|
|
|
|
|
let node = &*bump.alloc(VText {
|
2021-12-19 04:03:59 +00:00
|
|
|
text: "placeholdertext",
|
2021-11-08 03:36:57 +00:00
|
|
|
dom_id: Default::default(),
|
|
|
|
is_static: false,
|
|
|
|
});
|
2021-11-10 22:09:52 +00:00
|
|
|
let node = bump.alloc(VNode::Text(unsafe { std::mem::transmute(node) }));
|
2021-12-15 02:46:19 +00:00
|
|
|
let nodes = Cell::new(node as *const _);
|
2021-12-19 04:03:59 +00:00
|
|
|
Self { bump, node: nodes }
|
|
|
|
}
|
|
|
|
|
|
|
|
pub(crate) fn reset(&mut self) {
|
|
|
|
self.bump.reset();
|
|
|
|
let node = self.bump.alloc(VText {
|
|
|
|
text: "placeholdertext",
|
|
|
|
dom_id: Default::default(),
|
|
|
|
is_static: false,
|
|
|
|
});
|
|
|
|
let node = self
|
|
|
|
.bump
|
|
|
|
.alloc(VNode::Text(unsafe { std::mem::transmute(node) }));
|
|
|
|
self.node.set(node as *const _);
|
2021-11-08 03:36:57 +00:00
|
|
|
}
|
|
|
|
}
|
2021-11-09 17:10:11 +00:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn sizeof() {
|
2021-12-14 07:27:59 +00:00
|
|
|
dbg!(std::mem::size_of::<ScopeState>());
|
2021-11-09 17:10:11 +00:00
|
|
|
}
|