#[cfg(feature = "devtools")]
use crate::app::ctx::{
ComponentContextDebug, ComponentEffectDebug, ComponentMemoDebug, ComponentSignalDebug, DevtoolsInspectableDebug,
};
use crate::node::{color::Color, node::Node};
pub struct Element {
pub(crate) node: Box<Node>,
}
impl Clone for Element {
fn clone(&self) -> Self {
Self::from_node(self.node.clone_for_reuse())
}
}
#[derive(Clone, Copy)]
pub struct ElementRef<'a> {
pub(crate) node: &'a Node,
}
pub struct ElementChildren<'a> {
nodes: &'a [Node],
}
pub struct ElementIter<'a> {
inner: std::slice::Iter<'a, Node>,
}
mod node_boxes {
use std::{cell::RefCell, mem::MaybeUninit};
use crate::node::node::Node;
const KEPT: usize = 16;
thread_local! {
#[allow(clippy::vec_box)]
static EMPTY: RefCell<Vec<Box<MaybeUninit<Node>>>> = const { RefCell::new(Vec::new()) };
}
pub(crate) fn boxed(node: Node) -> Box<Node> {
let empty = EMPTY
.try_with(|empty| empty.try_borrow_mut().ok().and_then(|mut empty| empty.pop()))
.ok()
.flatten();
match empty {
Some(empty) => Box::write(empty, node),
None => Box::new(node),
}
}
pub(crate) fn unboxed(node: Box<Node>) -> Node {
let raw = Box::into_raw(node);
let (node, empty) = unsafe { (raw.read(), Box::from_raw(raw.cast::<MaybeUninit<Node>>())) };
let _ = EMPTY.try_with(|kept| {
if let Ok(mut kept) = kept.try_borrow_mut()
&& kept.len() < KEPT
{
if kept.capacity() == 0 {
kept.reserve_exact(KEPT);
}
kept.push(empty);
}
});
node
}
}
pub(crate) use node_boxes::boxed as boxed_node;
impl Element {
pub(crate) fn from_node(node: Node) -> Self {
Self {
node: node_boxes::boxed(node),
}
}
pub(crate) fn from_boxed_node(node: Box<Node>) -> Self {
Self { node }
}
pub(crate) fn map_node(self, f: impl FnOnce(Node) -> Node) -> Self {
Self::from_node(f(self.into_node()))
}
pub(crate) fn decorate_root(mut self, decorate: impl Fn(Node) -> Node + Send + Sync + 'static) -> Self {
let decorate: crate::node::outer_decoration::NodeDecoration = std::sync::Arc::new(decorate);
self.node.record_outer_decoration(&decorate);
self.map_node(|node| decorate(node))
}
pub(crate) fn root_id(&self) -> Option<&str> {
self.node.element_id()
}
pub(crate) fn into_node(self) -> Node {
node_boxes::unboxed(self.node)
}
pub fn new() -> Self {
Self::from_node(Node::new())
}
pub fn component<C: crate::app::component::Component>(props: C::Props) -> Self
where
C::Props: Clone,
{
Self::declaring::<C>(None, props)
}
pub fn component_keyed<C: crate::app::component::Component>(
key: impl Into<std::sync::Arc<str>>,
props: C::Props,
) -> Self
where
C::Props: Clone,
{
Self::declaring::<C>(Some(key.into()), props)
}
fn declaring<C: crate::app::component::Component>(key: Option<std::sync::Arc<str>>, props: C::Props) -> Self
where
C::Props: Clone,
{
let props = parking_lot::Mutex::new(props);
let mount: crate::node::outer_decoration::DeclaredMount =
std::sync::Arc::new(move |ctx: &mut crate::app::ctx::Ctx, key: Option<&str>| {
let props = props.lock().clone();
match key {
Some(key) => ctx.mount_keyed::<C>(key, props),
None => ctx.mount::<C>(props),
}
});
Self::from_node(Node::declaring(crate::node::outer_decoration::DeclaredComponent {
mount,
key,
}))
}
pub fn node_id(&self) -> crate::core::NodeId {
self.node.node_id()
}
pub fn key(mut self, key: impl Into<std::sync::Arc<str>>) -> Self {
let key = key.into();
self.node.record_outer_key(&key);
self.node.set_component_key(Some(&key));
self
}
pub fn id(mut self, id: impl Into<std::sync::Arc<str>>) -> Self {
let id = id.into();
self.node.record_outer_id(&id);
crate::node::NodeUpdate::id(&mut *self.node, id);
self
}
pub fn class(mut self, class: impl Into<std::sync::Arc<str>>) -> Self {
let class = class.into();
self.node.record_outer_class(&class);
crate::node::NodeUpdate::class(&mut *self.node, class);
self
}
pub fn classes<C: Into<std::sync::Arc<str>>>(mut self, classes: impl IntoIterator<Item = C>) -> Self {
for class in classes {
self = self.class(class);
}
self
}
}
impl Default for Element {
fn default() -> Self {
Self::new()
}
}
impl<T: crate::app::component::IntoComponent> From<T> for Element {
fn from(value: T) -> Self {
let key = value.component_key();
let props = value.into_props();
match key {
Some(key) => Self::component_keyed::<T::Component>(key, props),
None => Self::component::<T::Component>(props),
}
}
}
impl<'a> ElementRef<'a> {
#[cfg(feature = "canvas")]
pub fn as_canvas(&self) -> Option<crate::canvas::CanvasHandle> {
self.node.canvas_handle().filter(|canvas| canvas.is_attached())
}
pub(crate) fn new(node: &'a Node) -> Self {
Self { node }
}
pub fn node_id(&self) -> crate::core::NodeId {
self.node.node_id()
}
pub fn tag_name(&self) -> &'a str {
self.node.tag_name()
}
pub fn id(&self) -> Option<&'a str> {
self.node.element_id.as_deref()
}
pub fn classes(&self) -> impl Iterator<Item = &'a str> + use<'a> {
self.node.class_list().iter().map(|class| class.as_ref())
}
pub fn has_class(&self, class: &str) -> bool {
self.node.has_class(class)
}
#[allow(dead_code)]
pub(crate) fn component_key(&self) -> Option<&'a str> {
self.node.component_key()
}
pub fn text_content(&self) -> Option<&'a str> {
self.node.text_content()
}
pub fn color(&self) -> Option<Color> {
self.node.color()
}
#[cfg(feature = "devtools")]
#[allow(dead_code)]
pub(crate) fn component_props_debug(&self) -> Option<&DevtoolsInspectableDebug> {
self.node.component_props_debug()
}
#[cfg(feature = "devtools")]
#[allow(dead_code)]
pub(crate) fn component_signals_debug(&self) -> &[ComponentSignalDebug] {
self.node.component_signals_debug()
}
#[cfg(feature = "devtools")]
#[allow(dead_code)]
pub(crate) fn component_memos_debug(&self) -> &[ComponentMemoDebug] {
self.node.component_memos_debug()
}
#[cfg(feature = "devtools")]
#[allow(dead_code)]
pub(crate) fn component_effects_debug(&self) -> &[ComponentEffectDebug] {
self.node.component_effects_debug()
}
#[cfg(feature = "devtools")]
#[allow(dead_code)]
pub(crate) fn component_contexts_debug(&self) -> &[ComponentContextDebug] {
self.node.component_contexts_debug()
}
#[cfg(feature = "devtools")]
pub(crate) fn component_render_debug(&self) -> Option<crate::app::ctx::ComponentRenderDebug> {
self.node.component_render_debug()
}
#[cfg(feature = "devtools")]
#[allow(dead_code)]
pub(crate) fn debug_attrs(&self) -> std::borrow::Cow<'_, [(std::sync::Arc<str>, std::sync::Arc<str>)]> {
self.node.debug_attrs()
}
pub fn children(&self) -> ElementChildren<'a> {
ElementChildren {
nodes: self.node.children(),
}
}
}
impl<'a> ElementChildren<'a> {
pub fn len(&self) -> usize {
self.nodes.len()
}
pub fn is_empty(&self) -> bool {
self.nodes.is_empty()
}
pub fn iter(&self) -> ElementIter<'a> {
ElementIter {
inner: self.nodes.iter(),
}
}
}
impl<'a> IntoIterator for ElementChildren<'a> {
type Item = ElementRef<'a>;
type IntoIter = ElementIter<'a>;
fn into_iter(self) -> Self::IntoIter {
ElementIter {
inner: self.nodes.iter(),
}
}
}
impl<'a> Iterator for ElementIter<'a> {
type Item = ElementRef<'a>;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(ElementRef::new)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl ExactSizeIterator for ElementIter<'_> {}
#[cfg(test)]
mod tests {
use crate::{
components::{Column, Rect, Text},
node::Element,
};
#[test]
fn element_builders_create_node_tree() {
let node = Element::from(
Column::new()
.spacing(8.0)
.child(Text::new("hello"))
.child(Rect::new(10.0, 20.0).rounded(4.0)),
)
.node;
assert_eq!(node.children().len(), 2);
}
#[test]
fn an_element_reuses_the_box_its_predecessor_was_moved_out_of() {
let first = Element::from(Rect::new(10.0, 20.0));
let first_box = std::ptr::from_ref(&*first.node);
let node = first.into_node();
assert_eq!(node.frame.width, Some(crate::node::dimension::Dimension::Px(10.0)));
let second = Element::from(Rect::new(30.0, 40.0).id("second"));
assert!(std::ptr::eq(&*second.node, first_box));
assert_eq!(second.node.element_id(), Some("second"));
assert_eq!(
second.node.frame.width,
Some(crate::node::dimension::Dimension::Px(30.0))
);
}
}