dioxus/packages/core/src/scope.rs

244 lines
8.4 KiB
Rust
Raw Normal View History

use crate::innerlude::*;
use bumpalo::boxed::Box as BumpBox;
2021-07-29 22:04:09 +00:00
use fxhash::FxHashSet;
2021-07-09 05:42:26 +00:00
use std::{
any::{Any, TypeId},
2021-07-26 16:14:48 +00:00
borrow::BorrowMut,
2021-07-09 05:42:26 +00:00
cell::{Cell, RefCell},
2021-07-13 20:54:07 +00:00
collections::{HashMap, HashSet},
2021-07-09 05:42:26 +00:00
future::Future,
pin::Pin,
rc::Rc,
2021-07-09 05:42:26 +00:00
};
/// 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
/// usecase they might have.
2021-07-09 05:42:26 +00:00
pub struct Scope {
// Book-keeping about our spot in the arena
pub(crate) parent_idx: Option<ScopeId>,
pub(crate) our_arena_idx: ScopeId,
pub(crate) height: u32,
2021-07-29 22:04:09 +00:00
pub(crate) descendents: RefCell<FxHashSet<ScopeId>>,
2021-07-09 05:42:26 +00:00
// Nodes
2021-07-09 05:42:26 +00:00
// an internal, highly efficient storage of vnodes
2021-07-29 22:04:09 +00:00
// lots of safety condsiderations
pub(crate) frames: ActiveFrame,
pub(crate) caller: Rc<WrappedCaller>,
2021-07-26 16:14:48 +00:00
pub(crate) child_nodes: ScopeChildren<'static>,
2021-07-29 22:04:09 +00:00
pub(crate) pending_garbage: RefCell<Vec<*const VNode<'static>>>,
2021-07-09 05:42:26 +00:00
// Listeners
pub(crate) listeners: RefCell<Vec<*const Listener<'static>>>,
2021-07-09 05:42:26 +00:00
// State
pub(crate) hooks: HookList,
pub(crate) shared_contexts: RefCell<HashMap<TypeId, Rc<dyn Any>>>,
2021-07-09 05:42:26 +00:00
// A reference to the resources shared by all the comonents
pub(crate) vdom: SharedResources,
2021-07-09 05:42:26 +00:00
}
// The type of closure that wraps calling components
2021-07-18 16:39:32 +00:00
pub type WrappedCaller = dyn for<'b> Fn(&'b Scope) -> DomTree<'b>;
// The type of task that gets sent to the task scheduler
pub type FiberTask = Pin<Box<dyn Future<Output = EventTrigger>>>;
2021-07-09 05:42:26 +00:00
impl Scope {
// we are being created in the scope of an existing component (where the creator_node lifetime comes into play)
// we are going to break this lifetime by force in order to save it on ourselves.
// To make sure that the lifetime isn't truly broken, we receive a Weak RC so we can't keep it around after the parent dies.
// This should never happen, but is a good check to keep around
//
// Scopes cannot be made anywhere else except for this file
// Therefore, their lifetimes are connected exclusively to the virtual dom
pub fn new<'creator_node>(
caller: Rc<WrappedCaller>,
arena_idx: ScopeId,
parent: Option<ScopeId>,
2021-07-09 05:42:26 +00:00
height: u32,
2021-07-26 16:14:48 +00:00
child_nodes: ScopeChildren,
2021-07-29 22:04:09 +00:00
vdom: SharedResources,
2021-07-09 05:42:26 +00:00
) -> Self {
2021-07-26 16:14:48 +00:00
let child_nodes = unsafe { child_nodes.extend_lifetime() };
2021-07-29 22:04:09 +00:00
// insert ourself as a descendent of the parent
// when the parent is removed, this map will be traversed, and we will also be cleaned up.
if let Some(parent) = &parent {
let parent = unsafe { vdom.get_scope(*parent) }.unwrap();
parent.descendents.borrow_mut().insert(arena_idx);
}
2021-07-09 05:42:26 +00:00
Self {
child_nodes,
caller,
parent_idx: parent,
our_arena_idx: arena_idx,
2021-07-09 05:42:26 +00:00
height,
vdom,
2021-07-09 05:42:26 +00:00
frames: ActiveFrame::new(),
2021-07-29 22:04:09 +00:00
2021-07-09 05:42:26 +00:00
hooks: Default::default(),
shared_contexts: Default::default(),
listeners: Default::default(),
descendents: Default::default(),
2021-07-29 22:04:09 +00:00
pending_garbage: Default::default(),
2021-07-09 05:42:26 +00:00
}
}
pub(crate) fn update_scope_dependencies<'creator_node>(
2021-07-09 05:42:26 +00:00
&mut self,
caller: Rc<WrappedCaller>,
2021-07-26 16:14:48 +00:00
child_nodes: ScopeChildren,
2021-07-09 05:42:26 +00:00
) {
self.caller = caller;
2021-07-26 16:14:48 +00:00
// let child_nodes = unsafe { std::mem::transmute(child_nodes) };
let child_nodes = unsafe { child_nodes.extend_lifetime() };
2021-07-09 05:42:26 +00:00
self.child_nodes = child_nodes;
}
pub(crate) fn run_scope<'sel>(&'sel mut self) -> Result<()> {
2021-07-09 05:42:26 +00:00
// Cycle to the next frame and then reset it
// This breaks any latent references, invalidating every pointer referencing into it.
// Remove all the outdated listeners
2021-07-29 22:04:09 +00:00
if !self.pending_garbage.borrow().is_empty() {
panic!("cannot run scope while garbage is pending! Please clean up your mess first");
}
2021-07-26 16:14:48 +00:00
log::debug!("reset okay");
2021-07-09 05:42:26 +00:00
// make sure we call the drop implementation on all the listeners
// this is important to not leak memory
2021-07-27 04:27:07 +00:00
for listener in self
.listeners
.borrow_mut()
.drain(..)
.map(|li| unsafe { &*li })
{
let mut cb = listener.callback.borrow_mut();
match cb.take() {
Some(val) => std::mem::drop(val),
None => log::info!("no callback to drop. component must be broken"),
};
2021-07-26 16:14:48 +00:00
}
2021-07-27 04:27:07 +00:00
// Safety:
// - We dropped the listeners, so no more &mut T can be used while these are held
// - All children nodes that rely on &mut T are replaced with a new reference
2021-07-09 05:42:26 +00:00
unsafe { self.hooks.reset() };
2021-07-26 16:14:48 +00:00
2021-07-27 04:27:07 +00:00
// Safety:
// - We've dropped all references to the wip bump frame
unsafe { self.frames.reset_wip_frame() };
2021-07-26 16:14:48 +00:00
2021-07-09 05:42:26 +00:00
// Cast the caller ptr from static to one with our own reference
let c3: &WrappedCaller = self.caller.as_ref();
2021-07-09 05:42:26 +00:00
2021-07-20 23:03:49 +00:00
match c3(self) {
None => {
// the user's component failed. We avoid cycling to the next frame
log::error!("Running your component failed! It will no longer receive events.");
Err(Error::ComponentFailed)
}
Some(new_head) => {
// the user's component succeeded. We can safely cycle to the next frame
2021-07-26 16:14:48 +00:00
self.frames.wip_frame_mut().head_node = unsafe { std::mem::transmute(new_head) };
2021-07-20 23:03:49 +00:00
self.frames.cycle_frame();
2021-07-26 16:14:48 +00:00
log::debug!("Cycle okay");
2021-07-20 23:03:49 +00:00
Ok(())
}
}
2021-07-09 05:42:26 +00:00
}
// A safe wrapper around calling listeners
// calling listeners will invalidate the list of listeners
// The listener list will be completely drained because the next frame will write over previous listeners
pub(crate) fn call_listener(&mut self, trigger: EventTrigger) -> Result<()> {
2021-07-09 05:42:26 +00:00
let EventTrigger {
real_node_id,
event,
..
} = trigger;
2021-07-15 03:18:02 +00:00
if let &VirtualEvent::AsyncEvent { .. } = &event {
log::info!("arrived a fiber event");
return Ok(());
}
log::debug!(
"There are {:?} listeners associated with this scope {:#?}",
self.listeners.borrow().len(),
self.our_arena_idx
);
2021-07-13 20:48:47 +00:00
let listners = self.listeners.borrow_mut();
let raw_listener = listners.iter().find(|lis| {
let search = unsafe { &***lis };
let search_id = search.mounted_node.get();
2021-07-26 16:14:48 +00:00
log::info!(
"searching listener {:#?} for real {:?}",
search_id,
real_node_id
);
match (real_node_id, search_id) {
(Some(e), Some(search_id)) => search_id == e,
_ => false,
}
});
if let Some(raw_listener) = raw_listener {
let listener = unsafe { &**raw_listener };
2021-07-26 16:14:48 +00:00
2021-07-29 22:04:09 +00:00
// log::info!(
// "calling listener {:?}, {:?}",
// listener.event,
// // listener.scope
// );
let mut cb = listener.callback.borrow_mut();
2021-07-26 16:14:48 +00:00
if let Some(cb) = cb.as_mut() {
(cb)(event);
}
} else {
log::warn!("An event was triggered but there was no listener to handle it");
2021-07-09 05:42:26 +00:00
}
Ok(())
}
2021-07-26 16:14:48 +00:00
pub fn root(&self) -> &VNode {
self.frames.fin_head()
2021-07-09 05:42:26 +00:00
}
2021-07-26 16:14:48 +00:00
pub fn child_nodes<'a>(&'a self) -> ScopeChildren {
unsafe { self.child_nodes.unextend_lfetime() }
2021-07-29 22:04:09 +00:00
}
pub fn consume_garbage(&self) -> Vec<&VNode> {
let mut garbage = self.pending_garbage.borrow_mut();
garbage
.drain(..)
.map(|node| {
// safety: scopes cannot cycle without their garbage being collected. these nodes are safe
let node: &VNode<'static> = unsafe { &*node };
let node: &VNode = unsafe { std::mem::transmute(node) };
node
})
.collect::<Vec<_>>()
2021-07-18 16:39:32 +00:00
}
}