dioxus/packages/core/src/nodes.rs

462 lines
15 KiB
Rust
Raw Normal View History

2021-02-03 07:26:04 +00:00
//! Virtual Node Support
//! VNodes represent lazily-constructed VDom trees that support diffing and event handlers.
//!
//! These VNodes should be *very* cheap and *very* fast to construct - building a full tree should be insanely quick.
2021-03-11 00:42:10 +00:00
use crate::{
2021-07-09 15:54:07 +00:00
arena::SharedArena,
2021-03-11 00:42:10 +00:00
events::VirtualEvent,
2021-07-09 15:54:07 +00:00
innerlude::{Context, Properties, RealDom, RealDomNode, Scope, ScopeIdx, FC},
2021-07-01 18:14:59 +00:00
nodebuilder::{text3, NodeFactory},
2021-03-11 00:42:10 +00:00
};
2021-07-09 16:47:41 +00:00
use appendlist::AppendList;
2021-02-03 07:26:04 +00:00
use bumpalo::Bump;
2021-06-03 14:42:28 +00:00
use std::{
cell::{Cell, RefCell},
2021-06-23 05:44:48 +00:00
fmt::{Arguments, Debug, Formatter},
2021-06-03 14:42:28 +00:00
rc::Rc,
};
2021-02-21 02:59:16 +00:00
2021-02-03 07:26:04 +00:00
/// Tools for the base unit of the virtual dom - the VNode
/// VNodes are intended to be quickly-allocated, lightweight enum values.
///
/// Components will be generating a lot of these very quickly, so we want to
/// limit the amount of heap allocations / overly large enum sizes.
2021-03-11 00:42:10 +00:00
pub enum VNode<'src> {
/// An element node (node type `ELEMENT_NODE`).
Element(&'src VElement<'src>),
2021-02-03 07:26:04 +00:00
2021-03-11 00:42:10 +00:00
/// A text node (node type `TEXT_NODE`).
Text(VText<'src>),
2021-03-11 00:42:10 +00:00
2021-07-05 05:11:49 +00:00
/// A fragment is a list of elements that might have a dynamic order.
/// Normally, children will have a fixed order. However, Fragments allow a dynamic order and must be diffed differently.
///
/// Fragments don't have a single mount into the dom, so their position is characterized by the head and tail nodes.
///
2021-06-03 17:57:41 +00:00
/// Fragments may have children and keys
2021-06-03 14:42:28 +00:00
Fragment(&'src VFragment<'src>),
2021-03-11 00:42:10 +00:00
/// A "suspended component"
/// This is a masqeurade over an underlying future that needs to complete
/// When the future is completed, the VNode will then trigger a render
2021-06-27 02:13:57 +00:00
Suspended { real: Cell<RealDomNode> },
2021-03-11 00:42:10 +00:00
/// A User-defined componen node (node type COMPONENT_NODE)
Component(&'src VComponent<'src>),
}
// it's okay to clone because vnodes are just references to places into the bump
impl<'a> Clone for VNode<'a> {
fn clone(&self) -> Self {
match self {
VNode::Element(element) => VNode::Element(element),
VNode::Text(old) => VNode::Text(old.clone()),
VNode::Fragment(fragment) => VNode::Fragment(fragment),
VNode::Component(component) => VNode::Component(component),
2021-06-27 02:13:57 +00:00
VNode::Suspended { real } => VNode::Suspended { real: real.clone() },
}
}
2021-03-11 00:42:10 +00:00
}
2021-02-03 07:26:04 +00:00
2021-06-26 01:15:33 +00:00
impl<'old, 'new> VNode<'old> {
// performs a somewhat costly clone of this vnode into another bump
// this is used when you want to drag nodes from an old frame into a new frame
// There is no way to safely drag listeners over (no way to clone a closure)
//
// This method will only be called if a component was once a real node and then becomes suspended
fn deep_clone_to_new_bump(&self, new: &'new Bump) -> VNode<'new> {
match self {
VNode::Element(el) => {
let new_el: VElement<'new> = VElement {
key: NodeKey::NONE,
// key: el.key.clone(),
tag_name: el.tag_name,
// wipe listeners on deep clone, there's no way to know what other bump material they might be referencing (nodes, etc)
listeners: &[],
attributes: {
let attr_vec = bumpalo::collections::Vec::new_in(new);
attr_vec.into_bump_slice()
},
children: {
let attr_vec = bumpalo::collections::Vec::new_in(new);
attr_vec.into_bump_slice()
},
namespace: el.namespace.clone(),
dom_id: el.dom_id.clone(),
};
VNode::Element(new.alloc_with(move || new_el))
}
VNode::Text(_) => todo!(),
VNode::Fragment(_) => todo!(),
2021-06-27 02:13:57 +00:00
VNode::Suspended { real } => todo!(),
2021-06-26 01:15:33 +00:00
VNode::Component(_) => todo!(),
}
}
}
2021-03-11 00:42:10 +00:00
impl<'a> VNode<'a> {
/// Low-level constructor for making a new `Node` of type element with given
/// parts.
///
/// This is primarily intended for JSX and templating proc-macros to compile
/// down into. If you are building nodes by-hand, prefer using the
/// `dodrio::builder::*` APIs.
#[inline]
pub fn element(
bump: &'a Bump,
2021-04-01 04:01:42 +00:00
key: NodeKey<'a>,
2021-06-26 01:15:33 +00:00
tag_name: &'static str,
2021-03-11 00:42:10 +00:00
listeners: &'a [Listener<'a>],
attributes: &'a [Attribute<'a>],
children: &'a [VNode<'a>],
2021-06-26 01:15:33 +00:00
namespace: Option<&'static str>,
2021-03-11 00:42:10 +00:00
) -> VNode<'a> {
let element = bump.alloc_with(|| VElement {
key,
tag_name,
listeners,
attributes,
children,
namespace,
dom_id: Cell::new(RealDomNode::empty()),
2021-03-11 00:42:10 +00:00
});
VNode::Element(element)
}
/// Construct a new text node with the given text.
#[inline]
pub fn text(text: &'a str) -> VNode<'a> {
VNode::Text(VText {
text,
dom_id: Cell::new(RealDomNode::empty()),
})
2021-03-11 00:42:10 +00:00
}
2021-02-03 07:26:04 +00:00
2021-06-03 17:57:41 +00:00
pub fn text_args(bump: &'a Bump, args: Arguments) -> VNode<'a> {
text3(bump, args)
2021-06-03 14:42:28 +00:00
}
2021-03-11 00:42:10 +00:00
#[inline]
pub(crate) fn key(&self) -> NodeKey {
match &self {
VNode::Text { .. } => NodeKey::NONE,
2021-03-11 00:42:10 +00:00
VNode::Element(e) => e.key,
2021-06-03 14:42:28 +00:00
VNode::Fragment(frag) => frag.key,
2021-03-18 22:54:26 +00:00
VNode::Component(c) => c.key,
2021-06-03 17:57:41 +00:00
// todo suspend should be allowed to have keys
2021-06-27 02:13:57 +00:00
VNode::Suspended { .. } => NodeKey::NONE,
2021-02-08 00:14:04 +00:00
}
2021-02-03 07:26:04 +00:00
}
fn get_child(&self, id: u32) -> Option<&'a VNode<'a>> {
todo!()
}
pub fn is_real(&self) -> bool {
match self {
VNode::Element(_) => true,
VNode::Text(_) => true,
VNode::Fragment(_) => false,
2021-06-27 02:13:57 +00:00
VNode::Suspended { .. } => false,
VNode::Component(_) => false,
}
}
2021-07-09 15:54:07 +00:00
pub fn get_mounted_id(&self, components: &SharedArena) -> Option<RealDomNode> {
match self {
2021-06-23 05:44:48 +00:00
VNode::Element(el) => Some(el.dom_id.get()),
VNode::Text(te) => Some(te.dom_id.get()),
VNode::Fragment(_) => todo!(),
2021-06-27 02:13:57 +00:00
VNode::Suspended { .. } => todo!(),
2021-06-30 02:44:21 +00:00
VNode::Component(el) => Some(el.mounted_root.get()),
}
}
2021-02-03 07:26:04 +00:00
}
2021-06-23 05:44:48 +00:00
impl Debug for VNode<'_> {
fn fmt(&self, s: &mut Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
match self {
VNode::Element(el) => write!(s, "element, {}", el.tag_name),
VNode::Text(t) => write!(s, "text, {}", t.text),
VNode::Fragment(_) => write!(s, "fragment"),
2021-06-27 02:13:57 +00:00
VNode::Suspended { .. } => write!(s, "suspended"),
2021-06-23 05:44:48 +00:00
VNode::Component(_) => write!(s, "component"),
}
}
}
#[derive(Clone)]
pub struct VText<'src> {
pub text: &'src str,
pub dom_id: Cell<RealDomNode>,
}
2021-03-11 00:42:10 +00:00
// ========================================================
// VElement (div, h1, etc), attrs, keys, listener handle
// ========================================================
2021-06-26 01:15:33 +00:00
#[derive(Clone)]
2021-03-11 00:42:10 +00:00
pub struct VElement<'a> {
/// Elements have a tag name, zero or more attributes, and zero or more
2021-04-01 04:01:42 +00:00
pub key: NodeKey<'a>,
2021-06-26 01:15:33 +00:00
pub tag_name: &'static str,
2021-03-11 00:42:10 +00:00
pub listeners: &'a [Listener<'a>],
pub attributes: &'a [Attribute<'a>],
pub children: &'a [VNode<'a>],
2021-06-26 01:15:33 +00:00
pub namespace: Option<&'static str>,
pub dom_id: Cell<RealDomNode>,
2021-03-11 00:42:10 +00:00
}
2021-02-03 07:26:04 +00:00
2021-03-11 00:42:10 +00:00
/// An attribute on a DOM node, such as `id="my-thing"` or
/// `href="https://example.com"`.
#[derive(Clone, Debug)]
2021-03-11 00:42:10 +00:00
pub struct Attribute<'a> {
pub name: &'static str,
pub value: &'a str,
/// If an attribute is "namespaced", then it belongs to a group
/// The most common namespace is the "style" namespace
// pub is_dynamic: bool,
pub namespace: Option<&'static str>,
2021-03-11 00:42:10 +00:00
}
2021-02-03 07:26:04 +00:00
2021-03-11 00:42:10 +00:00
impl<'a> Attribute<'a> {
/// Get this attribute's name, such as `"id"` in `<div id="my-thing" />`.
#[inline]
pub fn name(&self) -> &'a str {
self.name
}
2021-02-03 07:26:04 +00:00
2021-03-11 00:42:10 +00:00
/// The attribute value, such as `"my-thing"` in `<div id="my-thing" />`.
#[inline]
pub fn value(&self) -> &'a str {
self.value
}
2021-02-03 07:26:04 +00:00
2021-03-11 00:42:10 +00:00
/// Certain attributes are considered "volatile" and can change via user
/// input that we can't see when diffing against the old virtual DOM. For
/// these attributes, we want to always re-set the attribute on the physical
/// DOM node, even if the old and new virtual DOM nodes have the same value.
#[inline]
pub(crate) fn is_volatile(&self) -> bool {
match self.name {
"value" | "checked" | "selected" => true,
_ => false,
2021-02-03 07:26:04 +00:00
}
}
2021-03-11 00:42:10 +00:00
}
2021-02-03 07:26:04 +00:00
2021-03-11 00:42:10 +00:00
pub struct ListenerHandle {
pub event: &'static str,
pub scope: ScopeIdx,
pub id: usize,
}
2021-03-03 07:27:26 +00:00
2021-03-11 00:42:10 +00:00
/// An event listener.
pub struct Listener<'bump> {
/// The type of event to listen for.
pub(crate) event: &'static str,
2021-02-15 19:14:28 +00:00
2021-06-23 05:44:48 +00:00
/// Which scope?
/// This might not actually be relevant
2021-03-11 00:42:10 +00:00
pub scope: ScopeIdx,
2021-06-23 05:44:48 +00:00
pub mounted_node: &'bump Cell<RealDomNode>,
2021-02-15 19:14:28 +00:00
/// The callback to invoke when the event happens.
2021-07-08 14:17:51 +00:00
pub(crate) callback: &'bump dyn FnMut(VirtualEvent),
2021-03-11 00:42:10 +00:00
}
2021-02-03 07:26:04 +00:00
2021-03-11 00:42:10 +00:00
/// The key for keyed children.
///
/// Keys must be unique among siblings.
///
/// If any sibling is keyed, then they all must be keyed.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2021-04-01 04:01:42 +00:00
pub struct NodeKey<'a>(pub(crate) Option<&'a str>);
2021-02-03 07:26:04 +00:00
2021-04-01 04:01:42 +00:00
impl<'a> Default for NodeKey<'a> {
fn default() -> NodeKey<'a> {
2021-03-11 00:42:10 +00:00
NodeKey::NONE
}
}
2021-04-01 04:01:42 +00:00
impl<'a> NodeKey<'a> {
2021-03-11 00:42:10 +00:00
/// The default, lack of a key.
2021-04-01 04:01:42 +00:00
pub const NONE: NodeKey<'a> = NodeKey(None);
2021-03-11 00:42:10 +00:00
/// Is this key `NodeKey::NONE`?
#[inline]
pub fn is_none(&self) -> bool {
*self == Self::NONE
2021-02-03 07:26:04 +00:00
}
2021-03-11 00:42:10 +00:00
/// Is this key not `NodeKey::NONE`?
#[inline]
pub fn is_some(&self) -> bool {
!self.is_none()
2021-02-03 07:26:04 +00:00
}
2021-03-11 00:42:10 +00:00
/// Create a new `NodeKey`.
///
/// `key` must not be `u32::MAX`.
#[inline]
2021-04-01 04:01:42 +00:00
pub fn new(key: &'a str) -> Self {
NodeKey(Some(key))
2021-03-11 00:42:10 +00:00
}
2021-07-02 05:30:52 +00:00
#[inline]
pub fn new_opt(key: Option<&'a str>) -> Self {
NodeKey(key)
}
2021-02-03 07:26:04 +00:00
}
2021-03-11 00:42:10 +00:00
// ==============================
// Custom components
// ==============================
2021-02-03 07:26:04 +00:00
/// Virtual Components for custom user-defined components
/// Only supports the functional syntax
pub type StableScopeAddres = Option<u32>;
pub type VCompAssociatedScope = Option<ScopeIdx>;
2021-03-11 00:42:10 +00:00
pub struct VComponent<'src> {
2021-04-01 04:01:42 +00:00
pub key: NodeKey<'src>,
2021-03-14 00:11:06 +00:00
2021-06-20 06:16:42 +00:00
pub mounted_root: Cell<RealDomNode>,
2021-06-23 05:44:48 +00:00
2021-06-30 02:44:21 +00:00
pub ass_scope: Cell<VCompAssociatedScope>,
2021-06-30 02:44:21 +00:00
// todo: swap the RC out with
2021-06-07 18:14:49 +00:00
pub caller: Rc<dyn Fn(&Scope) -> VNode>,
2021-05-31 22:55:56 +00:00
pub children: &'src [VNode<'src>],
pub comparator: Option<&'src dyn Fn(&VComponent) -> bool>,
// a pointer into the bump arena (given by the 'src lifetime)
2021-06-02 15:07:30 +00:00
// raw_props: Box<dyn Any>,
raw_props: *const (),
// a pointer to the raw fn typ
2021-03-14 00:11:06 +00:00
pub user_fc: *const (),
2021-03-11 00:42:10 +00:00
}
2021-02-12 05:29:46 +00:00
2021-03-11 00:42:10 +00:00
impl<'a> VComponent<'a> {
/// When the rsx! macro is called, it will check if the CanMemo flag is set to true (from the Props impl)
/// If it is set to true, then this method will be called which implements automatic memoization.
///
/// If the CanMemo is `false`, then the macro will call the backup method which always defaults to "false"
pub fn new<P: Properties + 'a>(
2021-07-01 18:14:59 +00:00
cx: &NodeFactory<'a>,
2021-06-02 15:07:30 +00:00
component: FC<P>,
props: P,
key: Option<&'a str>,
2021-06-08 18:00:29 +00:00
children: &'a [VNode<'a>],
2021-06-02 15:07:30 +00:00
) -> Self {
2021-06-26 01:15:33 +00:00
let bump = cx.bump();
let user_fc = component as *const ();
let props = bump.alloc(props);
let raw_props = props as *const P as *const ();
2021-06-30 02:44:21 +00:00
let comparator: Option<&dyn Fn(&VComponent) -> bool> = Some(bump.alloc_with(|| {
move |other: &VComponent| {
// Safety:
// ------
//
// Invariants:
// - Component function pointers are the same
// - Generic properties on the same function pointer are the same
// - Lifetime of P borrows from its parent
// - The parent scope still exists when method is called
// - Casting from T to *const () is portable
2021-06-30 02:44:21 +00:00
// - Casting raw props to P can only happen when P is static
//
// Explanation:
// We are guaranteed that the props will be of the same type because
// there is no way to create a VComponent other than this `new` method.
//
// Therefore, if the render functions are identical (by address), then so will be
// props type paramter (because it is the same render function). Therefore, we can be
// sure that it is safe to interperet the previous props raw pointer as the same props
// type. From there, we can call the props' "memoize" method to see if we can
// avoid re-rendering the component.
if user_fc == other.user_fc {
let real_other = unsafe { &*(other.raw_props as *const _ as *const P) };
let props_memoized = unsafe { props.memoize(&real_other) };
match (props_memoized, children.len() == 0) {
(true, true) => true,
_ => false,
}
} else {
false
}
2021-06-30 02:44:21 +00:00
}
}));
let key = match key {
Some(key) => NodeKey::new(key),
None => NodeKey(None),
};
Self {
user_fc,
comparator,
raw_props,
2021-06-08 18:00:29 +00:00
children,
2021-06-30 02:44:21 +00:00
ass_scope: Cell::new(None),
key,
caller: create_closure(component, raw_props),
2021-06-20 06:16:42 +00:00
mounted_root: Cell::new(RealDomNode::empty()),
}
2021-02-03 07:26:04 +00:00
}
}
2021-06-03 14:42:28 +00:00
2021-06-07 18:14:49 +00:00
type Captured<'a> = Rc<dyn for<'r> Fn(&'r Scope) -> VNode<'r> + 'a>;
fn create_closure<'a, P: 'a>(
2021-07-09 16:47:41 +00:00
user_component: FC<P>,
2021-06-07 18:14:49 +00:00
raw_props: *const (),
) -> Rc<dyn for<'r> Fn(&'r Scope) -> VNode<'r>> {
let g: Captured = Rc::new(move |scp: &Scope| -> VNode {
// cast back into the right lifetime
let safe_props: &'_ P = unsafe { &*(raw_props as *const P) };
2021-07-09 16:47:41 +00:00
let tasks = AppendList::new();
2021-06-26 01:15:33 +00:00
let cx: Context<P> = Context {
2021-06-07 18:14:49 +00:00
props: safe_props,
scope: scp,
2021-07-09 16:47:41 +00:00
tasks: &tasks,
2021-06-07 18:14:49 +00:00
};
2021-07-09 16:47:41 +00:00
let g = user_component(cx);
// collect the submitted tasks
println!("tasks submittted: {:#?}", tasks.len());
// log::debug!("tasks submittted: {:#?}", tasks.len());
2021-06-07 18:14:49 +00:00
let g2 = unsafe { std::mem::transmute(g) };
g2
});
let r: Captured<'static> = unsafe { std::mem::transmute(g) };
r
}
2021-06-03 14:42:28 +00:00
pub struct VFragment<'src> {
pub key: NodeKey<'src>,
pub children: &'src [VNode<'src>],
}
2021-06-08 18:00:29 +00:00
impl<'a> VFragment<'a> {
pub fn new(key: Option<&'a str>, children: &'a [VNode<'a>]) -> Self {
let key = match key {
Some(key) => NodeKey::new(key),
None => NodeKey(None),
};
Self { key, children }
}
}