wip: rewrite core to be template focused
This commit is contained in:
1 parent
67012c38df
commit
23603aaaf5
34 files changed
+3177
-2456
No files matched your search
@@ -0,0 +1,163 @@
|
||||
use std::{
|
||||
any::Any,
|
||||
fmt::{Arguments, Formatter},
|
||||
};
|
||||
|
||||
use bumpalo::Bump;
|
||||
|
||||
/// Possible values for an attribute
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum AttributeValue<'a> {
|
||||
/// Reference strs, most common
|
||||
Text(&'a str),
|
||||
/// Basic float values
|
||||
Float(f32),
|
||||
/// Basic Int values
|
||||
Int(i32),
|
||||
/// Basic bool values
|
||||
Bool(bool),
|
||||
/// Everything else
|
||||
Any(&'a dyn AnyAttributeValue),
|
||||
}
|
||||
|
||||
impl<'a> PartialEq for AttributeValue<'a> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
match (self, other) {
|
||||
(Self::Text(l0), Self::Text(r0)) => l0 == r0,
|
||||
(Self::Float(l0), Self::Float(r0)) => l0 == r0,
|
||||
(Self::Int(l0), Self::Int(r0)) => l0 == r0,
|
||||
(Self::Bool(l0), Self::Bool(r0)) => l0 == r0,
|
||||
(Self::Any(l0), Self::Any(r0)) => (*l0).cmp_any(*r0),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for AttributeValue<'_> {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
AttributeValue::Text(s) => write!(f, "AttributeValue::Text({:?})", s),
|
||||
AttributeValue::Float(v) => write!(f, "AttributeValue::Float({:?})", v),
|
||||
AttributeValue::Int(v) => write!(f, "AttributeValue::Int({:?})", v),
|
||||
AttributeValue::Bool(b) => write!(f, "AttributeValue::Bool({:?})", b),
|
||||
AttributeValue::Any(_) => write!(f, "AttributeValue::Any()"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 &'a str {
|
||||
fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
|
||||
AttributeValue::Text(self)
|
||||
}
|
||||
}
|
||||
impl<'a> IntoAttributeValue<'a> for f32 {
|
||||
fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
|
||||
AttributeValue::Float(self)
|
||||
}
|
||||
}
|
||||
impl<'a> IntoAttributeValue<'a> for i32 {
|
||||
fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
|
||||
AttributeValue::Int(self)
|
||||
}
|
||||
}
|
||||
impl<'a> IntoAttributeValue<'a> for bool {
|
||||
fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
|
||||
AttributeValue::Bool(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())
|
||||
}
|
||||
}
|
||||
|
||||
// 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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A trait that allows for comparing two values of the same type through the Any trait
|
||||
///
|
||||
/// Defaults to false if the types are not the same
|
||||
///
|
||||
/// This is an implicit trait, so any value that is 'static and PartialEq can be used directly
|
||||
///
|
||||
/// If you want to override the default behavior, you should implement PartialEq through a wrapper type
|
||||
pub trait AnyAttributeValue: Any {
|
||||
/// Perform a comparison between two values
|
||||
fn cmp_any<'a>(&'a self, _other: &'a dyn AnyAttributeValue) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Any + PartialEq> AnyAttributeValue for T {
|
||||
fn cmp_any(&self, other: &dyn AnyAttributeValue) -> bool {
|
||||
// we can't, for whatever reason use other as &dyn Any
|
||||
let right: &dyn Any = unsafe { std::mem::transmute(other) };
|
||||
|
||||
match right.downcast_ref::<T>() {
|
||||
Some(right) => self == right,
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmp_any_works_even_though_it_transmutes() {
|
||||
// same type, same value
|
||||
let a = 2;
|
||||
let b = 2;
|
||||
assert!(a.cmp_any(&b as &dyn AnyAttributeValue));
|
||||
|
||||
// same type, different value
|
||||
let a = "asds";
|
||||
let b = "asdsasd";
|
||||
assert!(!a.cmp_any(&b as &dyn AnyAttributeValue));
|
||||
|
||||
// different type, different values
|
||||
let a = 123;
|
||||
let b = "asdsasd";
|
||||
assert!(!a.cmp_any(&b as &dyn AnyAttributeValue));
|
||||
|
||||
// Custom structs
|
||||
#[derive(PartialEq)]
|
||||
struct CustomStruct {
|
||||
a: i32,
|
||||
}
|
||||
|
||||
let a = CustomStruct { a: 1 };
|
||||
let b = CustomStruct { a: 1 };
|
||||
assert!(a.cmp_any(&b as &dyn AnyAttributeValue));
|
||||
|
||||
let a = CustomStruct { a: 1 };
|
||||
let b = CustomStruct { a: 123 };
|
||||
assert!(!a.cmp_any(&b as &dyn AnyAttributeValue));
|
||||
|
||||
let a = CustomStruct { a: 1 };
|
||||
let b = "asdasd";
|
||||
assert!(!a.cmp_any(&b as &dyn AnyAttributeValue));
|
||||
}
|
||||
@@ -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<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,362 @@
|
||||
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,
|
||||
}))
|
||||
}
|
||||
|
||||
/// 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,
|
||||
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(ElementId(0)),
|
||||
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<'static>,
|
||||
nodes: &'a [VNode<'a>],
|
||||
attributes: &'a [Attribute<'a>],
|
||||
listeners: &'a [Listener<'a>],
|
||||
key: Option<Arguments>,
|
||||
) -> VNode<'a> {
|
||||
VNode::Template(
|
||||
self.bump.alloc(VTemplate {
|
||||
key: None,
|
||||
node_id: Cell::new(ElementId(0)),
|
||||
template,
|
||||
dynamic_nodes: self.bump.alloc([]),
|
||||
dynamic_attrs: self.bump.alloc([]),
|
||||
listeners,
|
||||
root_ids:
|
||||
bumpalo::vec![in self.bump; Cell::new(ElementId(0)); template.roots.len()]
|
||||
.into_bump_slice(),
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
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 if it exists
|
||||
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,207 @@
|
||||
//! 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 placeholder;
|
||||
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::*;
|
||||
|
||||
use self::placeholder::VPlaceholder;
|
||||
|
||||
/// 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::Template(t) => t.key,
|
||||
VNode::Text(_t) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
use std::{cell::Cell, num::NonZeroUsize};
|
||||
|
||||
/// A reference to a template along with any context needed to hydrate it
|
||||
pub struct VTemplate<'a> {
|
||||
// The ID assigned for the root of this template
|
||||
pub node_id: Cell<ElementId>,
|
||||
|
||||
pub template: &'static Template,
|
||||
|
||||
/// All the dynamic nodes for a template
|
||||
pub dynamic_nodes: &'a [DynamicNode<'a>],
|
||||
|
||||
pub dynamic_attrs: &'a [AttributeLocation<'a>],
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Template {
|
||||
pub id: &'static str,
|
||||
|
||||
pub root: TemplateNode<'static>,
|
||||
|
||||
// todo: locations of dynamic nodes
|
||||
pub node_pathways: &'static [&'static [u8]],
|
||||
|
||||
// todo: locations of dynamic nodes
|
||||
pub attr_pathways: &'static [&'static [u8]],
|
||||
}
|
||||
|
||||
/// A weird-ish variant of VNodes with way more limited types
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum TemplateNode<'a> {
|
||||
/// A simple element
|
||||
Element {
|
||||
tag: &'a str,
|
||||
namespace: Option<&'a str>,
|
||||
attrs: &'a [TemplateAttribute<'a>],
|
||||
children: &'a [TemplateNode<'a>],
|
||||
},
|
||||
Text(&'a str),
|
||||
Dynamic(usize),
|
||||
DynamicText(usize),
|
||||
}
|
||||
|
||||
pub enum DynamicNode<'a> {
|
||||
// Anything declared in component form
|
||||
// IE in caps or with underscores
|
||||
Component {
|
||||
name: &'static str,
|
||||
},
|
||||
|
||||
// Comes in with string interpolation or from format_args, include_str, etc
|
||||
Text {
|
||||
id: Cell<ElementId>,
|
||||
value: &'static str,
|
||||
},
|
||||
|
||||
// Anything that's coming in as an iterator
|
||||
Fragment {
|
||||
children: &'a [VTemplate<'a>],
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct TemplateAttribute<'a> {
|
||||
pub name: &'static str,
|
||||
pub value: &'a str,
|
||||
pub namespace: Option<&'static str>,
|
||||
pub volatile: bool,
|
||||
}
|
||||
|
||||
pub struct AttributeLocation<'a> {
|
||||
pub mounted_element: Cell<ElementId>,
|
||||
pub attrs: &'a [Attribute<'a>],
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Attribute<'a> {
|
||||
pub name: &'static str,
|
||||
pub value: &'a str,
|
||||
pub namespace: Option<&'static str>,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_are_the_sizes() {
|
||||
dbg!(std::mem::size_of::<VTemplate>());
|
||||
dbg!(std::mem::size_of::<Template>());
|
||||
dbg!(std::mem::size_of::<TemplateNode>());
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
use crate::ElementId;
|
||||
use std::cell::Cell;
|
||||
|
||||
/// A placeholder node
|
||||
pub struct VPlaceholder {
|
||||
pub id: Cell<Option<ElementId>>,
|
||||
pub dynamic_index: Option<usize>,
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,78 @@
|
||||
use std::{cell::Cell, 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>,
|
||||
|
||||
// The ID assigned for all nodes in this template
|
||||
pub node_id: Cell<ElementId>,
|
||||
|
||||
// All the IDs for the roots of this template
|
||||
// Non-assigned IDs are set to 0
|
||||
pub root_ids: &'a [Cell<ElementId>],
|
||||
|
||||
pub template: Template<'static>,
|
||||
|
||||
/// All the non-root dynamic nodes
|
||||
pub dynamic_nodes: &'a [NodeLocation<'a>],
|
||||
|
||||
pub dynamic_attrs: &'a [AttributeLocation<'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> {
|
||||
/// A simple element
|
||||
Element {
|
||||
tag: &'static str,
|
||||
namespace: Option<&'static str>,
|
||||
attrs: &'a [TemplateAttribute<'a>],
|
||||
children: &'a [TemplateNode<'a>],
|
||||
},
|
||||
Text(&'static str),
|
||||
Dynamic(usize),
|
||||
}
|
||||
|
||||
pub struct TemplateAttribute<'a> {
|
||||
pub name: &'static str,
|
||||
pub value: &'a str,
|
||||
pub namespace: Option<&'static str>,
|
||||
pub volatile: bool,
|
||||
}
|
||||
|
||||
pub struct AttributeLocation<'a> {
|
||||
pub pathway: &'static [u8],
|
||||
pub mounted_element: Cell<ElementId>,
|
||||
pub attrs: &'a [Attribute<'a>],
|
||||
pub listeners: &'a [Listener<'a>],
|
||||
}
|
||||
|
||||
pub struct NodeLocation<'a> {
|
||||
pub pathway: &'static [u8],
|
||||
pub node: VNode<'a>,
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
use crate::ElementId;
|
||||
use std::cell::Cell;
|
||||
|
||||
/// 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,
|
||||
}
|
||||
Reference in new issue
Block a user