Merge branch 'upstream-master' into fix-hot-reloading

This commit is contained in:
= committed 2022-12-16 10:07:11 -06:00
commit 14dd568987
92 files changed
+3469 -2468

No files matched your search

+18 -11
View File
@@ -34,14 +34,14 @@ impl ElementRef {
impl VirtualDom {
pub(crate) fn next_element(&mut self, template: &VNode, path: &'static [u8]) -> ElementId {
self.next(template, ElementPath::Deep(path))
self.next_reference(template, ElementPath::Deep(path))
}
pub(crate) fn next_root(&mut self, template: &VNode, path: usize) -> ElementId {
self.next(template, ElementPath::Root(path))
self.next_reference(template, ElementPath::Root(path))
}
fn next(&mut self, template: &VNode, path: ElementPath) -> ElementId {
fn next_reference(&mut self, template: &VNode, path: ElementPath) -> ElementId {
let entry = self.elements.vacant_entry();
let id = entry.key();
@@ -95,22 +95,27 @@ impl VirtualDom {
fn drop_scope_inner(&mut self, node: &VNode) {
node.clear_listeners();
node.dynamic_nodes.iter().for_each(|node| match node {
DynamicNode::Component(c) => self.drop_scope(c.scope.get().unwrap()),
DynamicNode::Component(c) => {
if let Some(f) = c.scope.get() {
self.drop_scope(f)
}
}
DynamicNode::Fragment(nodes) => {
nodes.iter().for_each(|node| self.drop_scope_inner(node))
}
DynamicNode::Placeholder(t) => {
self.try_reclaim(t.get());
self.try_reclaim(t.id.get().unwrap());
}
DynamicNode::Text(t) => {
self.try_reclaim(t.id.get());
self.try_reclaim(t.id.get().unwrap());
}
});
for root in node.root_ids {
let id = root.get();
if id.0 != 0 {
self.try_reclaim(id);
if let Some(id) = root.get() {
if id.0 != 0 {
self.try_reclaim(id);
}
}
}
}
@@ -131,8 +136,10 @@ impl VirtualDom {
node.dynamic_nodes.iter().for_each(|child| match child {
// Only descend if the props are borrowed
DynamicNode::Component(c) if !c.static_props => {
self.ensure_drop_safety(c.scope.get().unwrap());
c.props.set(None);
if let Some(scope) = c.scope.get() {
self.ensure_drop_safety(scope);
}
c.props.take();
}
DynamicNode::Fragment(f) => f
+253 -179
View File
@@ -1,13 +1,15 @@
use std::cell::Cell;
use std::rc::Rc;
use crate::innerlude::{VComponent, VText};
use crate::innerlude::{VComponent, VPlaceholder, VText};
use crate::mutations::Mutation;
use crate::mutations::Mutation::*;
use crate::nodes::VNode;
use crate::nodes::{DynamicNode, TemplateNode};
use crate::virtual_dom::VirtualDom;
use crate::{AttributeValue, ElementId, RenderReturn, ScopeId, SuspenseContext};
use std::cell::Cell;
use std::iter::{Enumerate, Peekable};
use std::rc::Rc;
use std::slice;
use TemplateNode::*;
impl<'b> VirtualDom {
/// Create a new template [`VNode`] and write it to the [`Mutations`] buffer.
@@ -17,187 +19,232 @@ impl<'b> VirtualDom {
self.scope_stack.push(scope);
let out = self.create(template);
self.scope_stack.pop();
out
}
/// Create this template and write its mutations
pub(crate) fn create(&mut self, template: &'b VNode<'b>) -> usize {
pub(crate) fn create(&mut self, node: &'b VNode<'b>) -> usize {
// The best renderers will have templates prehydrated and registered
// Just in case, let's create the template using instructions anyways
if !self.templates.contains_key(&template.template.name) {
self.register_template(template);
if !self.templates.contains_key(&node.template.name) {
self.register_template(node);
}
// we know that this will generate at least one mutation per node
self.mutations.edits.reserve(node.template.roots.len());
// Walk the roots, creating nodes and assigning IDs
// todo: adjust dynamic nodes to be in the order of roots and then leaves (ie BFS)
let mut dynamic_attrs = template.template.attr_paths.iter().enumerate().peekable();
let mut dynamic_nodes = template.template.node_paths.iter().enumerate().peekable();
let mut attrs = node.template.attr_paths.iter().enumerate().peekable();
let mut nodes = node.template.node_paths.iter().enumerate().peekable();
let cur_scope = self.scope_stack.last().copied().unwrap();
node.template
.roots
.iter()
.enumerate()
.map(|(idx, root)| match root {
DynamicText { id } | Dynamic { id } => self.write_dynamic_root(node, *id),
Element { .. } => self.write_element_root(node, idx, &mut attrs, &mut nodes),
Text { .. } => self.write_static_text_root(node, idx),
})
.sum()
}
let mut on_stack = 0;
for (root_idx, root) in template.template.roots.iter().enumerate() {
// We might need to generate an ID for the root node
on_stack += match root {
TemplateNode::DynamicText { id } | TemplateNode::Dynamic { id } => {
match &template.dynamic_nodes[*id] {
// a dynamic text node doesn't replace a template node, instead we create it on the fly
DynamicNode::Text(VText { id: slot, value }) => {
let id = self.next_element(template, template.template.node_paths[*id]);
slot.set(id);
fn write_static_text_root(&mut self, node: &VNode, idx: usize) -> usize {
// Simply just load the template root, no modifications needed
self.load_template_root(node, idx);
// Safety: we promise not to re-alias this text later on after committing it to the mutation
let unbounded_text = unsafe { std::mem::transmute(*value) };
self.mutations.push(CreateTextNode {
value: unbounded_text,
id,
});
// Text producs just one node on the stack
1
}
1
}
fn write_dynamic_root(&mut self, template: &'b VNode<'b>, idx: usize) -> usize {
use DynamicNode::*;
match &template.dynamic_nodes[idx] {
node @ Fragment(_) => self.create_dynamic_node(template, node, idx),
node @ Component { .. } => self.create_dynamic_node(template, node, idx),
Placeholder(VPlaceholder { id }) => {
let id = self.set_slot(template, id, idx);
self.mutations.push(CreatePlaceholder { id });
1
}
Text(VText { id, value }) => {
let id = self.set_slot(template, id, idx);
self.create_static_text(value, id);
1
}
}
}
DynamicNode::Placeholder(slot) => {
let id = self.next_element(template, template.template.node_paths[*id]);
slot.set(id);
self.mutations.push(CreatePlaceholder { id });
1
}
fn create_static_text(&mut self, value: &str, id: ElementId) {
// Safety: we promise not to re-alias this text later on after committing it to the mutation
let unbounded_text: &str = unsafe { std::mem::transmute(value) };
self.mutations.push(CreateTextNode {
value: unbounded_text,
id,
});
}
DynamicNode::Fragment(_) | DynamicNode::Component { .. } => {
self.create_dynamic_node(template, &template.dynamic_nodes[*id], *id)
}
}
/// We write all the descndent data for this element
///
/// Elements can contain other nodes - and those nodes can be dynamic or static
///
/// We want to make sure we write these nodes while on top of the root
fn write_element_root(
&mut self,
template: &'b VNode<'b>,
root_idx: usize,
dynamic_attrs: &mut Peekable<Enumerate<slice::Iter<&'static [u8]>>>,
dynamic_nodes: &mut Peekable<Enumerate<slice::Iter<&'static [u8]>>>,
) -> usize {
// Load the template root and get the ID for the node on the stack
let root_on_stack = self.load_template_root(template, root_idx);
// Write all the attributes below this root
self.write_attrs_on_root(dynamic_attrs, root_idx, root_on_stack, template);
// Load in all of the placeholder or dynamic content under this root too
self.load_placeholders(dynamic_nodes, root_idx, template);
1
}
/// Load all of the placeholder nodes for descendents of this root node
///
/// ```rust, ignore
/// rsx! {
/// div {
/// // This is a placeholder
/// some_value,
///
/// // Load this too
/// "{some_text}"
/// }
/// }
/// ```
fn load_placeholders(
&mut self,
dynamic_nodes: &mut Peekable<Enumerate<slice::Iter<&'static [u8]>>>,
root_idx: usize,
template: &'b VNode<'b>,
) {
let (start, end) = match collect_dyn_node_range(dynamic_nodes, root_idx) {
Some((a, b)) => (a, b),
None => return,
};
for idx in (start..=end).rev() {
let m = self.create_dynamic_node(template, &template.dynamic_nodes[idx], idx);
if m > 0 {
// The path is one shorter because the top node is the root
let path = &template.template.node_paths[idx][1..];
self.mutations.push(ReplacePlaceholder { m, path });
}
}
}
fn write_attrs_on_root(
&mut self,
attrs: &mut Peekable<Enumerate<slice::Iter<&'static [u8]>>>,
root_idx: usize,
root: ElementId,
node: &VNode,
) {
while let Some((mut attr_id, path)) = attrs.next_if(|(_, p)| p[0] == root_idx as u8) {
let id = self.assign_static_node_as_dynamic(path, root, node, attr_id);
loop {
self.write_attribute(&node.dynamic_attrs[attr_id], id);
// Only push the dynamic attributes forward if they match the current path (same element)
match attrs.next_if(|(_, p)| *p == path) {
Some((next_attr_id, _)) => attr_id = next_attr_id,
None => break,
}
}
}
}
TemplateNode::Element { .. } | TemplateNode::Text { .. } => {
let this_id = self.next_root(template, root_idx);
fn write_attribute(&mut self, attribute: &crate::Attribute, id: ElementId) {
// Make sure we set the attribute's associated id
attribute.mounted_element.set(id);
template.root_ids[root_idx].set(this_id);
self.mutations.push(LoadTemplate {
name: template.template.name,
index: root_idx,
id: this_id,
});
// Safety: we promise not to re-alias this text later on after committing it to the mutation
let unbounded_name = unsafe { std::mem::transmute(attribute.name) };
// we're on top of a node that has a dynamic attribute for a descendant
// Set that attribute now before the stack gets in a weird state
while let Some((mut attr_id, path)) =
dynamic_attrs.next_if(|(_, p)| p[0] == root_idx as u8)
{
// if attribute is on a root node, then we've already created the element
// Else, it's deep in the template and we should create a new id for it
let id = match path.len() {
1 => this_id,
_ => {
let id = self
.next_element(template, template.template.attr_paths[attr_id]);
self.mutations.push(Mutation::AssignId {
path: &path[1..],
id,
});
id
}
};
match &attribute.value {
AttributeValue::Text(value) => {
// Safety: we promise not to re-alias this text later on after committing it to the mutation
let unbounded_value = unsafe { std::mem::transmute(*value) };
loop {
let attribute = template.dynamic_attrs.get(attr_id).unwrap();
attribute.mounted_element.set(id);
self.mutations.push(SetAttribute {
name: unbounded_name,
value: unbounded_value,
ns: attribute.namespace,
id,
})
}
AttributeValue::Bool(value) => self.mutations.push(SetBoolAttribute {
name: unbounded_name,
value: *value,
id,
}),
AttributeValue::Listener(_) => {
self.mutations.push(NewEventListener {
// all listeners start with "on"
name: &unbounded_name[2..],
id,
})
}
AttributeValue::Float(_) => todo!(),
AttributeValue::Int(_) => todo!(),
AttributeValue::Any(_) => todo!(),
AttributeValue::None => todo!(),
}
}
// Safety: we promise not to re-alias this text later on after committing it to the mutation
let unbounded_name = unsafe { std::mem::transmute(attribute.name) };
fn load_template_root(&mut self, template: &VNode, root_idx: usize) -> ElementId {
// Get an ID for this root since it's a real root
let this_id = self.next_root(template, root_idx);
template.root_ids[root_idx].set(Some(this_id));
match &attribute.value {
AttributeValue::Text(value) => {
// Safety: we promise not to re-alias this text later on after committing it to the mutation
let unbounded_value = unsafe { std::mem::transmute(*value) };
self.mutations.push(LoadTemplate {
name: template.template.name,
index: root_idx,
id: this_id,
});
self.mutations.push(SetAttribute {
name: unbounded_name,
value: unbounded_value,
ns: attribute.namespace,
id,
})
}
AttributeValue::Bool(value) => {
self.mutations.push(SetBoolAttribute {
name: unbounded_name,
value: *value,
id,
})
}
AttributeValue::Listener(_) => {
self.mutations.push(NewEventListener {
// all listeners start with "on"
name: &unbounded_name[2..],
scope: cur_scope,
id,
})
}
AttributeValue::Float(_) => todo!(),
AttributeValue::Int(_) => todo!(),
AttributeValue::Any(_) => todo!(),
AttributeValue::None => todo!(),
}
this_id
}
// Only push the dynamic attributes forward if they match the current path (same element)
match dynamic_attrs.next_if(|(_, p)| *p == path) {
Some((next_attr_id, _)) => attr_id = next_attr_id,
None => break,
}
}
}
// We're on top of a node that has a dynamic child for a descendant
// Skip any node that's a root
let mut start = None;
let mut end = None;
// Collect all the dynamic nodes below this root
// We assign the start and end of the range of dynamic nodes since they area ordered in terms of tree path
//
// [0]
// [1, 1] <---|
// [1, 1, 1] <---| these are the range of dynamic nodes below root 1
// [1, 1, 2] <---|
// [2]
//
// We collect each range and then create them and replace the placeholder in the template
while let Some((idx, p)) =
dynamic_nodes.next_if(|(_, p)| p[0] == root_idx as u8)
{
if p.len() == 1 {
continue;
}
if start.is_none() {
start = Some(idx);
}
end = Some(idx);
}
//
if let (Some(start), Some(end)) = (start, end) {
for idx in start..=end {
let node = &template.dynamic_nodes[idx];
let m = self.create_dynamic_node(template, node, idx);
if m > 0 {
self.mutations.push(ReplacePlaceholder {
m,
path: &template.template.node_paths[idx][1..],
});
}
}
}
// elements create only one node :-)
1
}
};
/// We have some dynamic attributes attached to a some node
///
/// That node needs to be loaded at runtime, so we need to give it an ID
///
/// If the node in question is on the stack, we just return that ID
///
/// If the node is not on the stack, we create a new ID for it and assign it
fn assign_static_node_as_dynamic(
&mut self,
path: &'static [u8],
this_id: ElementId,
template: &VNode,
attr_id: usize,
) -> ElementId {
if path.len() == 1 {
return this_id;
}
on_stack
// if attribute is on a root node, then we've already created the element
// Else, it's deep in the template and we should create a new id for it
let id = self.next_element(template, template.template.attr_paths[attr_id]);
self.mutations.push(Mutation::AssignId {
path: &path[1..],
id,
});
id
}
/// Insert a new template into the VirtualDom's template registry
@@ -207,17 +254,9 @@ impl<'b> VirtualDom {
.insert(template.template.name, template.template);
// If it's all dynamic nodes, then we don't need to register it
// Quickly run through and see if it's all just dynamic nodes
if template.template.roots.iter().all(|root| {
matches!(
root,
TemplateNode::Dynamic { .. } | TemplateNode::DynamicText { .. }
)
}) {
return;
if !template.template.is_completely_dynamic() {
self.mutations.templates.push(template.template);
}
self.mutations.templates.push(template.template);
}
pub(crate) fn create_dynamic_node(
@@ -245,7 +284,7 @@ impl<'b> VirtualDom {
let new_id = self.next_element(template, template.template.node_paths[idx]);
// Make sure the text node is assigned to the correct element
text.id.set(new_id);
text.id.set(Some(new_id));
// Safety: we promise not to re-alias this text later on after committing it to the mutation
let value = unsafe { std::mem::transmute(text.value) };
@@ -263,7 +302,7 @@ impl<'b> VirtualDom {
pub(crate) fn create_placeholder(
&mut self,
slot: &Cell<ElementId>,
placeholder: &VPlaceholder,
template: &'b VNode<'b>,
idx: usize,
) -> usize {
@@ -271,7 +310,7 @@ impl<'b> VirtualDom {
let id = self.next_element(template, template.template.node_paths[idx]);
// Make sure the text node is assigned to the correct element
slot.set(id);
placeholder.id.set(Some(id));
// Assign the ID to the existing node in the template
self.mutations.push(AssignId {
@@ -284,7 +323,7 @@ impl<'b> VirtualDom {
}
pub(crate) fn create_fragment(&mut self, nodes: &'b [VNode<'b>]) -> usize {
nodes.iter().fold(0, |acc, child| acc + self.create(child))
nodes.iter().map(|child| self.create(child)).sum()
}
pub(super) fn create_component_node(
@@ -293,15 +332,17 @@ impl<'b> VirtualDom {
component: &'b VComponent<'b>,
idx: usize,
) -> usize {
let props = component
.props
.replace(None)
.expect("Props to always exist when a component is being created");
let scope = match component.props.take() {
Some(props) => {
let unbounded_props = unsafe { std::mem::transmute(props) };
let scope = self.new_scope(unbounded_props, component.name);
scope.id
}
let unbounded_props = unsafe { std::mem::transmute(props) };
// Component is coming back, it probably still exists, right?
None => component.scope.get().unwrap(),
};
let scope = self.new_scope(unbounded_props, component.name);
let scope = scope.id;
component.scope.set(Some(scope));
let return_nodes = unsafe { self.run_scope(scope).extend_lifetime_ref() };
@@ -391,4 +432,37 @@ impl<'b> VirtualDom {
0
}
fn set_slot(
&mut self,
template: &'b VNode<'b>,
slot: &'b Cell<Option<ElementId>>,
id: usize,
) -> ElementId {
let id = self.next_element(template, template.template.node_paths[id]);
slot.set(Some(id));
id
}
}
fn collect_dyn_node_range(
dynamic_nodes: &mut Peekable<Enumerate<slice::Iter<&[u8]>>>,
root_idx: usize,
) -> Option<(usize, usize)> {
let start = match dynamic_nodes.peek() {
Some((idx, p)) if p[0] == root_idx as u8 => *idx,
_ => return None,
};
let mut end = start;
while let Some((idx, p)) = dynamic_nodes.next_if(|(_, p)| p[0] == root_idx as u8) {
if p.len() == 1 {
continue;
}
end = idx;
}
Some((start, end))
}
+189 -123
View File
@@ -1,17 +1,15 @@
use std::cell::Cell;
use crate::{
arena::ElementId,
innerlude::{DirtyScope, VComponent, VText},
innerlude::{DirtyScope, VComponent, VPlaceholder, VText},
mutations::Mutation,
nodes::RenderReturn,
nodes::{DynamicNode, VNode},
scopes::ScopeId,
virtual_dom::VirtualDom,
AttributeValue, TemplateNode,
Attribute, AttributeValue, TemplateNode,
};
use fxhash::{FxHashMap, FxHashSet};
use rustc_hash::{FxHashMap, FxHashSet};
use DynamicNode::*;
impl<'b> VirtualDom {
@@ -56,87 +54,101 @@ impl<'b> VirtualDom {
fn diff_err_to_ok(&mut self, _e: &anyhow::Error, _l: &'b VNode<'b>) {}
fn diff_node(&mut self, left_template: &'b VNode<'b>, right_template: &'b VNode<'b>) {
if left_template.template.name != right_template.template.name {
// If the templates are the same, we don't need to do anything, nor do we want to
if templates_are_the_same(left_template, right_template) {
return;
}
// If the templates are different by name, we need to replace the entire template
if templates_are_different(left_template, right_template) {
return self.light_diff_templates(left_template, right_template);
}
for (left_attr, right_attr) in left_template
// If the templates are the same, we can diff the attributes and children
// Start with the attributes
left_template
.dynamic_attrs
.iter()
.zip(right_template.dynamic_attrs.iter())
{
// Move over the ID from the old to the new
right_attr
.mounted_element
.set(left_attr.mounted_element.get());
.for_each(|(left_attr, right_attr)| {
// Move over the ID from the old to the new
right_attr
.mounted_element
.set(left_attr.mounted_element.get());
// We want to make sure anything listener that gets pulled is valid
if let AttributeValue::Listener(_) = right_attr.value {
self.update_template(left_attr.mounted_element.get(), right_template);
}
if left_attr.value != right_attr.value || left_attr.volatile {
// todo: add more types of attribute values
match right_attr.value {
AttributeValue::Text(text) => {
let name = unsafe { std::mem::transmute(left_attr.name) };
let value = unsafe { std::mem::transmute(text) };
self.mutations.push(Mutation::SetAttribute {
id: left_attr.mounted_element.get(),
ns: right_attr.namespace,
name,
value,
});
}
// todo: more types of attribute values
_ => todo!("other attribute types"),
// We want to make sure anything listener that gets pulled is valid
if let AttributeValue::Listener(_) = right_attr.value {
self.update_template(left_attr.mounted_element.get(), right_template);
}
}
}
for (idx, (left_node, right_node)) in left_template
// If the attributes are different (or volatile), we need to update them
if left_attr.value != right_attr.value || left_attr.volatile {
self.update_attribute(right_attr, left_attr);
}
});
// Now diff the dynamic nodes
left_template
.dynamic_nodes
.iter()
.zip(right_template.dynamic_nodes.iter())
.enumerate()
{
match (left_node, right_node) {
(Text(left), Text(right)) => self.diff_vtext(left, right),
(Fragment(left), Fragment(right)) => self.diff_non_empty_fragment(left, right),
(Placeholder(left), Placeholder(right)) => {
right.set(left.get());
}
(Component(left), Component(right)) => {
self.diff_vcomponent(left, right, right_template, idx)
}
(Placeholder(left), Fragment(right)) => {
self.replace_placeholder_with_nodes(left, right)
}
(Fragment(left), Placeholder(right)) => {
self.replace_nodes_with_placeholder(left, right)
}
_ => todo!(),
};
}
.for_each(|(idx, (left_node, right_node))| {
self.diff_dynamic_node(left_node, right_node, right_template, idx);
});
// Make sure the roots get transferred over
for (left, right) in left_template
// Make sure the roots get transferred over while we're here
left_template
.root_ids
.iter()
.zip(right_template.root_ids.iter())
{
right.set(left.get());
.for_each(|(left, right)| right.set(left.get()));
}
fn diff_dynamic_node(
&mut self,
left_node: &'b DynamicNode<'b>,
right_node: &'b DynamicNode<'b>,
node: &'b VNode<'b>,
idx: usize,
) {
match (left_node, right_node) {
(Text(left), Text(right)) => self.diff_vtext(left, right, node),
(Fragment(left), Fragment(right)) => self.diff_non_empty_fragment(left, right),
(Placeholder(left), Placeholder(right)) => right.id.set(left.id.get()),
(Component(left), Component(right)) => self.diff_vcomponent(left, right, node, idx),
(Placeholder(left), Fragment(right)) => self.replace_placeholder(left, right),
(Fragment(left), Placeholder(right)) => self.node_to_placeholder(left, right),
_ => todo!("This is an usual custom case for dynamic nodes. We don't know how to handle it yet."),
};
}
fn update_attribute(&mut self, right_attr: &Attribute, left_attr: &Attribute) {
// todo: add more types of attribute values
match right_attr.value {
AttributeValue::Text(text) => {
let name = unsafe { std::mem::transmute(left_attr.name) };
let value = unsafe { std::mem::transmute(text) };
self.mutations.push(Mutation::SetAttribute {
id: left_attr.mounted_element.get(),
ns: right_attr.namespace,
name,
value,
});
}
// todo: more types of attribute values
_ => todo!("other attribute types"),
}
}
fn replace_placeholder_with_nodes(&mut self, l: &'b Cell<ElementId>, r: &'b [VNode<'b>]) {
fn replace_placeholder(&mut self, l: &'b VPlaceholder, r: &'b [VNode<'b>]) {
let m = self.create_children(r);
let id = l.get();
let id = l.id.get().unwrap();
self.mutations.push(Mutation::ReplaceWith { id, m });
self.reclaim(id);
}
fn replace_nodes_with_placeholder(&mut self, l: &'b [VNode<'b>], r: &'b Cell<ElementId>) {
fn node_to_placeholder(&mut self, l: &'b [VNode<'b>], r: &'b VPlaceholder) {
// Remove the old nodes, except for one
self.remove_nodes(&l[1..]);
@@ -145,7 +157,7 @@ impl<'b> VirtualDom {
// Create the placeholder first, ensuring we get a dedicated ID for the placeholder
let placeholder = self.next_element(&l[0], &[]);
r.set(placeholder);
r.id.set(Some(placeholder));
self.mutations
.push(Mutation::CreatePlaceholder { id: placeholder });
@@ -162,6 +174,10 @@ impl<'b> VirtualDom {
right_template: &'b VNode<'b>,
idx: usize,
) {
if std::ptr::eq(left, right) {
return;
}
// Replace components that have different render fns
if left.render_fn != right.render_fn {
let created = self.create_component_node(right_template, right, idx);
@@ -181,12 +197,22 @@ impl<'b> VirtualDom {
}
// Make sure the new vcomponent has the right scopeid associated to it
let scope_id = left.scope.get().unwrap();
let Some(scope_id) = left.scope.get() else {
return;
};
// let scope_id = left.scope.get().unwrap_or_else(|| {
// panic!(
// "A component should always have a scope associated to it. {:?}\n {:#?}",
// right.name,
// std::backtrace::Backtrace::force_capture()
// )
// });
right.scope.set(Some(scope_id));
// copy out the box for both
let old = self.scopes[scope_id.0].props.as_ref();
let new = right.props.replace(None).unwrap();
let new = right.props.take().unwrap();
// If the props are static, then we try to memoize by setting the new with the old
// The target scopestate still has the reference to the old props, so there's no need to update anything
@@ -201,6 +227,11 @@ impl<'b> VirtualDom {
// Now run the component and diff it
self.run_scope(scope_id);
self.diff_scope(scope_id);
self.dirty_scopes.remove(&DirtyScope {
height: self.scopes[scope_id.0].height,
id: scope_id,
});
}
/// Lightly diff the two templates, checking only their roots.
@@ -254,10 +285,13 @@ impl<'b> VirtualDom {
///
/// This just moves the ID of the old node over to the new node, and then sets the text of the new node if it's
/// different.
fn diff_vtext(&mut self, left: &'b VText<'b>, right: &'b VText<'b>) {
let id = left.id.get();
fn diff_vtext(&mut self, left: &'b VText<'b>, right: &'b VText<'b>, node: &'b VNode<'b>) {
let id = left
.id
.get()
.unwrap_or_else(|| self.next_element(node, &[0]));
right.id.set(id);
right.id.set(Some(id));
if left.value != right.value {
let value = unsafe { std::mem::transmute(right.value) };
self.mutations.push(Mutation::SetText { id, value });
@@ -269,9 +303,9 @@ impl<'b> VirtualDom {
/// All IDs will be garbage collected
fn replace_inner(&mut self, node: &'b VNode<'b>) -> ElementId {
let id = match node.dynamic_root(0) {
None => node.root_ids[0].get(),
Some(Text(t)) => t.id.get(),
Some(Placeholder(e)) => e.get(),
None => node.root_ids[0].get().unwrap(),
Some(Text(t)) => t.id.get().unwrap(),
Some(Placeholder(e)) => e.id.get().unwrap(),
Some(Fragment(nodes)) => {
let id = self.replace_inner(&nodes[0]);
self.remove_nodes(&nodes[1..]);
@@ -309,14 +343,23 @@ impl<'b> VirtualDom {
match dyn_node {
Component(comp) => {
let scope = comp.scope.get().unwrap();
match unsafe { self.scopes[scope.0].root_node().extend_lifetime_ref() } {
RenderReturn::Sync(Ok(t)) => self.clean_up_node(t),
_ => todo!("cannot handle nonstandard nodes"),
};
if let Some(scope) = comp.scope.take() {
match unsafe { self.scopes[scope.0].root_node().extend_lifetime_ref() } {
RenderReturn::Sync(Ok(t)) => self.clean_up_node(t),
_ => todo!("cannot handle nonstandard nodes"),
};
}
}
Text(t) => {
if let Some(id) = t.id.take() {
self.reclaim(id)
}
}
Placeholder(t) => {
if let Some(id) = t.id.take() {
self.reclaim(id)
}
}
Text(t) => self.reclaim(t.id.get()),
Placeholder(t) => self.reclaim(t.get()),
Fragment(nodes) => nodes.iter().for_each(|node| self.clean_up_node(node)),
};
}
@@ -344,25 +387,25 @@ impl<'b> VirtualDom {
fn remove_root_node(&mut self, node: &'b VNode<'b>, idx: usize) {
match node.dynamic_root(idx) {
Some(Text(i)) => {
let id = i.id.get();
let id = i.id.take().unwrap();
self.mutations.push(Mutation::Remove { id });
self.reclaim(id);
}
Some(Placeholder(e)) => {
let id = e.get();
let id = e.id.take().unwrap();
self.mutations.push(Mutation::Remove { id });
self.reclaim(id);
}
Some(Fragment(nodes)) => self.remove_nodes(nodes),
Some(Component(comp)) => {
let scope = comp.scope.get().unwrap();
let scope = comp.scope.take().unwrap();
match unsafe { self.scopes[scope.0].root_node().extend_lifetime_ref() } {
RenderReturn::Sync(Ok(t)) => self.remove_node(t),
_ => todo!("cannot handle nonstandard nodes"),
};
}
None => {
let id = node.root_ids[idx].get();
let id = node.root_ids[idx].get().unwrap();
self.mutations.push(Mutation::Remove { id });
self.reclaim(id);
}
@@ -432,7 +475,7 @@ impl<'b> VirtualDom {
// The stack is empty upon entry.
fn diff_keyed_children(&mut self, old: &'b [VNode<'b>], new: &'b [VNode<'b>]) {
if cfg!(debug_assertions) {
let mut keys = fxhash::FxHashSet::default();
let mut keys = rustc_hash::FxHashSet::default();
let mut assert_unique_keys = |children: &'b [VNode<'b>]| {
keys.clear();
for child in children {
@@ -748,12 +791,16 @@ impl<'b> VirtualDom {
fn remove_node(&mut self, node: &'b VNode<'b>) {
for (idx, _) in node.template.roots.iter().enumerate() {
let id = match node.dynamic_root(idx) {
Some(Text(t)) => t.id.get(),
Some(Placeholder(t)) => t.get(),
Some(Text(t)) => t.id.take(),
Some(Placeholder(t)) => t.id.take(),
Some(Fragment(t)) => return self.remove_nodes(t),
Some(Component(comp)) => return self.remove_component(comp.scope.get().unwrap()),
Some(Component(comp)) => {
comp.scope.set(None);
return self.remove_component(comp.scope.get().unwrap());
}
None => node.root_ids[idx].get(),
};
}
.unwrap();
self.mutations.push(Mutation::Remove { id })
}
@@ -761,7 +808,7 @@ impl<'b> VirtualDom {
self.clean_up_node(node);
for root in node.root_ids {
let id = root.get();
let id = root.get().unwrap();
if id.0 != 0 {
self.reclaim(id);
}
@@ -784,41 +831,45 @@ impl<'b> VirtualDom {
/// Push all the real nodes on the stack
fn push_all_real_nodes(&mut self, node: &'b VNode<'b>) -> usize {
let mut onstack = 0;
for (idx, _) in node.template.roots.iter().enumerate() {
match node.dynamic_root(idx) {
Some(Text(t)) => {
self.mutations.push(Mutation::PushRoot { id: t.id.get() });
onstack += 1;
}
Some(Placeholder(t)) => {
self.mutations.push(Mutation::PushRoot { id: t.get() });
onstack += 1;
}
Some(Fragment(nodes)) => {
for node in *nodes {
onstack += self.push_all_real_nodes(node);
node.template
.roots
.iter()
.enumerate()
.map(|(idx, _)| {
match node.dynamic_root(idx) {
Some(Text(t)) => {
self.mutations.push(Mutation::PushRoot {
id: t.id.get().unwrap(),
});
1
}
}
Some(Component(comp)) => {
let scope = comp.scope.get().unwrap();
onstack +=
Some(Placeholder(t)) => {
self.mutations.push(Mutation::PushRoot {
id: t.id.get().unwrap(),
});
1
}
Some(Fragment(nodes)) => nodes
.iter()
.map(|node| self.push_all_real_nodes(node))
.count(),
Some(Component(comp)) => {
let scope = comp.scope.get().unwrap();
match unsafe { self.scopes[scope.0].root_node().extend_lifetime_ref() } {
RenderReturn::Sync(Ok(node)) => self.push_all_real_nodes(node),
_ => todo!(),
}
}
None => {
self.mutations.push(Mutation::PushRoot {
id: node.root_ids[idx].get(),
});
onstack += 1;
}
};
}
onstack
}
None => {
self.mutations.push(Mutation::PushRoot {
id: node.root_ids[idx].get().unwrap(),
});
1
}
};
})
.count()
}
fn create_children(&mut self, nodes: &'b [VNode<'b>]) -> usize {
@@ -839,10 +890,10 @@ impl<'b> VirtualDom {
fn find_first_element(&self, node: &'b VNode<'b>) -> ElementId {
match node.dynamic_root(0) {
None => node.root_ids[0].get(),
Some(Text(t)) => t.id.get(),
None => node.root_ids[0].get().unwrap(),
Some(Text(t)) => t.id.get().unwrap(),
Some(Fragment(t)) => self.find_first_element(&t[0]),
Some(Placeholder(t)) => t.get(),
Some(Placeholder(t)) => t.id.get().unwrap(),
Some(Component(comp)) => {
let scope = comp.scope.get().unwrap();
match unsafe { self.scopes[scope.0].root_node().extend_lifetime_ref() } {
@@ -855,10 +906,10 @@ impl<'b> VirtualDom {
fn find_last_element(&self, node: &'b VNode<'b>) -> ElementId {
match node.dynamic_root(node.template.roots.len() - 1) {
None => node.root_ids.last().unwrap().get(),
Some(Text(t)) => t.id.get(),
None => node.root_ids.last().unwrap().get().unwrap(),
Some(Text(t)) => t.id.get().unwrap(),
Some(Fragment(t)) => self.find_last_element(t.last().unwrap()),
Some(Placeholder(t)) => t.get(),
Some(Placeholder(t)) => t.id.get().unwrap(),
Some(Component(comp)) => {
let scope = comp.scope.get().unwrap();
match unsafe { self.scopes[scope.0].root_node().extend_lifetime_ref() } {
@@ -892,6 +943,21 @@ impl<'b> VirtualDom {
}
}
/// Are the templates the same?
///
/// We need to check for the obvious case, and the non-obvious case where the template as cloned
///
/// We use the pointer of the dynamic_node list in this case
fn templates_are_the_same<'b>(left_template: &'b VNode<'b>, right_template: &'b VNode<'b>) -> bool {
std::ptr::eq(left_template, right_template)
|| std::ptr::eq(left_template.dynamic_nodes, right_template.dynamic_nodes)
}
fn templates_are_different(left_template: &VNode, right_template: &VNode) -> bool {
!std::ptr::eq(left_template.template.name, right_template.template.name)
&& left_template.template.name != right_template.template.name
}
fn matching_components<'a>(
left: &'a VNode<'a>,
right: &'a VNode<'a>,
+9 -7
View File
@@ -1,19 +1,21 @@
use std::hash::Hash;
use crate::ScopeId;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, Eq, PartialOrd, Ord)]
pub struct DirtyScope {
pub height: u32,
pub id: ScopeId,
}
impl PartialOrd for DirtyScope {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.height.cmp(&other.height))
impl PartialEq for DirtyScope {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl Ord for DirtyScope {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.height.cmp(&other.height)
impl Hash for DirtyScope {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
+9 -199
View File
@@ -11,8 +11,9 @@
//! The logic for this was borrowed from <https://docs.rs/stack_dst/0.6.1/stack_dst/>. Unfortunately, this crate does not
//! support non-static closures, so we've implemented the core logic of `ValueA` in this module.
use smallbox::{smallbox, space::S16, SmallBox};
use crate::{innerlude::VNode, ScopeState};
use std::mem;
/// A concrete type provider for closures that build [`VNode`] structures.
///
@@ -24,14 +25,7 @@ use std::mem;
/// LazyNodes::new(|f| f.element("div", [], [], [] None))
/// ```
pub struct LazyNodes<'a, 'b> {
inner: StackNodeStorage<'a, 'b>,
}
type StackHeapSize = [usize; 16];
enum StackNodeStorage<'a, 'b> {
Stack(LazyStack),
Heap(Box<dyn FnMut(Option<&'a ScopeState>) -> Option<VNode<'a>> + 'b>),
inner: SmallBox<dyn FnMut(&'a ScopeState) -> VNode<'a> + 'b, S16>,
}
impl<'a, 'b> LazyNodes<'a, 'b> {
@@ -44,114 +38,11 @@ impl<'a, 'b> LazyNodes<'a, 'b> {
// there's no way to call FnOnce without a box, so we need to store it in a slot and use static dispatch
let mut slot = Some(val);
let val = move |fac: Option<&'a ScopeState>| {
fac.map(
slot.take()
.expect("LazyNodes closure to be called only once"),
)
};
// miri does not know how to work with mucking directly into bytes
// just use a heap allocated type when miri is running
if cfg!(miri) {
Self {
inner: StackNodeStorage::Heap(Box::new(val)),
}
} else {
unsafe { LazyNodes::new_inner(val) }
}
}
/// Create a new [`LazyNodes`] closure, but force it onto the heap.
pub fn new_boxed<F>(inner: F) -> Self
where
F: FnOnce(&'a ScopeState) -> VNode<'a> + 'b,
{
// there's no way to call FnOnce without a box, so we need to store it in a slot and use static dispatch
let mut slot = Some(inner);
Self {
inner: StackNodeStorage::Heap(Box::new(move |fac: Option<&'a ScopeState>| {
fac.map(
slot.take()
.expect("LazyNodes closure to be called only once"),
)
})),
}
}
unsafe fn new_inner<F>(val: F) -> Self
where
F: FnMut(Option<&'a ScopeState>) -> Option<VNode<'a>> + 'b,
{
let mut ptr: *const _ = &val as &dyn FnMut(Option<&'a ScopeState>) -> Option<VNode<'a>>;
assert_eq!(
ptr as *const u8, &val as *const _ as *const u8,
"MISUSE: Closure returned different pointer"
);
assert_eq!(
std::mem::size_of_val(&*ptr),
std::mem::size_of::<F>(),
"MISUSE: Closure returned a subset pointer"
);
let words = ptr_as_slice(&mut ptr);
assert!(
words[0] == &val as *const _ as usize,
"BUG: Pointer layout is not (data_ptr, info...)"
);
// - Ensure that Self is aligned same as data requires
assert!(
std::mem::align_of::<F>() <= std::mem::align_of::<Self>(),
"TODO: Enforce alignment >{} (requires {})",
std::mem::align_of::<Self>(),
std::mem::align_of::<F>()
);
let info = &words[1..];
let data = words[0] as *mut ();
let size = mem::size_of::<F>();
let stored_size = info.len() * mem::size_of::<usize>() + size;
let max_size = mem::size_of::<StackHeapSize>();
if stored_size > max_size {
Self {
inner: StackNodeStorage::Heap(Box::new(val)),
}
} else {
let mut buf: StackHeapSize = StackHeapSize::default();
assert!(info.len() + round_to_words(size) <= buf.as_ref().len());
// Place pointer information at the end of the region
// - Allows the data to be at the start for alignment purposes
{
let info_ofs = buf.as_ref().len() - info.len();
let info_dst = &mut buf.as_mut()[info_ofs..];
for (d, v) in Iterator::zip(info_dst.iter_mut(), info.iter()) {
*d = *v;
}
}
let src_ptr = data as *const u8;
let dataptr = buf.as_mut_ptr().cast::<u8>();
for i in 0..size {
*dataptr.add(i) = *src_ptr.add(i);
}
std::mem::forget(val);
Self {
inner: StackNodeStorage::Stack(LazyStack {
_align: [],
buf,
dropped: false,
}),
}
inner: smallbox!(move |f| {
let val = slot.take().expect("cannot call LazyNodes twice");
val(f)
}),
}
}
@@ -163,88 +54,7 @@ impl<'a, 'b> LazyNodes<'a, 'b> {
/// let node = f.call(cac);
/// ```
#[must_use]
pub fn call(self, f: &'a ScopeState) -> VNode<'a> {
match self.inner {
StackNodeStorage::Heap(mut lazy) => {
lazy(Some(f)).expect("Closure should not be called twice")
}
StackNodeStorage::Stack(mut stack) => stack.call(f),
}
pub fn call(mut self, f: &'a ScopeState) -> VNode<'a> {
(self.inner)(f)
}
}
struct LazyStack {
_align: [u64; 0],
buf: StackHeapSize,
dropped: bool,
}
impl LazyStack {
fn call<'a>(&mut self, f: &'a ScopeState) -> VNode<'a> {
let LazyStack { buf, .. } = self;
let data = buf.as_ref();
let info_size =
mem::size_of::<*mut dyn FnMut(Option<&'a ScopeState>) -> Option<VNode<'a>>>()
/ mem::size_of::<usize>()
- 1;
let info_ofs = data.len() - info_size;
let g: *mut dyn FnMut(Option<&'a ScopeState>) -> Option<VNode<'a>> =
unsafe { make_fat_ptr(data[..].as_ptr() as usize, &data[info_ofs..]) };
self.dropped = true;
let clos = unsafe { &mut *g };
clos(Some(f)).unwrap()
}
}
impl Drop for LazyStack {
fn drop(&mut self) {
if !self.dropped {
let LazyStack { buf, .. } = self;
let data = buf.as_ref();
let info_size =
mem::size_of::<*mut dyn FnMut(Option<&ScopeState>) -> Option<VNode<'_>>>()
/ mem::size_of::<usize>()
- 1;
let info_ofs = data.len() - info_size;
let g: *mut dyn FnMut(Option<&ScopeState>) -> Option<VNode<'_>> =
unsafe { make_fat_ptr(data[..].as_ptr() as usize, &data[info_ofs..]) };
self.dropped = true;
let clos = unsafe { &mut *g };
clos(None);
}
}
}
/// Obtain mutable access to a pointer's words
fn ptr_as_slice<T>(ptr: &mut T) -> &mut [usize] {
assert!(mem::size_of::<T>() % mem::size_of::<usize>() == 0);
let words = mem::size_of::<T>() / mem::size_of::<usize>();
// SAFE: Points to valid memory (a raw pointer)
unsafe { core::slice::from_raw_parts_mut(ptr as *mut _ as *mut usize, words) }
}
/// Re-construct a fat pointer
unsafe fn make_fat_ptr<T: ?Sized>(data_ptr: usize, meta_vals: &[usize]) -> *mut T {
let mut rv = mem::MaybeUninit::<*mut T>::uninit();
{
let s = ptr_as_slice(&mut rv);
s[0] = data_ptr;
s[1..].copy_from_slice(meta_vals);
}
let rv = rv.assume_init();
assert_eq!(rv as *const (), data_ptr as *const ());
rv
}
fn round_to_words(len: usize) -> usize {
(len + mem::size_of::<usize>() - 1) / mem::size_of::<usize>()
}
+3 -3
View File
@@ -81,9 +81,9 @@ pub use crate::innerlude::{
/// This includes types like [`Scope`], [`Element`], and [`Component`].
pub mod prelude {
pub use crate::innerlude::{
fc_to_builder, Element, Event, EventHandler, Fragment, LazyNodes, Properties, Scope,
ScopeId, ScopeState, Scoped, TaskId, Template, TemplateAttribute, TemplateNode, VNode,
VirtualDom,
fc_to_builder, Component, Element, Event, EventHandler, Fragment, LazyNodes, Properties,
Scope, ScopeId, ScopeState, Scoped, TaskId, Template, TemplateAttribute, TemplateNode,
VNode, VirtualDom,
};
}
+1 -4
View File
@@ -1,4 +1,4 @@
use fxhash::FxHashSet;
use rustc_hash::FxHashSet;
use crate::{arena::ElementId, ScopeId, Template};
@@ -230,9 +230,6 @@ pub enum Mutation<'a> {
/// The name of the event to listen for.
name: &'a str,
/// The ID of the node to attach the listener to.
scope: ScopeId,
/// The ID of the node to attach the listener to.
id: ElementId,
},
+29 -4
View File
@@ -46,7 +46,7 @@ pub struct VNode<'a> {
/// The IDs for the roots of this template - to be used when moving the template around and removing it from
/// the actual Dom
pub root_ids: &'a [Cell<ElementId>],
pub root_ids: &'a [Cell<Option<ElementId>>],
/// The dynamic parts of the template
pub dynamic_nodes: &'a [DynamicNode<'a>],
@@ -145,6 +145,18 @@ where
Ok(&*Box::leak(deserialized))
}
impl<'a> Template<'a> {
/// Is this template worth caching at all, since it's completely runtime?
///
/// There's no point in saving templates that are completely dynamic, since they'll be recreated every time anyway.
pub fn is_completely_dynamic(&self) -> bool {
use TemplateNode::*;
self.roots
.iter()
.all(|root| matches!(root, Dynamic { .. } | DynamicText { .. }))
}
}
/// A statically known node in a layout.
///
/// This can be created at compile time, saving the VirtualDom time when diffing the tree
@@ -224,7 +236,7 @@ pub enum DynamicNode<'a> {
/// Used by suspense when a node isn't ready and by fragments that don't render anything
///
/// In code, this is just an ElementId whose initial value is set to 0 upon creation
Placeholder(Cell<ElementId>),
Placeholder(VPlaceholder),
/// A list of VNodes.
///
@@ -259,7 +271,7 @@ pub struct VComponent<'a> {
/// It is possible that components get folded at comppile time, so these shouldn't be really used as a key
pub render_fn: *const (),
pub(crate) props: Cell<Option<Box<dyn AnyProps<'a> + 'a>>>,
pub(crate) props: RefCell<Option<Box<dyn AnyProps<'a> + 'a>>>,
}
impl<'a> std::fmt::Debug for VComponent<'a> {
@@ -279,7 +291,14 @@ pub struct VText<'a> {
pub value: &'a str,
/// The ID of this node in the real DOM
pub id: Cell<ElementId>,
pub id: Cell<Option<ElementId>>,
}
/// A placeholder node, used by suspense and fragments
#[derive(Debug, Default)]
pub struct VPlaceholder {
/// The ID of this node in the real DOM
pub id: Cell<Option<ElementId>>,
}
/// An attribute of the TemplateNode, created at compile time
@@ -464,6 +483,12 @@ impl<'a> IntoDynNode<'a> for VNode<'a> {
}
}
impl<'a> IntoDynNode<'a> for DynamicNode<'a> {
fn into_vnode(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
self
}
}
// An element that's an error is currently lost into the ether
impl<'a> IntoDynNode<'a> for Element<'a> {
fn into_vnode(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
+13 -6
View File
@@ -8,6 +8,7 @@ use crate::{
scopes::{ScopeId, ScopeState},
virtual_dom::VirtualDom,
};
use bumpalo::Bump;
use futures_util::FutureExt;
use std::{
mem,
@@ -34,8 +35,8 @@ impl VirtualDom {
props: Some(props),
name,
placeholder: Default::default(),
node_arena_1: BumpFrame::new(50),
node_arena_2: BumpFrame::new(50),
node_arena_1: BumpFrame::new(0),
node_arena_2: BumpFrame::new(0),
spawned_tasks: Default::default(),
render_cnt: Default::default(),
hook_arena: Default::default(),
@@ -62,7 +63,13 @@ impl VirtualDom {
let mut new_nodes = unsafe {
let scope = self.scopes[scope_id.0].as_mut();
scope.previous_frame_mut().bump.reset();
// if this frame hasn't been intialized yet, we can guess the size of the next frame to be more efficient
if scope.previous_frame().bump.allocated_bytes() == 0 {
scope.previous_frame_mut().bump =
Bump::with_capacity(scope.current_frame().bump.allocated_bytes());
} else {
scope.previous_frame_mut().bump.reset();
}
// Make sure to reset the hook counter so we give out hooks in the right order
scope.hook_idx.set(0);
@@ -128,8 +135,8 @@ impl VirtualDom {
let frame = scope.previous_frame();
// set the new head of the bump frame
let alloced = &*frame.bump.alloc(new_nodes);
frame.node.set(alloced);
let allocated = &*frame.bump.alloc(new_nodes);
frame.node.set(allocated);
// And move the render generation forward by one
scope.render_cnt.set(scope.render_cnt.get() + 1);
@@ -141,6 +148,6 @@ impl VirtualDom {
});
// rebind the lifetime now that its stored internally
unsafe { mem::transmute(alloced) }
unsafe { mem::transmute(allocated) }
}
}
+7 -5
View File
@@ -10,10 +10,10 @@ use crate::{
Attribute, AttributeValue, Element, Event, Properties, TaskId,
};
use bumpalo::{boxed::Box as BumpBox, Bump};
use rustc_hash::{FxHashMap, FxHashSet};
use std::{
any::{Any, TypeId},
cell::{Cell, RefCell},
collections::{HashMap, HashSet},
fmt::Arguments,
future::Future,
rc::Rc,
@@ -82,10 +82,10 @@ pub struct ScopeState {
pub(crate) hook_list: RefCell<Vec<*mut dyn Any>>,
pub(crate) hook_idx: Cell<usize>,
pub(crate) shared_contexts: RefCell<HashMap<TypeId, Box<dyn Any>>>,
pub(crate) shared_contexts: RefCell<FxHashMap<TypeId, Box<dyn Any>>>,
pub(crate) tasks: Rc<Scheduler>,
pub(crate) spawned_tasks: HashSet<TaskId>,
pub(crate) spawned_tasks: FxHashSet<TaskId>,
pub(crate) props: Option<Box<dyn AnyProps<'static>>>,
pub(crate) placeholder: Cell<Option<ElementId>>,
@@ -237,7 +237,9 @@ impl<'src> ScopeState {
/// This method should be used when you want to schedule an update for a component
pub fn schedule_update_any(&self) -> Arc<dyn Fn(ScopeId) + Send + Sync> {
let chan = self.tasks.sender.clone();
Arc::new(move |id| drop(chan.unbounded_send(SchedulerMsg::Immediate(id))))
Arc::new(move |id| {
chan.unbounded_send(SchedulerMsg::Immediate(id)).unwrap();
})
}
/// Mark this scope as dirty, and schedule a render for it.
@@ -448,7 +450,7 @@ impl<'src> ScopeState {
name: fn_name,
render_fn: component as *const (),
static_props: P::IS_STATIC,
props: Cell::new(Some(extended)),
props: RefCell::new(Some(extended)),
scope: Cell::new(None),
})
}
+5 -9
View File
@@ -14,15 +14,9 @@ use crate::{
AttributeValue, Element, Event, Scope, SuspenseContext,
};
use futures_util::{pin_mut, StreamExt};
use rustc_hash::FxHashMap;
use slab::Slab;
use std::{
any::Any,
borrow::BorrowMut,
cell::Cell,
collections::{BTreeSet, HashMap},
future::Future,
rc::Rc,
};
use std::{any::Any, borrow::BorrowMut, cell::Cell, collections::BTreeSet, future::Future, rc::Rc};
/// A virtual node system that progresses user events and diffs UI trees.
///
@@ -148,7 +142,7 @@ use std::{
/// }
/// ```
pub struct VirtualDom {
pub(crate) templates: HashMap<TemplateId, Template<'static>>,
pub(crate) templates: FxHashMap<TemplateId, Template<'static>>,
pub(crate) scopes: Slab<Box<ScopeState>>,
pub(crate) dirty_scopes: BTreeSet<DirtyScope>,
pub(crate) scheduler: Rc<Scheduler>,
@@ -542,6 +536,8 @@ impl VirtualDom {
pub async fn render_with_deadline(&mut self, deadline: impl Future<Output = ()>) -> Mutations {
pin_mut!(deadline);
self.process_events();
loop {
// first, unload any complete suspense trees
for finished_fiber in self.finished_fibers.drain(..) {