get cargo check --all --examples --tests working!

This commit is contained in:
Jonathan Kelley committed 2024-01-19 15:01:01 -08:00
1 parent 83bce6ce97
commit 337c04557b
18 files changed
+109 -508

No files matched your search

@@ -0,0 +1,237 @@
use dioxus::prelude::*;
use dioxus_native_core::prelude::*;
use dioxus_native_core_macro::partial_derive_state;
use shipyard::Component;
macro_rules! dep {
( child( $name:ty, $dep:ty ) ) => {
#[partial_derive_state]
impl State for $name {
type ParentDependencies = ();
type ChildDependencies = $dep;
type NodeDependencies = ();
const NODE_MASK: NodeMaskBuilder<'static> = NodeMaskBuilder::ALL;
fn update<'a>(
&mut self,
_: NodeView,
_: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
_: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
_: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
_: &SendAnyMap,
) -> bool {
self.0 += 1;
true
}
fn create<'a>(
node_view: NodeView<()>,
node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
children: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
context: &SendAnyMap,
) -> Self {
let mut myself = Self::default();
myself.update(node_view, node, parent, children, context);
myself
}
}
};
( parent( $name:ty, $dep:ty ) ) => {
#[partial_derive_state]
impl State for $name {
type ParentDependencies = $dep;
type ChildDependencies = ();
type NodeDependencies = ();
const NODE_MASK: NodeMaskBuilder<'static> = NodeMaskBuilder::ALL;
fn update<'a>(
&mut self,
_: NodeView,
_: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
_: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
_: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
_: &SendAnyMap,
) -> bool {
self.0 += 1;
true
}
fn create<'a>(
node_view: NodeView<()>,
node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
children: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
context: &SendAnyMap,
) -> Self {
let mut myself = Self::default();
myself.update(node_view, node, parent, children, context);
myself
}
}
};
( node( $name:ty, $dep:ty ) ) => {
#[partial_derive_state]
impl State for $name {
type ParentDependencies = $dep;
type ChildDependencies = ();
type NodeDependencies = ();
const NODE_MASK: NodeMaskBuilder<'static> = NodeMaskBuilder::ALL;
fn update<'a>(
&mut self,
_: NodeView,
_: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
_: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
_: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
_: &SendAnyMap,
) -> bool {
self.0 += 1;
true
}
fn create<'a>(
node_view: NodeView<()>,
node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
children: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
context: &SendAnyMap,
) -> Self {
let mut myself = Self::default();
myself.update(node_view, node, parent, children, context);
myself
}
}
};
}
macro_rules! test_state{
( state: ( $( $state:ty ),* ) ) => {
#[test]
fn state_reduce_initally_called_minimally() {
#[allow(non_snake_case)]
fn Base() -> Element {
rsx!{
div {
div{
div{
p{}
}
p{
"hello"
}
div{
h1{}
}
p{
"world"
}
}
}
}
}
let mut vdom = VirtualDom::new(Base);
let mutations = vdom.rebuild();
let mut dom: RealDom = RealDom::new([$( <$state>::to_type_erased() ),*]);
let mut dioxus_state = DioxusState::create(&mut dom);
dioxus_state.apply_mutations(&mut dom, mutations);
dom.update_state(SendAnyMap::new());
dom.traverse_depth_first_advanced(false, |n| {
$(
assert_eq!(n.get::<$state>().unwrap().0, 1);
)*
});
}
}
}
mod node_depends_on_child_and_parent {
use super::*;
#[derive(Debug, Clone, Default, PartialEq, Component)]
struct Node(i32);
dep!(node(Node, (Child, Parent)));
#[derive(Debug, Clone, Default, PartialEq, Component)]
struct Child(i32);
dep!(child(Child, (Child,)));
#[derive(Debug, Clone, Default, PartialEq, Component)]
struct Parent(i32);
dep!(parent(Parent, (Parent,)));
test_state!(state: (Child, Node, Parent));
}
mod child_depends_on_node_that_depends_on_parent {
use super::*;
#[derive(Debug, Clone, Default, PartialEq, Component)]
struct Node(i32);
dep!(node(Node, (Parent,)));
#[derive(Debug, Clone, Default, PartialEq, Component)]
struct Child(i32);
dep!(child(Child, (Node,)));
#[derive(Debug, Clone, Default, PartialEq, Component)]
struct Parent(i32);
dep!(parent(Parent, (Parent,)));
test_state!(state: (Child, Node, Parent));
}
mod parent_depends_on_node_that_depends_on_child {
use super::*;
#[derive(Debug, Clone, Default, PartialEq, Component)]
struct Node(i32);
dep!(node(Node, (Child,)));
#[derive(Debug, Clone, Default, PartialEq, Component)]
struct Child(i32);
dep!(child(Child, (Child,)));
#[derive(Debug, Clone, Default, PartialEq, Component)]
struct Parent(i32);
dep!(parent(Parent, (Node,)));
test_state!(state: (Child, Node, Parent));
}
mod node_depends_on_other_node_state {
use super::*;
#[derive(Debug, Clone, Default, PartialEq, Component)]
struct Node1(i32);
dep!(node(Node1, (Node2,)));
#[derive(Debug, Clone, Default, PartialEq, Component)]
struct Node2(i32);
dep!(node(Node2, ()));
test_state!(state: (Node1, Node2));
}
mod node_child_and_parent_state_depends_on_self {
use super::*;
#[derive(Debug, Clone, Default, PartialEq, Component)]
struct Node(i32);
dep!(node(Node, ()));
#[derive(Debug, Clone, Default, PartialEq, Component)]
struct Child(i32);
dep!(child(Child, (Child,)));
#[derive(Debug, Clone, Default, PartialEq, Component)]
struct Parent(i32);
dep!(parent(Parent, (Parent,)));
test_state!(state: (Child, Node, Parent));
}
@@ -0,0 +1,389 @@
use dioxus::prelude::*;
use dioxus_native_core::{custom_element::CustomElement, prelude::*};
use dioxus_native_core_macro::partial_derive_state;
use shipyard::Component;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Component)]
pub struct ColorState {
color: usize,
}
#[partial_derive_state]
impl State for ColorState {
type ParentDependencies = (Self,);
type ChildDependencies = ();
type NodeDependencies = ();
// The color state should not be effected by the shadow dom
const TRAVERSE_SHADOW_DOM: bool = false;
const NODE_MASK: NodeMaskBuilder<'static> = NodeMaskBuilder::new()
.with_attrs(AttributeMaskBuilder::Some(&["color"]))
.with_element();
fn update<'a>(
&mut self,
view: NodeView,
_: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
_: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
_: &SendAnyMap,
) -> bool {
if let Some(size) = view
.attributes()
.into_iter()
.flatten()
.find(|attr| attr.attribute.name == "color")
{
self.color = size
.value
.as_float()
.or_else(|| size.value.as_int().map(|i| i as f64))
.or_else(|| size.value.as_text().and_then(|i| i.parse().ok()))
.unwrap_or(0.0) as usize;
} else if let Some((parent,)) = parent {
*self = *parent;
}
true
}
fn create<'a>(
node_view: NodeView<()>,
node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
children: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
context: &SendAnyMap,
) -> Self {
let mut myself = Self::default();
myself.update(node_view, node, parent, children, context);
myself
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Component)]
pub struct LayoutState {
size: usize,
}
#[partial_derive_state]
impl State for LayoutState {
type ParentDependencies = (Self,);
type ChildDependencies = ();
type NodeDependencies = ();
// The layout state should be effected by the shadow dom
const TRAVERSE_SHADOW_DOM: bool = true;
const NODE_MASK: NodeMaskBuilder<'static> = NodeMaskBuilder::new()
.with_attrs(AttributeMaskBuilder::Some(&["size"]))
.with_element();
fn update<'a>(
&mut self,
view: NodeView,
_: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
_: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
_: &SendAnyMap,
) -> bool {
if let Some(size) = view
.attributes()
.into_iter()
.flatten()
.find(|attr| attr.attribute.name == "size")
{
self.size = size
.value
.as_float()
.or_else(|| size.value.as_int().map(|i| i as f64))
.or_else(|| size.value.as_text().and_then(|i| i.parse().ok()))
.unwrap_or(0.0) as usize;
} else if let Some((parent,)) = parent {
if parent.size > 0 {
self.size = parent.size - 1;
}
}
true
}
fn create<'a>(
node_view: NodeView<()>,
node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
children: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
context: &SendAnyMap,
) -> Self {
let mut myself = Self::default();
myself.update(node_view, node, parent, children, context);
myself
}
}
mod dioxus_elements {
macro_rules! builder_constructors {
(
$(
$(#[$attr:meta])*
$name:ident {
$(
$(#[$attr_method:meta])*
$fil:ident: $vil:ident,
)*
};
)*
) => {
$(
#[allow(non_camel_case_types)]
$(#[$attr])*
pub struct $name;
#[allow(non_upper_case_globals, unused)]
impl $name {
pub const TAG_NAME: &'static str = stringify!($name);
pub const NAME_SPACE: Option<&'static str> = None;
$(
pub const $fil: (&'static str, Option<&'static str>, bool) = (stringify!($fil), None, false);
)*
}
impl GlobalAttributes for $name {}
)*
}
}
pub trait GlobalAttributes {}
pub trait SvgAttributes {}
builder_constructors! {
customelementslot {
size: attr,
color: attr,
};
customelementnoslot {
size: attr,
color: attr,
};
testing132 {
color: attr,
};
}
}
struct CustomElementWithSlot {
root: NodeId,
slot: NodeId,
}
impl CustomElement for CustomElementWithSlot {
const NAME: &'static str = "customelementslot";
fn create(mut node: NodeMut<()>) -> Self {
let dom = node.real_dom_mut();
let child = dom.create_node(ElementNode {
tag: "div".into(),
namespace: None,
attributes: Default::default(),
listeners: Default::default(),
});
let slot_id = child.id();
let mut root = dom.create_node(ElementNode {
tag: "div".into(),
namespace: None,
attributes: Default::default(),
listeners: Default::default(),
});
root.add_child(slot_id);
Self {
root: root.id(),
slot: slot_id,
}
}
fn slot(&self) -> Option<NodeId> {
Some(self.slot)
}
fn roots(&self) -> Vec<NodeId> {
vec![self.root]
}
fn attributes_changed(
&mut self,
node: NodeMut<()>,
attributes: &dioxus_native_core::node_ref::AttributeMask,
) {
println!("attributes_changed");
println!("{:?}", attributes);
println!("{:?}: {:#?}", node.id(), &*node.node_type());
}
}
struct CustomElementWithNoSlot {
root: NodeId,
}
impl CustomElement for CustomElementWithNoSlot {
const NAME: &'static str = "customelementnoslot";
fn create(mut node: NodeMut<()>) -> Self {
let dom = node.real_dom_mut();
let root = dom.create_node(ElementNode {
tag: "div".into(),
namespace: None,
attributes: Default::default(),
listeners: Default::default(),
});
Self { root: root.id() }
}
fn roots(&self) -> Vec<NodeId> {
vec![self.root]
}
fn attributes_changed(
&mut self,
node: NodeMut<()>,
attributes: &dioxus_native_core::node_ref::AttributeMask,
) {
println!("attributes_changed");
println!("{:?}", attributes);
println!("{:?}: {:#?}", node.id(), &*node.node_type());
}
}
#[test]
fn custom_elements_work() {
fn app() -> Element {
let count = use_signal(|| 0);
use_future(|count| async move {
count.with_mut(|count| *count += 1);
});
rsx! {
customelementslot {
size: "{count}",
color: "1",
customelementslot {
testing132 {}
}
}
})
}
let rt = tokio::runtime::Builder::new_current_thread()
.enable_time()
.build()
.unwrap();
rt.block_on(async {
let mut rdom = RealDom::new([LayoutState::to_type_erased(), ColorState::to_type_erased()]);
rdom.register_custom_element::<CustomElementWithSlot>();
let mut dioxus_state = DioxusState::create(&mut rdom);
let mut dom = VirtualDom::new(app);
let mutations = dom.rebuild();
dioxus_state.apply_mutations(&mut rdom, mutations);
let ctx = SendAnyMap::new();
rdom.update_state(ctx);
for i in 0..10usize {
dom.wait_for_work().await;
let mutations = dom.render_immediate();
dioxus_state.apply_mutations(&mut rdom, mutations);
let ctx = SendAnyMap::new();
rdom.update_state(ctx);
// render...
rdom.traverse_depth_first_advanced(true, |node| {
let node_type = &*node.node_type();
let height = node.height() as usize;
let indent = " ".repeat(height);
let color = *node.get::<ColorState>().unwrap();
let size = *node.get::<LayoutState>().unwrap();
let id = node.id();
println!("{indent}{id:?} {color:?} {size:?} {node_type:?}");
if let NodeType::Element(el) = node_type {
match el.tag.as_str() {
// the color should bubble up from customelementslot
"testing132" | "customelementslot" => {
assert_eq!(color.color, 1);
}
// the color of the light dom should not effect the color of the shadow dom, so the color of divs in the shadow dom should be 0
"div" => {
assert_eq!(color.color, 0);
}
_ => {}
}
if el.tag != "Root" {
assert_eq!(size.size, (i + 2).saturating_sub(height));
}
}
});
}
});
}
#[test]
#[should_panic]
fn slotless_custom_element_cant_have_children() {
fn app() -> Element {
rsx! {
customelementnoslot {
testing132 {}
}
})
}
let rt = tokio::runtime::Builder::new_current_thread()
.enable_time()
.build()
.unwrap();
rt.block_on(async {
let mut rdom = RealDom::new([LayoutState::to_type_erased(), ColorState::to_type_erased()]);
rdom.register_custom_element::<CustomElementWithNoSlot>();
let mut dioxus_state = DioxusState::create(&mut rdom);
let mut dom = VirtualDom::new(app);
let mutations = dom.rebuild();
dioxus_state.apply_mutations(&mut rdom, mutations);
let ctx = SendAnyMap::new();
rdom.update_state(ctx);
});
}
#[test]
fn slotless_custom_element() {
fn app() -> Element {
rsx! {
customelementnoslot {
}
})
}
let rt = tokio::runtime::Builder::new_current_thread()
.enable_time()
.build()
.unwrap();
rt.block_on(async {
let mut rdom = RealDom::new([LayoutState::to_type_erased(), ColorState::to_type_erased()]);
rdom.register_custom_element::<CustomElementWithNoSlot>();
let mut dioxus_state = DioxusState::create(&mut rdom);
let mut dom = VirtualDom::new(app);
let mutations = dom.rebuild();
dioxus_state.apply_mutations(&mut rdom, mutations);
let ctx = SendAnyMap::new();
rdom.update_state(ctx);
});
}
+386
View File
@@ -0,0 +1,386 @@
use std::cell::Cell;
use dioxus::prelude::Props;
use dioxus_core::*;
use dioxus_native_core::prelude::*;
use dioxus_native_core_macro::partial_derive_state;
use shipyard::Component;
fn random_ns() -> Option<&'static str> {
let namespace = rand::random::<u8>() % 2;
match namespace {
0 => None,
1 => Some(Box::leak(
format!("ns{}", rand::random::<usize>()).into_boxed_str(),
)),
_ => unreachable!(),
}
}
fn create_random_attribute(attr_idx: &mut usize) -> TemplateAttribute<'static> {
match rand::random::<u8>() % 2 {
0 => TemplateAttribute::Static {
name: Box::leak(format!("attr{}", rand::random::<usize>()).into_boxed_str()),
value: Box::leak(format!("value{}", rand::random::<usize>()).into_boxed_str()),
namespace: random_ns(),
},
1 => TemplateAttribute::Dynamic {
id: {
let old_idx = *attr_idx;
*attr_idx += 1;
old_idx
},
},
_ => unreachable!(),
}
}
fn create_random_template_node(
dynamic_node_types: &mut Vec<DynamicNodeType>,
template_idx: &mut usize,
attr_idx: &mut usize,
depth: usize,
) -> TemplateNode {
match rand::random::<u8>() % 4 {
0 => {
let attrs = {
let attrs: Vec<_> = (0..(rand::random::<usize>() % 10))
.map(|_| create_random_attribute(attr_idx))
.collect();
Box::leak(attrs.into_boxed_slice())
};
TemplateNode::Element {
tag: Box::leak(format!("tag{}", rand::random::<usize>()).into_boxed_str()),
namespace: random_ns(),
attrs,
children: {
if depth > 4 {
&[]
} else {
let children: Vec<_> = (0..(rand::random::<usize>() % 3))
.map(|_| {
create_random_template_node(
dynamic_node_types,
template_idx,
attr_idx,
depth + 1,
)
})
.collect();
Box::leak(children.into_boxed_slice())
}
},
}
}
1 => TemplateNode::Text {
text: Box::leak(format!("{}", rand::random::<usize>()).into_boxed_str()),
},
2 => TemplateNode::DynamicText {
id: {
let old_idx = *template_idx;
*template_idx += 1;
dynamic_node_types.push(DynamicNodeType::Text);
old_idx
},
},
3 => TemplateNode::Dynamic {
id: {
let old_idx = *template_idx;
*template_idx += 1;
dynamic_node_types.push(DynamicNodeType::Other);
old_idx
},
},
_ => unreachable!(),
}
}
fn generate_paths(
node: &TemplateNode,
current_path: &[u8],
node_paths: &mut Vec<Vec<u8>>,
attr_paths: &mut Vec<Vec<u8>>,
) {
match node {
TemplateNode::Element {
children, attrs, ..
} => {
for attr in *attrs {
match attr {
TemplateAttribute::Static { .. } => {}
TemplateAttribute::Dynamic { .. } => {
attr_paths.push(current_path.to_vec());
}
}
}
for (i, child) in children.iter().enumerate() {
let mut current_path = current_path.to_vec();
current_path.push(i as u8);
generate_paths(child, &current_path, node_paths, attr_paths);
}
}
TemplateNode::Text { .. } => {}
TemplateNode::DynamicText { .. } => {
node_paths.push(current_path.to_vec());
}
TemplateNode::Dynamic { .. } => {
node_paths.push(current_path.to_vec());
}
}
}
enum DynamicNodeType {
Text,
Other,
}
fn create_random_template(name: &'static str) -> (Template, Vec<DynamicNodeType>) {
let mut dynamic_node_type = Vec::new();
let mut template_idx = 0;
let mut attr_idx = 0;
let roots = (0..(1 + rand::random::<usize>() % 5))
.map(|_| {
create_random_template_node(&mut dynamic_node_type, &mut template_idx, &mut attr_idx, 0)
})
.collect::<Vec<_>>();
assert!(!roots.is_empty());
let roots = Box::leak(roots.into_boxed_slice());
let mut node_paths = Vec::new();
let mut attr_paths = Vec::new();
for (i, root) in roots.iter().enumerate() {
generate_paths(root, &[i as u8], &mut node_paths, &mut attr_paths);
}
let node_paths = Box::leak(
node_paths
.into_iter()
.map(|v| &*Box::leak(v.into_boxed_slice()))
.collect::<Vec<_>>()
.into_boxed_slice(),
);
let attr_paths = Box::leak(
attr_paths
.into_iter()
.map(|v| &*Box::leak(v.into_boxed_slice()))
.collect::<Vec<_>>()
.into_boxed_slice(),
);
(
Template {
name,
roots,
node_paths,
attr_paths,
},
dynamic_node_type,
)
}
fn create_random_dynamic_node(depth: usize) -> DynamicNode {
let range = if depth > 3 { 1 } else { 3 };
match rand::random::<u8>() % range {
0 => DynamicNode::Placeholder(Default::default()),
1 => cx.make_node((0..(rand::random::<u8>() % 5)).map(|_| {
cx.vnode(
None.into(),
Default::default(),
Cell::new(Template {
name: concat!(file!(), ":", line!(), ":", column!(), ":0"),
roots: &[TemplateNode::Dynamic { id: 0 }],
node_paths: &[&[0]],
attr_paths: &[],
}),
dioxus::dioxus_core::exports::bumpalo::collections::Vec::new_in(cx.bump()).into(),
cx.bump().alloc([cx.component(
create_random_element,
DepthProps { depth, root: false },
"create_random_element",
)]),
&[],
)
})),
2 => cx.component(
create_random_element,
DepthProps { depth, root: false },
"create_random_element",
),
_ => unreachable!(),
}
}
fn create_random_dynamic_attr() -> Attribute {
let value = match rand::random::<u8>() % 6 {
0 => AttributeValue::Text(Box::leak(
format!("{}", rand::random::<usize>()).into_boxed_str(),
)),
1 => AttributeValue::Float(rand::random()),
2 => AttributeValue::Int(rand::random()),
3 => AttributeValue::Bool(rand::random()),
4 => cx.any_value(rand::random::<usize>()),
5 => AttributeValue::None,
_ => unreachable!(),
};
Attribute::new(
Box::leak(format!("attr{}", rand::random::<usize>()).into_boxed_str()),
value,
random_ns(),
rand::random(),
)
}
static mut TEMPLATE_COUNT: usize = 0;
#[derive(PartialEq, Props, Component)]
struct DepthProps {
depth: usize,
root: bool,
}
fn create_random_element(cx: Scope<DepthProps>) -> Element {
cx.needs_update();
let range = if cx.props.root { 2 } else { 3 };
let node = match rand::random::<usize>() % range {
0 | 1 => {
let (template, dynamic_node_types) = create_random_template(Box::leak(
format!(
"{}{}",
concat!(file!(), ":", line!(), ":", column!(), ":"),
{
unsafe {
let old = TEMPLATE_COUNT;
TEMPLATE_COUNT += 1;
old
}
}
)
.into_boxed_str(),
));
println!("{template:#?}");
let node = cx.vnode(
None.into(),
None,
Cell::new(template),
dioxus::dioxus_core::exports::bumpalo::collections::Vec::new_in(cx.bump()).into(),
{
let dynamic_nodes: Vec<_> = dynamic_node_types
.iter()
.map(|ty| match ty {
DynamicNodeType::Text => DynamicNode::Text(VText::new(Box::leak(
format!("{}", rand::random::<usize>()).into_boxed_str(),
))),
DynamicNodeType::Other => {
create_random_dynamic_node(cx.props.depth + 1)
}
})
.collect();
cx.bump().alloc(dynamic_nodes)
},
cx.bump()
.alloc(
(0..template.attr_paths.len())
.map(|_| create_random_dynamic_attr(cx).into())
.collect::<Vec<_>>(),
)
.as_slice(),
);
Some(node)
}
_ => None,
};
println!("{node:#?}");
node
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Component)]
pub struct BlablaState {
count: usize,
}
#[partial_derive_state]
impl State for BlablaState {
type ParentDependencies = (Self,);
type ChildDependencies = ();
type NodeDependencies = ();
const NODE_MASK: NodeMaskBuilder<'static> = NodeMaskBuilder::new()
.with_attrs(AttributeMaskBuilder::Some(&["blabla"]))
.with_element();
fn update<'a>(
&mut self,
_: NodeView,
_: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
_: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
_: &SendAnyMap,
) -> bool {
if let Some((parent,)) = parent {
if parent.count != 0 {
self.count += 1;
}
}
true
}
fn create<'a>(
node_view: NodeView<()>,
node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
children: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
context: &SendAnyMap,
) -> Self {
let mut myself = Self::default();
myself.update(node_view, node, parent, children, context);
myself
}
}
// test for panics when creating random nodes and templates
#[test]
fn create() {
for _ in 0..100 {
let mut vdom = VirtualDom::new_with_props(
create_random_element,
DepthProps {
depth: 0,
root: true,
},
);
let mutations = vdom.rebuild();
let mut rdom: RealDom = RealDom::new([BlablaState::to_type_erased()]);
let mut dioxus_state = DioxusState::create(&mut rdom);
dioxus_state.apply_mutations(&mut rdom, mutations);
let ctx = SendAnyMap::new();
rdom.update_state(ctx);
}
}
// test for panics when diffing random nodes
// This test will change the template every render which is not very realistic, but it helps stress the system
#[test]
fn diff() {
for _ in 0..10 {
let mut vdom = VirtualDom::new_with_props(
create_random_element,
DepthProps {
depth: 0,
root: true,
},
);
let mutations = vdom.rebuild();
let mut rdom: RealDom = RealDom::new([BlablaState::to_type_erased()]);
let mut dioxus_state = DioxusState::create(&mut rdom);
dioxus_state.apply_mutations(&mut rdom, mutations);
let ctx = SendAnyMap::new();
rdom.update_state(ctx);
for _ in 0..10 {
let mutations = vdom.render_immediate();
dioxus_state.apply_mutations(&mut rdom, mutations);
let ctx = SendAnyMap::new();
rdom.update_state(ctx);
}
}
}
+154
View File
@@ -0,0 +1,154 @@
use dioxus::prelude::*;
use dioxus_native_core::prelude::*;
use dioxus_native_core_macro::partial_derive_state;
use shipyard::Component;
use tokio::time::sleep;
#[derive(Debug, Clone, PartialEq, Eq, Default, Component)]
pub struct BlablaState {
count: usize,
}
#[partial_derive_state]
impl State for BlablaState {
type ParentDependencies = (Self,);
type ChildDependencies = ();
type NodeDependencies = ();
const NODE_MASK: NodeMaskBuilder<'static> = NodeMaskBuilder::new()
.with_attrs(AttributeMaskBuilder::Some(&["blabla"]))
.with_element();
fn update<'a>(
&mut self,
_: NodeView,
_: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
_: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
_: &SendAnyMap,
) -> bool {
if let Some((parent,)) = parent {
if parent.count != 0 {
self.count += 1;
}
}
true
}
fn create<'a>(
node_view: NodeView<()>,
node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
children: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
context: &SendAnyMap,
) -> Self {
let mut myself = Self::default();
myself.update(node_view, node, parent, children, context);
myself
}
}
mod dioxus_elements {
macro_rules! builder_constructors {
(
$(
$(#[$attr:meta])*
$name:ident {
$(
$(#[$attr_method:meta])*
$fil:ident: $vil:ident,
)*
};
)*
) => {
$(
#[allow(non_camel_case_types)]
$(#[$attr])*
pub struct $name;
impl $name {
pub const TAG_NAME: &'static str = stringify!($name);
pub const NAME_SPACE: Option<&'static str> = None;
$(
pub const $fil: (&'static str, Option<&'static str>, bool) = (stringify!($fil), None, false);
)*
}
impl GlobalAttributes for $name {}
)*
}
}
pub trait GlobalAttributes {}
pub trait SvgAttributes {}
builder_constructors! {
blabla {
};
}
}
#[test]
fn native_core_is_okay() {
use std::sync::{Arc, Mutex};
use std::time::Duration;
fn app() -> Element {
let colors = use_signal(|| vec!["green", "blue", "red"]);
let padding = use_signal(|| 10);
use_effect(colors, |colors| async move {
sleep(Duration::from_millis(1000)).await;
colors.with_mut(|colors| colors.reverse());
});
use_effect(padding, |padding| async move {
sleep(Duration::from_millis(10)).await;
padding.with_mut(|padding| {
if *padding < 65 {
*padding += 1;
} else {
*padding = 5;
}
});
});
let _big = colors[0];
let _mid = colors[1];
let _small = colors[2];
rsx! {
blabla {}
})
}
let rt = tokio::runtime::Builder::new_current_thread()
.enable_time()
.build()
.unwrap();
rt.block_on(async {
let rdom = Arc::new(Mutex::new(RealDom::new([BlablaState::to_type_erased()])));
let mut dioxus_state = DioxusState::create(&mut rdom.lock().unwrap());
let mut dom = VirtualDom::new(app);
let mutations = dom.rebuild();
dioxus_state.apply_mutations(&mut rdom.lock().unwrap(), mutations);
let ctx = SendAnyMap::new();
rdom.lock().unwrap().update_state(ctx);
for _ in 0..10 {
dom.wait_for_work().await;
let mutations = dom.render_immediate();
dioxus_state.apply_mutations(&mut rdom.lock().unwrap(), mutations);
let ctx = SendAnyMap::new();
rdom.lock().unwrap().update_state(ctx);
}
});
}
+440
View File
@@ -0,0 +1,440 @@
use dioxus_native_core::node::NodeType;
use dioxus_native_core::prelude::*;
use dioxus_native_core_macro::partial_derive_state;
use rustc_hash::{FxHashMap, FxHashSet};
use shipyard::Component;
fn create_blank_element() -> NodeType {
NodeType::Element(ElementNode {
tag: "div".to_owned(),
namespace: None,
attributes: FxHashMap::default(),
listeners: FxHashSet::default(),
})
}
#[test]
fn node_pass() {
#[derive(Debug, Default, Clone, PartialEq, Component)]
struct Number(i32);
#[partial_derive_state]
impl State for Number {
type ChildDependencies = ();
type NodeDependencies = ();
type ParentDependencies = ();
const NODE_MASK: NodeMaskBuilder<'static> = NodeMaskBuilder::new();
fn update<'a>(
&mut self,
_: NodeView,
_: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
_: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
_: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
_: &SendAnyMap,
) -> bool {
self.0 += 1;
true
}
fn create<'a>(
node_view: NodeView<()>,
node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
children: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
context: &SendAnyMap,
) -> Self {
let mut myself = Self::default();
myself.update(node_view, node, parent, children, context);
myself
}
}
let mut tree: RealDom = RealDom::new([Number::to_type_erased()]);
tree.update_state(SendAnyMap::new());
assert_eq!(
tree.get(tree.root_id()).unwrap().get().as_deref(),
Some(&Number(1))
);
// mark the node as dirty
tree.get_mut(tree.root_id()).unwrap().get_mut::<Number>();
tree.update_state(SendAnyMap::new());
assert_eq!(
tree.get(tree.root_id()).unwrap().get().as_deref(),
Some(&Number(2))
);
}
#[test]
fn dependant_node_pass() {
#[derive(Debug, Default, Clone, PartialEq, Component)]
struct AddNumber(i32);
#[partial_derive_state]
impl State for AddNumber {
type ChildDependencies = ();
type NodeDependencies = (SubtractNumber,);
type ParentDependencies = ();
const NODE_MASK: NodeMaskBuilder<'static> = NodeMaskBuilder::new();
fn update<'a>(
&mut self,
_: NodeView,
_: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
_: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
_: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
_: &SendAnyMap,
) -> bool {
self.0 += 1;
true
}
fn create<'a>(
node_view: NodeView<()>,
node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
children: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
context: &SendAnyMap,
) -> Self {
let mut myself = Self::default();
myself.update(node_view, node, parent, children, context);
myself
}
}
#[derive(Debug, Default, Clone, PartialEq, Component)]
struct SubtractNumber(i32);
#[partial_derive_state]
impl State for SubtractNumber {
type ChildDependencies = ();
type NodeDependencies = ();
type ParentDependencies = ();
const NODE_MASK: NodeMaskBuilder<'static> = NodeMaskBuilder::new();
fn update<'a>(
&mut self,
_: NodeView,
_: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
_: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
_: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
_: &SendAnyMap,
) -> bool {
self.0 -= 1;
true
}
fn create<'a>(
node_view: NodeView<()>,
node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
children: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
context: &SendAnyMap,
) -> Self {
let mut myself = Self::default();
myself.update(node_view, node, parent, children, context);
myself
}
}
let mut tree: RealDom = RealDom::new([
AddNumber::to_type_erased(),
SubtractNumber::to_type_erased(),
]);
tree.update_state(SendAnyMap::new());
let root = tree.get(tree.root_id()).unwrap();
assert_eq!(root.get().as_deref(), Some(&AddNumber(1)));
assert_eq!(root.get().as_deref(), Some(&SubtractNumber(-1)));
// mark the subtract state as dirty, it should update the add state
tree.get_mut(tree.root_id())
.unwrap()
.get_mut::<SubtractNumber>();
tree.update_state(SendAnyMap::new());
let root = tree.get(tree.root_id()).unwrap();
assert_eq!(root.get().as_deref(), Some(&AddNumber(2)));
assert_eq!(root.get().as_deref(), Some(&SubtractNumber(-2)));
// mark the add state as dirty, it should ~not~ update the subtract state
tree.get_mut(tree.root_id()).unwrap().get_mut::<AddNumber>();
tree.update_state(SendAnyMap::new());
let root = tree.get(tree.root_id()).unwrap();
assert_eq!(root.get().as_deref(), Some(&AddNumber(3)));
assert_eq!(root.get().as_deref(), Some(&SubtractNumber(-2)));
}
#[test]
fn independant_node_pass() {
#[derive(Debug, Default, Clone, PartialEq, Component)]
struct AddNumber(i32);
#[partial_derive_state]
impl State for AddNumber {
type ChildDependencies = ();
type NodeDependencies = ();
type ParentDependencies = ();
const NODE_MASK: NodeMaskBuilder<'static> = NodeMaskBuilder::new();
fn update<'a>(
&mut self,
_: NodeView,
_: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
_: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
_: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
_: &SendAnyMap,
) -> bool {
self.0 += 1;
true
}
fn create<'a>(
node_view: NodeView<()>,
node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
children: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
context: &SendAnyMap,
) -> Self {
let mut myself = Self::default();
myself.update(node_view, node, parent, children, context);
myself
}
}
#[derive(Debug, Default, Clone, PartialEq, Component)]
struct SubtractNumber(i32);
#[partial_derive_state]
impl State for SubtractNumber {
type ChildDependencies = ();
type NodeDependencies = ();
type ParentDependencies = ();
const NODE_MASK: NodeMaskBuilder<'static> = NodeMaskBuilder::new();
fn update<'a>(
&mut self,
_: NodeView,
_: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
_: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
_: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
_: &SendAnyMap,
) -> bool {
self.0 -= 1;
true
}
fn create<'a>(
node_view: NodeView<()>,
node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
children: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
context: &SendAnyMap,
) -> Self {
let mut myself = Self::default();
myself.update(node_view, node, parent, children, context);
myself
}
}
let mut tree: RealDom = RealDom::new([
AddNumber::to_type_erased(),
SubtractNumber::to_type_erased(),
]);
tree.update_state(SendAnyMap::new());
let root = tree.get(tree.root_id()).unwrap();
assert_eq!(root.get().as_deref(), Some(&AddNumber(1)));
assert_eq!(root.get().as_deref(), Some(&SubtractNumber(-1)));
// mark the subtract state as dirty, it should ~not~ update the add state
tree.get_mut(tree.root_id())
.unwrap()
.get_mut::<SubtractNumber>();
tree.update_state(SendAnyMap::new());
let root = tree.get(tree.root_id()).unwrap();
assert_eq!(root.get().as_deref(), Some(&AddNumber(1)));
assert_eq!(root.get().as_deref(), Some(&SubtractNumber(-2)));
// mark the add state as dirty, it should ~not~ update the subtract state
tree.get_mut(tree.root_id()).unwrap().get_mut::<AddNumber>();
tree.update_state(SendAnyMap::new());
let root = tree.get(tree.root_id()).unwrap();
assert_eq!(root.get().as_deref(), Some(&AddNumber(2)));
assert_eq!(root.get().as_deref(), Some(&SubtractNumber(-2)));
}
#[test]
fn down_pass() {
#[derive(Debug, Clone, PartialEq, Component)]
struct AddNumber(i32);
impl Default for AddNumber {
fn default() -> Self {
Self(1)
}
}
#[partial_derive_state]
impl State for AddNumber {
type ChildDependencies = ();
type NodeDependencies = ();
type ParentDependencies = (AddNumber,);
const NODE_MASK: NodeMaskBuilder<'static> = NodeMaskBuilder::new();
fn update<'a>(
&mut self,
_: NodeView,
_: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
_: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
_: &SendAnyMap,
) -> bool {
if let Some((parent,)) = parent {
self.0 += parent.0;
}
true
}
fn create<'a>(
node_view: NodeView<()>,
node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
children: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
context: &SendAnyMap,
) -> Self {
let mut myself = Self::default();
myself.update(node_view, node, parent, children, context);
myself
}
}
let mut tree: RealDom = RealDom::new([AddNumber::to_type_erased()]);
let grandchild1 = tree.create_node(create_blank_element());
let grandchild1 = grandchild1.id();
let mut child1 = tree.create_node(create_blank_element());
child1.add_child(grandchild1);
let child1 = child1.id();
let grandchild2 = tree.create_node(create_blank_element());
let grandchild2 = grandchild2.id();
let mut child2 = tree.create_node(create_blank_element());
child2.add_child(grandchild2);
let child2 = child2.id();
let mut parent = tree.get_mut(tree.root_id()).unwrap();
parent.add_child(child1);
parent.add_child(child2);
tree.update_state(SendAnyMap::new());
let root = tree.get(tree.root_id()).unwrap();
dbg!(root.id());
assert_eq!(root.get().as_deref(), Some(&AddNumber(1)));
let child1 = tree.get(child1).unwrap();
dbg!(child1.id());
assert_eq!(child1.get().as_deref(), Some(&AddNumber(2)));
let grandchild1 = tree.get(grandchild1).unwrap();
assert_eq!(grandchild1.get().as_deref(), Some(&AddNumber(3)));
let child2 = tree.get(child2).unwrap();
assert_eq!(child2.get().as_deref(), Some(&AddNumber(2)));
let grandchild2 = tree.get(grandchild2).unwrap();
assert_eq!(grandchild2.get().as_deref(), Some(&AddNumber(3)));
}
#[test]
fn up_pass() {
// Tree before:
// 1=\
// 1=\
// 1
// 1=\
// 1
// Tree after:
// 4=\
// 2=\
// 1
// 2=\
// 1
#[derive(Debug, Clone, PartialEq, Component)]
struct AddNumber(i32);
#[partial_derive_state]
impl State for AddNumber {
type ChildDependencies = (AddNumber,);
type NodeDependencies = ();
type ParentDependencies = ();
const NODE_MASK: NodeMaskBuilder<'static> = NodeMaskBuilder::new();
fn update<'a>(
&mut self,
_: NodeView,
_: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
_: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
children: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
_: &SendAnyMap,
) -> bool {
self.0 += children.iter().map(|(i,)| i.0).sum::<i32>();
true
}
fn create<'a>(
node_view: NodeView<()>,
node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
children: Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
context: &SendAnyMap,
) -> Self {
let mut myself = Self(1);
myself.update(node_view, node, parent, children, context);
myself
}
}
let mut tree: RealDom = RealDom::new([AddNumber::to_type_erased()]);
let grandchild1 = tree.create_node(create_blank_element());
let grandchild1 = grandchild1.id();
let mut child1 = tree.create_node(create_blank_element());
child1.add_child(grandchild1);
let child1 = child1.id();
let grandchild2 = tree.create_node(create_blank_element());
let grandchild2 = grandchild2.id();
let mut child2 = tree.create_node(create_blank_element());
child2.add_child(grandchild2);
let child2 = child2.id();
let mut parent = tree.get_mut(tree.root_id()).unwrap();
parent.add_child(child1);
parent.add_child(child2);
tree.update_state(SendAnyMap::new());
let root = tree.get(tree.root_id()).unwrap();
assert_eq!(root.get().as_deref(), Some(&AddNumber(5)));
let child1 = tree.get(child1).unwrap();
assert_eq!(child1.get().as_deref(), Some(&AddNumber(2)));
let grandchild1 = tree.get(grandchild1).unwrap();
assert_eq!(grandchild1.get().as_deref(), Some(&AddNumber(1)));
let child2 = tree.get(child2).unwrap();
assert_eq!(child2.get().as_deref(), Some(&AddNumber(2)));
let grandchild2 = tree.get(grandchild2).unwrap();
assert_eq!(grandchild2.get().as_deref(), Some(&AddNumber(1)));
}