dioxus/packages/core/src/nodes.rs

491 lines
14 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::{
events::VirtualEvent,
2021-07-09 15:54:07 +00:00
innerlude::{Context, Properties, RealDom, RealDomNode, Scope, ScopeIdx, FC},
2021-03-11 00:42:10 +00:00
};
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-07-12 22:19:27 +00:00
marker::PhantomData,
2021-06-03 14:42:28 +00:00
rc::Rc,
};
2021-02-21 02:59:16 +00:00
2021-07-12 22:19:27 +00:00
pub struct VNode<'src> {
pub kind: VNodeKind<'src>,
pub dom_id: Cell<RealDomNode>,
pub key: Option<&'src str>,
}
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-07-12 22:19:27 +00:00
pub enum VNodeKind<'src> {
Text(VText<'src>),
2021-07-12 22:19:27 +00:00
Element(&'src VElement<'src>),
Fragment(VFragment<'src>),
Component(&'src VComponent<'src>),
2021-07-12 22:19:27 +00:00
Suspended,
}
pub struct VText<'src> {
pub text: &'src str,
pub is_static: bool,
}
2021-07-12 22:19:27 +00:00
pub struct VFragment<'src> {
pub children: &'src [VNode<'src>],
2021-07-13 03:44:20 +00:00
pub is_static: bool,
2021-07-12 22:19:27 +00:00
}
2021-06-26 01:15:33 +00:00
2021-07-12 22:19:27 +00:00
pub trait DioxusElement {
const TAG_NAME: &'static str;
const NAME_SPACE: Option<&'static str>;
2021-07-13 04:56:39 +00:00
#[inline]
2021-07-12 22:19:27 +00:00
fn tag_name(&self) -> &'static str {
Self::TAG_NAME
}
2021-07-13 04:56:39 +00:00
#[inline]
fn namespace(&self) -> Option<&'static str> {
Self::NAME_SPACE
}
2021-07-12 22:19:27 +00:00
}
2021-03-11 00:42:10 +00:00
pub struct VElement<'a> {
2021-07-12 22:19:27 +00:00
// tag is always static
2021-06-26 01:15:33 +00:00
pub tag_name: &'static str,
2021-07-13 03:44:20 +00:00
pub namespace: Option<&'static str>,
2021-07-12 22:19:27 +00:00
pub static_listeners: bool,
2021-03-11 00:42:10 +00:00
pub listeners: &'a [Listener<'a>],
2021-07-12 22:19:27 +00:00
pub static_attrs: bool,
2021-03-11 00:42:10 +00:00
pub attributes: &'a [Attribute<'a>],
2021-07-12 22:19:27 +00:00
pub static_children: bool,
2021-03-11 00:42:10 +00:00
pub children: &'a [VNode<'a>],
}
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,
pub is_static: bool,
2021-07-12 22:19:27 +00:00
pub is_volatile: bool,
// Doesn't exist in the html spec, mostly used to denote "style" tags - could be for any type of group
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
/// An event listener.
2021-07-12 22:19:27 +00:00
/// IE onclick, onkeydown, etc
2021-03-11 00:42:10 +00:00
pub struct Listener<'bump> {
/// The type of event to listen for.
pub(crate) event: &'static str,
pub scope: ScopeIdx,
2021-06-23 05:44:48 +00:00
pub mounted_node: &'bump Cell<RealDomNode>,
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-07-12 22:19:27 +00:00
/// Virtual Components for custom user-defined components
/// Only supports the functional syntax
pub struct VComponent<'src> {
pub ass_scope: Cell<Option<ScopeIdx>>,
2021-07-13 03:44:20 +00:00
pub(crate) caller: Rc<dyn Fn(&Scope) -> VNode>,
pub(crate) children: &'src [VNode<'src>],
pub(crate) comparator: Option<&'src dyn Fn(&VComponent) -> bool>,
pub is_static: bool,
2021-07-12 22:19:27 +00:00
// a pointer into the bump arena (given by the 'src lifetime)
2021-07-13 03:44:20 +00:00
pub(crate) raw_props: *const (),
2021-07-12 22:19:27 +00:00
// a pointer to the raw fn typ
2021-07-13 03:44:20 +00:00
pub(crate) user_fc: *const (),
2021-07-12 22:19:27 +00:00
}
2021-02-03 07:26:04 +00:00
2021-07-12 22:19:27 +00:00
/// This struct provides an ergonomic API to quickly build VNodes.
///
/// NodeFactory is used to build VNodes in the component's memory space.
/// This struct adds metadata to the final VNode about listeners, attributes, and children
#[derive(Copy, Clone)]
pub struct NodeFactory<'a> {
pub scope_ref: &'a Scope,
pub listener_id: &'a Cell<usize>,
2021-03-11 00:42:10 +00:00
}
2021-07-12 22:19:27 +00:00
impl<'a> NodeFactory<'a> {
2021-03-11 00:42:10 +00:00
#[inline]
2021-07-12 22:19:27 +00:00
pub fn bump(&self) -> &'a bumpalo::Bump {
&self.scope_ref.cur_frame().bump
2021-02-03 07:26:04 +00:00
}
2021-07-13 03:44:20 +00:00
pub const fn const_text(&self, text: &'static str) -> VNodeKind<'static> {
VNodeKind::Text(VText {
is_static: true,
text,
})
}
pub const fn const_fragment(&self, children: &'static [VNode<'static>]) -> VNodeKind<'static> {
VNodeKind::Fragment(VFragment {
children,
is_static: true,
})
}
2021-07-12 22:19:27 +00:00
pub fn static_text(text: &'static str) -> VNode {
VNode {
dom_id: RealDomNode::empty_cell(),
key: None,
kind: VNodeKind::Text(VText {
text,
is_static: true,
}),
}
2021-02-03 07:26:04 +00:00
}
2021-07-12 22:19:27 +00:00
pub fn raw_text(&self, args: Arguments) -> (&'a str, bool) {
match args.as_str() {
Some(static_str) => (static_str, true),
None => {
use bumpalo::core_alloc::fmt::Write;
let mut s = bumpalo::collections::String::new_in(self.bump());
s.write_fmt(args).unwrap();
(s.into_bump_str(), false)
}
}
2021-03-11 00:42:10 +00:00
}
2021-07-02 05:30:52 +00:00
2021-07-12 22:19:27 +00:00
/// Create some text that's allocated along with the other vnodes
pub fn text(&self, args: Arguments) -> VNode<'a> {
let (text, is_static) = self.raw_text(args);
VNode {
dom_id: RealDomNode::empty_cell(),
key: None,
kind: VNodeKind::Text(VText { text, is_static }),
}
2021-07-02 05:30:52 +00:00
}
2021-03-11 00:42:10 +00:00
2021-07-12 22:19:27 +00:00
pub fn raw_element(
&self,
tag: &'static str,
listeners: &[Listener],
attributes: &[Attribute],
children: &'a [VNode<'a>],
2021-07-13 04:56:39 +00:00
) -> VNode<'a> {
todo!()
2021-07-12 22:19:27 +00:00
}
2021-07-13 04:56:39 +00:00
pub fn element(
&self,
el: impl DioxusElement,
listeners: &'a [Listener<'a>],
attributes: &'a [Attribute<'a>],
children: &'a [VNode<'a>],
key: Option<&'a str>,
) -> VNode<'a> {
VNode {
dom_id: RealDomNode::empty_cell(),
key,
kind: VNodeKind::Element(self.bump().alloc(VElement {
tag_name: el.tag_name(),
namespace: el.namespace(),
static_listeners: false,
listeners,
static_attrs: false,
attributes,
static_children: false,
children,
})),
}
}
2021-07-12 22:19:27 +00:00
pub fn suspended() -> VNode<'static> {
VNode {
dom_id: RealDomNode::empty_cell(),
key: None,
kind: VNodeKind::Suspended,
}
}
2021-07-12 22:19:27 +00:00
pub fn attr(
&self,
name: &'static str,
val: Arguments,
namespace: Option<&'static str>,
is_volatile: bool,
) -> Attribute<'a> {
let (value, is_static) = self.raw_text(val);
Attribute {
name,
value,
is_static,
namespace,
is_volatile,
}
}
2021-02-12 05:29:46 +00:00
2021-07-13 04:56:39 +00:00
pub fn virtual_child<P>(
2021-07-12 22:19:27 +00:00
&self,
2021-06-02 15:07:30 +00:00
component: FC<P>,
props: P,
2021-07-12 22:19:27 +00:00
key: Option<&'a str>, // key: NodeKey<'a>,
2021-06-08 18:00:29 +00:00
children: &'a [VNode<'a>],
2021-07-12 22:19:27 +00:00
) -> VNode<'a>
where
P: Properties + 'a,
{
// We don't want the fat part of the fat pointer
// This function does static dispatch so we don't need any VTable stuff
let props = self.bump().alloc(props);
let raw_props = props as *const P as *const ();
2021-07-12 22:19:27 +00:00
let user_fc = component as *const ();
let comparator: Option<&dyn Fn(&VComponent) -> bool> = Some(self.bump().alloc_with(|| {
2021-06-30 02:44:21 +00:00
move |other: &VComponent| {
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
}
}));
2021-07-12 22:19:27 +00:00
VNode {
key,
dom_id: Cell::new(RealDomNode::empty()),
kind: VNodeKind::Component(self.bump().alloc_with(|| VComponent {
user_fc,
comparator,
raw_props,
children,
caller: NodeFactory::create_component_caller(component, raw_props),
is_static: children.len() == 0 && P::IS_STATIC && key.is_none(),
ass_scope: Cell::new(None),
})),
}
}
2021-07-12 22:19:27 +00:00
pub fn create_component_caller<'g, P: 'g>(
component: FC<P>,
raw_props: *const (),
) -> Rc<dyn for<'r> Fn(&'r Scope) -> VNode<'r>> {
type Captured<'a> = Rc<dyn for<'r> Fn(&'r Scope) -> VNode<'r> + 'a>;
let caller: Captured = Rc::new(move |scp: &Scope| -> VNode {
// cast back into the right lifetime
let safe_props: &'_ P = unsafe { &*(raw_props as *const P) };
let tasks = RefCell::new(Vec::new());
let cx: Context<P> = Context {
props: safe_props,
scope: scp,
tasks: &tasks,
};
let res = component(cx);
// submit any async tasks to the scope
for task in tasks.borrow_mut().drain(..) {
2021-07-13 20:48:11 +00:00
// scp.submit_task(task);
2021-07-12 22:19:27 +00:00
}
2021-07-12 22:19:27 +00:00
let g2 = unsafe { std::mem::transmute(res) };
2021-07-12 22:19:27 +00:00
g2
});
unsafe { std::mem::transmute::<_, Captured<'static>>(caller) }
}
pub fn fragment_from_iter(
self,
node_iter: impl IntoIterator<Item = impl IntoVNode<'a>>,
) -> VNode<'a> {
let mut nodes = bumpalo::collections::Vec::new_in(self.bump());
// TODO throw an error if there are nodes without keys
for node in node_iter.into_iter() {
nodes.push(node.into_vnode(self));
}
VNode {
dom_id: RealDomNode::empty_cell(),
key: None,
kind: VNodeKind::Fragment(VFragment {
children: nodes.into_bump_slice(),
2021-07-13 03:44:20 +00:00
is_static: false,
2021-07-12 22:19:27 +00:00
}),
}
2021-02-03 07:26:04 +00:00
}
}
2021-06-03 14:42:28 +00:00
2021-07-12 22:19:27 +00:00
impl<'a> IntoIterator for VNode<'a> {
type Item = VNode<'a>;
type IntoIter = std::iter::Once<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
std::iter::once(self)
}
}
impl<'a> IntoVNode<'a> for VNode<'a> {
fn into_vnode(self, _: NodeFactory<'a>) -> VNode<'a> {
self
}
}
impl<'a> IntoVNode<'a> for &VNode<'a> {
fn into_vnode(self, _: NodeFactory<'a>) -> VNode<'a> {
self.clone()
}
}
2021-06-07 18:14:49 +00:00
2021-07-12 22:19:27 +00:00
pub trait IntoVNode<'a> {
fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a>;
}
2021-06-07 18:14:49 +00:00
2021-07-12 22:19:27 +00:00
// Wrap the the node-builder closure in a concrete type.
// ---
// This is a bit of a hack to implement the IntoVNode trait for closure types.
pub struct LazyNodes<'a, G>
where
G: FnOnce(NodeFactory<'a>) -> VNode<'a>,
{
inner: G,
_p: PhantomData<&'a ()>,
}
2021-07-09 16:47:41 +00:00
2021-07-12 22:19:27 +00:00
impl<'a, G> LazyNodes<'a, G>
where
G: FnOnce(NodeFactory<'a>) -> VNode<'a>,
{
pub fn new(f: G) -> Self {
Self {
inner: f,
_p: PhantomData {},
}
2021-07-12 22:19:27 +00:00
}
}
2021-07-09 16:47:41 +00:00
2021-07-12 22:19:27 +00:00
// Cover the cases where nodes are used by macro.
// Likely used directly.
// ---
// let nodes = rsx!{ ... };
// rsx! { {nodes } }
impl<'a, G> IntoVNode<'a> for LazyNodes<'a, G>
where
G: FnOnce(NodeFactory<'a>) -> VNode<'a>,
{
fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
(self.inner)(cx)
}
}
2021-07-12 22:19:27 +00:00
// Required because anything that enters brackets in the rsx! macro needs to implement IntoIterator
impl<'a, G> IntoIterator for LazyNodes<'a, G>
where
G: FnOnce(NodeFactory<'a>) -> VNode<'a>,
{
type Item = Self;
type IntoIter = std::iter::Once<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
std::iter::once(self)
}
2021-06-07 18:14:49 +00:00
}
2021-07-12 22:19:27 +00:00
impl IntoVNode<'_> for () {
fn into_vnode<'a>(self, cx: NodeFactory<'a>) -> VNode<'a> {
cx.fragment_from_iter(None as Option<VNode>)
}
2021-06-03 14:42:28 +00:00
}
2021-06-08 18:00:29 +00:00
2021-07-12 22:19:27 +00:00
impl IntoVNode<'_> for Option<()> {
fn into_vnode<'a>(self, cx: NodeFactory<'a>) -> VNode<'a> {
cx.fragment_from_iter(None as Option<VNode>)
}
}
impl Debug for NodeFactory<'_> {
fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Ok(())
}
}
// 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 {
let kind = match &self.kind {
VNodeKind::Element(element) => VNodeKind::Element(element),
VNodeKind::Text(old) => VNodeKind::Text(VText {
text: old.text,
is_static: old.is_static,
}),
VNodeKind::Fragment(fragment) => VNodeKind::Fragment(VFragment {
children: fragment.children,
2021-07-13 03:44:20 +00:00
is_static: fragment.is_static,
2021-07-12 22:19:27 +00:00
}),
VNodeKind::Component(component) => VNodeKind::Component(component),
VNodeKind::Suspended => VNodeKind::Suspended,
2021-06-08 18:00:29 +00:00
};
2021-07-13 03:44:20 +00:00
VNode {
kind,
dom_id: self.dom_id.clone(),
key: self.key.clone(),
}
2021-07-12 22:19:27 +00:00
}
}
impl Debug for VNode<'_> {
fn fmt(&self, s: &mut Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
match &self.kind {
VNodeKind::Element(el) => write!(s, "element, {}", el.tag_name),
VNodeKind::Text(t) => write!(s, "text, {}", t.text),
VNodeKind::Fragment(_) => write!(s, "fragment"),
VNodeKind::Suspended { .. } => write!(s, "suspended"),
VNodeKind::Component(_) => write!(s, "component"),
2021-07-12 06:23:46 +00:00
}
2021-06-08 18:00:29 +00:00
}
}
2021-07-12 22:19:27 +00:00
mod tests {
use super::*;
2021-07-13 19:34:12 +00:00
static B1: &str = "hello world!";
static B2: &str = "hello world!";
2021-07-12 22:19:27 +00:00
#[test]
2021-07-13 19:34:12 +00:00
fn test() {
dbg!("Hello world!" as *const _ as *const ());
dbg!("Hello world!" as *const _ as *const ());
// dbg!(B1 as *const _ as *const ());
// dbg!(B2 as *const _ as *const ());
// goal: elements as const
// let b = A.clone();
// A.dom_id.set(RealDomNode::new(10));
// let p = &A;
// p.dom_id.set(RealDomNode::new(10));
// dbg!(p.dom_id.get());
// dbg!(p as *const _ as *const ());
// dbg!(&A as *const _ as *const ());
// // dbg!(b.dom_id.get());
// dbg!(A.dom_id.get());
// A.dom_id.set(RealDomNode::empty());
// let g = A.dom_id.get();
}
2021-07-12 22:19:27 +00:00
#[test]
fn sizing() {
dbg!(std::mem::size_of::<VElement>());
dbg!(std::mem::align_of::<VElement>());
}
}