Subtree memorization / reactive templates (#488)

This commit adds subtree memoization to Dioxus.

Subtree memoization is basically a compile-time step that drastically 
reduces the amount of work the diffing engine needs to do at runtime by
extracting non-changing nodes out into a static "template." Templates 
are then understood by the various renderers in the ecosystem as a 
faster way of rendering the same items. 

For example, in the web, templates are simply a set of DOM Nodes created 
once and then cloned later. This is the same pattern frameworks like Lithtml
and SolidJS use to achieve near-perfect performance. 

Subtree memoization adds an additional level of complexity to Dioxus. The RSX
macro needs to be much smarter to identify changing/nonchanging nodes and
generate a mapping between the Template and its runtime counterparts.

This commit represents a working starter point for this work, adding support 
for templates for the web, desktop, liveview, ssr, and native-core renderers.
In the future we will try to shrink code generation, generally improve 
performance, and simplify our implementation.
This commit is contained in:
Demonthos authored and GitHub committed 2022-09-30 12:03:06 -07:00
1 parent b32fd2d2cd
commit 047ed1e553
80 files changed
+6774 -2552

No files matched your search

+201
View File
@@ -233,3 +233,204 @@ impl<'a> AttributeValue<'a> {
}
}
}
/// A owned attribute value.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
all(feature = "serialize"),
derive(serde::Serialize, serde::Deserialize)
)]
#[allow(missing_docs)]
pub enum OwnedAttributeValue {
Text(String),
Float32(f32),
Float64(f64),
Int32(i32),
Int64(i64),
Uint32(u32),
Uint64(u64),
Bool(bool),
Vec3Float(f32, f32, f32),
Vec3Int(i32, i32, i32),
Vec3Uint(u32, u32, u32),
Vec4Float(f32, f32, f32, f32),
Vec4Int(i32, i32, i32, i32),
Vec4Uint(u32, u32, u32, u32),
Bytes(Vec<u8>),
// TODO: support other types
// Any(ArbitraryAttributeValue<'a>),
}
impl PartialEq<AttributeValue<'_>> for OwnedAttributeValue {
fn eq(&self, other: &AttributeValue<'_>) -> bool {
match (self, other) {
(Self::Text(l0), AttributeValue::Text(r0)) => l0 == r0,
(Self::Float32(l0), AttributeValue::Float32(r0)) => l0 == r0,
(Self::Float64(l0), AttributeValue::Float64(r0)) => l0 == r0,
(Self::Int32(l0), AttributeValue::Int32(r0)) => l0 == r0,
(Self::Int64(l0), AttributeValue::Int64(r0)) => l0 == r0,
(Self::Uint32(l0), AttributeValue::Uint32(r0)) => l0 == r0,
(Self::Uint64(l0), AttributeValue::Uint64(r0)) => l0 == r0,
(Self::Bool(l0), AttributeValue::Bool(r0)) => l0 == r0,
(Self::Vec3Float(l0, l1, l2), AttributeValue::Vec3Float(r0, r1, r2)) => {
l0 == r0 && l1 == r1 && l2 == r2
}
(Self::Vec3Int(l0, l1, l2), AttributeValue::Vec3Int(r0, r1, r2)) => {
l0 == r0 && l1 == r1 && l2 == r2
}
(Self::Vec3Uint(l0, l1, l2), AttributeValue::Vec3Uint(r0, r1, r2)) => {
l0 == r0 && l1 == r1 && l2 == r2
}
(Self::Vec4Float(l0, l1, l2, l3), AttributeValue::Vec4Float(r0, r1, r2, r3)) => {
l0 == r0 && l1 == r1 && l2 == r2 && l3 == r3
}
(Self::Vec4Int(l0, l1, l2, l3), AttributeValue::Vec4Int(r0, r1, r2, r3)) => {
l0 == r0 && l1 == r1 && l2 == r2 && l3 == r3
}
(Self::Vec4Uint(l0, l1, l2, l3), AttributeValue::Vec4Uint(r0, r1, r2, r3)) => {
l0 == r0 && l1 == r1 && l2 == r2 && l3 == r3
}
(Self::Bytes(l0), AttributeValue::Bytes(r0)) => l0 == r0,
(_, _) => false,
}
}
}
impl<'a> From<AttributeValue<'a>> for OwnedAttributeValue {
fn from(attr: AttributeValue<'a>) -> Self {
match attr {
AttributeValue::Text(t) => OwnedAttributeValue::Text(t.to_owned()),
AttributeValue::Float32(f) => OwnedAttributeValue::Float32(f),
AttributeValue::Float64(f) => OwnedAttributeValue::Float64(f),
AttributeValue::Int32(i) => OwnedAttributeValue::Int32(i),
AttributeValue::Int64(i) => OwnedAttributeValue::Int64(i),
AttributeValue::Uint32(u) => OwnedAttributeValue::Uint32(u),
AttributeValue::Uint64(u) => OwnedAttributeValue::Uint64(u),
AttributeValue::Bool(b) => OwnedAttributeValue::Bool(b),
AttributeValue::Vec3Float(f1, f2, f3) => OwnedAttributeValue::Vec3Float(f1, f2, f3),
AttributeValue::Vec3Int(f1, f2, f3) => OwnedAttributeValue::Vec3Int(f1, f2, f3),
AttributeValue::Vec3Uint(f1, f2, f3) => OwnedAttributeValue::Vec3Uint(f1, f2, f3),
AttributeValue::Vec4Float(f1, f2, f3, f4) => {
OwnedAttributeValue::Vec4Float(f1, f2, f3, f4)
}
AttributeValue::Vec4Int(f1, f2, f3, f4) => OwnedAttributeValue::Vec4Int(f1, f2, f3, f4),
AttributeValue::Vec4Uint(f1, f2, f3, f4) => {
OwnedAttributeValue::Vec4Uint(f1, f2, f3, f4)
}
AttributeValue::Bytes(b) => OwnedAttributeValue::Bytes(b.to_owned()),
AttributeValue::Any(_) => todo!(),
}
}
}
// todo
#[allow(missing_docs)]
impl OwnedAttributeValue {
pub fn as_text(&self) -> Option<&str> {
match self {
OwnedAttributeValue::Text(s) => Some(s),
_ => None,
}
}
pub fn as_float32(&self) -> Option<f32> {
match self {
OwnedAttributeValue::Float32(f) => Some(*f),
_ => None,
}
}
pub fn as_float64(&self) -> Option<f64> {
match self {
OwnedAttributeValue::Float64(f) => Some(*f),
_ => None,
}
}
pub fn as_int32(&self) -> Option<i32> {
match self {
OwnedAttributeValue::Int32(i) => Some(*i),
_ => None,
}
}
pub fn as_int64(&self) -> Option<i64> {
match self {
OwnedAttributeValue::Int64(i) => Some(*i),
_ => None,
}
}
pub fn as_uint32(&self) -> Option<u32> {
match self {
OwnedAttributeValue::Uint32(i) => Some(*i),
_ => None,
}
}
pub fn as_uint64(&self) -> Option<u64> {
match self {
OwnedAttributeValue::Uint64(i) => Some(*i),
_ => None,
}
}
pub fn as_bool(&self) -> Option<bool> {
match self {
OwnedAttributeValue::Bool(b) => Some(*b),
_ => None,
}
}
pub fn as_vec3_float(&self) -> Option<(f32, f32, f32)> {
match self {
OwnedAttributeValue::Vec3Float(x, y, z) => Some((*x, *y, *z)),
_ => None,
}
}
pub fn as_vec3_int(&self) -> Option<(i32, i32, i32)> {
match self {
OwnedAttributeValue::Vec3Int(x, y, z) => Some((*x, *y, *z)),
_ => None,
}
}
pub fn as_vec3_uint(&self) -> Option<(u32, u32, u32)> {
match self {
OwnedAttributeValue::Vec3Uint(x, y, z) => Some((*x, *y, *z)),
_ => None,
}
}
pub fn as_vec4_float(&self) -> Option<(f32, f32, f32, f32)> {
match self {
OwnedAttributeValue::Vec4Float(x, y, z, w) => Some((*x, *y, *z, *w)),
_ => None,
}
}
pub fn as_vec4_int(&self) -> Option<(i32, i32, i32, i32)> {
match self {
OwnedAttributeValue::Vec4Int(x, y, z, w) => Some((*x, *y, *z, *w)),
_ => None,
}
}
pub fn as_vec4_uint(&self) -> Option<(u32, u32, u32, u32)> {
match self {
OwnedAttributeValue::Vec4Uint(x, y, z, w) => Some((*x, *y, *z, *w)),
_ => None,
}
}
pub fn as_bytes(&self) -> Option<&[u8]> {
match self {
OwnedAttributeValue::Bytes(b) => Some(b),
_ => None,
}
}
}
+336 -29
View File
@@ -91,10 +91,19 @@
//! More info on how to improve this diffing algorithm:
//! - <https://hacks.mozilla.org/2019/03/fast-bump-allocated-virtual-doms-with-rust-and-wasm/>
use crate::innerlude::{
AnyProps, ElementId, Mutations, ScopeArena, ScopeId, VComponent, VElement, VFragment, VNode,
VPlaceholder, VText,
use crate::{
dynamic_template_context::TemplateContext,
innerlude::{
AnyProps, ElementId, GlobalNodeId, Mutations, RendererTemplateId, ScopeArena, ScopeId,
VComponent, VElement, VFragment, VNode, VPlaceholder, VText,
},
template::{
Template, TemplateAttribute, TemplateElement, TemplateNode, TemplateNodeId,
TemplateNodeType, TemplateValue, TextTemplateSegment, VTemplateRef,
},
Attribute, TemplateAttributeValue,
};
use bumpalo::Bump;
use fxhash::{FxHashMap, FxHashSet};
use smallvec::{smallvec, SmallVec};
@@ -102,7 +111,7 @@ pub(crate) struct DiffState<'bump> {
pub(crate) scopes: &'bump ScopeArena,
pub(crate) mutations: Mutations<'bump>,
pub(crate) force_diff: bool,
pub(crate) element_stack: SmallVec<[ElementId; 10]>,
pub(crate) element_stack: SmallVec<[GlobalNodeId; 10]>,
pub(crate) scope_stack: SmallVec<[ScopeId; 5]>,
}
@@ -133,7 +142,7 @@ impl<'b> DiffState<'b> {
}
pub fn diff_node(&mut self, old_node: &'b VNode<'b>, new_node: &'b VNode<'b>) {
use VNode::{Component, Element, Fragment, Placeholder, Text};
use VNode::{Component, Element, Fragment, Placeholder, TemplateRef, Text};
match (old_node, new_node) {
(Text(old), Text(new)) => {
self.diff_text_nodes(old, new, old_node, new_node);
@@ -148,16 +157,20 @@ impl<'b> DiffState<'b> {
}
(Component(old), Component(new)) => {
self.diff_component_nodes(old_node, new_node, *old, *new);
self.diff_component_nodes(*old, *new, old_node, new_node);
}
(Fragment(old), Fragment(new)) => {
self.diff_fragment_nodes(old, new);
}
(TemplateRef(old), TemplateRef(new)) => {
self.diff_template_ref_nodes(old, new, old_node, new_node);
}
(
Component(_) | Fragment(_) | Text(_) | Element(_) | Placeholder(_),
Component(_) | Fragment(_) | Text(_) | Element(_) | Placeholder(_),
Component(_) | Fragment(_) | Text(_) | Element(_) | Placeholder(_) | TemplateRef(_),
Component(_) | Fragment(_) | Text(_) | Element(_) | Placeholder(_) | TemplateRef(_),
) => self.replace_node(old_node, new_node),
}
}
@@ -169,6 +182,7 @@ impl<'b> DiffState<'b> {
VNode::Element(element) => self.create_element_node(element, node),
VNode::Fragment(frag) => self.create_fragment_node(frag),
VNode::Component(component) => self.create_component_node(*component),
VNode::TemplateRef(temp) => self.create_template_ref_node(*temp, node),
}
}
@@ -204,19 +218,21 @@ impl<'b> DiffState<'b> {
dom_id.set(Some(real_id));
self.element_stack.push(real_id);
self.element_stack.push(GlobalNodeId::VNodeId(real_id));
{
self.mutations.create_element(tag_name, *namespace, real_id);
let cur_scope_id = self.current_scope();
for listener in listeners.iter() {
listener.mounted_node.set(Some(real_id));
listener
.mounted_node
.set(Some(GlobalNodeId::VNodeId(real_id)));
self.mutations.new_event_listener(listener, cur_scope_id);
}
for attr in attributes.iter() {
self.mutations.set_attribute(attr, real_id.as_u64());
self.mutations.set_attribute(attr, real_id);
}
if !children.is_empty() {
@@ -249,7 +265,6 @@ impl<'b> DiffState<'b> {
props,
Some(parent_idx),
self.element_stack.last().copied().unwrap(),
0,
)
};
@@ -286,6 +301,37 @@ impl<'b> DiffState<'b> {
created
}
pub(crate) fn create_template_ref_node(
&mut self,
new: &'b VTemplateRef<'b>,
node: &'b VNode<'b>,
) -> usize {
let (id, created) = {
let mut resolver = self.scopes.template_resolver.borrow_mut();
resolver.get_or_create_client_id(&new.template_id)
};
let template = {
let templates = self.scopes.templates.borrow();
templates.get(&new.template_id).unwrap().clone()
};
let template = template.borrow();
if created {
self.register_template(&template, id);
}
let real_id = self.scopes.reserve_node(node);
new.id.set(Some(real_id));
self.mutations.create_template_ref(real_id, id.into());
new.hydrate(&template, self);
1
}
pub(crate) fn diff_text_nodes(
&mut self,
old: &'b VText<'b>,
@@ -304,7 +350,7 @@ impl<'b> DiffState<'b> {
};
if old.text != new.text {
self.mutations.set_text(new.text, root.as_u64());
self.mutations.set_text(new.text, root);
}
self.scopes.update_node(new_node, root);
@@ -377,16 +423,18 @@ impl<'b> DiffState<'b> {
// TODO: take a more efficient path than this
if old.attributes.len() == new.attributes.len() {
for (old_attr, new_attr) in old.attributes.iter().zip(new.attributes.iter()) {
if old_attr.value != new_attr.value || new_attr.is_volatile {
self.mutations.set_attribute(new_attr, root.as_u64());
if !old_attr.is_static && old_attr.value != new_attr.value
|| new_attr.attribute.volatile
{
self.mutations.set_attribute(new_attr, root);
}
}
} else {
for attribute in old.attributes {
self.mutations.remove_attribute(attribute, root.as_u64());
self.mutations.remove_attribute(attribute, root);
}
for attribute in new.attributes {
self.mutations.set_attribute(attribute, root.as_u64());
self.mutations.set_attribute(attribute, root);
}
}
@@ -404,18 +452,16 @@ impl<'b> DiffState<'b> {
for (old_l, new_l) in old.listeners.iter().zip(new.listeners.iter()) {
new_l.mounted_node.set(old_l.mounted_node.get());
if old_l.event != new_l.event {
self.mutations
.remove_event_listener(old_l.event, root.as_u64());
self.mutations.remove_event_listener(old_l.event, root);
self.mutations.new_event_listener(new_l, cur_scope_id);
}
}
} else {
for listener in old.listeners {
self.mutations
.remove_event_listener(listener.event, root.as_u64());
self.mutations.remove_event_listener(listener.event, root);
}
for listener in new.listeners {
listener.mounted_node.set(Some(root));
listener.mounted_node.set(Some(GlobalNodeId::VNodeId(root)));
self.mutations.new_event_listener(listener, cur_scope_id);
}
}
@@ -434,10 +480,10 @@ impl<'b> DiffState<'b> {
fn diff_component_nodes(
&mut self,
old_node: &'b VNode<'b>,
new_node: &'b VNode<'b>,
old: &'b VComponent<'b>,
new: &'b VComponent<'b>,
old_node: &'b VNode<'b>,
new_node: &'b VNode<'b>,
) {
let scope_addr = old
.scope
@@ -526,6 +572,228 @@ impl<'b> DiffState<'b> {
self.diff_children(old.children, new.children);
}
fn diff_template_ref_nodes(
&mut self,
old: &'b VTemplateRef<'b>,
new: &'b VTemplateRef<'b>,
old_node: &'b VNode<'b>,
new_node: &'b VNode<'b>,
) {
if std::ptr::eq(old, new) {
return;
}
// if the templates are different, just rebuild it
if old.template_id != new.template_id
|| self
.scopes
.template_resolver
.borrow()
.is_dirty(&new.template_id)
{
self.replace_node(old_node, new_node);
return;
}
// if the node is comming back not assigned, that means it was borrowed but removed
let root = match old.id.get() {
Some(id) => id,
None => self.scopes.reserve_node(new_node),
};
self.scopes.update_node(new_node, root);
new.id.set(Some(root));
self.element_stack.push(GlobalNodeId::VNodeId(root));
self.mutations.enter_template_ref(root);
let scope_bump = &self.current_scope_bump();
let template = {
let templates = self.scopes.templates.borrow();
templates.get(&new.template_id).unwrap().clone()
};
let template = template.borrow();
fn diff_attributes<'b, Nodes, Attributes, V, Children, Listeners, TextSegments, Text>(
nodes: &Nodes,
ctx: (
&mut Mutations<'b>,
&'b Bump,
&VTemplateRef<'b>,
&Template,
usize,
),
) where
Nodes: AsRef<[TemplateNode<Attributes, V, Children, Listeners, TextSegments, Text>]>,
Attributes: AsRef<[TemplateAttribute<V>]>,
V: TemplateValue,
Children: AsRef<[TemplateNodeId]>,
Listeners: AsRef<[usize]>,
TextSegments: AsRef<[TextTemplateSegment<Text>]>,
Text: AsRef<str>,
{
let (mutations, scope_bump, new, template, idx) = ctx;
for (node_id, attr_idx) in template.get_dynamic_nodes_for_attribute_index(idx) {
if let TemplateNodeType::Element(el) = &nodes.as_ref()[node_id.0].node_type {
let TemplateElement { attributes, .. } = el;
let attr = &attributes.as_ref()[*attr_idx];
let attribute = Attribute {
attribute: attr.attribute,
value: new.dynamic_context.resolve_attribute(idx).clone(),
is_static: false,
};
mutations.set_attribute(scope_bump.alloc(attribute), *node_id);
} else {
panic!("expected element node");
}
}
}
// diff dynamic attributes
for (idx, (old_attr, new_attr)) in old
.dynamic_context
.attributes
.iter()
.zip(new.dynamic_context.attributes.iter())
.enumerate()
{
if old_attr != new_attr {
template.with_nodes(
diff_attributes,
diff_attributes,
(&mut self.mutations, scope_bump, new, &template, idx),
);
}
}
fn set_attribute<'b, Attributes, V, Children, Listeners, TextSegments, Text>(
node: &TemplateNode<Attributes, V, Children, Listeners, TextSegments, Text>,
ctx: (&mut Mutations<'b>, &'b Bump, &VTemplateRef<'b>, usize),
) where
Attributes: AsRef<[TemplateAttribute<V>]>,
V: TemplateValue,
Children: AsRef<[TemplateNodeId]>,
Listeners: AsRef<[usize]>,
TextSegments: AsRef<[TextTemplateSegment<Text>]>,
Text: AsRef<str>,
{
let (mutations, scope_bump, new, template_attr_idx) = ctx;
if let TemplateNodeType::Element(el) = &node.node_type {
let TemplateElement { attributes, .. } = el;
let attr = &attributes.as_ref()[template_attr_idx];
let value = match &attr.value {
TemplateAttributeValue::Dynamic(idx) => {
new.dynamic_context.resolve_attribute(*idx).clone()
}
TemplateAttributeValue::Static(value) => value.allocate(scope_bump),
};
let attribute = Attribute {
attribute: attr.attribute,
value,
is_static: false,
};
mutations.set_attribute(scope_bump.alloc(attribute), node.id);
} else {
panic!("expected element node");
}
}
// set all volatile attributes
for (id, idx) in template.volatile_attributes() {
template.with_node(
id,
set_attribute,
set_attribute,
(&mut self.mutations, scope_bump, new, idx),
)
}
fn diff_dynamic_node<'b, Attributes, V, Children, Listeners, TextSegments, Text>(
node: &TemplateNode<Attributes, V, Children, Listeners, TextSegments, Text>,
ctx: (&mut DiffState<'b>, &'b VNode<'b>, &'b VNode<'b>, ElementId),
) where
Attributes: AsRef<[TemplateAttribute<V>]>,
V: TemplateValue,
Children: AsRef<[TemplateNodeId]>,
Listeners: AsRef<[usize]>,
TextSegments: AsRef<[TextTemplateSegment<Text>]>,
Text: AsRef<str>,
{
let (diff, old_node, new_node, root) = ctx;
if let TemplateNodeType::Element { .. } = node.node_type {
diff.element_stack.push(GlobalNodeId::VNodeId(root));
diff.diff_node(old_node, new_node);
diff.element_stack.pop();
} else {
diff.diff_node(old_node, new_node);
}
}
// diff dynmaic nodes
for (idx, (old_node, new_node)) in old
.dynamic_context
.nodes
.iter()
.zip(new.dynamic_context.nodes.iter())
.enumerate()
{
if let Some(id) = template.get_dynamic_nodes_for_node_index(idx) {
template.with_node(
id,
diff_dynamic_node,
diff_dynamic_node,
(self, old_node, new_node, root),
);
}
}
// diff dynamic text
// text nodes could rely on multiple dynamic text parts, so we keep a record of which ones to rerender and send the diffs at the end
let mut dirty_text_nodes = FxHashSet::default();
for (idx, (old_text, new_text)) in old
.dynamic_context
.text_segments
.iter()
.zip(new.dynamic_context.text_segments.iter())
.enumerate()
{
if old_text != new_text {
for node_id in template.get_dynamic_nodes_for_text_index(idx) {
dirty_text_nodes.insert(*node_id);
}
}
}
for node_id in dirty_text_nodes {
fn diff_text<'b, Attributes, V, Children, Listeners, TextSegments, Text>(
node: &TemplateNode<Attributes, V, Children, Listeners, TextSegments, Text>,
ctx: (&mut DiffState<'b>, &TemplateContext<'b>),
) where
Attributes: AsRef<[TemplateAttribute<V>]>,
V: TemplateValue,
Children: AsRef<[TemplateNodeId]>,
Listeners: AsRef<[usize]>,
TextSegments: AsRef<[TextTemplateSegment<Text>]>,
Text: AsRef<str>,
{
let (diff, dynamic_context) = ctx;
if let TemplateNodeType::Text(text) = &node.node_type {
let text = dynamic_context.resolve_text(&text.segments.as_ref());
diff.mutations
.set_text(diff.current_scope_bump().alloc(text), node.id);
} else {
panic!("expected text node");
}
}
template.with_node(node_id, diff_text, diff_text, (self, &new.dynamic_context));
}
self.mutations.exit_template_ref();
self.element_stack.pop();
}
// Diff the given set of old and new children.
//
// The parent must be on top of the change list stack when this function is
@@ -970,6 +1238,16 @@ impl<'b> DiffState<'b> {
}
self.leave_scope();
}
VNode::TemplateRef(t) => {
let id = old
.try_mounted_id()
.unwrap_or_else(|| panic!("broke on {:?}", old));
self.mutations.replace_with(id, nodes_created as u32);
self.remove_nodes(t.dynamic_context.nodes, true);
self.scopes.collect_garbage(id);
}
}
}
@@ -983,7 +1261,7 @@ impl<'b> DiffState<'b> {
t.id.set(None);
if gen_muts {
self.mutations.remove(id.as_u64());
self.mutations.remove(id);
}
}
}
@@ -993,14 +1271,14 @@ impl<'b> DiffState<'b> {
a.id.set(None);
if gen_muts {
self.mutations.remove(id.as_u64());
self.mutations.remove(id);
}
}
VNode::Element(e) => {
let id = e.id.get().unwrap();
if gen_muts {
self.mutations.remove(id.as_u64());
self.mutations.remove(id);
}
self.scopes.collect_garbage(id);
@@ -1029,6 +1307,19 @@ impl<'b> DiffState<'b> {
}
self.leave_scope();
}
VNode::TemplateRef(t) => {
let id = t.id.get().unwrap();
if gen_muts {
self.mutations.remove(id);
}
self.scopes.collect_garbage(id);
t.id.set(None);
self.remove_nodes(t.dynamic_context.nodes, gen_muts);
}
}
}
}
@@ -1058,7 +1349,7 @@ impl<'b> DiffState<'b> {
self.mutations.insert_before(first, created as u32);
}
fn current_scope(&self) -> ScopeId {
pub fn current_scope(&self) -> ScopeId {
self.scope_stack.last().copied().expect("no current scope")
}
@@ -1082,6 +1373,7 @@ impl<'b> DiffState<'b> {
let scope_id = el.scope.get().unwrap();
search_node = Some(self.scopes.root_node(scope_id));
}
VNode::TemplateRef(t) => break t.id.get(),
}
}
}
@@ -1098,6 +1390,7 @@ impl<'b> DiffState<'b> {
let scope = el.scope.get().expect("element to have a scope assigned");
search_node = Some(self.scopes.root_node(scope));
}
VNode::TemplateRef(t) => break t.id.get(),
}
}
}
@@ -1105,7 +1398,7 @@ impl<'b> DiffState<'b> {
// recursively push all the nodes of a tree onto the stack and return how many are there
fn push_all_real_nodes(&mut self, node: &'b VNode<'b>) -> usize {
match node {
VNode::Text(_) | VNode::Placeholder(_) | VNode::Element(_) => {
VNode::Text(_) | VNode::Placeholder(_) | VNode::Element(_) | VNode::TemplateRef(_) => {
self.mutations.push_root(node.mounted_id());
1
}
@@ -1125,4 +1418,18 @@ impl<'b> DiffState<'b> {
}
}
}
pub(crate) fn current_scope_bump(&self) -> &'b Bump {
&self
.scopes
.get_scope(self.current_scope())
.unwrap()
.fin_frame()
.bump
}
pub fn register_template(&mut self, template: &Template, id: RendererTemplateId) {
let bump = &self.scopes.template_bump;
template.create(&mut self.mutations, bump, id);
}
}
@@ -0,0 +1,195 @@
use std::{marker::PhantomData, ops::Deref};
use once_cell::sync::Lazy;
use crate::{
template::{TemplateNodeId, TextTemplateSegment},
AttributeValue, Listener, VNode,
};
/// A lazily initailized vector
#[derive(Debug, Clone, Copy)]
pub struct LazyStaticVec<T: 'static>(pub &'static Lazy<Vec<T>>);
impl<T: 'static> AsRef<[T]> for LazyStaticVec<T> {
fn as_ref(&self) -> &[T] {
let v: &Vec<_> = self.0.deref();
v.as_ref()
}
}
impl<T> PartialEq for LazyStaticVec<T> {
fn eq(&self, other: &Self) -> bool {
std::ptr::eq(self.0, other.0)
}
}
/// Stores what nodes depend on specific dynamic parts of the template to allow the diffing algorithm to jump to that part of the template instead of travering it
/// This makes adding constant template nodes add no additional cost to diffing.
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
pub struct DynamicNodeMapping<
Nodes,
TextOuter,
TextInner,
AttributesOuter,
AttributesInner,
Volatile,
Listeners,
> where
Nodes: AsRef<[Option<TemplateNodeId>]>,
TextOuter: AsRef<[TextInner]>,
TextInner: AsRef<[TemplateNodeId]>,
AttributesOuter: AsRef<[AttributesInner]>,
AttributesInner: AsRef<[(TemplateNodeId, usize)]>,
Volatile: AsRef<[(TemplateNodeId, usize)]>,
Listeners: AsRef<[TemplateNodeId]>,
{
/// The node that depend on each node in the dynamic template
pub nodes: Nodes,
text_inner: PhantomData<TextInner>,
/// The text nodes that depend on each text segment of the dynamic template
pub text: TextOuter,
/// The attributes along with the attribute index in the template that depend on each attribute of the dynamic template
pub attributes: AttributesOuter,
attributes_inner: PhantomData<AttributesInner>,
/// The attributes that are marked as volatile in the template
pub volatile_attributes: Volatile,
/// The listeners that depend on each listener of the dynamic template
pub nodes_with_listeners: Listeners,
}
impl<Nodes, TextOuter, TextInner, AttributesOuter, AttributesInner, Volatile, Listeners>
DynamicNodeMapping<
Nodes,
TextOuter,
TextInner,
AttributesOuter,
AttributesInner,
Volatile,
Listeners,
>
where
Nodes: AsRef<[Option<TemplateNodeId>]>,
TextOuter: AsRef<[TextInner]>,
TextInner: AsRef<[TemplateNodeId]>,
AttributesOuter: AsRef<[AttributesInner]>,
AttributesInner: AsRef<[(TemplateNodeId, usize)]>,
Volatile: AsRef<[(TemplateNodeId, usize)]>,
Listeners: AsRef<[TemplateNodeId]>,
{
/// Creates a new dynamic node mapping
pub const fn new(
nodes: Nodes,
text: TextOuter,
attributes: AttributesOuter,
volatile_attributes: Volatile,
listeners: Listeners,
) -> Self {
DynamicNodeMapping {
nodes,
text_inner: PhantomData,
text,
attributes,
attributes_inner: PhantomData,
volatile_attributes,
nodes_with_listeners: listeners,
}
}
pub(crate) fn all_dynamic<'a>(&'a self) -> impl Iterator<Item = TemplateNodeId> + 'a {
self.nodes
.as_ref()
.iter()
.filter_map(|o| o.as_ref())
.chain(
self.text
.as_ref()
.iter()
.map(|ids| ids.as_ref().iter())
.flatten(),
)
.copied()
.chain(
self.attributes
.as_ref()
.iter()
.map(|ids| ids.as_ref().iter())
.flatten()
.map(|dynamic| dynamic.0),
)
.chain(self.nodes_with_listeners.as_ref().iter().copied())
}
}
/// A dynamic node mapping that is stack allocated
pub type StaticDynamicNodeMapping = DynamicNodeMapping<
&'static [Option<TemplateNodeId>],
&'static [&'static [TemplateNodeId]],
&'static [TemplateNodeId],
&'static [&'static [(TemplateNodeId, usize)]],
&'static [(TemplateNodeId, usize)],
// volatile attribute information is available at compile time, but there is no way for the macro to generate it, so we initialize it lazily instead
LazyStaticVec<(TemplateNodeId, usize)>,
&'static [TemplateNodeId],
>;
#[cfg(any(feature = "hot-reload", debug_assertions))]
/// A dynamic node mapping that is heap allocated
pub type OwnedDynamicNodeMapping = DynamicNodeMapping<
Vec<Option<TemplateNodeId>>,
Vec<Vec<TemplateNodeId>>,
Vec<TemplateNodeId>,
Vec<Vec<(TemplateNodeId, usize)>>,
Vec<(TemplateNodeId, usize)>,
Vec<(TemplateNodeId, usize)>,
Vec<TemplateNodeId>,
>;
/// The dynamic parts used to saturate a template durring runtime
pub struct TemplateContext<'b> {
/// The dynamic nodes
pub nodes: &'b [VNode<'b>],
/// The dynamic text
pub text_segments: &'b [&'b str],
/// The dynamic attributes
pub attributes: &'b [AttributeValue<'b>],
/// The dynamic attributes
// The listeners must not change during the lifetime of the context, use a dynamic node if the listeners change
pub listeners: &'b [Listener<'b>],
/// A optional key for diffing
pub key: Option<&'b str>,
}
impl<'b> TemplateContext<'b> {
/// Resolve text segments to a string
pub fn resolve_text<TextSegments, Text>(&self, text: &TextSegments) -> String
where
TextSegments: AsRef<[TextTemplateSegment<Text>]>,
Text: AsRef<str>,
{
let mut result = String::new();
for seg in text.as_ref() {
match seg {
TextTemplateSegment::Static(s) => result += s.as_ref(),
TextTemplateSegment::Dynamic(idx) => result += self.text_segments[*idx],
}
}
result
}
/// Resolve an attribute value
pub fn resolve_attribute(&self, idx: usize) -> &'b AttributeValue<'b> {
&self.attributes[idx]
}
/// Resolve a listener
pub fn resolve_listener(&self, idx: usize) -> &'b Listener<'b> {
&self.listeners[idx]
}
/// Resolve a node
pub fn resolve_node(&self, idx: usize) -> &'b VNode<'b> {
&self.nodes[idx]
}
}
+2 -2
View File
@@ -3,7 +3,7 @@
//!
//! This is all kinda WIP, but the bones are there.
use crate::{ElementId, ScopeId};
use crate::{nodes::GlobalNodeId, ScopeId};
use std::{any::Any, cell::Cell, fmt::Debug, rc::Rc, sync::Arc};
pub(crate) struct BubbleState {
@@ -58,7 +58,7 @@ pub struct UserEvent {
pub priority: EventPriority,
/// The optional real node associated with the trigger
pub element: Option<ElementId>,
pub element: Option<GlobalNodeId>,
/// The event type IE "onclick" or "onmouseover"
pub name: &'static str,
+28 -7
View File
@@ -4,23 +4,27 @@
pub(crate) mod arbitrary_value;
pub(crate) mod diff;
pub(crate) mod dynamic_template_context;
pub(crate) mod events;
pub(crate) mod lazynodes;
pub(crate) mod mutations;
pub(crate) mod nodes;
pub(crate) mod properties;
pub(crate) mod scopes;
pub(crate) mod template;
pub(crate) mod util;
pub(crate) mod virtual_dom;
pub(crate) mod innerlude {
pub use crate::arbitrary_value::*;
pub use crate::dynamic_template_context::*;
pub use crate::events::*;
pub use crate::lazynodes::*;
pub use crate::mutations::*;
pub use crate::nodes::*;
pub use crate::properties::*;
pub use crate::scopes::*;
pub use crate::template::*;
pub use crate::util::*;
pub use crate::virtual_dom::*;
@@ -63,20 +67,36 @@ pub(crate) mod innerlude {
}
pub use crate::innerlude::{
AnyEvent, ArbitraryAttributeValue, Attribute, AttributeValue, Component, DioxusElement,
DomEdit, Element, ElementId, ElementIdIterator, EventHandler, EventPriority, IntoVNode,
LazyNodes, Listener, Mutations, NodeFactory, Properties, SchedulerMsg, Scope, ScopeId,
ScopeState, TaskId, UiEvent, UserEvent, VComponent, VElement, VFragment, VNode, VPlaceholder,
VText, VirtualDom,
AnyEvent, ArbitraryAttributeValue, Attribute, AttributeDiscription, AttributeValue,
CodeLocation, Component, DioxusElement, DomEdit, DynamicNodeMapping, Element, ElementId,
ElementIdIterator, EventHandler, EventPriority, GlobalNodeId, IntoVNode, LazyNodes, Listener,
Mutations, NodeFactory, OwnedAttributeValue, Properties, RendererTemplateId, SchedulerMsg,
Scope, ScopeId, ScopeState, StaticCodeLocation, StaticDynamicNodeMapping, StaticTemplateNode,
StaticTemplateNodes, TaskId, Template, TemplateAttribute, TemplateAttributeValue,
TemplateContext, TemplateElement, TemplateId, TemplateNode, TemplateNodeId, TemplateNodeType,
TemplateValue, TextTemplate, TextTemplateSegment, UiEvent, UserEvent, VComponent, VElement,
VFragment, VNode, VPlaceholder, VText, VirtualDom, JS_MAX_INT,
};
#[cfg(any(feature = "hot-reload", debug_assertions))]
pub use crate::innerlude::{
OwnedCodeLocation, OwnedDynamicNodeMapping, OwnedTemplateNode, OwnedTemplateNodes,
SetTemplateMsg,
};
/// The purpose of this module is to alleviate imports of many common types
///
/// This includes types like [`Scope`], [`Element`], and [`Component`].
pub mod prelude {
pub use crate::get_line_num;
#[cfg(any(feature = "hot-reload", debug_assertions))]
pub use crate::innerlude::OwnedTemplate;
pub use crate::innerlude::{
fc_to_builder, Attributes, Component, DioxusElement, Element, EventHandler, Fragment,
LazyNodes, NodeFactory, Properties, Scope, ScopeId, ScopeState, VNode, VirtualDom,
fc_to_builder, AttributeDiscription, AttributeValue, Attributes, CodeLocation, Component,
DioxusElement, Element, EventHandler, Fragment, LazyNodes, LazyStaticVec, NodeFactory,
Properties, Scope, ScopeId, ScopeState, StaticAttributeValue, StaticCodeLocation,
StaticDynamicNodeMapping, StaticTemplate, StaticTemplateNodes, Template, TemplateAttribute,
TemplateAttributeValue, TemplateContext, TemplateElement, TemplateId, TemplateNode,
TemplateNodeId, TemplateNodeType, TextTemplate, TextTemplateSegment, VNode, VirtualDom,
};
}
@@ -85,6 +105,7 @@ pub mod exports {
//! Feel free to just add the dependencies in your own Crates.toml
pub use bumpalo;
pub use futures_channel;
pub use once_cell;
}
/// Functions that wrap unsafe functionality to prevent us from misusing it at the callsite
+201 -33
View File
@@ -128,6 +128,59 @@ pub enum DomEdit<'bump> {
root: u64,
},
/// Create a new purely-text node in a template
CreateTextNodeTemplate {
/// The ID the new node should have.
root: u64,
/// The textcontent of the noden
text: &'bump str,
/// If the id of the node must be kept in the refrences
locally_static: bool,
},
/// Create a new purely-element node in a template
CreateElementTemplate {
/// The ID the new node should have.
root: u64,
/// The tagname of the node
tag: &'bump str,
/// If the id of the node must be kept in the refrences
locally_static: bool,
/// If any children of this node must be kept in the references
fully_static: bool,
},
/// Create a new purely-comment node with a given namespace in a template
CreateElementNsTemplate {
/// The ID the new node should have.
root: u64,
/// The namespace of the node
tag: &'bump str,
/// The namespace of the node (like `SVG`)
ns: &'static str,
/// If the id of the node must be kept in the refrences
locally_static: bool,
/// If any children of this node must be kept in the references
fully_static: bool,
},
/// Create a new placeholder node.
/// In most implementations, this will either be a hidden div or a comment node. in a template
/// Always both locally and fully static
CreatePlaceholderTemplate {
/// The ID the new node should have.
root: u64,
},
/// Create a new Event Listener.
NewEventListener {
/// The name of the event to listen for.
@@ -189,6 +242,38 @@ pub enum DomEdit<'bump> {
/// Manually pop a root node from the stack.
PopRoot {},
/// Enter a TemplateRef tree
EnterTemplateRef {
/// The ID of the node to enter.
root: u64,
},
/// Exit a TemplateRef tree
ExitTemplateRef {},
/// Create a refrence to a template node.
CreateTemplateRef {
/// The ID of the new template refrence.
id: u64,
/// The ID of the template the node is refrencing.
template_id: u64,
},
/// Create a new templete.
/// IMPORTANT: When adding nodes to a templete, id's will reset to zero, so they must be allocated on a different stack.
/// It is recommended to use Cow<NativeNode>.
CreateTemplate {
/// The ID of the new template.
id: u64,
},
/// Finish a templete
FinishTemplate {
/// The number of root nodes in the template
len: u32,
},
}
use fxhash::FxHashSet;
@@ -204,8 +289,8 @@ impl<'a> Mutations<'a> {
}
// Navigation
pub(crate) fn push_root(&mut self, root: ElementId) {
let id = root.as_u64();
pub(crate) fn push_root(&mut self, root: impl Into<u64>) {
let id = root.into();
self.edits.push(PushRoot { root: id });
}
@@ -214,18 +299,18 @@ impl<'a> Mutations<'a> {
self.edits.push(PopRoot {});
}
pub(crate) fn replace_with(&mut self, root: ElementId, m: u32) {
let root = root.as_u64();
pub(crate) fn replace_with(&mut self, root: impl Into<u64>, m: u32) {
let root = root.into();
self.edits.push(ReplaceWith { m, root });
}
pub(crate) fn insert_after(&mut self, root: ElementId, n: u32) {
let root = root.as_u64();
pub(crate) fn insert_after(&mut self, root: impl Into<u64>, n: u32) {
let root = root.into();
self.edits.push(InsertAfter { n, root });
}
pub(crate) fn insert_before(&mut self, root: ElementId, n: u32) {
let root = root.as_u64();
pub(crate) fn insert_before(&mut self, root: impl Into<u64>, n: u32) {
let root = root.into();
self.edits.push(InsertBefore { n, root });
}
@@ -234,13 +319,13 @@ impl<'a> Mutations<'a> {
}
// Remove Nodes from the dom
pub(crate) fn remove(&mut self, id: u64) {
self.edits.push(Remove { root: id });
pub(crate) fn remove(&mut self, id: impl Into<u64>) {
self.edits.push(Remove { root: id.into() });
}
// Create
pub(crate) fn create_text_node(&mut self, text: &'a str, id: ElementId) {
let id = id.as_u64();
pub(crate) fn create_text_node(&mut self, text: &'a str, id: impl Into<u64>) {
let id = id.into();
self.edits.push(CreateTextNode { text, root: id });
}
@@ -248,20 +333,68 @@ impl<'a> Mutations<'a> {
&mut self,
tag: &'static str,
ns: Option<&'static str>,
id: ElementId,
id: impl Into<u64>,
) {
let id = id.as_u64();
let id = id.into();
match ns {
Some(ns) => self.edits.push(CreateElementNs { root: id, ns, tag }),
None => self.edits.push(CreateElement { root: id, tag }),
}
}
// placeholders are nodes that don't get rendered but still exist as an "anchor" in the real dom
pub(crate) fn create_placeholder(&mut self, id: ElementId) {
let id = id.as_u64();
pub(crate) fn create_placeholder(&mut self, id: impl Into<u64>) {
let id = id.into();
self.edits.push(CreatePlaceholder { root: id });
}
// Create
pub(crate) fn create_text_node_template(
&mut self,
text: &'a str,
id: impl Into<u64>,
locally_static: bool,
) {
let id = id.into();
self.edits.push(CreateTextNodeTemplate {
text,
root: id,
locally_static,
});
}
pub(crate) fn create_element_template(
&mut self,
tag: &'static str,
ns: Option<&'static str>,
id: impl Into<u64>,
locally_static: bool,
fully_static: bool,
) {
let id = id.into();
match ns {
Some(ns) => self.edits.push(CreateElementNsTemplate {
root: id,
ns,
tag,
locally_static,
fully_static,
}),
None => self.edits.push(CreateElementTemplate {
root: id,
tag,
locally_static,
fully_static,
}),
}
}
// placeholders are nodes that don't get rendered but still exist as an "anchor" in the real dom
pub(crate) fn create_placeholder_template(&mut self, id: impl Into<u64>) {
let id = id.into();
self.edits.push(CreatePlaceholderTemplate { root: id });
}
// events
pub(crate) fn new_event_listener(&mut self, listener: &Listener, scope: ScopeId) {
let Listener {
@@ -270,7 +403,13 @@ impl<'a> Mutations<'a> {
..
} = listener;
let element_id = mounted_node.get().unwrap().as_u64();
let element_id = match mounted_node.get().unwrap() {
GlobalNodeId::TemplateId {
template_ref_id: _,
template_node_id,
} => template_node_id.into(),
GlobalNodeId::VNodeId(id) => id.into(),
};
self.edits.push(NewEventListener {
scope,
@@ -278,39 +417,41 @@ impl<'a> Mutations<'a> {
root: element_id,
});
}
pub(crate) fn remove_event_listener(&mut self, event: &'static str, root: u64) {
self.edits.push(RemoveEventListener { event, root });
pub(crate) fn remove_event_listener(&mut self, event: &'static str, root: impl Into<u64>) {
self.edits.push(RemoveEventListener {
event,
root: root.into(),
});
}
// modify
pub(crate) fn set_text(&mut self, text: &'a str, root: u64) {
pub(crate) fn set_text(&mut self, text: &'a str, root: impl Into<u64>) {
let root = root.into();
self.edits.push(SetText { text, root });
}
pub(crate) fn set_attribute(&mut self, attribute: &'a Attribute<'a>, root: u64) {
pub(crate) fn set_attribute(&mut self, attribute: &'a Attribute<'a>, root: impl Into<u64>) {
let root = root.into();
let Attribute {
name,
value,
namespace,
..
value, attribute, ..
} = attribute;
self.edits.push(SetAttribute {
field: name,
field: attribute.name,
value: value.clone(),
ns: *namespace,
ns: attribute.namespace,
root,
});
}
pub(crate) fn remove_attribute(&mut self, attribute: &Attribute, root: u64) {
let Attribute {
name, namespace, ..
} = attribute;
pub(crate) fn remove_attribute(&mut self, attribute: &Attribute, root: impl Into<u64>) {
let root = root.into();
let Attribute { attribute, .. } = attribute;
self.edits.push(RemoveAttribute {
name,
ns: *namespace,
name: attribute.name,
ns: attribute.namespace,
root,
});
}
@@ -318,6 +459,33 @@ impl<'a> Mutations<'a> {
pub(crate) fn mark_dirty_scope(&mut self, scope: ScopeId) {
self.dirty_scopes.insert(scope);
}
pub(crate) fn create_templete(&mut self, id: impl Into<u64>) {
self.edits.push(CreateTemplate { id: id.into() });
}
pub(crate) fn finish_templete(&mut self, len: u32) {
self.edits.push(FinishTemplate { len });
}
pub(crate) fn create_template_ref(&mut self, id: impl Into<u64>, template_id: u64) {
self.edits.push(CreateTemplateRef {
id: id.into(),
template_id,
})
}
pub(crate) fn enter_template_ref(&mut self, id: impl Into<u64>) {
self.edits.push(EnterTemplateRef { root: id.into() });
}
pub(crate) fn exit_template_ref(&mut self) {
if let Some(&DomEdit::EnterTemplateRef { .. }) = self.edits.last() {
self.edits.pop();
} else {
self.edits.push(ExitTemplateRef {});
}
}
}
// refs are only assigned once
+162 -28
View File
@@ -3,16 +3,70 @@
//! 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 quick.
use crate::{
innerlude::{AttributeValue, ComponentPtr, Element, Properties, Scope, ScopeId, ScopeState},
dynamic_template_context::TemplateContext,
innerlude::{
AttributeValue, ComponentPtr, Element, Properties, Scope, ScopeId, ScopeState, Template,
TemplateId,
},
lazynodes::LazyNodes,
template::{TemplateNodeId, VTemplateRef},
AnyEvent, Component,
};
use bumpalo::{boxed::Box as BumpBox, Bump};
use std::{
cell::{Cell, RefCell},
fmt::{Arguments, Debug, Formatter},
num::ParseIntError,
rc::Rc,
str::FromStr,
};
/// The ID of a node in the vdom that is either standalone or in a template
#[derive(Clone, Copy, Debug, PartialEq, Hash, Eq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(untagged))]
pub enum GlobalNodeId {
/// The ID of a node and the template that contains it
TemplateId {
/// The template that contains the node
template_ref_id: ElementId,
/// The ID of the node in the template
template_node_id: TemplateNodeId,
},
/// The ID of a regular node
VNodeId(ElementId),
}
impl Into<GlobalNodeId> for ElementId {
fn into(self) -> GlobalNodeId {
GlobalNodeId::VNodeId(self)
}
}
impl PartialEq<ElementId> for GlobalNodeId {
fn eq(&self, other: &ElementId) -> bool {
match self {
GlobalNodeId::TemplateId { .. } => false,
GlobalNodeId::VNodeId(id) => id == other,
}
}
}
impl FromStr for GlobalNodeId {
type Err = ParseIntError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if let Some((tmpl_id, node_id)) = s.split_once(',') {
Ok(GlobalNodeId::TemplateId {
template_ref_id: ElementId(tmpl_id.parse()?),
template_node_id: TemplateNodeId(node_id.parse()?),
})
} else {
Ok(GlobalNodeId::VNodeId(ElementId(s.parse()?)))
}
}
}
/// A composable "VirtualNode" to declare a User Interface in the Dioxus VirtualDOM.
///
/// VNodes are designed to be lightweight and used with with a bump allocator. To create a VNode, you can use either of:
@@ -112,6 +166,9 @@ pub enum VNode<'src> {
/// }
/// ```
Placeholder(&'src VPlaceholder),
/// Templetes ase generated by the rsx macro to eleminate diffing static nodes.
TemplateRef(&'src VTemplateRef<'src>),
}
impl<'src> VNode<'src> {
@@ -123,6 +180,7 @@ impl<'src> VNode<'src> {
VNode::Fragment(f) => f.key,
VNode::Text(_t) => None,
VNode::Placeholder(_f) => None,
VNode::TemplateRef(t) => t.dynamic_context.key,
}
}
@@ -143,6 +201,7 @@ impl<'src> VNode<'src> {
VNode::Placeholder(el) => el.id.get(),
VNode::Fragment(_) => None,
VNode::Component(_) => None,
VNode::TemplateRef(t) => t.id.get(),
}
}
@@ -154,6 +213,7 @@ impl<'src> VNode<'src> {
VNode::Component(c) => VNode::Component(c),
VNode::Placeholder(a) => VNode::Placeholder(a),
VNode::Fragment(f) => VNode::Fragment(f),
VNode::TemplateRef(t) => VNode::TemplateRef(t),
}
}
}
@@ -189,6 +249,11 @@ impl Debug for VNode<'_> {
.field("key", &comp.key)
.field("scope", &comp.scope)
.finish(),
VNode::TemplateRef(temp) => s
.debug_struct("VNode::TemplateRef")
.field("template_id", &temp.template_id)
.field("id", &temp.id)
.finish(),
}
}
}
@@ -198,6 +263,8 @@ impl Debug for VNode<'_> {
/// `ElementId` is a `usize` that is unique across the entire VirtualDOM - but not unique across time. If a component is
/// unmounted, then the `ElementId` will be reused for a new component.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(transparent))]
pub struct ElementId(pub usize);
impl std::fmt::Display for ElementId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
@@ -206,13 +273,19 @@ impl std::fmt::Display for ElementId {
}
impl ElementId {
/// Convertt the ElementId to a `u64`.
pub fn as_u64(self) -> u64 {
/// Convert the ElementId to a `u64`.
pub fn as_u64(&self) -> u64 {
(*self).into()
}
}
impl Into<u64> for ElementId {
fn into(self) -> u64 {
self.0 as u64
}
}
fn empty_cell() -> Cell<Option<ElementId>> {
fn empty_cell<T>() -> Cell<Option<T>> {
Cell::new(None)
}
@@ -267,7 +340,7 @@ pub struct VElement<'a> {
/// The parent of the Element (if any).
///
/// Used when bubbling events
pub parent: Cell<Option<ElementId>>,
pub parent: Cell<Option<GlobalNodeId>>,
/// The Listeners of the VElement.
pub listeners: &'a [Listener<'a>],
@@ -330,30 +403,52 @@ pub trait DioxusElement {
}
}
type StaticStr = &'static str;
/// A discription of the attribute
#[derive(Clone, Copy, Debug, PartialEq, Hash, Eq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(
all(feature = "serialize", any(feature = "hot-reload", debug_assertions)),
derive(serde::Deserialize)
)]
pub struct AttributeDiscription {
/// The name of the attribute.
#[cfg_attr(
all(feature = "serialize", any(feature = "hot-reload", debug_assertions)),
serde(deserialize_with = "crate::util::deserialize_static_leaky")
)]
pub name: StaticStr,
/// The namespace of the attribute.
///
/// Doesn't exist in the html spec.
/// Used in Dioxus to denote "style" tags and other attribute groups.
#[cfg_attr(
all(feature = "serialize", any(feature = "hot-reload", debug_assertions)),
serde(deserialize_with = "crate::util::deserialize_static_leaky_ns")
)]
pub namespace: Option<StaticStr>,
/// An indication of we should always try and set the attribute.
/// Used in controlled components to ensure changes are propagated.
pub volatile: bool,
}
/// An attribute on a DOM node, such as `id="my-thing"` or
/// `href="https://example.com"`.
#[derive(Clone, Debug)]
pub struct Attribute<'a> {
/// The name of the attribute.
pub name: &'static str,
/// The value of the attribute.
pub value: AttributeValue<'a>,
/// The discription of the attribute.
pub attribute: AttributeDiscription,
/// An indication if this attribute can be ignored during diffing
///
/// Usually only when there are no strings to be formatted (so the value is &'static str)
pub is_static: bool,
/// An indication of we should always try and set the attribute.
/// Used in controlled components to ensure changes are propagated.
pub is_volatile: bool,
/// The namespace of the attribute.
///
/// Doesn't exist in the html spec.
/// Used in Dioxus to denote "style" tags and other attribute groups.
pub namespace: Option<&'static str>,
/// The value of the attribute.
pub value: AttributeValue<'a>,
}
/// An event listener.
@@ -361,7 +456,7 @@ pub struct Attribute<'a> {
pub struct Listener<'bump> {
/// The ID of the node that this listener is mounted to
/// Used to generate the event listener's ID on the DOM
pub mounted_node: Cell<Option<ElementId>>,
pub mounted_node: Cell<Option<GlobalNodeId>>,
/// The type of event to listen for.
///
@@ -599,6 +694,20 @@ impl<'a> NodeFactory<'a> {
}))
}
/// Create a new [`Attribute`] from a attribute discrimination and a value
pub fn attr_disciption(
&self,
discription: AttributeDiscription,
val: Arguments,
) -> Attribute<'a> {
let (value, is_static) = self.raw_text(val);
Attribute {
attribute: discription,
is_static,
value: AttributeValue::Text(value),
}
}
/// Create a new [`Attribute`]
pub fn attr(
&self,
@@ -609,11 +718,13 @@ impl<'a> NodeFactory<'a> {
) -> Attribute<'a> {
let (value, is_static) = self.raw_text(val);
Attribute {
name,
value: AttributeValue::Text(value),
attribute: AttributeDiscription {
name,
namespace,
volatile: is_volatile,
},
is_static,
namespace,
is_volatile,
value: AttributeValue::Text(value),
}
}
@@ -627,11 +738,13 @@ impl<'a> NodeFactory<'a> {
is_static: bool,
) -> Attribute<'a> {
Attribute {
name,
value,
attribute: AttributeDiscription {
name,
namespace,
volatile: is_volatile,
},
is_static,
namespace,
is_volatile,
value,
}
}
@@ -743,6 +856,27 @@ impl<'a> NodeFactory<'a> {
let callback = RefCell::new(Some(caller));
EventHandler { callback }
}
/// Create a refrence to a template
pub fn template_ref(
&self,
id: TemplateId,
template: Template,
dynamic_context: TemplateContext<'a>,
) -> VNode<'a> {
let borrow_ref = self.scope.templates.borrow();
// We only create the template if it doesn't already exist to allow for hot reloading
if !borrow_ref.contains_key(&id) {
drop(borrow_ref);
let mut borrow_mut = self.scope.templates.borrow_mut();
borrow_mut.insert(id.clone(), Rc::new(RefCell::new(template)));
}
VNode::TemplateRef(self.bump.alloc(VTemplateRef {
id: empty_cell(),
dynamic_context,
template_id: id,
}))
}
}
impl Debug for NodeFactory<'_> {
+149 -92
View File
@@ -1,12 +1,19 @@
use crate::{innerlude::*, unsafe_utils::extend_vnode};
use crate::{
dynamic_template_context::TemplateContext,
innerlude::*,
template::{
TemplateAttribute, TemplateElement, TemplateNode, TemplateNodeId, TemplateNodeType,
TemplateValue, TextTemplateSegment,
},
unsafe_utils::extend_vnode,
};
use bumpalo::Bump;
use futures_channel::mpsc::UnboundedSender;
use fxhash::FxHashMap;
use slab::Slab;
use std::{
any::{Any, TypeId},
borrow::Borrow,
cell::{Cell, RefCell},
cell::{Cell, Ref, RefCell},
collections::{HashMap, HashSet},
future::Future,
pin::Pin,
@@ -35,6 +42,10 @@ pub(crate) struct ScopeArena {
pub free_scopes: RefCell<Vec<*mut ScopeState>>,
pub nodes: RefCell<Slab<*const VNode<'static>>>,
pub tasks: Rc<TaskQueue>,
pub template_resolver: RefCell<TemplateResolver>,
pub templates: Rc<RefCell<FxHashMap<TemplateId, Rc<RefCell<Template>>>>>,
// this is used to store intermidiate artifacts of creating templates, so that the lifetime aligns with Mutations<'bump>.
pub template_bump: Bump,
}
impl ScopeArena {
@@ -74,6 +85,9 @@ impl ScopeArena {
gen: Cell::new(0),
sender,
}),
template_resolver: RefCell::new(TemplateResolver::default()),
templates: Rc::new(RefCell::new(FxHashMap::default())),
template_bump: Bump::new(),
}
}
@@ -93,8 +107,7 @@ impl ScopeArena {
fc_ptr: ComponentPtr,
vcomp: Box<dyn AnyProps>,
parent_scope: Option<ScopeId>,
container: ElementId,
subtree: u32,
container: GlobalNodeId,
) -> ScopeId {
// Increment the ScopeId system. ScopeIDs are never reused
let new_scope_id = ScopeId(self.scope_gen.get());
@@ -124,7 +137,6 @@ impl ScopeArena {
scope.height = height;
scope.fnptr = fc_ptr;
scope.props.get_mut().replace(vcomp);
scope.subtree.set(subtree);
scope.frames[0].reset();
scope.frames[1].reset();
scope.shared_contexts.get_mut().clear();
@@ -155,10 +167,6 @@ impl ScopeArena {
props: RefCell::new(Some(vcomp)),
frames: [BumpFrame::new(node_capacity), BumpFrame::new(node_capacity)],
// todo: subtrees
subtree: Cell::new(0),
is_subtree_root: Cell::default(),
generation: 0.into(),
tasks: self.tasks.clone(),
@@ -172,6 +180,8 @@ impl ScopeArena {
hook_arena: Bump::new(),
hook_vals: RefCell::new(Vec::with_capacity(hook_capacity)),
hook_idx: Cell::default(),
templates: self.templates.clone(),
}),
);
}
@@ -314,44 +324,140 @@ impl ScopeArena {
scope.cycle_frame();
}
pub fn call_listener_with_bubbling(&self, event: &UserEvent, element: ElementId) {
pub fn call_listener_with_bubbling(&self, event: &UserEvent, element: GlobalNodeId) {
let nodes = self.nodes.borrow();
let mut cur_el = Some(element);
let state = Rc::new(BubbleState::new());
while let Some(id) = cur_el.take() {
if let Some(el) = nodes.get(id.0) {
let real_el = unsafe { &**el };
if let VNode::Element(real_el) = real_el {
for listener in real_el.listeners.borrow().iter() {
if listener.event == event.name {
if state.canceled.get() {
// stop bubbling if canceled
return;
}
let mut cb = listener.callback.borrow_mut();
if let Some(cb) = cb.as_mut() {
// todo: arcs are pretty heavy to clone
// we really want to convert arc to rc
// unfortunately, the SchedulerMsg must be send/sync to be sent across threads
// we could convert arc to rc internally or something
(cb)(AnyEvent {
bubble_state: state.clone(),
data: event.data.clone(),
});
}
if !event.bubbles {
return;
}
if state.canceled.get() {
// stop bubbling if canceled
return;
}
match id {
GlobalNodeId::TemplateId {
template_ref_id,
template_node_id,
} => {
log::trace!(
"looking for listener in {:?} in node {:?}",
template_ref_id,
template_node_id
);
if let Some(template) = nodes.get(template_ref_id.0) {
let template = unsafe { &**template };
if let VNode::TemplateRef(template_ref) = template {
let templates = self.templates.borrow();
let template = templates.get(&template_ref.template_id).unwrap();
cur_el = template.borrow().with_node(
template_node_id,
bubble_template,
bubble_template,
(
&nodes,
&template_ref.dynamic_context,
&event,
&state,
template_ref_id,
),
);
}
}
cur_el = real_el.parent.get();
}
GlobalNodeId::VNodeId(id) => {
if let Some(el) = nodes.get(id.0) {
let real_el = unsafe { &**el };
log::trace!("looking for listener on {:?}", real_el);
if let VNode::Element(real_el) = real_el {
for listener in real_el.listeners.iter() {
if listener.event == event.name {
log::trace!("calling listener {:?}", listener.event);
let mut cb = listener.callback.borrow_mut();
if let Some(cb) = cb.as_mut() {
// todo: arcs are pretty heavy to clone
// we really want to convert arc to rc
// unfortunately, the SchedulerMsg must be send/sync to be sent across threads
// we could convert arc to rc internally or something
(cb)(AnyEvent {
bubble_state: state.clone(),
data: event.data.clone(),
});
}
break;
}
}
cur_el = real_el.parent.get();
}
}
}
}
if !event.bubbles {
return;
}
}
fn bubble_template<'b, Attributes, V, Children, Listeners, TextSegments, Text>(
node: &TemplateNode<Attributes, V, Children, Listeners, TextSegments, Text>,
ctx: (
&Ref<Slab<*const VNode>>,
&TemplateContext<'b>,
&UserEvent,
&Rc<BubbleState>,
ElementId,
),
) -> Option<GlobalNodeId>
where
Attributes: AsRef<[TemplateAttribute<V>]>,
V: TemplateValue,
Children: AsRef<[TemplateNodeId]>,
Listeners: AsRef<[usize]>,
TextSegments: AsRef<[TextTemplateSegment<Text>]>,
Text: AsRef<str>,
{
let (vnodes, dynamic_context, event, state, template_ref_id) = ctx;
if let TemplateNodeType::Element(el) = &node.node_type {
let TemplateElement { listeners, .. } = el;
for listener_idx in listeners.as_ref() {
let listener = dynamic_context.resolve_listener(*listener_idx);
if listener.event == event.name {
log::trace!("calling listener {:?}", listener.event);
let mut cb = listener.callback.borrow_mut();
if let Some(cb) = cb.as_mut() {
// todo: arcs are pretty heavy to clone
// we really want to convert arc to rc
// unfortunately, the SchedulerMsg must be send/sync to be sent across threads
// we could convert arc to rc internally or something
(cb)(AnyEvent {
bubble_state: state.clone(),
data: event.data.clone(),
});
}
break;
}
}
if let Some(id) = el.parent {
Some(GlobalNodeId::TemplateId {
template_ref_id,
template_node_id: id,
})
} else {
vnodes.get(template_ref_id.0).and_then(|el| {
let real_el = unsafe { &**el };
if let VNode::Element(real_el) = real_el {
real_el.parent.get()
} else {
None
}
})
}
} else {
None
}
}
}
@@ -463,14 +569,10 @@ pub struct TaskId {
/// use case they might have.
pub struct ScopeState {
pub(crate) parent_scope: Option<*mut ScopeState>,
pub(crate) container: ElementId,
pub(crate) container: GlobalNodeId,
pub(crate) our_arena_idx: ScopeId,
pub(crate) height: u32,
pub(crate) fnptr: ComponentPtr,
// todo: subtrees
pub(crate) is_subtree_root: Cell<bool>,
pub(crate) subtree: Cell<u32>,
pub(crate) props: RefCell<Option<Box<dyn AnyProps>>>,
// nodes, items
@@ -486,6 +588,9 @@ pub struct ScopeState {
// shared state -> todo: move this out of scopestate
pub(crate) shared_contexts: RefCell<HashMap<TypeId, Box<dyn Any>>>,
pub(crate) tasks: Rc<TaskQueue>,
// templates
pub(crate) templates: Rc<RefCell<FxHashMap<TemplateId, Rc<RefCell<Template>>>>>,
}
pub struct SelfReferentialItems<'a> {
@@ -495,52 +600,6 @@ pub struct SelfReferentialItems<'a> {
// Public methods exposed to libraries and components
impl ScopeState {
/// 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| 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: Scope) -> Element {
/// render!(div { "Subtree {id}"})
/// };
/// ```
///
/// todo: enable subtree
pub(crate) fn _create_subtree(&self) -> Option<u32> {
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.
@@ -903,8 +962,6 @@ impl ScopeState {
self.hook_idx.set(0);
self.parent_scope = None;
self.generation.set(0);
self.is_subtree_root.set(false);
self.subtree.set(0);
// next: shared context data
self.shared_contexts.get_mut().clear();
File diff suppressed because it is too large. Load diff
+45 -1
View File
@@ -34,7 +34,10 @@ impl<'a> Iterator for ElementIdIterator<'a> {
if let Some((count, node)) = self.stack.last_mut() {
match node {
// We can only exit our looping when we get "real" nodes
VNode::Element(_) | VNode::Text(_) | VNode::Placeholder(_) => {
VNode::Element(_)
| VNode::Text(_)
| VNode::Placeholder(_)
| VNode::TemplateRef(_) => {
// We've recursed INTO an element/text
// We need to recurse *out* of it and move forward to the next
// println!("Found element! Returning it!");
@@ -81,3 +84,44 @@ impl<'a> Iterator for ElementIdIterator<'a> {
returned_node
}
}
/// This intentionally leaks once per element name to allow more flexability when hot reloding templetes
#[cfg(all(any(feature = "hot-reload", debug_assertions), feature = "serde"))]
mod leaky {
use std::sync::Mutex;
use fxhash::FxHashSet;
use once_cell::sync::Lazy;
static STATIC_CACHE: Lazy<Mutex<FxHashSet<&'static str>>> =
Lazy::new(|| Mutex::new(FxHashSet::default()));
pub fn deserialize_static_leaky<'de, D>(d: D) -> Result<&'static str, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::Deserialize;
let s = <&str>::deserialize(d)?;
Ok(if let Some(stat) = STATIC_CACHE.lock().unwrap().get(s) {
*stat
} else {
Box::leak(s.into())
})
}
pub fn deserialize_static_leaky_ns<'de, D>(d: D) -> Result<Option<&'static str>, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::Deserialize;
Ok(<Option<&str>>::deserialize(d)?.map(|s| {
if let Some(stat) = STATIC_CACHE.lock().unwrap().get(s) {
*stat
} else {
Box::leak(s.into())
}
}))
}
}
#[cfg(all(any(feature = "hot-reload", debug_assertions), feature = "serde"))]
pub use leaky::*;
+52 -8
View File
@@ -128,6 +128,10 @@ pub enum SchedulerMsg {
/// Mark all components as dirty and update them
DirtyAll,
#[cfg(any(feature = "hot-reload", debug_assertions))]
/// Mark a template as dirty, used for hot reloading
SetTemplate(Box<SetTemplateMsg>),
/// New tasks from components that should be polled when the next poll is ready
NewTask(ScopeId),
}
@@ -226,8 +230,7 @@ impl VirtualDom {
render_fn: root,
}),
None,
ElementId(0),
0,
GlobalNodeId::VNodeId(ElementId(0)),
);
Self {
@@ -398,6 +401,25 @@ impl VirtualDom {
self.dirty_scopes.insert(*id);
}
}
#[cfg(any(feature = "hot-reload", debug_assertions))]
SchedulerMsg::SetTemplate(msg) => {
let SetTemplateMsg(id, tmpl) = *msg;
if self
.scopes
.templates
.borrow_mut()
.insert(
id.clone(),
std::rc::Rc::new(std::cell::RefCell::new(Template::Owned(tmpl))),
)
.is_some()
{
self.scopes.template_resolver.borrow_mut().mark_dirty(&id)
}
// mark any scopes that used the template as dirty
self.process_message(SchedulerMsg::DirtyAll);
}
}
}
@@ -449,6 +471,7 @@ impl VirtualDom {
#[allow(unused)]
pub fn work_with_deadline(&mut self, mut deadline: impl FnMut() -> bool) -> Vec<Mutations> {
let mut committed_mutations = vec![];
self.scopes.template_bump.reset();
while !self.dirty_scopes.is_empty() {
let scopes = &self.scopes;
@@ -524,11 +547,13 @@ impl VirtualDom {
/// ```
pub fn rebuild(&mut self) -> Mutations {
let scope_id = ScopeId(0);
let mut diff_state = DiffState::new(&self.scopes);
let mut diff_state = DiffState::new(&self.scopes);
self.scopes.run_scope(scope_id);
diff_state.element_stack.push(ElementId(0));
diff_state
.element_stack
.push(GlobalNodeId::VNodeId(ElementId(0)));
diff_state.scope_stack.push(scope_id);
let node = self.scopes.fin_head(scope_id);
@@ -625,7 +650,9 @@ impl VirtualDom {
/// ```
pub fn diff_vnodes<'a>(&'a self, old: &'a VNode<'a>, new: &'a VNode<'a>) -> Mutations<'a> {
let mut machine = DiffState::new(&self.scopes);
machine.element_stack.push(ElementId(0));
machine
.element_stack
.push(GlobalNodeId::VNodeId(ElementId(0)));
machine.scope_stack.push(ScopeId(0));
machine.diff_node(old, new);
@@ -648,7 +675,9 @@ impl VirtualDom {
pub fn create_vnodes<'a>(&'a self, nodes: LazyNodes<'a, '_>) -> Mutations<'a> {
let mut machine = DiffState::new(&self.scopes);
machine.scope_stack.push(ScopeId(0));
machine.element_stack.push(ElementId(0));
machine
.element_stack
.push(GlobalNodeId::VNodeId(ElementId(0)));
let node = self.render_vnodes(nodes);
let created = machine.create_node(node);
machine.mutations.append_children(created as u32);
@@ -677,17 +706,32 @@ impl VirtualDom {
let mut create = DiffState::new(&self.scopes);
create.scope_stack.push(ScopeId(0));
create.element_stack.push(ElementId(0));
create
.element_stack
.push(GlobalNodeId::VNodeId(ElementId(0)));
let created = create.create_node(old);
create.mutations.append_children(created as u32);
let mut edit = DiffState::new(&self.scopes);
edit.scope_stack.push(ScopeId(0));
edit.element_stack.push(ElementId(0));
edit.element_stack.push(GlobalNodeId::VNodeId(ElementId(0)));
edit.diff_node(old, new);
(create.mutations, edit.mutations)
}
/// Runs a function with the template associated with a given id.
pub fn with_template<R>(&self, id: &TemplateId, mut f: impl FnMut(&Template) -> R) -> R {
self.scopes
.templates
.borrow()
.get(id)
.map(|inner| {
let borrow = &*inner;
f(&borrow.borrow())
})
.unwrap()
}
}
/*