use crate::innerlude::*;
use futures_channel::mpsc::UnboundedSender;
use smallvec::SmallVec;
use std::{
any::{Any, TypeId},
cell::{Cell, RefCell},
collections::HashMap,
future::Future,
pin::Pin,
rc::Rc,
};
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
/// #[derive(Props)]
/// struct ExampleProps {
/// name: String
/// }
///
/// fn Example(cx: Context, props: &ExampleProps) -> Element {
/// cx.render(rsx!{ div {"Hello, {props.name}"} })
/// }
/// ```
pub struct Context<'a, P: 'static> {
pub scope: &'a Scope,
pub props: &'a P,
}
impl
Clone for Context<'_, P> {
fn clone(&self) -> Self {
Self {
scope: self.scope,
props: self.props,
}
}
}
impl
Copy for Context<'_, P> {}
impl
std::ops::Deref for Context<'_, P> {
type Target = Scope;
fn deref(&self) -> &Self::Target {
&self.scope
}
}
pub trait AnyContext<'a> {
fn get_scope(&self) -> &'a Scope;
}
impl<'a, P> AnyContext<'a> for Context<'a, P> {
fn get_scope(&self) -> &'a Scope {
&self.scope
}
}
/// 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);
/// Every component in Dioxus is represented by a `Scope`.
///
/// 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.
///
/// We expose the `Scope` type so downstream users can traverse the Dioxus VirtualDOM for whatever
/// use case they might have.
pub struct Scope {
pub(crate) parent_scope: Option<*mut Scope>,
pub(crate) container: ElementId,
pub(crate) our_arena_idx: ScopeId,
pub(crate) height: u32,
pub(crate) subtree: Cell,
pub(crate) is_subtree_root: Cell,
pub(crate) generation: Cell,
pub(crate) frames: [BumpFrame; 2],
pub(crate) caller: *const dyn Fn(&Scope) -> Element,
pub(crate) items: RefCell>,
pub(crate) hook_arena: Bump,
pub(crate) hook_vals: RefCell>,
pub(crate) hook_idx: Cell,
pub(crate) shared_contexts: RefCell>>,
pub(crate) sender: UnboundedSender,
}
pub struct SelfReferentialItems<'a> {
pub(crate) listeners: Vec<&'a Listener<'a>>,
pub(crate) borrowed_props: Vec<&'a VComponent<'a>>,
pub(crate) tasks: Vec>>>,
}
// Public methods exposed to libraries and components
impl Scope {
/// 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
///
/// ```rust, ignore
/// let mut dom = VirtualDom::new(|cx, props|cx.render(rsx!{ div {} }));
/// dom.rebuild();
///
/// let base = dom.base_scope();
///
/// assert_eq!(base.subtree(), 0);
/// ```
///
/// todo: enable
pub(crate) fn _subtree(&self) -> u32 {
self.subtree.get()
}
/// 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
/// fn App(cx: Context, props: &()) -> Element {
/// todo!();
/// rsx!(cx, div { "Subtree {id}"})
/// };
/// ```
///
/// todo: enable subtree
pub(crate) fn _create_subtree(&self) -> Option {
if self.is_subtree_root.get() {
None
} else {
todo!()
}
}
/// 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
///
/// ```rust, ignore
/// let mut dom = VirtualDom::new(|cx, props| cx.render(rsx!{ div {} }));
/// 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
///
/// ```rust, ignore
/// let mut dom = VirtualDom::new(|cx, props| cx.render(rsx!{ div {} }));
/// dom.rebuild();
///
/// let base = dom.base_scope();
///
/// assert_eq!(base.parent(), None);
/// ```
pub fn parent(&self) -> Option {
// safety: the pointer to our parent is *always* valid thanks to the bump arena
self.parent_scope.map(|p| unsafe { &*p }.our_arena_idx)
}
/// 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
///
/// ```rust, ignore
/// let mut dom = VirtualDom::new(|cx, props| cx.render(rsx!{ div {} }));
/// dom.rebuild();
/// let base = dom.base_scope();
///
/// assert_eq!(base.scope_id(), 0);
/// ```
pub fn scope_id(&self) -> ScopeId {
self.our_arena_idx
}
/// 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 {
let (chan, id) = (self.sender.clone(), self.scope_id());
Rc::new(move || {
let _ = chan.unbounded_send(SchedulerMsg::Immediate(id));
})
}
/// 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 {
let chan = self.sender.clone();
Rc::new(move |id| {
let _ = chan.unbounded_send(SchedulerMsg::Immediate(id));
})
}
/// 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) {
self.needs_update_any(self.scope_id())
}
/// 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) {
let _ = self.sender.unbounded_send(SchedulerMsg::Immediate(id));
}
/// Get the Root Node of this scope
pub fn root_node(&self) -> &VNode {
todo!("Portals have changed how we address nodes. Still fixing this, sorry.");
// let node = *self.wip_frame().nodes.borrow().get(0).unwrap();
// unsafe { std::mem::transmute(&*node) }
}
/// 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
///
/// ```rust, ignore
/// struct SharedState(&'static str);
///
/// static App: FC<()> = |cx, props|{
/// cx.use_hook(|_| cx.provide_state(SharedState("world")), |_| {}, |_| {});
/// rsx!(cx, Child {})
/// }
///
/// static Child: FC<()> = |cx, props| {
/// let state = cx.consume_state::();
/// rsx!(cx, div { "hello {state.0}" })
/// }
/// ```
pub fn provide_state(&self, value: T) {
self.shared_contexts
.borrow_mut()
.insert(TypeId::of::(), Rc::new(value))
.map(|f| f.downcast::().ok())
.flatten();
}
/// Try to retrieve a SharedState with type T from the any parent Scope.
pub fn consume_state(&self) -> Option> {
if let Some(shared) = self.shared_contexts.borrow().get(&TypeId::of::()) {
Some(shared.clone().downcast::().unwrap())
} else {
let mut search_parent = self.parent_scope;
while let Some(parent_ptr) = search_parent {
// safety: all parent pointers are valid thanks to the bump arena
let parent = unsafe { &*parent_ptr };
if let Some(shared) = parent.shared_contexts.borrow().get(&TypeId::of::()) {
return Some(shared.clone().downcast::().unwrap());
}
search_parent = parent.parent_scope;
}
None
}
}
/// Pushes the future onto the poll queue to be polled after the component renders.
///
/// The future is forcibly dropped if the component is not ready by the next render
pub fn push_task<'src, F>(&'src self, fut: impl FnOnce() -> F + 'src) -> usize
where
F: Future