use crate::{
innerlude::{ComponentPtr, Element, Properties, Scope, ScopeId, ScopeState},
lazynodes::LazyNodes,
AnyEvent, Component,
};
use bumpalo::{boxed::Box as BumpBox, Bump};
use std::{
cell::{Cell, RefCell},
fmt::{Arguments, Debug, Formatter},
};
pub enum VNode<'src> {
Text(&'src VText<'src>),
Element(&'src VElement<'src>),
Fragment(&'src VFragment<'src>),
Component(&'src VComponent<'src>),
Placeholder(&'src VPlaceholder),
}
impl<'src> VNode<'src> {
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::Placeholder(_f) => None,
}
}
pub fn mounted_id(&self) -> ElementId {
self.try_mounted_id().unwrap()
}
pub fn try_mounted_id(&self) -> Option<ElementId> {
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,
}
}
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::Placeholder(a) => VNode::Placeholder(a),
VNode::Fragment(f) => VNode::Fragment(f),
}
}
}
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::Placeholder(t) => s
.debug_struct("VNode::Placholder")
.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(),
}
}
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct ElementId(pub usize);
impl std::fmt::Display for ElementId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl ElementId {
pub fn as_u64(self) -> u64 {
self.0 as u64
}
}
fn empty_cell() -> Cell<Option<ElementId>> {
Cell::new(None)
}
pub struct VPlaceholder {
pub id: Cell<Option<ElementId>>,
}
pub struct VText<'src> {
pub id: Cell<Option<ElementId>>,
pub text: &'src str,
pub is_static: bool,
}
pub struct VFragment<'src> {
pub key: Option<&'src str>,
pub children: &'src [VNode<'src>],
}
pub struct VElement<'a> {
pub id: Cell<Option<ElementId>>,
pub key: Option<&'a str>,
pub tag: &'static str,
pub namespace: Option<&'static str>,
pub parent: Cell<Option<ElementId>>,
pub listeners: &'a [Listener<'a>],
pub attributes: &'a [Attribute<'a>],
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()
}
}
pub trait DioxusElement {
const TAG_NAME: &'static str;
const NAME_SPACE: Option<&'static str>;
#[inline]
fn tag_name(&self) -> &'static str {
Self::TAG_NAME
}
#[inline]
fn namespace(&self) -> Option<&'static str> {
Self::NAME_SPACE
}
}
#[derive(Clone, Debug)]
pub struct Attribute<'a> {
pub name: &'static str,
pub value: &'a str,
pub is_static: bool,
pub is_volatile: bool,
pub namespace: Option<&'static str>,
}
pub struct Listener<'bump> {
pub mounted_node: Cell<Option<ElementId>>,
pub event: &'static str,
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>;
pub struct EventHandler<'bump, T = ()> {
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> {
pub fn call(&self, event: T) {
if let Some(callback) = self.callback.borrow_mut().as_mut() {
callback(event);
}
}
pub fn release(&self) {
self.callback.replace(None);
}
}
pub struct VComponent<'src> {
pub key: Option<&'src str>,
pub scope: Cell<Option<ScopeId>>,
pub can_memoize: bool,
pub user_fc: ComponentPtr,
pub fn_name: &'static str,
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 ()
}
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 })
}
}
#[derive(Copy, Clone)]
pub struct NodeFactory<'a> {
pub(crate) scope: &'a ScopeState,
pub(crate) bump: &'a Bump,
}
impl<'a> NodeFactory<'a> {
pub fn new(scope: &'a ScopeState) -> NodeFactory<'a> {
NodeFactory {
scope,
bump: &scope.wip_frame().bump,
}
}
#[inline]
pub fn bump(&self) -> &'a bumpalo::Bump {
self.bump
}
pub fn static_text(&self, text: &'static str) -> VNode<'a> {
VNode::Text(self.bump.alloc(VText {
id: empty_cell(),
text,
is_static: true,
}))
}
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)
}
}
}
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: empty_cell(),
}))
}
pub fn element(
&self,
el: impl DioxusElement,
listeners: &'a [Listener<'a>],
attributes: &'a [Attribute<'a>],
children: &'a [VNode<'a>],
key: Option<Arguments>,
) -> VNode<'a> {
self.raw_element(
el.tag_name(),
el.namespace(),
listeners,
attributes,
children,
key,
)
}
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: empty_cell(),
parent: empty_cell(),
}))
}
pub fn attr(
&self,
name: &'static str,
val: Arguments,
namespace: Option<&'static str>,
is_volatile: bool,
) -> Attribute<'a> {
let (value, is_static) = self.raw_text(val);
Attribute {
name,
value,
is_static,
namespace,
is_volatile,
}
}
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,
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)
}
pub fn listener(self, event: &'static str, callback: InternalHandler<'a>) -> Listener<'a> {
Listener {
event,
mounted_node: Cell::new(None),
callback,
}
}
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 fragment_from_iter<'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 {
let children = nodes.into_bump_slice();
if cfg!(debug_assertions)
&& children.len() > 1
&& children.last().unwrap().key().is_none()
{
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(self.bump.alloc(VFragment {
children,
key: None,
}))
}
}
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,
})))
}
}
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 }
}
}
impl Debug for NodeFactory<'_> {
fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Ok(())
}
}
pub trait IntoVNode<'a> {
fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a>;
}
impl<'a> IntoIterator for VNode<'a> {
type Item = VNode<'a>;
type IntoIter = std::iter::Once<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
std::iter::once(self)
}
}
impl<'a> IntoVNode<'a> for VNode<'a> {
fn into_vnode(self, _: NodeFactory<'a>) -> VNode<'a> {
self
}
}
impl IntoVNode<'_> for () {
fn into_vnode(self, cx: NodeFactory) -> VNode {
cx.fragment_from_iter(None as Option<VNode>)
}
}
impl IntoVNode<'_> for Option<()> {
fn into_vnode(self, cx: NodeFactory) -> VNode {
cx.fragment_from_iter(None as Option<VNode>)
}
}
impl<'a> IntoVNode<'a> for Option<VNode<'a>> {
fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
self.unwrap_or_else(|| cx.fragment_from_iter(None as Option<VNode>))
}
}
impl<'a> IntoVNode<'a> for Option<LazyNodes<'a, '_>> {
fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
match self {
Some(lazy) => lazy.call(cx),
None => VNode::Placeholder(cx.bump.alloc(VPlaceholder { id: empty_cell() })),
}
}
}
impl<'a, 'b> IntoIterator for LazyNodes<'a, 'b> {
type Item = LazyNodes<'a, 'b>;
type IntoIter = std::iter::Once<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
std::iter::once(self)
}
}
impl<'a, 'b> IntoVNode<'a> for LazyNodes<'a, 'b> {
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 &Option<VNode<'a>> {
fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a> {
self.as_ref()
.map(|f| f.into_vnode(cx))
.unwrap_or_else(|| cx.fragment_from_iter(None as Option<VNode>))
}
}
impl<'a> IntoVNode<'a> for &VNode<'a> {
fn into_vnode(self, _cx: NodeFactory<'a>) -> VNode<'a> {
self.decouple()
}
}