wip: start to refactor out hot reloading from packages
Also implement alternative simpler template system
This commit is contained in:
1 parent
3b7b503333
commit
90982e0ccb
44 files changed
+3865
-5133
No files matched your search
@@ -1,7 +1,4 @@
|
||||
use std::fmt::{Arguments, Formatter};
|
||||
|
||||
use bumpalo::Bump;
|
||||
use dyn_clone::{clone_box, DynClone};
|
||||
use std::{any::Any, fmt::Formatter};
|
||||
|
||||
/// Possible values for an attribute
|
||||
// trying to keep values at 3 bytes
|
||||
@@ -28,134 +25,7 @@ pub enum AttributeValue<'a> {
|
||||
Vec4Uint(u32, u32, u32, u32),
|
||||
|
||||
Bytes(&'a [u8]),
|
||||
Any(ArbitraryAttributeValue<'a>),
|
||||
}
|
||||
|
||||
/// A value that can be converted into an attribute value
|
||||
pub trait IntoAttributeValue<'a> {
|
||||
/// Convert into an attribute value
|
||||
fn into_value(self, bump: &'a Bump) -> AttributeValue<'a>;
|
||||
}
|
||||
|
||||
impl<'a> IntoAttributeValue<'a> for u32 {
|
||||
fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
|
||||
AttributeValue::Uint32(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoAttributeValue<'a> for u64 {
|
||||
fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
|
||||
AttributeValue::Uint64(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoAttributeValue<'a> for i32 {
|
||||
fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
|
||||
AttributeValue::Int32(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoAttributeValue<'a> for i64 {
|
||||
fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
|
||||
AttributeValue::Int64(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoAttributeValue<'a> for f32 {
|
||||
fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
|
||||
AttributeValue::Float32(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoAttributeValue<'a> for f64 {
|
||||
fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
|
||||
AttributeValue::Float64(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoAttributeValue<'a> for bool {
|
||||
fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
|
||||
AttributeValue::Bool(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoAttributeValue<'a> for &'a str {
|
||||
fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
|
||||
AttributeValue::Text(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoAttributeValue<'a> for Arguments<'_> {
|
||||
fn into_value(self, bump: &'a Bump) -> AttributeValue<'a> {
|
||||
use bumpalo::core_alloc::fmt::Write;
|
||||
let mut str_buf = bumpalo::collections::String::new_in(bump);
|
||||
str_buf.write_fmt(self).unwrap();
|
||||
AttributeValue::Text(str_buf.into_bump_str())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoAttributeValue<'a> for &'a [u8] {
|
||||
fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
|
||||
AttributeValue::Bytes(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoAttributeValue<'a> for (f32, f32, f32) {
|
||||
fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
|
||||
AttributeValue::Vec3Float(self.0, self.1, self.2)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoAttributeValue<'a> for (i32, i32, i32) {
|
||||
fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
|
||||
AttributeValue::Vec3Int(self.0, self.1, self.2)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoAttributeValue<'a> for (u32, u32, u32) {
|
||||
fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
|
||||
AttributeValue::Vec3Uint(self.0, self.1, self.2)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoAttributeValue<'a> for (f32, f32, f32, f32) {
|
||||
fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
|
||||
AttributeValue::Vec4Float(self.0, self.1, self.2, self.3)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoAttributeValue<'a> for (i32, i32, i32, i32) {
|
||||
fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
|
||||
AttributeValue::Vec4Int(self.0, self.1, self.2, self.3)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoAttributeValue<'a> for (u32, u32, u32, u32) {
|
||||
fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
|
||||
AttributeValue::Vec4Uint(self.0, self.1, self.2, self.3)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> IntoAttributeValue<'a> for &'a T
|
||||
where
|
||||
T: AnyClone + PartialEq,
|
||||
{
|
||||
fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
|
||||
AttributeValue::Any(ArbitraryAttributeValue {
|
||||
value: self,
|
||||
cmp: |a, b| {
|
||||
if let Some(a) = a.as_any().downcast_ref::<T>() {
|
||||
if let Some(b) = b.as_any().downcast_ref::<T>() {
|
||||
a == b
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} else {
|
||||
false
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
// Any(ArbitraryAttributeValue<'a>),
|
||||
}
|
||||
|
||||
// todo
|
||||
@@ -196,7 +66,7 @@ impl<'a> std::fmt::Display for AttributeValue<'a> {
|
||||
AttributeValue::Vec4Int(_, _, _, _) => todo!(),
|
||||
AttributeValue::Vec4Uint(_, _, _, _) => todo!(),
|
||||
AttributeValue::Bytes(a) => write!(f, "{:?}", a),
|
||||
AttributeValue::Any(a) => write!(f, "{:?}", a),
|
||||
// AttributeValue::Any(a) => write!(f, "{:?}", a),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -204,15 +74,17 @@ impl<'a> std::fmt::Display for AttributeValue<'a> {
|
||||
#[derive(Clone, Copy)]
|
||||
#[allow(missing_docs)]
|
||||
pub struct ArbitraryAttributeValue<'a> {
|
||||
pub value: &'a dyn AnyClone,
|
||||
pub cmp: fn(&dyn AnyClone, &dyn AnyClone) -> bool,
|
||||
pub value: &'a dyn Any,
|
||||
pub cmp: fn(&'a dyn std::any::Any, &'a dyn std::any::Any) -> bool,
|
||||
}
|
||||
|
||||
impl PartialEq for ArbitraryAttributeValue<'_> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
(self.cmp)(self.value, other.value)
|
||||
}
|
||||
}
|
||||
// pub trait AnyAttrValue {}
|
||||
|
||||
// impl PartialEq for ArbitraryAttributeValue<'_> {
|
||||
// fn eq(&self, other: &Self) -> bool {
|
||||
// (self.cmp)(self.value, other.value)
|
||||
// }
|
||||
// }
|
||||
|
||||
impl std::fmt::Debug for ArbitraryAttributeValue<'_> {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
@@ -248,79 +120,6 @@ impl<'de, 'a> serde::Deserialize<'de> for ArbitraryAttributeValue<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A clone, sync and send version of `Any`
|
||||
// we only need the Sync + Send bound when hot reloading is enabled
|
||||
#[cfg(any(feature = "hot-reload", debug_assertions))]
|
||||
pub trait AnyClone: std::any::Any + DynClone + Send + Sync {
|
||||
fn as_any(&self) -> &dyn std::any::Any;
|
||||
}
|
||||
#[cfg(not(any(feature = "hot-reload", debug_assertions)))]
|
||||
pub trait AnyClone: std::any::Any + DynClone {
|
||||
fn as_any(&self) -> &dyn std::any::Any;
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "hot-reload", debug_assertions))]
|
||||
impl<T: std::any::Any + DynClone + Send + Sync> AnyClone for T {
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
#[cfg(not(any(feature = "hot-reload", debug_assertions)))]
|
||||
impl<T: std::any::Any + DynClone> AnyClone for T {
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
dyn_clone::clone_trait_object!(AnyClone);
|
||||
|
||||
#[derive(Clone)]
|
||||
#[allow(missing_docs)]
|
||||
pub struct OwnedArbitraryAttributeValue {
|
||||
pub value: Box<dyn AnyClone>,
|
||||
pub cmp: fn(&dyn AnyClone, &dyn AnyClone) -> bool,
|
||||
}
|
||||
|
||||
impl PartialEq for OwnedArbitraryAttributeValue {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
(self.cmp)(&*self.value, &*other.value)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for OwnedArbitraryAttributeValue {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("OwnedArbitraryAttributeValue").finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serialize")]
|
||||
impl serde::Serialize for OwnedArbitraryAttributeValue {
|
||||
fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
panic!("OwnedArbitraryAttributeValue should not be serialized")
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "serialize")]
|
||||
impl<'de> serde::Deserialize<'de> for &OwnedArbitraryAttributeValue {
|
||||
fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
panic!("OwnedArbitraryAttributeValue is not deserializable!")
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "serialize")]
|
||||
impl<'de> serde::Deserialize<'de> for OwnedArbitraryAttributeValue {
|
||||
fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
panic!("OwnedArbitraryAttributeValue is not deserializable!")
|
||||
}
|
||||
}
|
||||
|
||||
// todo
|
||||
#[allow(missing_docs)]
|
||||
impl<'a> AttributeValue<'a> {
|
||||
@@ -429,214 +228,10 @@ impl<'a> AttributeValue<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_any(&self) -> Option<&'a ArbitraryAttributeValue> {
|
||||
match self {
|
||||
AttributeValue::Any(a) => Some(a),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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(OwnedArbitraryAttributeValue),
|
||||
}
|
||||
|
||||
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(a) => OwnedAttributeValue::Any(OwnedArbitraryAttributeValue {
|
||||
value: clone_box(a.value),
|
||||
cmp: a.cmp,
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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,
|
||||
}
|
||||
}
|
||||
// pub fn as_any(&self) -> Option<&'a ArbitraryAttributeValue> {
|
||||
// match self {
|
||||
// AttributeValue::Any(a) => Some(a),
|
||||
// _ => None,
|
||||
// }
|
||||
// }
|
||||
}
|
||||
+294
-612
File diff suppressed because it is too large.
Load diff
@@ -1,190 +0,0 @@
|
||||
use std::{fmt::Write, marker::PhantomData, ops::Deref};
|
||||
|
||||
use once_cell::sync::Lazy;
|
||||
|
||||
use crate::{
|
||||
template::{TemplateNodeId, TextTemplateSegment},
|
||||
AttributeValue, Listener, TextTemplate, 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, Eq)]
|
||||
#[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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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: &TextTemplate<TextSegments, Text>,
|
||||
) -> String
|
||||
where
|
||||
TextSegments: AsRef<[TextTemplateSegment<Text>]>,
|
||||
Text: AsRef<str>,
|
||||
{
|
||||
let mut result = String::with_capacity(text.min_size);
|
||||
self.resolve_text_into(text, &mut result);
|
||||
result
|
||||
}
|
||||
|
||||
/// Resolve text and writes the result
|
||||
pub fn resolve_text_into<TextSegments, Text>(
|
||||
&self,
|
||||
text: &TextTemplate<TextSegments, Text>,
|
||||
result: &mut impl Write,
|
||||
) where
|
||||
TextSegments: AsRef<[TextTemplateSegment<Text>]>,
|
||||
Text: AsRef<str>,
|
||||
{
|
||||
for seg in text.segments.as_ref() {
|
||||
match seg {
|
||||
TextTemplateSegment::Static(s) => {
|
||||
let _ = result.write_str(s.as_ref());
|
||||
}
|
||||
TextTemplateSegment::Dynamic(idx) => {
|
||||
let _ = result.write_str(self.text_segments[*idx]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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]
|
||||
}
|
||||
}
|
||||
@@ -251,72 +251,72 @@ fn round_to_words(len: usize) -> usize {
|
||||
(len + mem::size_of::<usize>() - 1) / mem::size_of::<usize>()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::innerlude::{Element, Scope, VirtualDom};
|
||||
// #[cfg(test)]
|
||||
// mod tests {
|
||||
// use super::*;
|
||||
// use crate::innerlude::{Element, Scope, VirtualDom};
|
||||
|
||||
#[test]
|
||||
fn it_works() {
|
||||
fn app(cx: Scope<()>) -> Element {
|
||||
cx.render(LazyNodes::new(|f| f.text(format_args!("hello world!"))))
|
||||
}
|
||||
// #[test]
|
||||
// fn it_works() {
|
||||
// fn app(cx: Scope<()>) -> Element {
|
||||
// cx.render(LazyNodes::new(|f| f.text(format_args!("hello world!"))))
|
||||
// }
|
||||
|
||||
let mut dom = VirtualDom::new(app);
|
||||
dom.rebuild();
|
||||
// let mut dom = VirtualDom::new(app);
|
||||
// dom.rebuild();
|
||||
|
||||
let g = dom.base_scope().root_node();
|
||||
dbg!(g);
|
||||
}
|
||||
// let g = dom.base_scope().root_node();
|
||||
// dbg!(g);
|
||||
// }
|
||||
|
||||
#[test]
|
||||
fn it_drops() {
|
||||
use std::rc::Rc;
|
||||
// #[test]
|
||||
// fn it_drops() {
|
||||
// use std::rc::Rc;
|
||||
|
||||
struct AppProps {
|
||||
inner: Rc<i32>,
|
||||
}
|
||||
// struct AppProps {
|
||||
// inner: Rc<i32>,
|
||||
// }
|
||||
|
||||
fn app(cx: Scope<AppProps>) -> Element {
|
||||
struct DropInner {
|
||||
id: i32,
|
||||
}
|
||||
impl Drop for DropInner {
|
||||
fn drop(&mut self) {
|
||||
eprintln!("dropping inner");
|
||||
}
|
||||
}
|
||||
// fn app(cx: Scope<AppProps>) -> Element {
|
||||
// struct DropInner {
|
||||
// id: i32,
|
||||
// }
|
||||
// impl Drop for DropInner {
|
||||
// fn drop(&mut self) {
|
||||
// eprintln!("dropping inner");
|
||||
// }
|
||||
// }
|
||||
|
||||
let caller = {
|
||||
let it = (0..10).map(|i| {
|
||||
let val = cx.props.inner.clone();
|
||||
LazyNodes::new(move |f| {
|
||||
eprintln!("hell closure");
|
||||
let inner = DropInner { id: i };
|
||||
f.text(format_args!("hello world {:?}, {:?}", inner.id, val))
|
||||
})
|
||||
});
|
||||
// let caller = {
|
||||
// let it = (0..10).map(|i| {
|
||||
// let val = cx.props.inner.clone();
|
||||
// LazyNodes::new(move |f| {
|
||||
// eprintln!("hell closure");
|
||||
// let inner = DropInner { id: i };
|
||||
// f.text(format_args!("hello world {:?}, {:?}", inner.id, val))
|
||||
// })
|
||||
// });
|
||||
|
||||
LazyNodes::new(|f| {
|
||||
eprintln!("main closure");
|
||||
f.fragment_from_iter(it)
|
||||
})
|
||||
};
|
||||
// LazyNodes::new(|f| {
|
||||
// eprintln!("main closure");
|
||||
// f.fragment_from_iter(it)
|
||||
// })
|
||||
// };
|
||||
|
||||
cx.render(caller)
|
||||
}
|
||||
// cx.render(caller)
|
||||
// }
|
||||
|
||||
let inner = Rc::new(0);
|
||||
let mut dom = VirtualDom::new_with_props(
|
||||
app,
|
||||
AppProps {
|
||||
inner: inner.clone(),
|
||||
},
|
||||
);
|
||||
dom.rebuild();
|
||||
// let inner = Rc::new(0);
|
||||
// let mut dom = VirtualDom::new_with_props(
|
||||
// app,
|
||||
// AppProps {
|
||||
// inner: inner.clone(),
|
||||
// },
|
||||
// );
|
||||
// dom.rebuild();
|
||||
|
||||
drop(dom);
|
||||
// drop(dom);
|
||||
|
||||
assert_eq!(Rc::strong_count(&inner), 1);
|
||||
}
|
||||
}
|
||||
// assert_eq!(Rc::strong_count(&inner), 1);
|
||||
// }
|
||||
// }
|
||||
+24
-36
@@ -1,31 +1,23 @@
|
||||
#![allow(non_snake_case)]
|
||||
#![doc = include_str!("../README.md")]
|
||||
#![deny(missing_docs)]
|
||||
#![warn(missing_docs)]
|
||||
|
||||
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::*;
|
||||
|
||||
/// An [`Element`] is a possibly-none [`VNode`] created by calling `render` on [`Scope`] or [`ScopeState`].
|
||||
@@ -67,38 +59,19 @@ pub(crate) mod innerlude {
|
||||
}
|
||||
|
||||
pub use crate::innerlude::{
|
||||
AnyEvent, ArbitraryAttributeValue, Attribute, AttributeDiscription, AttributeValue,
|
||||
CodeLocation, Component, DioxusElement, DomEdit, DynamicNodeMapping, Element, ElementId,
|
||||
ElementIdIterator, EventHandler, EventPriority, IntoAttributeValue, IntoVNode, LazyNodes,
|
||||
Listener, Mutations, NodeFactory, OwnedAttributeValue, PathSeg, Properties, RendererTemplateId,
|
||||
SchedulerMsg, Scope, ScopeId, ScopeState, StaticCodeLocation, StaticDynamicNodeMapping,
|
||||
StaticPathSeg, StaticTemplateNode, StaticTemplateNodes, StaticTraverse, TaskId, Template,
|
||||
TemplateAttribute, TemplateAttributeValue, TemplateContext, TemplateElement, TemplateId,
|
||||
TemplateNode, TemplateNodeId, TemplateNodeType, TemplateValue, TextTemplate,
|
||||
TextTemplateSegment, UiEvent, UpdateOp, UserEvent, VComponent, VElement, VFragment, VNode,
|
||||
VPlaceholder, VText, VirtualDom,
|
||||
};
|
||||
#[cfg(any(feature = "hot-reload", debug_assertions))]
|
||||
pub use crate::innerlude::{
|
||||
OwnedCodeLocation, OwnedDynamicNodeMapping, OwnedPathSeg, OwnedTemplateNode,
|
||||
OwnedTemplateNodes, OwnedTraverse, SetTemplateMsg,
|
||||
AnyEvent, ArbitraryAttributeValue, Attribute, AttributeValue, Component, Element, ElementId,
|
||||
EventHandler, EventPriority, IntoVNode, LazyNodes, Listener, NodeFactory, Properties, Renderer,
|
||||
SchedulerMsg, Scope, ScopeId, ScopeState, TaskId, Template, TemplateAttribute, TemplateNode,
|
||||
UiEvent, UserEvent, VComponent, VElement, VNode, VTemplate, VText, VirtualDom,
|
||||
};
|
||||
|
||||
/// 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, AttributeDiscription, AttributeValue, Attributes, CodeLocation, Component,
|
||||
DioxusElement, Element, EventHandler, Fragment, IntoAttributeValue, LazyNodes,
|
||||
LazyStaticVec, NodeFactory, Properties, Scope, ScopeId, ScopeState, StaticAttributeValue,
|
||||
StaticCodeLocation, StaticDynamicNodeMapping, StaticPathSeg, StaticTemplate,
|
||||
StaticTemplateNodes, StaticTraverse, Template, TemplateAttribute, TemplateAttributeValue,
|
||||
TemplateContext, TemplateElement, TemplateId, TemplateNode, TemplateNodeId,
|
||||
TemplateNodeType, TextTemplate, TextTemplateSegment, UpdateOp, VNode, VirtualDom,
|
||||
fc_to_builder, Attributes, Component, Element, EventHandler, LazyNodes, NodeFactory,
|
||||
Properties, Scope, ScopeId, ScopeState, Template, VNode, VirtualDom,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -107,7 +80,6 @@ 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
|
||||
@@ -136,8 +108,24 @@ pub(crate) mod unsafe_utils {
|
||||
/// }
|
||||
/// ```
|
||||
macro_rules! to_owned {
|
||||
($($es:ident),+$(,)?) => {$(
|
||||
($($es:ident),+) => {$(
|
||||
#[allow(unused_mut)]
|
||||
let mut $es = $es.to_owned();
|
||||
)*}
|
||||
}
|
||||
|
||||
/// get the code location of the code that called this function
|
||||
#[macro_export]
|
||||
macro_rules! get_line_num {
|
||||
() => {
|
||||
concat!(
|
||||
file!(),
|
||||
":",
|
||||
line!(),
|
||||
":",
|
||||
column!(),
|
||||
":",
|
||||
env!("CARGO_MANIFEST_DIR")
|
||||
)
|
||||
};
|
||||
}
|
||||
+50
-393
@@ -6,402 +6,59 @@
|
||||
//! interpreters for these types of DomEdits.
|
||||
|
||||
use crate::innerlude::*;
|
||||
use std::{any::Any, fmt::Debug};
|
||||
|
||||
/// ## Mutations
|
||||
/// A renderer for Dioxus to modify during diffing
|
||||
///
|
||||
/// This method returns "mutations" - IE the necessary changes to get the RealDOM to match the VirtualDOM. It also
|
||||
/// includes a list of NodeRefs that need to be applied and effects that need to be triggered after the RealDOM has
|
||||
/// applied the edits.
|
||||
/// The renderer should implement a Stack Machine. IE each call to the below methods are modifications to the renderer's
|
||||
/// internal stack for creating and modifying nodes.
|
||||
///
|
||||
/// Mutations are the only link between the RealDOM and the VirtualDOM.
|
||||
pub struct Mutations<'a> {
|
||||
/// The list of edits that need to be applied for the RealDOM to match the VirtualDOM.
|
||||
pub edits: Vec<DomEdit<'a>>,
|
||||
/// Dioxus guarantees that the stack is always in a valid state.
|
||||
pub trait Renderer<'a> {
|
||||
/// Load this element onto the stack
|
||||
fn push_root(&mut self, root: ElementId);
|
||||
/// Pop the topmost element from the stack
|
||||
fn pop_root(&mut self);
|
||||
/// Replace the given element with the next m elements on the stack
|
||||
fn replace_with(&mut self, root: ElementId, m: u32);
|
||||
/// Insert the next m elements on the stack after the given element
|
||||
fn insert_after(&mut self, root: ElementId, n: u32);
|
||||
/// Insert the next m elements on the stack before the given element
|
||||
fn insert_before(&mut self, root: ElementId, n: u32);
|
||||
/// Append the next n elements on the stack to the n+1 element on the stack
|
||||
fn append_children(&mut self, n: u32);
|
||||
|
||||
/// The list of Scopes that were diffed, created, and removed during the Diff process.
|
||||
pub dirty_scopes: FxHashSet<ScopeId>,
|
||||
/// Create a new element with the given text and ElementId
|
||||
fn create_text_node(&mut self, text: &'a str, root: ElementId);
|
||||
/// Create an element with the given tag name, optional namespace, and ElementId
|
||||
/// Note that namespaces do not cascade down the tree, so the renderer must handle this if it implements namespaces
|
||||
fn create_element(&mut self, tag: &'static str, ns: Option<&'static str>, id: ElementId);
|
||||
/// Create a hidden element to be used later for replacement.
|
||||
/// Used in suspense, lists, and other places where we need to hide a node before it is ready to be shown.
|
||||
/// This is up to the renderer to implement, but it should not be visible to the user.
|
||||
fn create_placeholder(&mut self, id: ElementId);
|
||||
|
||||
/// The list of nodes to connect to the RealDOM.
|
||||
pub refs: Vec<NodeRefMutation<'a>>,
|
||||
}
|
||||
|
||||
impl Debug for Mutations<'_> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Mutations")
|
||||
.field("edits", &self.edits)
|
||||
.field("noderefs", &self.refs)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// A `DomEdit` represents a serialized form of the VirtualDom's trait-based API. This allows streaming edits across the
|
||||
/// network or through FFI boundaries.
|
||||
#[derive(Debug, PartialEq)]
|
||||
#[cfg_attr(
|
||||
feature = "serialize",
|
||||
derive(serde::Serialize, serde::Deserialize),
|
||||
serde(tag = "type")
|
||||
)]
|
||||
pub enum DomEdit<'bump> {
|
||||
/// Pop the topmost node from our stack and append them to the node
|
||||
/// at the top of the stack.
|
||||
AppendChildren {
|
||||
/// The parent to append nodes to.
|
||||
root: Option<u64>,
|
||||
|
||||
/// The ids of the children to append.
|
||||
children: Vec<u64>,
|
||||
},
|
||||
|
||||
/// Replace a given (single) node with a handful of nodes currently on the stack.
|
||||
ReplaceWith {
|
||||
/// The ID of the node to be replaced.
|
||||
root: Option<u64>,
|
||||
|
||||
/// The ids of the nodes to replace the root with.
|
||||
nodes: Vec<u64>,
|
||||
},
|
||||
|
||||
/// Insert a number of nodes after a given node.
|
||||
InsertAfter {
|
||||
/// The ID of the node to insert after.
|
||||
root: Option<u64>,
|
||||
|
||||
/// The ids of the nodes to insert after the target node.
|
||||
nodes: Vec<u64>,
|
||||
},
|
||||
|
||||
/// Insert a number of nodes before a given node.
|
||||
InsertBefore {
|
||||
/// The ID of the node to insert before.
|
||||
root: Option<u64>,
|
||||
|
||||
/// The ids of the nodes to insert before the target node.
|
||||
nodes: Vec<u64>,
|
||||
},
|
||||
|
||||
/// Remove a particular node from the DOM
|
||||
Remove {
|
||||
/// The ID of the node to remove.
|
||||
root: Option<u64>,
|
||||
},
|
||||
|
||||
/// Create a new purely-text node
|
||||
CreateTextNode {
|
||||
/// The ID the new node should have.
|
||||
root: Option<u64>,
|
||||
|
||||
/// The textcontent of the node
|
||||
text: &'bump str,
|
||||
},
|
||||
|
||||
/// Create a new purely-element node
|
||||
CreateElement {
|
||||
/// The ID the new node should have.
|
||||
root: Option<u64>,
|
||||
|
||||
/// The tagname of the node
|
||||
tag: &'bump str,
|
||||
|
||||
/// The number of children nodes that will follow this message.
|
||||
children: u32,
|
||||
},
|
||||
|
||||
/// Create a new purely-comment node with a given namespace
|
||||
CreateElementNs {
|
||||
/// The ID the new node should have.
|
||||
root: Option<u64>,
|
||||
|
||||
/// The namespace of the node
|
||||
tag: &'bump str,
|
||||
|
||||
/// The namespace of the node (like `SVG`)
|
||||
ns: &'static str,
|
||||
|
||||
/// The number of children nodes that will follow this message.
|
||||
children: u32,
|
||||
},
|
||||
|
||||
/// Create a new placeholder node.
|
||||
/// In most implementations, this will either be a hidden div or a comment node.
|
||||
CreatePlaceholder {
|
||||
/// The ID the new node should have.
|
||||
root: Option<u64>,
|
||||
},
|
||||
|
||||
/// Create a new Event Listener.
|
||||
NewEventListener {
|
||||
/// The name of the event to listen for.
|
||||
event_name: &'static str,
|
||||
|
||||
/// The ID of the node to attach the listener to.
|
||||
scope: ScopeId,
|
||||
|
||||
/// The ID of the node to attach the listener to.
|
||||
root: Option<u64>,
|
||||
},
|
||||
|
||||
/// Remove an existing Event Listener.
|
||||
RemoveEventListener {
|
||||
/// The ID of the node to remove.
|
||||
root: Option<u64>,
|
||||
|
||||
/// The name of the event to remove.
|
||||
event: &'static str,
|
||||
},
|
||||
|
||||
/// Set the textcontent of a node.
|
||||
SetText {
|
||||
/// The ID of the node to set the textcontent of.
|
||||
root: Option<u64>,
|
||||
|
||||
/// The textcontent of the node
|
||||
text: &'bump str,
|
||||
},
|
||||
|
||||
/// Set the value of a node's attribute.
|
||||
SetAttribute {
|
||||
/// The ID of the node to set the attribute of.
|
||||
root: Option<u64>,
|
||||
|
||||
/// The name of the attribute to set.
|
||||
field: &'static str,
|
||||
|
||||
/// The value of the attribute.
|
||||
value: AttributeValue<'bump>,
|
||||
|
||||
// value: &'bump str,
|
||||
/// The (optional) namespace of the attribute.
|
||||
/// For instance, "style" is in the "style" namespace.
|
||||
ns: Option<&'bump str>,
|
||||
},
|
||||
|
||||
/// Remove an attribute from a node.
|
||||
RemoveAttribute {
|
||||
/// The ID of the node to remove.
|
||||
root: Option<u64>,
|
||||
|
||||
/// The name of the attribute to remove.
|
||||
name: &'static str,
|
||||
|
||||
/// The namespace of the attribute.
|
||||
ns: Option<&'bump str>,
|
||||
},
|
||||
|
||||
/// Clones a node.
|
||||
CloneNode {
|
||||
/// The ID of the node to clone.
|
||||
id: Option<u64>,
|
||||
|
||||
/// The ID of the new node.
|
||||
new_id: u64,
|
||||
},
|
||||
|
||||
/// Clones the children of a node. (allows cloning fragments)
|
||||
CloneNodeChildren {
|
||||
/// The ID of the node to clone.
|
||||
id: Option<u64>,
|
||||
|
||||
/// The ID of the new node.
|
||||
new_ids: Vec<u64>,
|
||||
},
|
||||
|
||||
/// Navigates to the last node to the first child of the current node.
|
||||
FirstChild {},
|
||||
|
||||
/// Navigates to the last node to the last child of the current node.
|
||||
NextSibling {},
|
||||
|
||||
/// Navigates to the last node to the parent of the current node.
|
||||
ParentNode {},
|
||||
|
||||
/// Stores the last node with a new id.
|
||||
StoreWithId {
|
||||
/// The ID of the node to store.
|
||||
id: u64,
|
||||
},
|
||||
|
||||
/// Manually set the last node.
|
||||
SetLastNode {
|
||||
/// The ID to set the last node to.
|
||||
id: u64,
|
||||
},
|
||||
}
|
||||
|
||||
use rustc_hash::FxHashSet;
|
||||
use DomEdit::*;
|
||||
|
||||
#[allow(unused)]
|
||||
impl<'a> Mutations<'a> {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
edits: Vec::new(),
|
||||
refs: Vec::new(),
|
||||
dirty_scopes: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn replace_with(&mut self, root: Option<u64>, nodes: Vec<u64>) {
|
||||
self.edits.push(ReplaceWith { nodes, root });
|
||||
}
|
||||
|
||||
pub(crate) fn insert_after(&mut self, root: Option<u64>, nodes: Vec<u64>) {
|
||||
self.edits.push(InsertAfter { nodes, root });
|
||||
}
|
||||
|
||||
pub(crate) fn insert_before(&mut self, root: Option<u64>, nodes: Vec<u64>) {
|
||||
self.edits.push(InsertBefore { nodes, root });
|
||||
}
|
||||
|
||||
pub(crate) fn append_children(&mut self, root: Option<u64>, children: Vec<u64>) {
|
||||
self.edits.push(AppendChildren { root, children });
|
||||
}
|
||||
|
||||
// Remove Nodes from the dom
|
||||
pub(crate) fn remove(&mut self, id: Option<u64>) {
|
||||
self.edits.push(Remove { root: id });
|
||||
}
|
||||
|
||||
// Create
|
||||
pub(crate) fn create_text_node(&mut self, text: &'a str, id: Option<u64>) {
|
||||
self.edits.push(CreateTextNode { text, root: id });
|
||||
}
|
||||
|
||||
pub(crate) fn create_element(
|
||||
&mut self,
|
||||
tag: &'static str,
|
||||
ns: Option<&'static str>,
|
||||
id: Option<u64>,
|
||||
children: u32,
|
||||
) {
|
||||
match ns {
|
||||
Some(ns) => self.edits.push(CreateElementNs {
|
||||
root: id,
|
||||
ns,
|
||||
tag,
|
||||
children,
|
||||
}),
|
||||
None => self.edits.push(CreateElement {
|
||||
root: id,
|
||||
tag,
|
||||
children,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
// 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: Option<u64>) {
|
||||
self.edits.push(CreatePlaceholder { root: id });
|
||||
}
|
||||
|
||||
// events
|
||||
pub(crate) fn new_event_listener(&mut self, listener: &Listener, scope: ScopeId) {
|
||||
let Listener {
|
||||
event,
|
||||
mounted_node,
|
||||
..
|
||||
} = listener;
|
||||
|
||||
let element_id = Some(mounted_node.get().unwrap().into());
|
||||
|
||||
self.edits.push(NewEventListener {
|
||||
scope,
|
||||
event_name: event,
|
||||
root: element_id,
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn remove_event_listener(&mut self, event: &'static str, root: Option<u64>) {
|
||||
self.edits.push(RemoveEventListener { event, root });
|
||||
}
|
||||
|
||||
// modify
|
||||
pub(crate) fn set_text(&mut self, text: &'a str, root: Option<u64>) {
|
||||
self.edits.push(SetText { text, root });
|
||||
}
|
||||
|
||||
pub(crate) fn set_attribute(&mut self, attribute: &'a Attribute<'a>, root: Option<u64>) {
|
||||
let Attribute {
|
||||
value, attribute, ..
|
||||
} = attribute;
|
||||
|
||||
self.edits.push(SetAttribute {
|
||||
field: attribute.name,
|
||||
value: value.clone(),
|
||||
ns: attribute.namespace,
|
||||
root,
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn remove_attribute(&mut self, attribute: &Attribute, root: Option<u64>) {
|
||||
let Attribute { attribute, .. } = attribute;
|
||||
|
||||
self.edits.push(RemoveAttribute {
|
||||
name: attribute.name,
|
||||
ns: attribute.namespace,
|
||||
root,
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn mark_dirty_scope(&mut self, scope: ScopeId) {
|
||||
self.dirty_scopes.insert(scope);
|
||||
}
|
||||
|
||||
pub(crate) fn clone_node(&mut self, id: Option<u64>, new_id: u64) {
|
||||
self.edits.push(CloneNode { id, new_id });
|
||||
}
|
||||
|
||||
pub(crate) fn clone_node_children(&mut self, id: Option<u64>, new_ids: Vec<u64>) {
|
||||
self.edits.push(CloneNodeChildren { id, new_ids });
|
||||
}
|
||||
|
||||
pub(crate) fn first_child(&mut self) {
|
||||
self.edits.push(FirstChild {});
|
||||
}
|
||||
|
||||
pub(crate) fn next_sibling(&mut self) {
|
||||
self.edits.push(NextSibling {});
|
||||
}
|
||||
|
||||
pub(crate) fn parent_node(&mut self) {
|
||||
self.edits.push(ParentNode {});
|
||||
}
|
||||
|
||||
pub(crate) fn store_with_id(&mut self, id: u64) {
|
||||
self.edits.push(StoreWithId { id });
|
||||
}
|
||||
|
||||
pub(crate) fn set_last_node(&mut self, id: u64) {
|
||||
self.edits.push(SetLastNode { id });
|
||||
}
|
||||
}
|
||||
|
||||
// refs are only assigned once
|
||||
pub struct NodeRefMutation<'a> {
|
||||
pub element: &'a mut Option<once_cell::sync::OnceCell<Box<dyn Any>>>,
|
||||
pub element_id: ElementId,
|
||||
}
|
||||
|
||||
impl<'a> std::fmt::Debug for NodeRefMutation<'a> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("NodeRefMutation")
|
||||
.field("element_id", &self.element_id)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> NodeRefMutation<'a> {
|
||||
pub fn downcast_ref<T: 'static>(&self) -> Option<&T> {
|
||||
self.element
|
||||
.as_ref()
|
||||
.and_then(|f| f.get())
|
||||
.and_then(|f| f.downcast_ref::<T>())
|
||||
}
|
||||
pub fn downcast_mut<T: 'static>(&mut self) -> Option<&mut T> {
|
||||
self.element
|
||||
.as_mut()
|
||||
.and_then(|f| f.get_mut())
|
||||
.and_then(|f| f.downcast_mut::<T>())
|
||||
}
|
||||
/// Remove the targeted node from the DOM
|
||||
fn remove(&mut self, root: ElementId);
|
||||
/// Remove an attribute from an existing element
|
||||
fn remove_attribute(&mut self, attribute: &Attribute, root: ElementId);
|
||||
|
||||
/// Attach a new listener to the dom
|
||||
fn new_event_listener(&mut self, listener: &Listener, scope: ScopeId);
|
||||
/// Remove an existing listener from the dom
|
||||
fn remove_event_listener(&mut self, event: &'static str, root: ElementId);
|
||||
|
||||
/// Set the text content of a node
|
||||
fn set_text(&mut self, text: &'a str, root: ElementId);
|
||||
/// Set an attribute on an element
|
||||
fn set_attribute(&mut self, attribute: &'a Attribute<'a>, root: ElementId);
|
||||
|
||||
/// Save the current n nodes to the ID to be loaded later
|
||||
fn save(&mut self, id: &str, num: u32);
|
||||
/// Loads a set of saved nodes from the ID
|
||||
fn load(&mut self, id: &str);
|
||||
|
||||
// General statistics for doing things that extend outside of the renderer
|
||||
|
||||
///
|
||||
fn mark_dirty_scope(&mut self, scope: ScopeId);
|
||||
}
|
||||
@@ -3,22 +3,18 @@
|
||||
//! 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::{
|
||||
dynamic_template_context::TemplateContext,
|
||||
innerlude::{
|
||||
AttributeValue, ComponentPtr, Element, IntoAttributeValue, Properties, Scope, ScopeId,
|
||||
ScopeState, Template, TemplateId,
|
||||
},
|
||||
innerlude::{AttributeValue, ComponentPtr, Element, Properties, Scope, ScopeId, ScopeState},
|
||||
lazynodes::LazyNodes,
|
||||
template::VTemplateRef,
|
||||
AnyEvent, Component,
|
||||
};
|
||||
use bumpalo::{boxed::Box as BumpBox, Bump};
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
fmt::{Arguments, Debug, Formatter},
|
||||
rc::Rc,
|
||||
};
|
||||
|
||||
use crate::template::*;
|
||||
|
||||
/// 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:
|
||||
@@ -101,26 +97,10 @@ pub enum VNode<'src> {
|
||||
/// ```
|
||||
Component(&'src VComponent<'src>),
|
||||
|
||||
/// Placeholders are a type of placeholder VNode used when fragments don't contain any children.
|
||||
/// Templates are containers for other nodes
|
||||
///
|
||||
/// Placeholders cannot be directly constructed via public APIs.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust, ignore
|
||||
/// let mut vdom = VirtualDom::new();
|
||||
///
|
||||
/// let node = vdom.render_vnode(rsx!( Fragment {} ));
|
||||
///
|
||||
/// if let VNode::Fragment(frag) = node {
|
||||
/// let root = &frag.children[0];
|
||||
/// assert_eq!(root, VNode::Anchor);
|
||||
/// }
|
||||
/// ```
|
||||
Placeholder(&'src VPlaceholder),
|
||||
|
||||
/// Templetes ase generated by the rsx macro to eleminate diffing static nodes.
|
||||
TemplateRef(&'src VTemplateRef<'src>),
|
||||
Template(&'src VTemplate<'src>),
|
||||
}
|
||||
|
||||
impl<'src> VNode<'src> {
|
||||
@@ -129,10 +109,9 @@ impl<'src> VNode<'src> {
|
||||
match &self {
|
||||
VNode::Element(el) => el.key,
|
||||
VNode::Component(c) => c.key,
|
||||
VNode::Fragment(f) => f.key,
|
||||
VNode::Text(_t) => None,
|
||||
VNode::Placeholder(_f) => None,
|
||||
VNode::TemplateRef(t) => t.dynamic_context.key,
|
||||
VNode::Template(_t) => None,
|
||||
VNode::Fragment(_f) => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,10 +129,9 @@ impl<'src> VNode<'src> {
|
||||
match &self {
|
||||
VNode::Text(el) => el.id.get(),
|
||||
VNode::Element(el) => el.id.get(),
|
||||
VNode::Placeholder(el) => el.id.get(),
|
||||
VNode::Fragment(_) => None,
|
||||
VNode::Component(_) => None,
|
||||
VNode::TemplateRef(_) => None,
|
||||
VNode::Template(_) => todo!(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,9 +141,8 @@ impl<'src> VNode<'src> {
|
||||
VNode::Text(t) => VNode::Text(t),
|
||||
VNode::Element(e) => VNode::Element(e),
|
||||
VNode::Component(c) => VNode::Component(c),
|
||||
VNode::Placeholder(a) => VNode::Placeholder(a),
|
||||
VNode::Fragment(f) => VNode::Fragment(f),
|
||||
VNode::TemplateRef(t) => VNode::TemplateRef(t),
|
||||
VNode::Template(_) => todo!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -186,10 +163,6 @@ impl Debug for VNode<'_> {
|
||||
.field("text", &t.text)
|
||||
.field("id", &t.id)
|
||||
.finish(),
|
||||
VNode::Placeholder(t) => s
|
||||
.debug_struct("VNode::Placholder")
|
||||
.field("id", &t.id)
|
||||
.finish(),
|
||||
VNode::Fragment(frag) => s
|
||||
.debug_struct("VNode::Fragment")
|
||||
.field("children", &frag.children)
|
||||
@@ -201,10 +174,7 @@ 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)
|
||||
.finish(),
|
||||
VNode::Template(_) => todo!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -214,8 +184,6 @@ 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 {
|
||||
@@ -224,19 +192,13 @@ impl std::fmt::Display for ElementId {
|
||||
}
|
||||
|
||||
impl ElementId {
|
||||
/// Convert the ElementId to a `u64`.
|
||||
pub fn as_u64(&self) -> u64 {
|
||||
(*self).into()
|
||||
/// Convertt the ElementId to a `u64`.
|
||||
pub fn as_u64(self) -> u64 {
|
||||
self.0 as u64
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ElementId> for u64 {
|
||||
fn from(el: ElementId) -> u64 {
|
||||
el.0 as u64
|
||||
}
|
||||
}
|
||||
|
||||
fn empty_cell<T>() -> Cell<Option<T>> {
|
||||
fn empty_cell() -> Cell<Option<ElementId>> {
|
||||
Cell::new(None)
|
||||
}
|
||||
|
||||
@@ -264,12 +226,20 @@ pub struct VFragment<'src> {
|
||||
/// The key of the fragment to be used during keyed diffing.
|
||||
pub key: Option<&'src str>,
|
||||
|
||||
pub memo: Option<FragmentMemo<'src>>,
|
||||
|
||||
/// Fragments can never have zero children. Enforced by NodeFactory.
|
||||
///
|
||||
/// You *can* make a fragment with no children, but it's not a valid fragment and your VDom will panic.
|
||||
pub children: &'src [VNode<'src>],
|
||||
}
|
||||
|
||||
pub struct FragmentMemo<'a> {
|
||||
pub template: TemplateDef<'static>,
|
||||
|
||||
pub dynamic_nodes: &'a Cell<[ElementId]>,
|
||||
}
|
||||
|
||||
/// An element like a "div" with children, listeners, and attributes.
|
||||
pub struct VElement<'a> {
|
||||
/// The [`ElementId`] of the VText.
|
||||
@@ -354,52 +324,30 @@ 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 discription of the attribute.
|
||||
pub attribute: AttributeDiscription,
|
||||
/// The name of the attribute.
|
||||
pub name: &'static str,
|
||||
|
||||
/// The value of the attribute.
|
||||
pub value: AttributeValue<'a>,
|
||||
|
||||
/// 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,
|
||||
|
||||
/// The value of the attribute.
|
||||
pub value: AttributeValue<'a>,
|
||||
/// 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>,
|
||||
}
|
||||
|
||||
/// An event listener.
|
||||
@@ -466,11 +414,9 @@ impl<'a, T> Default for EventHandler<'a, T> {
|
||||
impl<T> EventHandler<'_, T> {
|
||||
/// Call this event handler with the appropriate event type
|
||||
pub fn call(&self, event: T) {
|
||||
log::trace!("calling event handler");
|
||||
if let Some(callback) = self.callback.borrow_mut().as_mut() {
|
||||
callback(event);
|
||||
}
|
||||
log::trace!("done");
|
||||
}
|
||||
|
||||
/// Forcibly drop the internal handler callback, releasing memory
|
||||
@@ -647,35 +593,21 @@ impl<'a> NodeFactory<'a> {
|
||||
}))
|
||||
}
|
||||
|
||||
/// Create a new [`Attribute`] from a attribute discrimination and a value
|
||||
pub fn attr_disciption(
|
||||
&self,
|
||||
discription: AttributeDiscription,
|
||||
val: impl IntoAttributeValue<'a>,
|
||||
) -> Attribute<'a> {
|
||||
Attribute {
|
||||
attribute: discription,
|
||||
is_static: false,
|
||||
value: val.into_value(self.bump),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new [`Attribute`]
|
||||
pub fn attr(
|
||||
&self,
|
||||
name: &'static str,
|
||||
val: impl IntoAttributeValue<'a>,
|
||||
val: Arguments,
|
||||
namespace: Option<&'static str>,
|
||||
is_volatile: bool,
|
||||
) -> Attribute<'a> {
|
||||
let (value, is_static) = self.raw_text(val);
|
||||
Attribute {
|
||||
attribute: AttributeDiscription {
|
||||
name,
|
||||
namespace,
|
||||
volatile: is_volatile,
|
||||
},
|
||||
is_static: false,
|
||||
value: val.into_value(self.bump),
|
||||
name,
|
||||
value: AttributeValue::Text(value),
|
||||
is_static,
|
||||
namespace,
|
||||
is_volatile,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -689,13 +621,11 @@ impl<'a> NodeFactory<'a> {
|
||||
is_static: bool,
|
||||
) -> Attribute<'a> {
|
||||
Attribute {
|
||||
attribute: AttributeDiscription {
|
||||
name,
|
||||
namespace,
|
||||
volatile: is_volatile,
|
||||
},
|
||||
is_static,
|
||||
name,
|
||||
value,
|
||||
is_static,
|
||||
namespace,
|
||||
is_volatile,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -746,59 +676,67 @@ impl<'a> NodeFactory<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new [`VNode::Fragment`] from a root of the rsx! call
|
||||
pub fn fragment_root<'b, 'c>(
|
||||
self,
|
||||
node_iter: impl IntoIterator<Item = impl IntoVNode<'a> + 'c> + 'b,
|
||||
) -> VNode<'a> {
|
||||
let mut nodes = bumpalo::collections::Vec::new_in(self.bump);
|
||||
|
||||
for node in node_iter {
|
||||
nodes.push(node.into_vnode(self));
|
||||
}
|
||||
|
||||
if nodes.is_empty() {
|
||||
VNode::Placeholder(self.bump.alloc(VPlaceholder { id: empty_cell() }))
|
||||
} else {
|
||||
VNode::Fragment(self.bump.alloc(VFragment {
|
||||
children: nodes.into_bump_slice(),
|
||||
key: None,
|
||||
}))
|
||||
}
|
||||
pub fn template(&self, def: &'static TemplateDef, dynamic_nodes: &'a [VNode<'a>]) -> VNode<'a> {
|
||||
VNode::Template(self.bump.alloc(VTemplate {
|
||||
def,
|
||||
dynamic_nodes,
|
||||
rendered_nodes: &[],
|
||||
}))
|
||||
}
|
||||
|
||||
/// Create a new [`VNode::Fragment`] from any iterator
|
||||
pub fn fragment_from_iter<'c, I, J>(
|
||||
self,
|
||||
node_iter: impl IntoVNode<'a, I, J> + 'c,
|
||||
) -> VNode<'a> {
|
||||
node_iter.into_vnode(self)
|
||||
}
|
||||
// /// Create a new [`VNode::Fragment`] from a root of the rsx! call
|
||||
// pub fn fragment_root<'b, 'c>(
|
||||
// self,
|
||||
// node_iter: impl IntoIterator<Item = impl IntoVNode<'a> + 'c> + 'b,
|
||||
// ) -> VNode<'a> {
|
||||
// let mut nodes = bumpalo::collections::Vec::new_in(self.bump);
|
||||
|
||||
/// Create a new [`VNode`] from any iterator of children
|
||||
pub fn create_children(
|
||||
self,
|
||||
node_iter: impl IntoIterator<Item = impl IntoVNode<'a>>,
|
||||
) -> Element<'a> {
|
||||
let mut nodes = bumpalo::collections::Vec::new_in(self.bump);
|
||||
// for node in node_iter {
|
||||
// nodes.push(node.into_vnode(self));
|
||||
// }
|
||||
|
||||
for node in node_iter {
|
||||
nodes.push(node.into_vnode(self));
|
||||
}
|
||||
// if nodes.is_empty() {
|
||||
// VNode::Placeholder(self.bump.alloc(VPlaceholder { id: empty_cell() }))
|
||||
// } else {
|
||||
// VNode::Fragment(self.bump.alloc(VFragment {
|
||||
// children: nodes.into_bump_slice(),
|
||||
// key: None,
|
||||
// }))
|
||||
// }
|
||||
// }
|
||||
|
||||
if nodes.is_empty() {
|
||||
Some(VNode::Placeholder(
|
||||
self.bump.alloc(VPlaceholder { id: empty_cell() }),
|
||||
))
|
||||
} else {
|
||||
let children = nodes.into_bump_slice();
|
||||
// /// Create a new [`VNode::Fragment`] from any iterator
|
||||
// pub fn fragment_from_iter<'c, I, J>(
|
||||
// self,
|
||||
// node_iter: impl IntoVNode<'a, I, J> + 'c,
|
||||
// ) -> VNode<'a> {
|
||||
// node_iter.into_vnode(self)
|
||||
// }
|
||||
|
||||
Some(VNode::Fragment(self.bump.alloc(VFragment {
|
||||
children,
|
||||
key: None,
|
||||
})))
|
||||
}
|
||||
}
|
||||
// /// Create a new [`VNode`] from any iterator of children
|
||||
// pub fn create_children(
|
||||
// self,
|
||||
// node_iter: impl IntoIterator<Item = impl IntoVNode<'a>>,
|
||||
// ) -> Element<'a> {
|
||||
// let mut nodes = bumpalo::collections::Vec::new_in(self.bump);
|
||||
|
||||
// for node in node_iter {
|
||||
// nodes.push(node.into_vnode(self));
|
||||
// }
|
||||
|
||||
// if nodes.is_empty() {
|
||||
// Some(VNode::Placeholder(
|
||||
// self.bump.alloc(VPlaceholder { id: empty_cell() }),
|
||||
// ))
|
||||
// } else {
|
||||
// let children = nodes.into_bump_slice();
|
||||
|
||||
// Some(VNode::Fragment(self.bump.alloc(VFragment {
|
||||
// children,
|
||||
// key: None,
|
||||
// })))
|
||||
// }
|
||||
// }
|
||||
|
||||
/// Create a new [`EventHandler`] from an [`FnMut`]
|
||||
pub fn event_handler<T>(self, f: impl FnMut(T) + 'a) -> EventHandler<'a, T> {
|
||||
@@ -807,29 +745,6 @@ 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 {
|
||||
dynamic_context,
|
||||
template_id: id,
|
||||
node_ids: RefCell::new(Vec::new()),
|
||||
parent: Cell::new(None),
|
||||
template_ref_id: Cell::new(None),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
impl Debug for NodeFactory<'_> {
|
||||
@@ -869,7 +784,8 @@ impl<'a> IntoVNode<'a> for VNode<'a> {
|
||||
// Conveniently, we also support "null" (nothing) passed in
|
||||
impl IntoVNode<'_> for () {
|
||||
fn into_vnode(self, cx: NodeFactory) -> VNode {
|
||||
VNode::Placeholder(cx.bump.alloc(VPlaceholder { id: empty_cell() }))
|
||||
todo!()
|
||||
// VNode::Placeholder(cx.bump.alloc(VPlaceholder { id: empty_cell() }))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -918,32 +834,33 @@ where
|
||||
nodes.push(node.into_vnode(cx));
|
||||
}
|
||||
|
||||
if nodes.is_empty() {
|
||||
VNode::Placeholder(cx.bump.alloc(VPlaceholder { id: empty_cell() }))
|
||||
} else {
|
||||
let children = nodes.into_bump_slice();
|
||||
todo!()
|
||||
// if nodes.is_empty() {
|
||||
// VNode::Placeholder(cx.bump.alloc(VPlaceholder { id: empty_cell() }))
|
||||
// } else {
|
||||
// let children = nodes.into_bump_slice();
|
||||
|
||||
if cfg!(debug_assertions)
|
||||
&& children.len() > 1
|
||||
&& children.last().unwrap().key().is_none()
|
||||
{
|
||||
// todo: make the backtrace prettier or remove it altogether
|
||||
log::error!(
|
||||
r#"
|
||||
Warning: Each child in an array or iterator should have a unique "key" prop.
|
||||
Not providing a key will lead to poor performance with lists.
|
||||
See docs.rs/dioxus for more information.
|
||||
-------------
|
||||
{:?}
|
||||
"#,
|
||||
backtrace::Backtrace::new()
|
||||
);
|
||||
}
|
||||
// if cfg!(debug_assertions)
|
||||
// && children.len() > 1
|
||||
// && children.last().unwrap().key().is_none()
|
||||
// {
|
||||
// // todo: make the backtrace prettier or remove it altogether
|
||||
// log::error!(
|
||||
// r#"
|
||||
// Warning: Each child in an array or iterator should have a unique "key" prop.
|
||||
// Not providing a key will lead to poor performance with lists.
|
||||
// See docs.rs/dioxus for more information.
|
||||
// -------------
|
||||
// {:?}
|
||||
// "#,
|
||||
// backtrace::Backtrace::new()
|
||||
// );
|
||||
// }
|
||||
|
||||
VNode::Fragment(cx.bump.alloc(VFragment {
|
||||
children,
|
||||
key: None,
|
||||
}))
|
||||
}
|
||||
// VNode::Fragment(cx.bump.alloc(VFragment {
|
||||
// children,
|
||||
// key: None,
|
||||
// }))
|
||||
// }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
use std::{
|
||||
any::Any,
|
||||
fmt::{Arguments, Display, Formatter},
|
||||
};
|
||||
|
||||
use bumpalo::Bump;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Possible values for an attribute
|
||||
// trying to keep values at 3 bytes
|
||||
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[cfg_attr(feature = "serialize", serde(untagged))]
|
||||
#[derive(Clone, PartialEq)]
|
||||
#[allow(missing_docs)]
|
||||
pub enum AttributeValue<'a> {
|
||||
Text(&'a str),
|
||||
Float32(f32),
|
||||
Bool(bool),
|
||||
Any(ArbitraryAttributeValue<'a>),
|
||||
}
|
||||
|
||||
impl<'a> Display for AttributeValue<'a> {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for AttributeValue<'_> {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
todo!()
|
||||
// match self {
|
||||
// AttributeValue::Text(s) => write!(f, "AttributeValue::Text({:?})", s),
|
||||
// AttributeValue::Float32(f) => write!(f, "AttributeValue::Float32({:?})", f),
|
||||
// AttributeValue::Bool(b) => write!(f, "AttributeValue::Bool({:?})", b),
|
||||
// AttributeValue::Any(a) => write!(f, "AttributeValue::Any({:?})", a),
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
/// A value that can be converted into an attribute value
|
||||
pub trait IntoAttributeValue<'a> {
|
||||
/// Convert into an attribute value
|
||||
fn into_value(self, bump: &'a Bump) -> AttributeValue<'a>;
|
||||
}
|
||||
impl<'a> IntoAttributeValue<'a> for f32 {
|
||||
fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
|
||||
AttributeValue::Float32(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoAttributeValue<'a> for bool {
|
||||
fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
|
||||
AttributeValue::Bool(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoAttributeValue<'a> for &'a str {
|
||||
fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
|
||||
AttributeValue::Text(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoAttributeValue<'a> for Arguments<'_> {
|
||||
fn into_value(self, bump: &'a Bump) -> AttributeValue<'a> {
|
||||
use bumpalo::core_alloc::fmt::Write;
|
||||
let mut str_buf = bumpalo::collections::String::new_in(bump);
|
||||
str_buf.write_fmt(self).unwrap();
|
||||
AttributeValue::Text(str_buf.into_bump_str())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> IntoAttributeValue<'a> for &'a T
|
||||
where
|
||||
T: PartialEq,
|
||||
{
|
||||
fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
|
||||
todo!()
|
||||
// AttributeValue::Any(ArbitraryAttributeValue {
|
||||
// value: self,
|
||||
// cmp: |a, b| {
|
||||
// if let Some(a) = a.as_any().downcast_ref::<T>() {
|
||||
// if let Some(b) = b.as_any().downcast_ref::<T>() {
|
||||
// a == b
|
||||
// } else {
|
||||
// false
|
||||
// }
|
||||
// } else {
|
||||
// false
|
||||
// }
|
||||
// },
|
||||
// })
|
||||
}
|
||||
}
|
||||
|
||||
// todo
|
||||
#[allow(missing_docs)]
|
||||
impl<'a> AttributeValue<'a> {
|
||||
pub fn is_truthy(&self) -> bool {
|
||||
match self {
|
||||
AttributeValue::Text(t) => *t == "true",
|
||||
AttributeValue::Bool(t) => *t,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_falsy(&self) -> bool {
|
||||
match self {
|
||||
AttributeValue::Text(t) => *t == "false",
|
||||
AttributeValue::Bool(t) => !(*t),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
#[allow(missing_docs)]
|
||||
pub struct ArbitraryAttributeValue<'a> {
|
||||
pub value: &'a dyn Any,
|
||||
// pub value: &'a dyn AnyClone,
|
||||
// pub cmp: fn(&dyn AnyClone, &dyn AnyClone) -> bool,
|
||||
}
|
||||
|
||||
#[cfg(feature = "serialize")]
|
||||
impl<'a> Serialize for ArbitraryAttributeValue<'a> {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "serialize")]
|
||||
impl<'a, 'de> Deserialize<'de> for ArbitraryAttributeValue<'a> {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for ArbitraryAttributeValue<'_> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
todo!()
|
||||
// (self.cmp)(self.value, other.value)
|
||||
}
|
||||
}
|
||||
|
||||
// todo
|
||||
#[allow(missing_docs)]
|
||||
impl<'a> AttributeValue<'a> {
|
||||
pub fn as_text(&self) -> Option<&'a str> {
|
||||
match self {
|
||||
AttributeValue::Text(s) => Some(s),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_float32(&self) -> Option<f32> {
|
||||
match self {
|
||||
AttributeValue::Float32(f) => Some(*f),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_any(&self) -> Option<&'a ArbitraryAttributeValue> {
|
||||
match self {
|
||||
AttributeValue::Any(a) => Some(a),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
use crate::{
|
||||
innerlude::{ComponentPtr, Element, Scope, ScopeId, ScopeState},
|
||||
Component,
|
||||
};
|
||||
use std::cell::{Cell, RefCell};
|
||||
|
||||
/// Virtual Components for custom user-defined components
|
||||
/// Only supports the functional syntax
|
||||
pub struct VComponent<'src> {
|
||||
/// The key of the component to be used during keyed diffing.
|
||||
pub key: Option<&'src str>,
|
||||
|
||||
/// The ID of the component.
|
||||
/// Will not be assigned until after the component has been initialized.
|
||||
pub scope: Cell<Option<ScopeId>>,
|
||||
|
||||
/// An indication if the component is static (can be memozied)
|
||||
pub can_memoize: bool,
|
||||
|
||||
/// The function pointer to the component's render function.
|
||||
pub user_fc: ComponentPtr,
|
||||
|
||||
/// The actual name of the component.
|
||||
pub fn_name: &'static str,
|
||||
|
||||
/// The props of the component.
|
||||
pub props: RefCell<Option<Box<dyn AnyProps + 'src>>>,
|
||||
}
|
||||
|
||||
pub(crate) struct VComponentProps<P> {
|
||||
pub render_fn: Component<P>,
|
||||
pub memo: unsafe fn(&P, &P) -> bool,
|
||||
pub props: P,
|
||||
}
|
||||
|
||||
pub trait AnyProps {
|
||||
fn as_ptr(&self) -> *const ();
|
||||
fn render<'a>(&'a self, bump: &'a ScopeState) -> Element<'a>;
|
||||
unsafe fn memoize(&self, other: &dyn AnyProps) -> bool;
|
||||
}
|
||||
|
||||
impl<P> AnyProps for VComponentProps<P> {
|
||||
fn as_ptr(&self) -> *const () {
|
||||
&self.props as *const _ as *const ()
|
||||
}
|
||||
|
||||
// Safety:
|
||||
// this will downcast the other ptr as our swallowed type!
|
||||
// you *must* make this check *before* calling this method
|
||||
// if your functions are not the same, then you will downcast a pointer into a different type (UB)
|
||||
unsafe fn memoize(&self, other: &dyn AnyProps) -> bool {
|
||||
let real_other: &P = &*(other.as_ptr() as *const _ as *const P);
|
||||
let real_us: &P = &*(self.as_ptr() as *const _ as *const P);
|
||||
(self.memo)(real_us, real_other)
|
||||
}
|
||||
|
||||
fn render<'a>(&'a self, scope: &'a ScopeState) -> Element<'a> {
|
||||
let props = unsafe { std::mem::transmute::<&P, &P>(&self.props) };
|
||||
(self.render_fn)(Scope { scope, props })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
use crate::{innerlude::AttributeValue, AnyEvent, ElementId, VNode};
|
||||
use bumpalo::boxed::Box as BumpBox;
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
fmt::{Debug, Formatter},
|
||||
};
|
||||
|
||||
/// An element like a "div" with children, listeners, and attributes.
|
||||
pub struct VElement<'a> {
|
||||
/// The [`ElementId`] of the VText.
|
||||
pub id: Cell<Option<ElementId>>,
|
||||
|
||||
/// The key of the element to be used during keyed diffing.
|
||||
pub key: Option<&'a str>,
|
||||
|
||||
/// The tag name of the element.
|
||||
///
|
||||
/// IE "div"
|
||||
pub tag: &'static str,
|
||||
|
||||
/// The namespace of the VElement
|
||||
///
|
||||
/// IE "svg"
|
||||
pub namespace: Option<&'static str>,
|
||||
|
||||
/// The parent of the Element (if any).
|
||||
///
|
||||
/// Used when bubbling events
|
||||
pub parent: Cell<Option<ElementId>>,
|
||||
|
||||
/// The Listeners of the VElement.
|
||||
pub listeners: &'a [Listener<'a>],
|
||||
|
||||
/// The attributes of the VElement.
|
||||
pub attributes: &'a [Attribute<'a>],
|
||||
|
||||
/// The children of the VElement.
|
||||
pub children: &'a [VNode<'a>],
|
||||
}
|
||||
|
||||
impl Debug for VElement<'_> {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("VElement")
|
||||
.field("tag_name", &self.tag)
|
||||
.field("namespace", &self.namespace)
|
||||
.field("key", &self.key)
|
||||
.field("id", &self.id)
|
||||
.field("parent", &self.parent)
|
||||
.field("listeners", &self.listeners.len())
|
||||
.field("attributes", &self.attributes)
|
||||
.field("children", &self.children)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 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>,
|
||||
|
||||
/// An indication of we should always try and set the attribute.
|
||||
/// Used in controlled components to ensure changes are propagated.
|
||||
pub volatile: bool,
|
||||
|
||||
/// The value of the attribute.
|
||||
pub value: AttributeValue<'a>,
|
||||
}
|
||||
|
||||
/// An event listener.
|
||||
/// IE onclick, onkeydown, etc
|
||||
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>>,
|
||||
|
||||
/// The type of event to listen for.
|
||||
///
|
||||
/// IE "click" - whatever the renderer needs to attach the listener by name.
|
||||
pub event: &'static str,
|
||||
|
||||
/// The actual callback that the user specified
|
||||
pub(crate) callback: InternalHandler<'bump>,
|
||||
}
|
||||
|
||||
pub type InternalHandler<'bump> = &'bump RefCell<Option<InternalListenerCallback<'bump>>>;
|
||||
type InternalListenerCallback<'bump> = BumpBox<'bump, dyn FnMut(AnyEvent) + 'bump>;
|
||||
type ExternalListenerCallback<'bump, T> = BumpBox<'bump, dyn FnMut(T) + 'bump>;
|
||||
|
||||
/// The callback type generated by the `rsx!` macro when an `on` field is specified for components.
|
||||
///
|
||||
/// This makes it possible to pass `move |evt| {}` style closures into components as property fields.
|
||||
///
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust, ignore
|
||||
///
|
||||
/// rsx!{
|
||||
/// MyComponent { onclick: move |evt| log::info!("clicked"), }
|
||||
/// }
|
||||
///
|
||||
/// #[derive(Props)]
|
||||
/// struct MyProps<'a> {
|
||||
/// onclick: EventHandler<'a, MouseEvent>,
|
||||
/// }
|
||||
///
|
||||
/// fn MyComponent(cx: Scope<'a, MyProps<'a>>) -> Element {
|
||||
/// cx.render(rsx!{
|
||||
/// button {
|
||||
/// onclick: move |evt| cx.props.onclick.call(evt),
|
||||
/// }
|
||||
/// })
|
||||
/// }
|
||||
///
|
||||
/// ```
|
||||
pub struct EventHandler<'bump, T = ()> {
|
||||
/// The (optional) callback that the user specified
|
||||
/// Uses a `RefCell` to allow for interior mutability, and FnMut closures.
|
||||
pub callback: RefCell<Option<ExternalListenerCallback<'bump, T>>>,
|
||||
}
|
||||
|
||||
impl<'a, T> Default for EventHandler<'a, T> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
callback: RefCell::new(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> EventHandler<'_, T> {
|
||||
/// Call this event handler with the appropriate event type
|
||||
pub fn call(&self, event: T) {
|
||||
if let Some(callback) = self.callback.borrow_mut().as_mut() {
|
||||
callback(event);
|
||||
}
|
||||
}
|
||||
|
||||
/// Forcibly drop the internal handler callback, releasing memory
|
||||
pub fn release(&self) {
|
||||
self.callback.replace(None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
use crate::{innerlude::*, Attribute, Listener, VElement, VNode, VText};
|
||||
use bumpalo::{boxed::Box as BumpBox, Bump};
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
fmt::{Arguments, Debug},
|
||||
};
|
||||
|
||||
/// This struct provides an ergonomic API to quickly build VNodes.
|
||||
///
|
||||
/// NodeFactory is used to build VNodes in the component's memory space.
|
||||
/// This struct adds metadata to the final VNode about listeners, attributes, and children
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct NodeFactory<'a> {
|
||||
pub(crate) scope: &'a ScopeState,
|
||||
pub(crate) bump: &'a Bump,
|
||||
}
|
||||
|
||||
impl<'a> NodeFactory<'a> {
|
||||
/// Create a new [`NodeFactory`] from a [`Scope`] or [`ScopeState`]
|
||||
pub fn new(scope: &'a ScopeState) -> NodeFactory<'a> {
|
||||
NodeFactory {
|
||||
scope,
|
||||
bump: &scope.wip_frame().bump,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the custom allocator for this component
|
||||
#[inline]
|
||||
pub fn bump(&self) -> &'a bumpalo::Bump {
|
||||
self.bump
|
||||
}
|
||||
|
||||
/// Directly pass in text blocks without the need to use the format_args macro.
|
||||
pub fn static_text(&self, text: &'static str) -> VNode<'a> {
|
||||
VNode::Text(self.bump.alloc(VText {
|
||||
id: Default::default(),
|
||||
text,
|
||||
is_static: true,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Parses a lazy text Arguments and returns a string and a flag indicating if the text is 'static
|
||||
///
|
||||
/// Text that's static may be pointer compared, making it cheaper to diff
|
||||
pub fn raw_text(&self, args: Arguments) -> (&'a str, bool) {
|
||||
match args.as_str() {
|
||||
Some(static_str) => (static_str, true),
|
||||
None => {
|
||||
use bumpalo::core_alloc::fmt::Write;
|
||||
let mut str_buf = bumpalo::collections::String::new_in(self.bump);
|
||||
str_buf.write_fmt(args).unwrap();
|
||||
(str_buf.into_bump_str(), false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Create some text that's allocated along with the other vnodes
|
||||
///
|
||||
pub fn text(&self, args: Arguments) -> VNode<'a> {
|
||||
let (text, is_static) = self.raw_text(args);
|
||||
|
||||
VNode::Text(self.bump.alloc(VText {
|
||||
text,
|
||||
is_static,
|
||||
id: Default::default(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Create a new [`VNode::Element`] without the trait bound
|
||||
///
|
||||
/// IE pass in "div" instead of `div`
|
||||
pub fn raw_element(
|
||||
&self,
|
||||
tag_name: &'static str,
|
||||
namespace: Option<&'static str>,
|
||||
listeners: &'a [Listener<'a>],
|
||||
attributes: &'a [Attribute<'a>],
|
||||
children: &'a [VNode<'a>],
|
||||
key: Option<Arguments>,
|
||||
) -> VNode<'a> {
|
||||
let key = key.map(|f| self.raw_text(f).0);
|
||||
|
||||
let mut items = self.scope.items.borrow_mut();
|
||||
for listener in listeners {
|
||||
let long_listener = unsafe { std::mem::transmute(listener) };
|
||||
items.listeners.push(long_listener);
|
||||
}
|
||||
|
||||
VNode::Element(self.bump.alloc(VElement {
|
||||
tag: tag_name,
|
||||
key,
|
||||
namespace,
|
||||
listeners,
|
||||
attributes,
|
||||
children,
|
||||
id: Default::default(),
|
||||
parent: Default::default(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Create a new [`Attribute`]
|
||||
pub fn attr(
|
||||
&self,
|
||||
name: &'static str,
|
||||
val: impl IntoAttributeValue<'a>,
|
||||
namespace: Option<&'static str>,
|
||||
is_volatile: bool,
|
||||
) -> Attribute<'a> {
|
||||
Attribute {
|
||||
name,
|
||||
namespace,
|
||||
volatile: is_volatile,
|
||||
value: val.into_value(self.bump),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new [`Attribute`] using non-arguments
|
||||
pub fn custom_attr(
|
||||
&self,
|
||||
name: &'static str,
|
||||
value: AttributeValue<'a>,
|
||||
namespace: Option<&'static str>,
|
||||
is_volatile: bool,
|
||||
) -> Attribute<'a> {
|
||||
Attribute {
|
||||
name,
|
||||
namespace,
|
||||
volatile: is_volatile,
|
||||
value,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new [`VNode::Component`]
|
||||
pub fn component<P>(
|
||||
&self,
|
||||
component: fn(Scope<'a, P>) -> Element,
|
||||
props: P,
|
||||
key: Option<Arguments>,
|
||||
fn_name: &'static str,
|
||||
) -> VNode<'a>
|
||||
where
|
||||
P: Properties + 'a,
|
||||
{
|
||||
let vcomp = self.bump.alloc(VComponent {
|
||||
key: key.map(|f| self.raw_text(f).0),
|
||||
scope: Default::default(),
|
||||
can_memoize: P::IS_STATIC,
|
||||
user_fc: component as ComponentPtr,
|
||||
fn_name,
|
||||
props: RefCell::new(Some(Box::new(VComponentProps {
|
||||
props,
|
||||
memo: P::memoize, // smuggle the memoization function across borders
|
||||
|
||||
// i'm sorry but I just need to bludgeon the lifetimes into place here
|
||||
// this is safe because we're managing all lifetimes to originate from previous calls
|
||||
// the intricacies of Rust's lifetime system make it difficult to properly express
|
||||
// the transformation from this specific lifetime to the for<'a> lifetime
|
||||
render_fn: unsafe { std::mem::transmute(component) },
|
||||
}))),
|
||||
});
|
||||
|
||||
if !P::IS_STATIC {
|
||||
let vcomp = &*vcomp;
|
||||
let vcomp = unsafe { std::mem::transmute(vcomp) };
|
||||
self.scope.items.borrow_mut().borrowed_props.push(vcomp);
|
||||
}
|
||||
|
||||
VNode::Component(vcomp)
|
||||
}
|
||||
|
||||
/// Create a new [`Listener`]
|
||||
pub fn listener(self, event: &'static str, callback: InternalHandler<'a>) -> Listener<'a> {
|
||||
Listener {
|
||||
event,
|
||||
mounted_node: Cell::new(None),
|
||||
callback,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new [`VNode::Fragment`] from a root of the rsx! call
|
||||
pub fn fragment_root<'b, 'c>(
|
||||
self,
|
||||
node_iter: impl IntoIterator<Item = impl IntoVNode<'a> + 'c> + 'b,
|
||||
) -> VNode<'a> {
|
||||
let mut nodes = bumpalo::collections::Vec::new_in(self.bump);
|
||||
|
||||
for node in node_iter {
|
||||
nodes.push(node.into_vnode(self));
|
||||
}
|
||||
|
||||
VNode::Fragment(self.bump.alloc(VFragment {
|
||||
children: nodes.into_bump_slice(),
|
||||
placeholder: Default::default(),
|
||||
key: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Create a new [`VNode::Fragment`] from any iterator
|
||||
pub fn fragment_from_iter<'c, I, J>(
|
||||
self,
|
||||
node_iter: impl IntoVNode<'a, I, J> + 'c,
|
||||
) -> VNode<'a> {
|
||||
node_iter.into_vnode(self)
|
||||
}
|
||||
|
||||
/// Create a new [`VNode`] from any iterator of children
|
||||
pub fn create_children(
|
||||
self,
|
||||
node_iter: impl IntoIterator<Item = impl IntoVNode<'a>>,
|
||||
) -> Element<'a> {
|
||||
let mut nodes = bumpalo::collections::Vec::new_in(self.bump);
|
||||
|
||||
for node in node_iter {
|
||||
nodes.push(node.into_vnode(self));
|
||||
}
|
||||
|
||||
let children = nodes.into_bump_slice();
|
||||
|
||||
Some(VNode::Fragment(self.bump.alloc(VFragment {
|
||||
children,
|
||||
key: None,
|
||||
placeholder: Default::default(),
|
||||
})))
|
||||
}
|
||||
|
||||
/// Create a new [`EventHandler`] from an [`FnMut`]
|
||||
pub fn event_handler<T>(self, f: impl FnMut(T) + 'a) -> EventHandler<'a, T> {
|
||||
let handler: &mut dyn FnMut(T) = self.bump.alloc(f);
|
||||
let caller = unsafe { BumpBox::from_raw(handler as *mut dyn FnMut(T)) };
|
||||
let callback = RefCell::new(Some(caller));
|
||||
EventHandler { callback }
|
||||
}
|
||||
|
||||
/// Create a refrence to a template
|
||||
pub fn template_ref(
|
||||
&self,
|
||||
template: Template,
|
||||
nodes: &'a [VNode<'a>],
|
||||
attributes: &'a [Attribute<'a>],
|
||||
listeners: &'a [Listener<'a>],
|
||||
key: Option<Arguments>,
|
||||
) -> 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)));
|
||||
// }
|
||||
todo!()
|
||||
// VNode::TemplateRef(self.bump.alloc(VTemplate {
|
||||
// dynamic_context,
|
||||
// template_id: id,
|
||||
// node_ids: RefCell::new(Vec::new()),
|
||||
// parent: Cell::new(None),
|
||||
// template_ref_id: Cell::new(None),
|
||||
// }))
|
||||
}
|
||||
}
|
||||
|
||||
impl Debug for NodeFactory<'_> {
|
||||
fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait implementations for use in the rsx! and html! macros.
|
||||
///
|
||||
/// ## Details
|
||||
///
|
||||
/// This section provides convenience methods and trait implementations for converting common structs into a format accepted
|
||||
/// by the macros.
|
||||
///
|
||||
/// All dynamic content in the macros must flow in through `fragment_from_iter`. Everything else must be statically layed out.
|
||||
/// We pipe basically everything through `fragment_from_iter`, so we expect a very specific type:
|
||||
/// ```rust, ignore
|
||||
/// impl IntoIterator<Item = impl IntoVNode<'a>>
|
||||
/// ```
|
||||
///
|
||||
/// As such, all node creation must go through the factory, which is only available in the component context.
|
||||
/// These strict requirements make it possible to manage lifetimes and state.
|
||||
pub trait IntoVNode<'a, I = (), J = ()> {
|
||||
/// Convert this into a [`VNode`], using the [`NodeFactory`] as a source of allocation
|
||||
fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a>;
|
||||
}
|
||||
|
||||
// TODO: do we even need this? It almost seems better not to
|
||||
// // For the case where a rendered VNode is passed into the rsx! macro through curly braces
|
||||
impl<'a> IntoVNode<'a> for VNode<'a> {
|
||||
fn into_vnode(self, _: NodeFactory<'a>) -> VNode<'a> {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, 'b> IntoVNode<'a> for LazyNodes<'a, '_> {
|
||||
fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
|
||||
self.call(cx)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'b> IntoVNode<'_> for &'b str {
|
||||
fn into_vnode(self, cx: NodeFactory) -> VNode {
|
||||
cx.text(format_args!("{}", self))
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoVNode<'_> for String {
|
||||
fn into_vnode(self, cx: NodeFactory) -> VNode {
|
||||
cx.text(format_args!("{}", self))
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoVNode<'_> for Arguments<'_> {
|
||||
fn into_vnode(self, cx: NodeFactory) -> VNode {
|
||||
cx.text(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoVNode<'a> for &VNode<'a> {
|
||||
fn into_vnode(self, _cx: NodeFactory<'a>) -> VNode<'a> {
|
||||
// borrowed nodes are strange
|
||||
self.decouple()
|
||||
}
|
||||
}
|
||||
|
||||
// Note that we're using the E as a generic but this is never crafted anyways.
|
||||
pub struct FromNodeIterator;
|
||||
impl<'a, T, I, E> IntoVNode<'a, FromNodeIterator, E> for T
|
||||
where
|
||||
T: IntoIterator<Item = I>,
|
||||
I: IntoVNode<'a, E>,
|
||||
{
|
||||
fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
|
||||
let mut nodes = bumpalo::collections::Vec::new_in(cx.bump);
|
||||
|
||||
for node in self {
|
||||
nodes.push(node.into_vnode(cx));
|
||||
}
|
||||
|
||||
let children = nodes.into_bump_slice();
|
||||
|
||||
if cfg!(debug_assertions) && children.len() > 1 && children.last().unwrap().key().is_none()
|
||||
{
|
||||
// let bt = backtrace::Backtrace::new();
|
||||
let bt = "no backtrace available";
|
||||
|
||||
// todo: make the backtrace prettier or remove it altogether
|
||||
log::error!(
|
||||
r#"
|
||||
Warning: Each child in an array or iterator should have a unique "key" prop.
|
||||
Not providing a key will lead to poor performance with lists.
|
||||
See docs.rs/dioxus for more information.
|
||||
-------------
|
||||
{:?}
|
||||
"#,
|
||||
bt
|
||||
);
|
||||
}
|
||||
|
||||
VNode::Fragment(cx.bump.alloc(VFragment {
|
||||
children,
|
||||
placeholder: Default::default(),
|
||||
key: None,
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
use crate::{ElementId, VNode};
|
||||
use std::cell::Cell;
|
||||
|
||||
/// A list of VNodes with no single root.
|
||||
pub struct VFragment<'src> {
|
||||
/// The key of the fragment to be used during keyed diffing.
|
||||
pub key: Option<&'src str>,
|
||||
|
||||
/// The [`ElementId`] of the placeholder.
|
||||
pub placeholder: Cell<Option<ElementId>>,
|
||||
|
||||
/// Fragments can never have zero children. Enforced by NodeFactory.
|
||||
///
|
||||
/// You *can* make a fragment with no children, but it's not a valid fragment and your VDom will panic.
|
||||
pub children: &'src [VNode<'src>],
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
//! Virtual Node Support
|
||||
//!
|
||||
//! VNodes represent lazily-constructed VDom trees that support diffing and event handlers. These VNodes should be *very*
|
||||
//! cheap and *very* fast to construct - building a full tree should be quick.
|
||||
|
||||
use std::fmt::{Debug, Formatter};
|
||||
|
||||
mod arbitrary_value;
|
||||
mod component;
|
||||
mod element;
|
||||
mod factory;
|
||||
mod fragment;
|
||||
mod suspense;
|
||||
mod template;
|
||||
mod text;
|
||||
|
||||
pub use arbitrary_value::*;
|
||||
pub use component::*;
|
||||
pub use element::*;
|
||||
pub use factory::*;
|
||||
pub use fragment::*;
|
||||
pub use suspense::*;
|
||||
pub use template::*;
|
||||
pub use text::*;
|
||||
|
||||
/// 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:
|
||||
///
|
||||
/// - the `rsx!` macro
|
||||
/// - the [`NodeFactory`] API
|
||||
pub enum VNode<'src> {
|
||||
/// Text VNodes are simply bump-allocated (or static) string slices
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust, ignore
|
||||
/// let mut vdom = VirtualDom::new();
|
||||
/// let node = vdom.render_vnode(rsx!( "hello" ));
|
||||
///
|
||||
/// if let VNode::Text(vtext) = node {
|
||||
/// assert_eq!(vtext.text, "hello");
|
||||
/// assert_eq!(vtext.dom_id.get(), None);
|
||||
/// assert_eq!(vtext.is_static, true);
|
||||
/// }
|
||||
/// ```
|
||||
Text(&'src VText<'src>),
|
||||
|
||||
/// Element VNodes are VNodes that may contain attributes, listeners, a key, a tag, and children.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust, ignore
|
||||
/// let mut vdom = VirtualDom::new();
|
||||
///
|
||||
/// let node = vdom.render_vnode(rsx!{
|
||||
/// div {
|
||||
/// key: "a",
|
||||
/// onclick: |e| log::info!("clicked"),
|
||||
/// hidden: "true",
|
||||
/// style: { background_color: "red" },
|
||||
/// "hello"
|
||||
/// }
|
||||
/// });
|
||||
///
|
||||
/// if let VNode::Element(velement) = node {
|
||||
/// assert_eq!(velement.tag_name, "div");
|
||||
/// assert_eq!(velement.namespace, None);
|
||||
/// assert_eq!(velement.key, Some("a"));
|
||||
/// }
|
||||
/// ```
|
||||
Element(&'src VElement<'src>),
|
||||
|
||||
/// Fragment nodes may contain many VNodes without a single root.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust, ignore
|
||||
/// rsx!{
|
||||
/// a {}
|
||||
/// link {}
|
||||
/// style {}
|
||||
/// "asd"
|
||||
/// Example {}
|
||||
/// }
|
||||
/// ```
|
||||
Fragment(&'src VFragment<'src>),
|
||||
|
||||
/// Component nodes represent a mounted component with props, children, and a key.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust, ignore
|
||||
/// fn Example(cx: Scope) -> Element {
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// let mut vdom = VirtualDom::new();
|
||||
///
|
||||
/// let node = vdom.render_vnode(rsx!( Example {} ));
|
||||
///
|
||||
/// if let VNode::Component(vcomp) = node {
|
||||
/// assert_eq!(vcomp.user_fc, Example as *const ());
|
||||
/// }
|
||||
/// ```
|
||||
Component(&'src VComponent<'src>),
|
||||
|
||||
/// Templetes ase generated by the rsx macro to eleminate diffing static nodes.
|
||||
///
|
||||
///
|
||||
///
|
||||
///
|
||||
///
|
||||
///
|
||||
Template(&'src VTemplate<'src>),
|
||||
}
|
||||
|
||||
/// An Element's unique identifier.
|
||||
///
|
||||
/// `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<'src> VNode<'src> {
|
||||
/// Get the VNode's "key" used in the keyed diffing algorithm.
|
||||
pub fn key(&self) -> Option<&'src str> {
|
||||
match &self {
|
||||
VNode::Element(el) => el.key,
|
||||
VNode::Component(c) => c.key,
|
||||
VNode::Fragment(f) => f.key,
|
||||
VNode::Text(_t) => None,
|
||||
VNode::Template(t) => t.key,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the ElementID of the mounted VNode.
|
||||
///
|
||||
/// Panics if the mounted ID is None or if the VNode is not represented by a single Element.
|
||||
pub fn mounted_id(&self) -> ElementId {
|
||||
self.try_mounted_id().unwrap()
|
||||
}
|
||||
|
||||
/// Try to get the ElementID of the mounted VNode.
|
||||
///
|
||||
/// Returns None if the VNode is not mounted, or if the VNode cannot be presented by a mounted ID (Fragment/Component)
|
||||
pub fn try_mounted_id(&self) -> Option<ElementId> {
|
||||
match &self {
|
||||
VNode::Text(el) => el.id.get(),
|
||||
VNode::Element(el) => el.id.get(),
|
||||
VNode::Fragment(_) => None,
|
||||
VNode::Component(_) => None,
|
||||
VNode::Template(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
// Create an "owned" version of the vnode.
|
||||
pub(crate) fn decouple(&self) -> VNode<'src> {
|
||||
match *self {
|
||||
VNode::Text(t) => VNode::Text(t),
|
||||
VNode::Element(e) => VNode::Element(e),
|
||||
VNode::Component(c) => VNode::Component(c),
|
||||
VNode::Fragment(f) => VNode::Fragment(f),
|
||||
VNode::Template(t) => VNode::Template(t),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Debug for VNode<'_> {
|
||||
fn fmt(&self, s: &mut Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
|
||||
match &self {
|
||||
VNode::Element(el) => s
|
||||
.debug_struct("VNode::Element")
|
||||
.field("name", &el.tag)
|
||||
.field("key", &el.key)
|
||||
.field("attrs", &el.attributes)
|
||||
.field("children", &el.children)
|
||||
.field("id", &el.id)
|
||||
.finish(),
|
||||
VNode::Text(t) => s
|
||||
.debug_struct("VNode::Text")
|
||||
.field("text", &t.text)
|
||||
.field("id", &t.id)
|
||||
.finish(),
|
||||
VNode::Fragment(frag) => s
|
||||
.debug_struct("VNode::Fragment")
|
||||
.field("children", &frag.children)
|
||||
.finish(),
|
||||
VNode::Component(comp) => s
|
||||
.debug_struct("VNode::Component")
|
||||
.field("name", &comp.fn_name)
|
||||
.field("fnptr", &comp.user_fc)
|
||||
.field("key", &comp.key)
|
||||
.field("scope", &comp.scope)
|
||||
.finish(),
|
||||
VNode::Template(temp) => s
|
||||
.debug_struct("VNode::Templates")
|
||||
.field("template_id", &temp.template.id)
|
||||
.finish(),
|
||||
}
|
||||
}
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,60 @@
|
||||
use std::hash::Hash;
|
||||
|
||||
use crate::{Attribute, ElementId, Listener, VNode};
|
||||
|
||||
/// A reference to a template along with any context needed to hydrate it
|
||||
pub struct VTemplate<'a> {
|
||||
pub key: Option<&'a str>,
|
||||
|
||||
pub template: Template<'static>,
|
||||
|
||||
pub dynamic_nodes: &'a [VNode<'a>],
|
||||
|
||||
pub dynamic_attrs: &'a [Attribute<'a>],
|
||||
|
||||
pub listeners: &'a [Listener<'a>],
|
||||
}
|
||||
|
||||
/// A template that is created at compile time
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Template<'a> {
|
||||
/// name, line, col, or some sort of identifier
|
||||
pub id: &'static str,
|
||||
|
||||
/// All the roots of the template. ie rsx! { div {} div{} } would have two roots
|
||||
pub roots: &'a [TemplateNode<'a>],
|
||||
}
|
||||
|
||||
impl<'a> Eq for Template<'a> {}
|
||||
|
||||
impl<'a> PartialEq for Template<'a> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.id == other.id
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Hash for Template<'a> {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.id.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
/// A weird-ish variant of VNodes with way more limited types
|
||||
pub enum TemplateNode<'a> {
|
||||
Element {
|
||||
tag: &'static str,
|
||||
attrs: &'a [TemplateAttribute],
|
||||
children: &'a [TemplateNode<'a>],
|
||||
},
|
||||
Text(&'static str),
|
||||
Dynamic(usize),
|
||||
}
|
||||
|
||||
pub enum TemplateAttribute {
|
||||
// todo: more values
|
||||
Static {
|
||||
name: &'static str,
|
||||
value: &'static str,
|
||||
},
|
||||
Dynamic(usize),
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::{
|
||||
innerlude::{
|
||||
AttributeValue, ComponentPtr, Element, IntoAttributeValue, Properties, Scope, ScopeId,
|
||||
ScopeState, Template,
|
||||
},
|
||||
AnyEvent, Component, ElementId,
|
||||
};
|
||||
use bumpalo::{boxed::Box as BumpBox, Bump};
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
fmt::{Arguments, Debug, Formatter},
|
||||
};
|
||||
|
||||
/// A bump-allocated string slice and metadata.
|
||||
pub struct VText<'src> {
|
||||
/// The [`ElementId`] of the VText.
|
||||
pub id: Cell<Option<ElementId>>,
|
||||
|
||||
/// The text of the VText.
|
||||
pub text: &'src str,
|
||||
|
||||
/// An indiciation if this VText can be ignored during diffing
|
||||
/// Is usually only when there are no strings to be formatted (so the text is &'static str)
|
||||
pub is_static: bool,
|
||||
}
|
||||
@@ -64,36 +64,36 @@ impl<'a> Properties for FragmentProps<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Create inline fragments using Component syntax.
|
||||
///
|
||||
/// ## Details
|
||||
///
|
||||
/// Fragments capture a series of children without rendering extra nodes.
|
||||
///
|
||||
/// Creating fragments explicitly with the Fragment component is particularly useful when rendering lists or tables and
|
||||
/// a key is needed to identify each item.
|
||||
///
|
||||
/// ## Example
|
||||
///
|
||||
/// ```rust, ignore
|
||||
/// rsx!{
|
||||
/// Fragment { key: "abc" }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// Fragments are incredibly useful when necessary, but *do* add cost in the diffing phase.
|
||||
/// Try to avoid highly nested fragments if you can. Unlike React, there is no protection against infinitely nested fragments.
|
||||
///
|
||||
/// This function defines a dedicated `Fragment` component that can be used to create inline fragments in the RSX macro.
|
||||
///
|
||||
/// You want to use this free-function when your fragment needs a key and simply returning multiple nodes from rsx! won't cut it.
|
||||
#[allow(non_upper_case_globals, non_snake_case)]
|
||||
pub fn Fragment<'a>(cx: Scope<'a, FragmentProps<'a>>) -> Element {
|
||||
let i = cx.props.0.as_ref().map(|f| f.decouple());
|
||||
cx.render(LazyNodes::new(|f| f.fragment_from_iter(i)))
|
||||
}
|
||||
// /// Create inline fragments using Component syntax.
|
||||
// ///
|
||||
// /// ## Details
|
||||
// ///
|
||||
// /// Fragments capture a series of children without rendering extra nodes.
|
||||
// ///
|
||||
// /// Creating fragments explicitly with the Fragment component is particularly useful when rendering lists or tables and
|
||||
// /// a key is needed to identify each item.
|
||||
// ///
|
||||
// /// ## Example
|
||||
// ///
|
||||
// /// ```rust, ignore
|
||||
// /// rsx!{
|
||||
// /// Fragment { key: "abc" }
|
||||
// /// }
|
||||
// /// ```
|
||||
// ///
|
||||
// /// ## Usage
|
||||
// ///
|
||||
// /// Fragments are incredibly useful when necessary, but *do* add cost in the diffing phase.
|
||||
// /// Try to avoid highly nested fragments if you can. Unlike React, there is no protection against infinitely nested fragments.
|
||||
// ///
|
||||
// /// This function defines a dedicated `Fragment` component that can be used to create inline fragments in the RSX macro.
|
||||
// ///
|
||||
// /// You want to use this free-function when your fragment needs a key and simply returning multiple nodes from rsx! won't cut it.
|
||||
// #[allow(non_upper_case_globals, non_snake_case)]
|
||||
// pub fn Fragment<'a>(cx: Scope<'a, FragmentProps<'a>>) -> Element {
|
||||
// let i = cx.props.0.as_ref().map(|f| f.decouple());
|
||||
// cx.render(LazyNodes::new(|f| f.fragment_from_iter(i)))
|
||||
// }
|
||||
|
||||
/// Every "Props" used for a component must implement the `Properties` trait. This trait gives some hints to Dioxus
|
||||
/// on how to memoize the props and some additional optimizations that can be made. We strongly encourage using the
|
||||
|
||||
+90
-185
@@ -1,10 +1,11 @@
|
||||
use crate::{innerlude::*, template::TemplateNodeId, unsafe_utils::extend_vnode};
|
||||
use crate::{innerlude::*, unsafe_utils::extend_vnode};
|
||||
use bumpalo::Bump;
|
||||
use futures_channel::mpsc::UnboundedSender;
|
||||
use rustc_hash::FxHashMap;
|
||||
use fxhash::FxHashMap;
|
||||
use slab::Slab;
|
||||
use std::{
|
||||
any::{Any, TypeId},
|
||||
borrow::Borrow,
|
||||
cell::{Cell, RefCell},
|
||||
collections::{HashMap, HashSet},
|
||||
future::Future,
|
||||
@@ -13,17 +14,6 @@ use std::{
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
pub(crate) enum NodePtr {
|
||||
VNode(*const VNode<'static>),
|
||||
TemplateNode {
|
||||
template_ref: TemplateRefId,
|
||||
node_id: TemplateNodeId,
|
||||
},
|
||||
Phantom,
|
||||
}
|
||||
|
||||
pub(crate) type NodeSlab = Slab<NodePtr>;
|
||||
|
||||
/// for traceability, we use the raw fn pointer to identify the function
|
||||
/// we also get the component name, but that's not necessarily unique in the app
|
||||
pub(crate) type ComponentPtr = *mut std::os::raw::c_void;
|
||||
@@ -43,16 +33,9 @@ pub(crate) struct ScopeArena {
|
||||
pub scopes: RefCell<FxHashMap<ScopeId, *mut ScopeState>>,
|
||||
pub heuristics: RefCell<FxHashMap<ComponentPtr, Heuristic>>,
|
||||
pub free_scopes: RefCell<Vec<*mut ScopeState>>,
|
||||
// All nodes are stored here. This mimics the allocations needed on the renderer side.
|
||||
// Some allocations are needed on the renderer to render nodes in templates that are
|
||||
// not needed in dioxus, for these allocations None is used so that the id is preseved and passive memory managment is preserved.
|
||||
pub nodes: RefCell<NodeSlab>,
|
||||
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,
|
||||
pub template_refs: RefCell<Slab<*const VTemplateRef<'static>>>,
|
||||
pub template_cache: RefCell<HashSet<Template<'static>>>,
|
||||
}
|
||||
|
||||
impl ScopeArena {
|
||||
@@ -75,9 +58,7 @@ impl ScopeArena {
|
||||
|
||||
let node = bump.alloc(VNode::Element(el));
|
||||
let mut nodes = Slab::new();
|
||||
let root_id = nodes.insert(NodePtr::VNode(unsafe {
|
||||
std::mem::transmute(node as *const _)
|
||||
}));
|
||||
let root_id = nodes.insert(unsafe { std::mem::transmute(node as *const _) });
|
||||
|
||||
debug_assert_eq!(root_id, 0);
|
||||
|
||||
@@ -94,10 +75,7 @@ impl ScopeArena {
|
||||
gen: Cell::new(0),
|
||||
sender,
|
||||
}),
|
||||
template_resolver: RefCell::new(TemplateResolver::default()),
|
||||
templates: Rc::new(RefCell::new(FxHashMap::default())),
|
||||
template_bump: Bump::new(),
|
||||
template_refs: RefCell::new(Slab::new()),
|
||||
template_cache: RefCell::new(HashSet::new()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,6 +96,7 @@ impl ScopeArena {
|
||||
vcomp: Box<dyn AnyProps>,
|
||||
parent_scope: Option<ScopeId>,
|
||||
container: ElementId,
|
||||
subtree: u32,
|
||||
) -> ScopeId {
|
||||
// Increment the ScopeId system. ScopeIDs are never reused
|
||||
let new_scope_id = ScopeId(self.scope_gen.get());
|
||||
@@ -147,6 +126,7 @@ 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();
|
||||
@@ -177,6 +157,10 @@ 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(),
|
||||
@@ -190,8 +174,6 @@ impl ScopeArena {
|
||||
hook_arena: Bump::new(),
|
||||
hook_vals: RefCell::new(Vec::with_capacity(hook_capacity)),
|
||||
hook_idx: Cell::default(),
|
||||
|
||||
templates: self.templates.clone(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -227,61 +209,13 @@ impl ScopeArena {
|
||||
let key = entry.key();
|
||||
let id = ElementId(key);
|
||||
let node = unsafe { extend_vnode(node) };
|
||||
entry.insert(NodePtr::VNode(node as *const _));
|
||||
id
|
||||
}
|
||||
|
||||
pub fn reserve_template_ref<'a>(&self, template_ref: &'a VTemplateRef<'a>) -> TemplateRefId {
|
||||
let mut refs = self.template_refs.borrow_mut();
|
||||
let entry = refs.vacant_entry();
|
||||
let key = entry.key();
|
||||
let id = TemplateRefId(key);
|
||||
let static_ref: &VTemplateRef<'static> = unsafe { std::mem::transmute(template_ref) };
|
||||
entry.insert(static_ref as *const _);
|
||||
id
|
||||
}
|
||||
|
||||
pub fn reserve_template_node(
|
||||
&self,
|
||||
template_ref_id: TemplateRefId,
|
||||
node_id: TemplateNodeId,
|
||||
) -> ElementId {
|
||||
let mut els = self.nodes.borrow_mut();
|
||||
let entry = els.vacant_entry();
|
||||
let key = entry.key();
|
||||
let id = ElementId(key);
|
||||
entry.insert(NodePtr::TemplateNode {
|
||||
template_ref: template_ref_id,
|
||||
node_id,
|
||||
});
|
||||
id
|
||||
}
|
||||
|
||||
pub fn reserve_phantom_node(&self) -> ElementId {
|
||||
let mut els = self.nodes.borrow_mut();
|
||||
let entry = els.vacant_entry();
|
||||
let key = entry.key();
|
||||
let id = ElementId(key);
|
||||
entry.insert(NodePtr::Phantom);
|
||||
entry.insert(node as *const _);
|
||||
id
|
||||
}
|
||||
|
||||
pub fn update_node<'a>(&self, node: &'a VNode<'a>, id: ElementId) {
|
||||
let node = unsafe { extend_vnode(node) };
|
||||
*self.nodes.borrow_mut().get_mut(id.0).unwrap() = NodePtr::VNode(node);
|
||||
}
|
||||
|
||||
pub fn update_template_ref<'a>(
|
||||
&self,
|
||||
template_ref_id: TemplateRefId,
|
||||
template_ref: &'a VTemplateRef<'a>,
|
||||
) {
|
||||
let template_ref = unsafe { std::mem::transmute(template_ref) };
|
||||
*self
|
||||
.template_refs
|
||||
.borrow_mut()
|
||||
.get_mut(template_ref_id.0)
|
||||
.unwrap() = template_ref;
|
||||
*self.nodes.borrow_mut().get_mut(id.0).unwrap() = node;
|
||||
}
|
||||
|
||||
pub fn collect_garbage(&self, id: ElementId) {
|
||||
@@ -369,11 +303,11 @@ impl ScopeArena {
|
||||
frame.node.set(unsafe { extend_vnode(node) });
|
||||
} else {
|
||||
let frame = scope.wip_frame();
|
||||
let node = frame
|
||||
.bump
|
||||
.alloc(VNode::Placeholder(frame.bump.alloc(VPlaceholder {
|
||||
id: Cell::default(),
|
||||
})));
|
||||
let node = frame.bump.alloc(VNode::Text(frame.bump.alloc(VText {
|
||||
id: Cell::default(),
|
||||
text: "asd",
|
||||
is_static: false,
|
||||
})));
|
||||
frame.node.set(unsafe { extend_vnode(node) });
|
||||
}
|
||||
|
||||
@@ -389,92 +323,16 @@ impl ScopeArena {
|
||||
let state = Rc::new(BubbleState::new());
|
||||
|
||||
while let Some(id) = cur_el.take() {
|
||||
if state.canceled.get() {
|
||||
// stop bubbling if canceled
|
||||
return;
|
||||
}
|
||||
if let Some(ptr) = nodes.get(id.0) {
|
||||
match ptr {
|
||||
NodePtr::VNode(ptr) => {
|
||||
let real_el = unsafe { &**ptr };
|
||||
log::trace!("looking for listener on {:?}", real_el);
|
||||
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.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();
|
||||
}
|
||||
}
|
||||
NodePtr::TemplateNode {
|
||||
node_id,
|
||||
template_ref,
|
||||
} => {
|
||||
let template_refs = self.template_refs.borrow();
|
||||
let template_ptr = template_refs.get(template_ref.0).unwrap();
|
||||
let template_ref = unsafe { &**template_ptr };
|
||||
log::trace!("looking for listener in node {:?}", node_id);
|
||||
let templates = self.templates.borrow();
|
||||
let template = templates.get(&template_ref.template_id).unwrap();
|
||||
cur_el = template.borrow().with_nodes(
|
||||
bubble_template,
|
||||
bubble_template,
|
||||
(*node_id, template_ref, event, &state),
|
||||
);
|
||||
}
|
||||
_ => panic!("Expected Real Node"),
|
||||
}
|
||||
}
|
||||
|
||||
if !event.bubbles {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
fn bubble_template<'b, Attributes, V, Children, Listeners, TextSegments, Text, Nodes>(
|
||||
nodes: &Nodes,
|
||||
ctx: (
|
||||
TemplateNodeId,
|
||||
&VTemplateRef<'b>,
|
||||
&UserEvent,
|
||||
&Rc<BubbleState>,
|
||||
),
|
||||
) -> Option<ElementId>
|
||||
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 (start, template_ref, event, state) = ctx;
|
||||
let dynamic_context = &template_ref.dynamic_context;
|
||||
let mut current = &nodes.as_ref()[start.0];
|
||||
loop {
|
||||
if let TemplateNodeType::Element(el) = ¤t.node_type {
|
||||
let TemplateElement { listeners, .. } = el;
|
||||
for listener_idx in listeners.as_ref() {
|
||||
let listener = dynamic_context.resolve_listener(*listener_idx);
|
||||
if let VNode::Element(real_el) = real_el {
|
||||
for listener in real_el.listeners.borrow().iter() {
|
||||
if listener.event == event.name {
|
||||
log::trace!("calling listener {:?}", listener.event);
|
||||
if state.canceled.get() {
|
||||
// stop bubbling if canceled
|
||||
return;
|
||||
}
|
||||
|
||||
let mut cb = listener.callback.borrow_mut();
|
||||
if let Some(cb) = cb.as_mut() {
|
||||
@@ -487,17 +345,14 @@ impl ScopeArena {
|
||||
data: event.data.clone(),
|
||||
});
|
||||
}
|
||||
break;
|
||||
|
||||
if !event.bubbles {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(id) = current.parent {
|
||||
current = &nodes.as_ref()[id.0];
|
||||
} else {
|
||||
return template_ref.parent.get();
|
||||
}
|
||||
} else {
|
||||
return None;
|
||||
cur_el = real_el.parent.get();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -525,10 +380,11 @@ impl ScopeArena {
|
||||
|
||||
// this is totally okay since all our nodes are always in a valid state
|
||||
pub fn get_element(&self, id: ElementId) -> Option<&VNode> {
|
||||
self.nodes.borrow().get(id.0).and_then(|ptr| match ptr {
|
||||
NodePtr::VNode(ptr) => Some(unsafe { extend_vnode(&**ptr) }),
|
||||
_ => None,
|
||||
})
|
||||
self.nodes
|
||||
.borrow()
|
||||
.get(id.0)
|
||||
.copied()
|
||||
.map(|ptr| unsafe { extend_vnode(&*ptr) })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -613,6 +469,10 @@ pub struct ScopeState {
|
||||
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
|
||||
@@ -628,9 +488,6 @@ 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> {
|
||||
@@ -640,6 +497,52 @@ 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.
|
||||
@@ -1002,6 +905,8 @@ 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
@@ -34,13 +34,9 @@ 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::TemplateRef(_) => {
|
||||
VNode::Element(_) | VNode::Text(_) | VNode::Placeholder(_) => {
|
||||
// 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!");
|
||||
should_pop = true;
|
||||
returned_node = Some(&**node);
|
||||
}
|
||||
@@ -61,6 +57,8 @@ impl<'a> Iterator for ElementIdIterator<'a> {
|
||||
// Simply swap the current node on the stack with the root of the component
|
||||
*node = scope.root_node();
|
||||
}
|
||||
|
||||
VNode::Template(_) => todo!(),
|
||||
}
|
||||
} else {
|
||||
// If there's no more items on the stack, we're done!
|
||||
@@ -84,44 +82,3 @@ 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 once_cell::sync::Lazy;
|
||||
use rustc_hash::FxHashSet;
|
||||
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::*;
|
||||
+119
-162
@@ -6,8 +6,8 @@ use crate::diff::DiffState;
|
||||
use crate::innerlude::*;
|
||||
use futures_channel::mpsc::{UnboundedReceiver, UnboundedSender};
|
||||
use futures_util::{future::poll_fn, StreamExt};
|
||||
use fxhash::FxHashSet;
|
||||
use indexmap::IndexSet;
|
||||
use rustc_hash::FxHashSet;
|
||||
use std::{collections::VecDeque, iter::FromIterator, task::Poll};
|
||||
|
||||
/// A virtual node system that progresses user events and diffs UI trees.
|
||||
@@ -103,7 +103,6 @@ use std::{collections::VecDeque, iter::FromIterator, task::Poll};
|
||||
/// }
|
||||
/// ```
|
||||
pub struct VirtualDom {
|
||||
root: ElementId,
|
||||
scopes: ScopeArena,
|
||||
|
||||
pending_messages: VecDeque<SchedulerMsg>,
|
||||
@@ -129,10 +128,6 @@ 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),
|
||||
}
|
||||
@@ -232,10 +227,10 @@ impl VirtualDom {
|
||||
}),
|
||||
None,
|
||||
ElementId(0),
|
||||
0,
|
||||
);
|
||||
|
||||
Self {
|
||||
root: ElementId(0),
|
||||
scopes,
|
||||
channel,
|
||||
dirty_scopes: IndexSet::from_iter([ScopeId(0)]),
|
||||
@@ -403,25 +398,6 @@ 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -470,14 +446,14 @@ impl VirtualDom {
|
||||
/// apply_mutations(mutations);
|
||||
/// }
|
||||
/// ```
|
||||
#[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();
|
||||
|
||||
pub fn work_with_deadline<'a>(
|
||||
&'a mut self,
|
||||
renderer: &mut impl Renderer<'a>,
|
||||
mut deadline: impl FnMut() -> bool,
|
||||
) {
|
||||
while !self.dirty_scopes.is_empty() {
|
||||
let scopes = &self.scopes;
|
||||
let mut diff_state = DiffState::new(scopes);
|
||||
let mut diff_state = DiffState::new(scopes, renderer);
|
||||
|
||||
let mut ran_scopes = FxHashSet::default();
|
||||
|
||||
@@ -497,17 +473,18 @@ impl VirtualDom {
|
||||
|
||||
self.scopes.run_scope(scopeid);
|
||||
|
||||
diff_state.diff_scope(self.root, scopeid);
|
||||
diff_state.diff_scope(scopeid);
|
||||
|
||||
let DiffState { mutations, .. } = diff_state;
|
||||
|
||||
for scope in &mutations.dirty_scopes {
|
||||
self.dirty_scopes.remove(scope);
|
||||
}
|
||||
todo!()
|
||||
// for scope in &mutations.dirty_scopes {
|
||||
// self.dirty_scopes.remove(scope);
|
||||
// }
|
||||
|
||||
if !mutations.edits.is_empty() {
|
||||
committed_mutations.push(mutations);
|
||||
}
|
||||
// if !mutations.edits.is_empty() {
|
||||
// committed_mutations.push(mutations);
|
||||
// }
|
||||
|
||||
// todo: pause the diff machine
|
||||
// if diff_state.work(&mut deadline) {
|
||||
@@ -526,8 +503,6 @@ impl VirtualDom {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
committed_mutations
|
||||
}
|
||||
|
||||
/// Performs a *full* rebuild of the virtual dom, returning every edit required to generate the actual dom from scratch.
|
||||
@@ -547,26 +522,22 @@ impl VirtualDom {
|
||||
///
|
||||
/// apply_edits(edits);
|
||||
/// ```
|
||||
pub fn rebuild(&mut self) -> Mutations {
|
||||
pub fn rebuild<'a>(&'a mut self, dom: &mut impl Renderer<'a>) {
|
||||
let scope_id = ScopeId(0);
|
||||
let mut diff_state = DiffState::new(&self.scopes, dom);
|
||||
|
||||
let mut diff_state = DiffState::new(&self.scopes);
|
||||
self.scopes.run_scope(scope_id);
|
||||
|
||||
diff_state.element_stack.push(ElementId(0));
|
||||
diff_state.scope_stack.push(scope_id);
|
||||
|
||||
let node = self.scopes.fin_head(scope_id);
|
||||
let mut created = Vec::new();
|
||||
diff_state.create_node(self.root, node, &mut created);
|
||||
let created = diff_state.create_node(node);
|
||||
|
||||
diff_state
|
||||
.mutations
|
||||
.append_children(Some(self.root.as_u64()), created);
|
||||
diff_state.mutations.append_children(created as u32);
|
||||
|
||||
self.dirty_scopes.clear();
|
||||
assert!(self.dirty_scopes.is_empty());
|
||||
|
||||
diff_state.mutations
|
||||
}
|
||||
|
||||
/// Compute a manual diff of the VirtualDom between states.
|
||||
@@ -599,8 +570,8 @@ impl VirtualDom {
|
||||
///
|
||||
/// let edits = dom.hard_diff(ScopeId(0));
|
||||
/// ```
|
||||
pub fn hard_diff(&mut self, scope_id: ScopeId) -> Mutations {
|
||||
let mut diff_machine = DiffState::new(&self.scopes);
|
||||
pub fn hard_diff<'a>(&'a mut self, scope_id: ScopeId, dom: &mut impl Renderer<'a>) {
|
||||
let mut diff_machine = DiffState::new(&self.scopes, dom);
|
||||
self.scopes.run_scope(scope_id);
|
||||
|
||||
let (old, new) = (
|
||||
@@ -611,124 +582,108 @@ impl VirtualDom {
|
||||
diff_machine.force_diff = true;
|
||||
diff_machine.scope_stack.push(scope_id);
|
||||
let scope = diff_machine.scopes.get_scope(scope_id).unwrap();
|
||||
diff_machine.element_stack.push(scope.container);
|
||||
|
||||
diff_machine.diff_node(scope.container, old, new);
|
||||
|
||||
diff_machine.mutations
|
||||
diff_machine.diff_node(old, new);
|
||||
}
|
||||
|
||||
/// Renders an `rsx` call into the Base Scope's allocator.
|
||||
///
|
||||
/// Useful when needing to render nodes from outside the VirtualDom, such as in a test.
|
||||
///
|
||||
/// ```rust, ignore
|
||||
/// fn Base(cx: Scope) -> Element {
|
||||
/// render!(div {})
|
||||
/// }
|
||||
///
|
||||
/// let dom = VirtualDom::new(Base);
|
||||
/// let nodes = dom.render_nodes(rsx!("div"));
|
||||
/// ```
|
||||
pub fn render_vnodes<'a>(&'a self, lazy_nodes: LazyNodes<'a, '_>) -> &'a VNode<'a> {
|
||||
let scope = self.scopes.get_scope(ScopeId(0)).unwrap();
|
||||
let frame = scope.wip_frame();
|
||||
let factory = NodeFactory::new(scope);
|
||||
let node = lazy_nodes.call(factory);
|
||||
frame.bump.alloc(node)
|
||||
}
|
||||
// /// Renders an `rsx` call into the Base Scope's allocator.
|
||||
// ///
|
||||
// /// Useful when needing to render nodes from outside the VirtualDom, such as in a test.
|
||||
// ///
|
||||
// /// ```rust, ignore
|
||||
// /// fn Base(cx: Scope) -> Element {
|
||||
// /// render!(div {})
|
||||
// /// }
|
||||
// ///
|
||||
// /// let dom = VirtualDom::new(Base);
|
||||
// /// let nodes = dom.render_nodes(rsx!("div"));
|
||||
// /// ```
|
||||
// pub fn render_vnodes<'a>(&'a self, lazy_nodes: LazyNodes<'a, '_>) -> &'a VNode<'a> {
|
||||
// let scope = self.scopes.get_scope(ScopeId(0)).unwrap();
|
||||
// let frame = scope.wip_frame();
|
||||
// let factory = NodeFactory::new(scope);
|
||||
// let node = lazy_nodes.call(factory);
|
||||
// frame.bump.alloc(node)
|
||||
// }
|
||||
|
||||
/// Renders an `rsx` call into the Base Scope's allocator.
|
||||
///
|
||||
/// Useful when needing to render nodes from outside the VirtualDom, such as in a test.
|
||||
///
|
||||
/// ```rust, ignore
|
||||
/// fn Base(cx: Scope) -> Element {
|
||||
/// render!(div {})
|
||||
/// }
|
||||
///
|
||||
/// let dom = VirtualDom::new(Base);
|
||||
/// let nodes = dom.render_nodes(rsx!("div"));
|
||||
/// ```
|
||||
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.scope_stack.push(ScopeId(0));
|
||||
machine.diff_node(self.root, old, new);
|
||||
// /// Renders an `rsx` call into the Base Scope's allocator.
|
||||
// ///
|
||||
// /// Useful when needing to render nodes from outside the VirtualDom, such as in a test.
|
||||
// ///
|
||||
// /// ```rust, ignore
|
||||
// /// fn Base(cx: Scope) -> Element {
|
||||
// /// render!(div {})
|
||||
// /// }
|
||||
// ///
|
||||
// /// let dom = VirtualDom::new(Base);
|
||||
// /// let nodes = dom.render_nodes(rsx!("div"));
|
||||
// /// ```
|
||||
// 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.scope_stack.push(ScopeId(0));
|
||||
// machine.diff_node(old, new);
|
||||
|
||||
machine.mutations
|
||||
}
|
||||
// machine.mutations
|
||||
// }
|
||||
|
||||
/// Renders an `rsx` call into the Base Scope's allocator.
|
||||
///
|
||||
/// Useful when needing to render nodes from outside the VirtualDom, such as in a test.
|
||||
///
|
||||
///
|
||||
/// ```rust, ignore
|
||||
/// fn Base(cx: Scope) -> Element {
|
||||
/// render!(div {})
|
||||
/// }
|
||||
///
|
||||
/// let dom = VirtualDom::new(Base);
|
||||
/// let nodes = dom.render_nodes(rsx!("div"));
|
||||
/// ```
|
||||
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));
|
||||
let node = self.render_vnodes(nodes);
|
||||
let mut created = Vec::new();
|
||||
machine.create_node(self.root, node, &mut created);
|
||||
machine
|
||||
.mutations
|
||||
.append_children(Some(self.root.as_u64()), created);
|
||||
machine.mutations
|
||||
}
|
||||
// /// Renders an `rsx` call into the Base Scope's allocator.
|
||||
// ///
|
||||
// /// Useful when needing to render nodes from outside the VirtualDom, such as in a test.
|
||||
// ///
|
||||
// ///
|
||||
// /// ```rust, ignore
|
||||
// /// fn Base(cx: Scope) -> Element {
|
||||
// /// render!(div {})
|
||||
// /// }
|
||||
// ///
|
||||
// /// let dom = VirtualDom::new(Base);
|
||||
// /// let nodes = dom.render_nodes(rsx!("div"));
|
||||
// /// ```
|
||||
// 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));
|
||||
// let node = self.render_vnodes(nodes);
|
||||
// let created = machine.create_node(node);
|
||||
// machine.mutations.append_children(created as u32);
|
||||
// machine.mutations
|
||||
// }
|
||||
|
||||
/// Renders an `rsx` call into the Base Scopes's arena.
|
||||
///
|
||||
/// Useful when needing to diff two rsx! calls from outside the VirtualDom, such as in a test.
|
||||
///
|
||||
///
|
||||
/// ```rust, ignore
|
||||
/// fn Base(cx: Scope) -> Element {
|
||||
/// render!(div {})
|
||||
/// }
|
||||
///
|
||||
/// let dom = VirtualDom::new(Base);
|
||||
/// let nodes = dom.render_nodes(rsx!("div"));
|
||||
/// ```
|
||||
pub fn diff_lazynodes<'a>(
|
||||
&'a self,
|
||||
left: LazyNodes<'a, '_>,
|
||||
right: LazyNodes<'a, '_>,
|
||||
) -> (Mutations<'a>, Mutations<'a>) {
|
||||
let (old, new) = (self.render_vnodes(left), self.render_vnodes(right));
|
||||
// /// Renders an `rsx` call into the Base Scopes's arena.
|
||||
// ///
|
||||
// /// Useful when needing to diff two rsx! calls from outside the VirtualDom, such as in a test.
|
||||
// ///
|
||||
// ///
|
||||
// /// ```rust, ignore
|
||||
// /// fn Base(cx: Scope) -> Element {
|
||||
// /// render!(div {})
|
||||
// /// }
|
||||
// ///
|
||||
// /// let dom = VirtualDom::new(Base);
|
||||
// /// let nodes = dom.render_nodes(rsx!("div"));
|
||||
// /// ```
|
||||
// pub fn diff_lazynodes<'a>(
|
||||
// &'a self,
|
||||
// left: LazyNodes<'a, '_>,
|
||||
// right: LazyNodes<'a, '_>,
|
||||
// ) -> (Mutations<'a>, Mutations<'a>) {
|
||||
// let (old, new) = (self.render_vnodes(left), self.render_vnodes(right));
|
||||
|
||||
let mut create = DiffState::new(&self.scopes);
|
||||
create.scope_stack.push(ScopeId(0));
|
||||
let mut created = Vec::new();
|
||||
create.create_node(self.root, old, &mut created);
|
||||
create
|
||||
.mutations
|
||||
.append_children(Some(self.root.as_u64()), created);
|
||||
// let mut create = DiffState::new(&self.scopes);
|
||||
// create.scope_stack.push(ScopeId(0));
|
||||
// create.element_stack.push(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.diff_node(self.root, old, new);
|
||||
// let mut edit = DiffState::new(&self.scopes);
|
||||
// edit.scope_stack.push(ScopeId(0));
|
||||
// edit.element_stack.push(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()
|
||||
}
|
||||
// (create.mutations, edit.mutations)
|
||||
// }
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -762,8 +717,10 @@ impl Drop for VirtualDom {
|
||||
|
||||
// todo: move the remove nodes method onto scopearena
|
||||
// this will clear *all* scopes *except* the root scope
|
||||
let mut machine = DiffState::new(&self.scopes);
|
||||
machine.remove_nodes([scope.root_node()], false);
|
||||
// let mut machine = DiffState::new(&self.scopes);
|
||||
// machine.remove_nodes([scope.root_node()], false);
|
||||
|
||||
todo!("drop the root scope without leaking anything");
|
||||
|
||||
// Now, clean up the root scope
|
||||
// safety: there are no more references to the root scope
|
||||
|
||||
Reference in new issue
Block a user