Skip to main content

strata_dom/
lib.rs

1//! Strata DOM: Fine-grained reactive signal graph, DOM representations, and node blueprints.
2//!
3//! # Examples
4//!
5//! ```rust
6//! use strata_dom::reactive::Signal;
7//!
8//! let count = Signal::new(100);
9//! assert_eq!(count.get(), 100);
10//! count.set(200);
11//! assert_eq!(count.get(), 200);
12//! ```
13
14use std::rc::Rc;
15
16/// Represents an opaque handle to a rendered UI subtree.
17#[derive(Debug, Clone)]
18pub struct View {
19    pub root: NodeBlueprint,
20}
21
22impl View {
23    pub fn new(root: NodeBlueprint) -> Self {
24        Self { root }
25    }
26
27    /// Recursively flattens nested Fragment nodes within Element children.
28    pub fn flatten_fragments(self) -> Self {
29        Self {
30            root: self.root.flatten_fragments(),
31        }
32    }
33}
34
35pub mod classes;
36pub mod error_boundary;
37pub mod events;
38pub mod hooks;
39pub mod ir;
40pub mod portal;
41pub mod reactive;
42pub mod spring;
43pub mod text_input;
44
45pub use classes::{standard_class_index, ClassBitmask, ClassIter, ClassList, STANDARD_CLASSES};
46pub use error_boundary::{ErrorBoundary, ErrorBoundaryBuilder, ErrorBoundaryInfo};
47pub use events::{Event, EventDispatcher, EventPhase, EventType};
48pub use hooks::*;
49pub use ir::{
50    ChildIter, DisplayChunkRange, FixedRect, IrNodeFlags, IrTag, MemoCache, MemoEntry, NodeId,
51    StackGuard, UiIrGraph, UiIrNode,
52};
53pub use portal::{
54    create_anchored_portal, create_dropdown_portal, create_portal, AnchorPlacement, Portal,
55    PortalBuilder,
56};
57pub use reactive::{
58    batch, clear_persistent_signals, create_context, create_signal, has_dirty_signals, mark_dirty,
59    provide_context, reset_component_hooks, take_dirty_signals, untrack, use_callback, use_context,
60    use_effect, use_effect_with_deps, use_id, use_memo, use_persistent_signal, use_reducer,
61    use_reducer_init, use_ref, use_signal, use_state, with_component_key, ComponentScopeGuard,
62    Context, Effect, EffectGuard, IntoInitialState, Memo, ReactiveRuntime, ReadSignal, Ref,
63    ScopeId, SetSignal, Signal, SignalId, SubscriberId, WriteSignal,
64};
65pub use spring::{SpringConfig, SpringSignal};
66pub use strata_primitives::EntityId;
67pub use text_input::{InputKey, InputKeyResult, InputModifiers, TextInputState};
68
69/// Ergonomic conversion into `Option<String>` for `#[component]` builder setters.
70///
71/// Accepts string literals (`"hello"`), `String`, `&String`, `Cow<'_, str>`, `Option<String>`,
72/// and bare `None` without `.to_string()` boilerplate or type-inference ambiguity on `None`.
73pub trait IntoOptionalString {
74    fn into_optional_string(self) -> Option<String>;
75}
76
77impl IntoOptionalString for String {
78    #[inline]
79    fn into_optional_string(self) -> Option<String> {
80        Some(self)
81    }
82}
83
84impl IntoOptionalString for &str {
85    #[inline]
86    fn into_optional_string(self) -> Option<String> {
87        Some(self.to_string())
88    }
89}
90
91impl IntoOptionalString for &String {
92    #[inline]
93    fn into_optional_string(self) -> Option<String> {
94        Some(self.clone())
95    }
96}
97
98impl IntoOptionalString for std::borrow::Cow<'_, str> {
99    #[inline]
100    fn into_optional_string(self) -> Option<String> {
101        Some(self.into_owned())
102    }
103}
104
105impl IntoOptionalString for Option<String> {
106    #[inline]
107    fn into_optional_string(self) -> Option<String> {
108        self
109    }
110}
111
112/// Trait abstracting event handlers accepting `()` or `(Event)`.
113pub trait EventHandlerMarker<Args> {
114    fn call_handler(&self, event: Event);
115}
116
117impl<F: Fn(Event) + 'static> EventHandlerMarker<(Event,)> for F {
118    fn call_handler(&self, event: Event) {
119        (self)(event);
120    }
121}
122
123impl<F: Fn() + 'static> EventHandlerMarker<()> for F {
124    fn call_handler(&self, _event: Event) {
125        (self)();
126    }
127}
128
129impl EventHandlerMarker<()> for Rc<dyn Fn()> {
130    fn call_handler(&self, _event: Event) {
131        (self)();
132    }
133}
134
135impl EventHandlerMarker<(Event,)> for Rc<dyn Fn(Event)> {
136    fn call_handler(&self, event: Event) {
137        (self)(event);
138    }
139}
140
141impl<F: Fn(Event) + 'static> EventHandlerMarker<(Rc<()>, Event)> for Rc<F> {
142    fn call_handler(&self, event: Event) {
143        (self)(event);
144    }
145}
146
147impl<F: Fn() + 'static> EventHandlerMarker<(Rc<()>,)> for Rc<F> {
148    fn call_handler(&self, _event: Event) {
149        (self)();
150    }
151}
152
153impl<Args, F: EventHandlerMarker<Args>> EventHandlerMarker<Args> for Option<F> {
154    fn call_handler(&self, event: Event) {
155        if let Some(ref handler) = self {
156            handler.call_handler(event);
157        }
158    }
159}
160
161/// Trait abstracting input/change value handlers accepting `()` or `(String)`.
162pub trait ValueHandlerMarker<Args> {
163    fn call_handler(&self, val: String);
164}
165
166impl<F: Fn(String) + 'static> ValueHandlerMarker<(String,)> for F {
167    fn call_handler(&self, val: String) {
168        (self)(val);
169    }
170}
171
172impl<F: Fn() + 'static> ValueHandlerMarker<()> for F {
173    fn call_handler(&self, _val: String) {
174        (self)();
175    }
176}
177
178impl ValueHandlerMarker<(String,)> for Rc<dyn Fn(String)> {
179    fn call_handler(&self, val: String) {
180        (self)(val);
181    }
182}
183
184impl ValueHandlerMarker<()> for Rc<dyn Fn()> {
185    fn call_handler(&self, _val: String) {
186        (self)();
187    }
188}
189
190impl<F: Fn(String) + 'static> ValueHandlerMarker<(Rc<()>, String)> for Rc<F> {
191    fn call_handler(&self, val: String) {
192        (self)(val);
193    }
194}
195
196impl<F: Fn() + 'static> ValueHandlerMarker<(Rc<()>,)> for Rc<F> {
197    fn call_handler(&self, _val: String) {
198        (self)();
199    }
200}
201
202impl<Args, F: ValueHandlerMarker<Args>> ValueHandlerMarker<Args> for Option<F> {
203    fn call_handler(&self, val: String) {
204        if let Some(ref handler) = self {
205            handler.call_handler(val);
206        }
207    }
208}
209
210/// DOM element attribute or event listener.
211#[derive(Clone)]
212pub enum Attribute {
213    Property {
214        key: String,
215        value: String,
216    },
217    EventListener {
218        event: EventType,
219        handler: Rc<dyn Fn(Event)>,
220    },
221    DirectStyle(Rc<dyn std::any::Any>),
222    /// Thread-safe type-erased 3D scene handle (e.g. `Arc<strata_render::Scene3D>`) attached to a viewport element.
223    ScenePayload(std::sync::Arc<dyn std::any::Any + Send + Sync>),
224    Entity(EntityId),
225}
226
227impl Attribute {
228    pub fn property(key: impl Into<String>, value: impl Into<String>) -> Self {
229        Self::Property {
230            key: key.into(),
231            value: value.into(),
232        }
233    }
234
235    pub fn direct_style<T: 'static>(style: T) -> Self {
236        Self::DirectStyle(Rc::new(style))
237    }
238
239    pub fn scene_payload<T: Send + Sync + 'static>(payload: T) -> Self {
240        Self::ScenePayload(std::sync::Arc::new(payload))
241    }
242
243    pub fn scene_payload_arc(payload: std::sync::Arc<dyn std::any::Any + Send + Sync>) -> Self {
244        Self::ScenePayload(payload)
245    }
246
247    pub fn entity(id: EntityId) -> Self {
248        Self::Entity(id)
249    }
250
251    pub fn event_listener<Args, F: EventHandlerMarker<Args> + 'static>(
252        event: EventType,
253        handler: F,
254    ) -> Self {
255        Self::EventListener {
256            event,
257            handler: Rc::new(move |e| handler.call_handler(e)),
258        }
259    }
260
261    pub fn value_listener<Args, F: ValueHandlerMarker<Args> + 'static>(
262        event: EventType,
263        handler: F,
264    ) -> Self {
265        Self::EventListener {
266            event,
267            handler: Rc::new(move |e| handler.call_handler(e.value.clone())),
268        }
269    }
270}
271
272impl std::fmt::Debug for Attribute {
273    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
274        match self {
275            Self::Property { key, value } => f
276                .debug_struct("Property")
277                .field("key", key)
278                .field("value", value)
279                .finish(),
280            Self::EventListener { event, .. } => f
281                .debug_struct("EventListener")
282                .field("event", event)
283                .field("handler", &"<callback>")
284                .finish(),
285            Self::DirectStyle(_) => f
286                .debug_tuple("DirectStyle")
287                .field(&"<typed_style>")
288                .finish(),
289            Self::ScenePayload(_) => f.debug_tuple("ScenePayload").field(&"<scene_3d>").finish(),
290            Self::Entity(id) => f.debug_tuple("Entity").field(id).finish(),
291        }
292    }
293}
294
295/// Core reactive blueprint tree representation.
296#[derive(Clone)]
297pub enum NodeBlueprint {
298    Element {
299        tag: Tag,
300        classes: ClassList,
301        attributes: Vec<Attribute>,
302        children: Vec<NodeBlueprint>,
303    },
304    Text(String),
305    DynamicText(Rc<dyn Fn() -> String>),
306    Fragment(Vec<NodeBlueprint>),
307    Empty,
308}
309
310impl std::fmt::Debug for NodeBlueprint {
311    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
312        match self {
313            Self::Element {
314                tag,
315                classes,
316                attributes,
317                children,
318            } => f
319                .debug_struct("Element")
320                .field("tag", tag)
321                .field("classes", classes)
322                .field("attributes", attributes)
323                .field("children", children)
324                .finish(),
325            Self::Text(t) => f.debug_tuple("Text").field(t).finish(),
326            Self::DynamicText(_) => f.debug_tuple("DynamicText").field(&"<dynamic>").finish(),
327            Self::Fragment(c) => f.debug_tuple("Fragment").field(c).finish(),
328            Self::Empty => write!(f, "Empty"),
329        }
330    }
331}
332
333impl NodeBlueprint {
334    pub fn element(
335        tag: Tag,
336        classes: impl Into<ClassList>,
337        attributes: Vec<Attribute>,
338        children: Vec<NodeBlueprint>,
339    ) -> Self {
340        Self::Element {
341            tag,
342            classes: classes.into(),
343            attributes,
344            children,
345        }
346    }
347
348    pub fn element_simple(
349        tag: Tag,
350        classes: impl Into<ClassList>,
351        children: Vec<NodeBlueprint>,
352    ) -> Self {
353        Self::Element {
354            tag,
355            classes: classes.into(),
356            attributes: Vec::new(),
357            children,
358        }
359    }
360
361    pub fn text(content: impl Into<String>) -> Self {
362        Self::Text(content.into())
363    }
364
365    pub fn dynamic_text(f: impl Fn() -> String + 'static) -> Self {
366        Self::DynamicText(Rc::new(f))
367    }
368
369    pub fn fragment(children: Vec<NodeBlueprint>) -> Self {
370        Self::Fragment(children)
371    }
372
373    pub fn empty() -> Self {
374        Self::Empty
375    }
376
377    /// Returns the EntityId assigned to this blueprint element if present.
378    pub fn entity_id(&self) -> Option<EntityId> {
379        match self {
380            Self::Element { attributes, .. } => {
381                for attr in attributes {
382                    if let Attribute::Entity(id) = attr {
383                        if id.is_valid() {
384                            return Some(*id);
385                        }
386                    }
387                }
388                None
389            }
390            _ => None,
391        }
392    }
393
394    /// Assigns or overrides the EntityId for an Element node blueprint.
395    pub fn with_entity_id(mut self, entity_id: EntityId) -> Self {
396        self.set_entity_id(entity_id);
397        self
398    }
399
400    /// Mutably assigns or overrides the EntityId for an Element node blueprint.
401    pub fn set_entity_id(&mut self, entity_id: EntityId) {
402        if let Self::Element { attributes, .. } = self {
403            if let Some(pos) = attributes
404                .iter()
405                .position(|a| matches!(a, Attribute::Entity(_)))
406            {
407                attributes[pos] = Attribute::Entity(entity_id);
408            } else {
409                attributes.push(Attribute::Entity(entity_id));
410            }
411        }
412    }
413
414    /// Recursively ensures all Element nodes in this blueprint tree have a valid EntityId.
415    pub fn ensure_entity_ids(&mut self) {
416        match self {
417            Self::Element {
418                attributes,
419                children,
420                ..
421            } => {
422                let has_id = attributes
423                    .iter()
424                    .any(|a| matches!(a, Attribute::Entity(id) if id.is_valid()));
425                if !has_id {
426                    attributes.push(Attribute::Entity(EntityId::next()));
427                }
428                for child in children {
429                    child.ensure_entity_ids();
430                }
431            }
432            Self::Fragment(children) => {
433                for child in children {
434                    child.ensure_entity_ids();
435                }
436            }
437            _ => {}
438        }
439    }
440
441    /// Recursively locates an element blueprint node by its EntityId.
442    pub fn find_by_entity_id(&self, target_id: EntityId) -> Option<&NodeBlueprint> {
443        if !target_id.is_valid() {
444            return None;
445        }
446        if self.entity_id() == Some(target_id) {
447            return Some(self);
448        }
449        match self {
450            Self::Element { children, .. } | Self::Fragment(children) => {
451                for child in children {
452                    if let Some(found) = child.find_by_entity_id(target_id) {
453                        return Some(found);
454                    }
455                }
456            }
457            _ => {}
458        }
459        None
460    }
461
462    /// Recursively locates a mutable element blueprint node by its EntityId.
463    pub fn find_by_entity_id_mut(&mut self, target_id: EntityId) -> Option<&mut NodeBlueprint> {
464        if !target_id.is_valid() {
465            return None;
466        }
467        if self.entity_id() == Some(target_id) {
468            return Some(self);
469        }
470        match self {
471            Self::Element { children, .. } | Self::Fragment(children) => {
472                for child in children {
473                    if let Some(found) = child.find_by_entity_id_mut(target_id) {
474                        return Some(found);
475                    }
476                }
477            }
478            _ => {}
479        }
480        None
481    }
482
483    /// Returns the DOM node UID from a `data-strata-node-uid` attribute if present.
484    pub fn dom_uid(&self) -> Option<u64> {
485        match self {
486            Self::Element { attributes, .. } => {
487                for attr in attributes {
488                    if let Attribute::Property { key, value } = attr {
489                        if key == "data-strata-node-uid" {
490                            if let Ok(uid) = value.parse::<u64>() {
491                                return Some(uid);
492                            }
493                        }
494                    }
495                }
496                None
497            }
498            _ => None,
499        }
500    }
501
502    /// Recursively locates an element blueprint node by its DOM node UID.
503    pub fn find_by_dom_uid(&self, target_uid: u64) -> Option<&NodeBlueprint> {
504        if self.dom_uid() == Some(target_uid) {
505            return Some(self);
506        }
507        match self {
508            Self::Element { children, .. } | Self::Fragment(children) => {
509                for child in children {
510                    if let Some(found) = child.find_by_dom_uid(target_uid) {
511                        return Some(found);
512                    }
513                }
514            }
515            _ => {}
516        }
517        None
518    }
519
520    /// Recursively locates a mutable element blueprint node by its DOM node UID.
521    pub fn find_by_dom_uid_mut(&mut self, target_uid: u64) -> Option<&mut NodeBlueprint> {
522        if self.dom_uid() == Some(target_uid) {
523            return Some(self);
524        }
525        match self {
526            Self::Element { children, .. } | Self::Fragment(children) => {
527                for child in children {
528                    if let Some(found) = child.find_by_dom_uid_mut(target_uid) {
529                        return Some(found);
530                    }
531                }
532            }
533            _ => {}
534        }
535        None
536    }
537
538    /// Recursively calculates the index path to the element blueprint node with matching DOM node UID.
539    pub fn find_path_by_dom_uid(&self, target_uid: u64) -> Option<Vec<usize>> {
540        let mut path = Vec::new();
541        if self.find_path_by_dom_uid_internal(target_uid, &mut path) {
542            Some(path)
543        } else {
544            None
545        }
546    }
547
548    fn find_path_by_dom_uid_internal(&self, target_uid: u64, path: &mut Vec<usize>) -> bool {
549        if self.dom_uid() == Some(target_uid) {
550            return true;
551        }
552        match self {
553            Self::Element { children, .. } | Self::Fragment(children) => {
554                for (i, child) in children.iter().enumerate() {
555                    path.push(i);
556                    if child.find_path_by_dom_uid_internal(target_uid, path) {
557                        return true;
558                    }
559                    path.pop();
560                }
561            }
562            _ => {}
563        }
564        false
565    }
566
567    /// Recursively calculates the index path to the element blueprint node with matching EntityId.
568    pub fn find_path_by_entity_id(&self, target_id: EntityId) -> Option<Vec<usize>> {
569        if !target_id.is_valid() {
570            return None;
571        }
572        let mut path = Vec::new();
573        if self.find_path_by_entity_id_internal(target_id, &mut path) {
574            Some(path)
575        } else {
576            None
577        }
578    }
579
580    fn find_path_by_entity_id_internal(&self, target_id: EntityId, path: &mut Vec<usize>) -> bool {
581        if self.entity_id() == Some(target_id) {
582            return true;
583        }
584        match self {
585            Self::Element { children, .. } | Self::Fragment(children) => {
586                for (i, child) in children.iter().enumerate() {
587                    path.push(i);
588                    if child.find_path_by_entity_id_internal(target_id, path) {
589                        return true;
590                    }
591                    path.pop();
592                }
593            }
594            _ => {}
595        }
596        false
597    }
598
599    /// Recursively flattens nested Fragment nodes within Element children,
600    /// splicing fragment children directly into their parent elements.
601    pub fn flatten_fragments(self) -> Self {
602        match self {
603            Self::Element {
604                tag,
605                classes,
606                attributes,
607                children,
608            } => {
609                let mut flat_children = Vec::with_capacity(children.len());
610                for child in children {
611                    let flat_child = child.flatten_fragments();
612                    Self::splice_fragment_into(flat_child, &mut flat_children);
613                }
614                Self::Element {
615                    tag,
616                    classes,
617                    attributes,
618                    children: flat_children,
619                }
620            }
621            Self::Fragment(children) => {
622                let mut flat_children = Vec::with_capacity(children.len());
623                for child in children {
624                    let flat_child = child.flatten_fragments();
625                    Self::splice_fragment_into(flat_child, &mut flat_children);
626                }
627                Self::Fragment(flat_children)
628            }
629            other => other,
630        }
631    }
632
633    fn splice_fragment_into(node: Self, out: &mut Vec<Self>) {
634        match node {
635            Self::Fragment(children) => {
636                for child in children {
637                    Self::splice_fragment_into(child, out);
638                }
639            }
640            Self::Empty => {}
641            other => out.push(other),
642        }
643    }
644
645    fn append_ir_children(graph: &mut UiIrGraph, parent_id: NodeId, children: &[NodeBlueprint]) {
646        for child in children {
647            match child {
648                NodeBlueprint::Fragment(subchildren) => {
649                    Self::append_ir_children(graph, parent_id, subchildren);
650                }
651                NodeBlueprint::Empty => {}
652                _ => {
653                    let child_id = child.compile_to_ir(graph);
654                    if !child_id.is_null() {
655                        graph.append_child(parent_id, child_id);
656                    }
657                }
658            }
659        }
660    }
661
662    /// Compiles this reactive blueprint tree into a contiguous 64-byte aligned `UiIrGraph`.
663    pub fn compile_to_ir(&self, graph: &mut UiIrGraph) -> NodeId {
664        match self {
665            Self::Element {
666                tag,
667                classes,
668                attributes,
669                children,
670            } => {
671                let mut ir_tag = tag.to_ir_tag();
672                if classes
673                    .iter()
674                    .any(|c| c == "grid" || c.starts_with("grid-"))
675                {
676                    ir_tag = IrTag::GridContainer;
677                } else if classes
678                    .iter()
679                    .any(|c| c == "flex" || c.starts_with("flex-"))
680                {
681                    ir_tag = IrTag::FlexContainer;
682                } else if classes.iter().any(|c| {
683                    c == "overflow-auto"
684                        || c == "overflow-scroll"
685                        || c == "overflow-y-auto"
686                        || c == "overflow-y-scroll"
687                }) {
688                    ir_tag = IrTag::ScrollView;
689                }
690
691                let mut flags = IrNodeFlags::IS_VISIBLE;
692                for attr in attributes {
693                    if matches!(attr, Attribute::EventListener { .. }) {
694                        flags |= IrNodeFlags::HAS_EVENT_LISTENERS;
695                    }
696                }
697                if classes.iter().any(|c| {
698                    c == "contain-strict" || c == "contain-paint" || c == "overflow-hidden"
699                }) {
700                    flags |= IrNodeFlags::IS_CONTAINMENT_BOUNDARY;
701                }
702
703                let node_id = graph.alloc_node(ir_tag);
704                let memo_hash = Self::compute_hash(ir_tag as u8, classes);
705                if let Some(node) = graph.get_mut(node_id) {
706                    node.flags = flags;
707                    node.memo_hash = memo_hash;
708                }
709
710                Self::append_ir_children(graph, node_id, children);
711                node_id
712            }
713            Self::Text(text) => {
714                let node_id = graph.alloc_node(IrTag::Text);
715                let mut h = 0xcbf29ce484222325u64;
716                for &b in text.as_bytes() {
717                    h ^= b as u64;
718                    h = h.wrapping_mul(0x100000001b3u64);
719                }
720                if let Some(node) = graph.get_mut(node_id) {
721                    node.flags = IrNodeFlags::IS_VISIBLE | IrNodeFlags::IS_TEXT_LEAF;
722                    node.memo_hash = h;
723                }
724                node_id
725            }
726            Self::DynamicText(_) => {
727                let node_id = graph.alloc_node(IrTag::Text);
728                if let Some(node) = graph.get_mut(node_id) {
729                    node.flags = IrNodeFlags::IS_VISIBLE | IrNodeFlags::IS_TEXT_LEAF;
730                }
731                node_id
732            }
733            Self::Fragment(children) => {
734                if children.is_empty() {
735                    return NodeId::NULL;
736                }
737                let node_id = graph.alloc_node(IrTag::ComponentRoot);
738                if let Some(node) = graph.get_mut(node_id) {
739                    node.flags = IrNodeFlags::IS_VISIBLE;
740                }
741                for child in children {
742                    let child_id = child.compile_to_ir(graph);
743                    if !child_id.is_null() {
744                        graph.append_child(node_id, child_id);
745                    }
746                }
747                node_id
748            }
749            Self::Empty => NodeId::NULL,
750        }
751    }
752
753    fn compute_hash(tag_u8: u8, classes: &ClassList) -> u64 {
754        let mut h = 0xcbf29ce484222325u64;
755        h ^= tag_u8 as u64;
756        h = h.wrapping_mul(0x100000001b3u64);
757        for c in classes.iter() {
758            for &b in c.as_bytes() {
759                h ^= b as u64;
760                h = h.wrapping_mul(0x100000001b3u64);
761            }
762        }
763        h
764    }
765}
766
767/// Supported HTML tag variants.
768#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
769pub enum Tag {
770    Div,
771    Span,
772    Button,
773    Input,
774    Select,
775    Option,
776    Textarea,
777    Label,
778    Form,
779    Header,
780    Nav,
781    Main,
782    Section,
783    Aside,
784    Footer,
785    H1,
786    H2,
787    H3,
788    H4,
789    H5,
790    H6,
791    P,
792    Ul,
793    Ol,
794    Li,
795    A,
796    Img,
797    Svg,
798    Path,
799    Canvas,
800    Table,
801    Thead,
802    Tbody,
803    Tr,
804    Th,
805    Td,
806    Hr,
807    Br,
808    Custom(&'static str),
809}
810
811impl Tag {
812    /// Maps this DOM tag to its corresponding 1-byte IR tag variant.
813    pub fn to_ir_tag(self) -> IrTag {
814        match self {
815            Tag::Div
816            | Tag::Main
817            | Tag::Section
818            | Tag::Header
819            | Tag::Footer
820            | Tag::Nav
821            | Tag::Aside
822            | Tag::Form
823            | Tag::Table
824            | Tag::Thead
825            | Tag::Tbody
826            | Tag::Tr
827            | Tag::Th
828            | Tag::Td
829            | Tag::Ul
830            | Tag::Ol
831            | Tag::Li
832            | Tag::Hr => IrTag::Div,
833            Tag::Span
834            | Tag::Label
835            | Tag::P
836            | Tag::H1
837            | Tag::H2
838            | Tag::H3
839            | Tag::H4
840            | Tag::H5
841            | Tag::H6
842            | Tag::A
843            | Tag::Br => IrTag::Span,
844            Tag::Button => IrTag::Button,
845            Tag::Input | Tag::Textarea | Tag::Select | Tag::Option => IrTag::Input,
846            Tag::Img => IrTag::Image,
847            Tag::Svg | Tag::Path => IrTag::Svg,
848            Tag::Canvas => IrTag::Canvas3D,
849            Tag::Custom(_) => IrTag::Div,
850        }
851    }
852}
853
854/// Universal trait converting Rust expressions into `NodeBlueprint` in RSX children.
855pub trait IntoNodeBlueprint {
856    fn into_node_blueprint(self) -> NodeBlueprint;
857}
858
859impl IntoNodeBlueprint for NodeBlueprint {
860    #[inline]
861    fn into_node_blueprint(self) -> NodeBlueprint {
862        self
863    }
864}
865
866impl IntoNodeBlueprint for View {
867    #[inline]
868    fn into_node_blueprint(self) -> NodeBlueprint {
869        self.root
870    }
871}
872
873impl IntoNodeBlueprint for () {
874    #[inline]
875    fn into_node_blueprint(self) -> NodeBlueprint {
876        NodeBlueprint::Empty
877    }
878}
879
880impl IntoNodeBlueprint for &str {
881    #[inline]
882    fn into_node_blueprint(self) -> NodeBlueprint {
883        NodeBlueprint::Text(self.to_string())
884    }
885}
886
887impl IntoNodeBlueprint for String {
888    #[inline]
889    fn into_node_blueprint(self) -> NodeBlueprint {
890        NodeBlueprint::Text(self)
891    }
892}
893
894impl IntoNodeBlueprint for &String {
895    #[inline]
896    fn into_node_blueprint(self) -> NodeBlueprint {
897        NodeBlueprint::Text(self.clone())
898    }
899}
900
901impl IntoNodeBlueprint for bool {
902    #[inline]
903    fn into_node_blueprint(self) -> NodeBlueprint {
904        NodeBlueprint::Text(self.to_string())
905    }
906}
907
908macro_rules! impl_into_node_blueprint_for_num {
909    ($($t:ty),*) => {
910        $(
911            impl IntoNodeBlueprint for $t {
912                #[inline]
913                fn into_node_blueprint(self) -> NodeBlueprint {
914                    NodeBlueprint::Text(self.to_string())
915                }
916            }
917        )*
918    };
919}
920
921impl_into_node_blueprint_for_num!(
922    i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64
923);
924
925impl<T: IntoNodeBlueprint> IntoNodeBlueprint for Option<T> {
926    #[inline]
927    fn into_node_blueprint(self) -> NodeBlueprint {
928        match self {
929            Some(val) => val.into_node_blueprint(),
930            None => NodeBlueprint::Empty,
931        }
932    }
933}
934
935impl<T: IntoNodeBlueprint> IntoNodeBlueprint for Vec<T> {
936    #[inline]
937    fn into_node_blueprint(self) -> NodeBlueprint {
938        let children: Vec<NodeBlueprint> = self
939            .into_iter()
940            .map(|item| item.into_node_blueprint())
941            .collect();
942        NodeBlueprint::Fragment(children)
943    }
944}
945
946impl<I, F, T> IntoNodeBlueprint for std::iter::Map<I, F>
947where
948    I: Iterator,
949    F: FnMut(I::Item) -> T,
950    T: IntoNodeBlueprint,
951{
952    #[inline]
953    fn into_node_blueprint(self) -> NodeBlueprint {
954        let children: Vec<NodeBlueprint> = self.map(|item| item.into_node_blueprint()).collect();
955        NodeBlueprint::Fragment(children)
956    }
957}
958
959impl IntoNodeBlueprint for Rc<dyn Fn() -> String> {
960    #[inline]
961    fn into_node_blueprint(self) -> NodeBlueprint {
962        NodeBlueprint::DynamicText(self)
963    }
964}
965
966impl<T: std::fmt::Display + Clone + 'static> IntoNodeBlueprint for reactive::Signal<T> {
967    #[inline]
968    fn into_node_blueprint(self) -> NodeBlueprint {
969        NodeBlueprint::DynamicText(Rc::new(move || self.get().to_string()))
970    }
971}
972
973impl<T: std::fmt::Display + Clone + 'static> IntoNodeBlueprint for &reactive::Signal<T> {
974    #[inline]
975    fn into_node_blueprint(self) -> NodeBlueprint {
976        let sig = self.clone();
977        NodeBlueprint::DynamicText(Rc::new(move || sig.get().to_string()))
978    }
979}
980
981impl<T: std::fmt::Display + Clone + 'static> IntoNodeBlueprint for reactive::ReadSignal<T> {
982    #[inline]
983    fn into_node_blueprint(self) -> NodeBlueprint {
984        NodeBlueprint::DynamicText(Rc::new(move || self.get().to_string()))
985    }
986}
987
988impl<T: std::fmt::Display + Clone + 'static> IntoNodeBlueprint for &reactive::ReadSignal<T> {
989    #[inline]
990    fn into_node_blueprint(self) -> NodeBlueprint {
991        let sig = self.clone();
992        NodeBlueprint::DynamicText(Rc::new(move || sig.get().to_string()))
993    }
994}
995
996#[cfg(test)]
997mod entity_tests {
998    use super::*;
999
1000    #[test]
1001    fn test_node_blueprint_entity_id_assignment_and_lookup() {
1002        let id1 = EntityId::new(101);
1003        let id2 = EntityId::new(102);
1004
1005        let bp = NodeBlueprint::element_simple(
1006            Tag::Div,
1007            "container",
1008            vec![NodeBlueprint::element_simple(
1009                Tag::P,
1010                "child",
1011                vec![NodeBlueprint::text("Hello")],
1012            )
1013            .with_entity_id(id2)],
1014        )
1015        .with_entity_id(id1);
1016
1017        assert_eq!(bp.entity_id(), Some(id1));
1018        let found1 = bp.find_by_entity_id(id1);
1019        assert!(found1.is_some());
1020        assert_eq!(found1.unwrap().entity_id(), Some(id1));
1021
1022        let found2 = bp.find_by_entity_id(id2);
1023        assert!(found2.is_some());
1024        assert_eq!(found2.unwrap().entity_id(), Some(id2));
1025
1026        assert!(bp.find_by_entity_id(EntityId::new(999)).is_none());
1027    }
1028
1029    #[test]
1030    fn test_ensure_entity_ids_preserves_flattening() {
1031        let mut tree = NodeBlueprint::element_simple(
1032            Tag::Div,
1033            "root",
1034            vec![NodeBlueprint::fragment(vec![
1035                NodeBlueprint::element_simple(Tag::Span, "first", vec![]),
1036                NodeBlueprint::element_simple(Tag::Span, "second", vec![]),
1037            ])],
1038        );
1039
1040        tree.ensure_entity_ids();
1041        let root_id = tree.entity_id().unwrap();
1042        assert!(root_id.is_valid());
1043
1044        let flat = tree.flatten_fragments();
1045        assert_eq!(flat.entity_id(), Some(root_id));
1046
1047        if let NodeBlueprint::Element { children, .. } = &flat {
1048            assert_eq!(children.len(), 2);
1049            assert!(children[0].entity_id().is_some());
1050            assert!(children[1].entity_id().is_some());
1051            assert_ne!(children[0].entity_id(), children[1].entity_id());
1052        } else {
1053            panic!("Expected Element node");
1054        }
1055    }
1056}