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
35impl Default for View {
36    #[inline]
37    fn default() -> Self {
38        Self::new(NodeBlueprint::Empty)
39    }
40}
41
42pub mod classes;
43pub mod clipboard;
44pub mod error_boundary;
45pub mod events;
46pub mod hooks;
47pub mod ir;
48pub mod portal;
49pub mod reactive;
50pub mod spring;
51pub mod text_input;
52
53pub use classes::{
54    standard_class_index, ClassBitmask, ClassIter, ClassList, IntoClassList, STANDARD_CLASSES,
55};
56pub use clipboard::{
57    clear_system_clipboard_bridge, get_clipboard_text, register_system_clipboard_bridge,
58    set_clipboard_text,
59};
60pub use error_boundary::{ErrorBoundary, ErrorBoundaryBuilder, ErrorBoundaryInfo};
61pub use events::{Event, EventDispatcher, EventPhase, EventType};
62pub use hooks::*;
63pub use ir::{
64    ChildIter, DisplayChunkRange, FixedRect, IrNodeFlags, IrTag, MemoCache, MemoEntry, NodeId,
65    StackGuard, UiIrGraph, UiIrNode,
66};
67pub use portal::{
68    create_anchored_portal, create_dropdown_portal, create_portal, AnchorPlacement, Portal,
69    PortalBuilder,
70};
71pub use reactive::{
72    batch, clear_hmr_signals, clear_persistent_signals, create_context, create_signal,
73    export_hmr_signals, has_dirty_signals, import_hmr_signals, mark_dirty, peek_dirty_signal_names,
74    provide_context, reactive_telemetry_snapshot, reset_component_hooks, set_signal_name,
75    signal_name, take_dirty_signal_names, take_dirty_signals, untrack, use_callback, use_context,
76    use_effect, use_effect_with_deps, use_hmr_signal, use_id, use_memo, use_memo_with_deps,
77    use_persistent_signal, use_reducer, use_reducer_init, use_ref, use_signal, use_state,
78    with_component_key, with_root_component_scope, ComponentScopeGuard, Context, Effect,
79    EffectGuard, HmrCodec, IntoEffectCleanup, IntoInitialState, Memo, ReactiveRuntime,
80    ReactiveTelemetrySnapshot, ReadSignal, Ref, ScopeId, SetSignal, Signal, SignalId,
81    SignalTelemetryEntry, SubscriberId, WriteSignal,
82};
83pub use spring::{SpringConfig, SpringSignal};
84pub use strata_primitives::EntityId;
85pub use text_input::{InputKey, InputKeyResult, InputModifiers, TextInputState};
86
87/// Ergonomic conversion into `Option<String>` for `#[component]` builder setters.
88///
89/// Accepts string literals (`"hello"`), `String`, `&String`, `Cow<'_, str>`, `Option<String>`,
90/// and bare `None` without `.to_string()` boilerplate or type-inference ambiguity.
91pub trait IntoOptionalString {
92    fn into_optional_string(self) -> Option<String>;
93}
94
95impl IntoOptionalString for String {
96    #[inline]
97    fn into_optional_string(self) -> Option<String> {
98        Some(self)
99    }
100}
101
102impl IntoOptionalString for &str {
103    #[inline]
104    fn into_optional_string(self) -> Option<String> {
105        Some(self.to_string())
106    }
107}
108
109impl IntoOptionalString for &String {
110    #[inline]
111    fn into_optional_string(self) -> Option<String> {
112        Some(self.clone())
113    }
114}
115
116impl IntoOptionalString for std::borrow::Cow<'_, str> {
117    #[inline]
118    fn into_optional_string(self) -> Option<String> {
119        Some(self.into_owned())
120    }
121}
122
123impl IntoOptionalString for Option<String> {
124    #[inline]
125    fn into_optional_string(self) -> Option<String> {
126        self
127    }
128}
129
130/// Converts RSX children lists (`Vec<NodeBlueprint>`), single `NodeBlueprint`, or `View` values
131/// into the `children` parameter type declared on a `#[component]` (`View`, `NodeBlueprint`,
132/// `Vec<NodeBlueprint>`, or their `Option<...>` forms).
133pub trait IntoChildren<Target> {
134    fn into_children(self) -> Target;
135}
136
137impl IntoChildren<Vec<NodeBlueprint>> for Vec<NodeBlueprint> {
138    #[inline]
139    fn into_children(self) -> Vec<NodeBlueprint> {
140        self
141    }
142}
143
144impl IntoChildren<Vec<NodeBlueprint>> for Option<Vec<NodeBlueprint>> {
145    #[inline]
146    fn into_children(self) -> Vec<NodeBlueprint> {
147        self.unwrap_or_default()
148    }
149}
150
151impl IntoChildren<Vec<NodeBlueprint>> for NodeBlueprint {
152    #[inline]
153    fn into_children(mut self) -> Vec<NodeBlueprint> {
154        match &mut self {
155            NodeBlueprint::Empty => Vec::new(),
156            NodeBlueprint::Fragment(children) => std::mem::take(children),
157            _ => vec![self],
158        }
159    }
160}
161
162impl IntoChildren<Vec<NodeBlueprint>> for View {
163    #[inline]
164    fn into_children(self) -> Vec<NodeBlueprint> {
165        self.root.into_children()
166    }
167}
168
169impl IntoChildren<View> for View {
170    #[inline]
171    fn into_children(self) -> View {
172        self
173    }
174}
175
176impl IntoChildren<View> for NodeBlueprint {
177    #[inline]
178    fn into_children(self) -> View {
179        View::new(self)
180    }
181}
182
183impl IntoChildren<View> for Vec<NodeBlueprint> {
184    #[inline]
185    fn into_children(mut self) -> View {
186        match self.len() {
187            0 => View::new(NodeBlueprint::Empty),
188            1 => View::new(self.remove(0)),
189            _ => View::new(NodeBlueprint::Fragment(self)),
190        }
191    }
192}
193
194impl IntoChildren<View> for Option<Vec<NodeBlueprint>> {
195    #[inline]
196    fn into_children(self) -> View {
197        self.unwrap_or_default().into_children()
198    }
199}
200
201impl IntoChildren<NodeBlueprint> for NodeBlueprint {
202    #[inline]
203    fn into_children(self) -> NodeBlueprint {
204        self
205    }
206}
207
208impl IntoChildren<NodeBlueprint> for View {
209    #[inline]
210    fn into_children(self) -> NodeBlueprint {
211        self.root
212    }
213}
214
215impl IntoChildren<NodeBlueprint> for Vec<NodeBlueprint> {
216    #[inline]
217    fn into_children(self) -> NodeBlueprint {
218        IntoChildren::<View>::into_children(self).root
219    }
220}
221
222impl IntoChildren<Option<Vec<NodeBlueprint>>> for Option<Vec<NodeBlueprint>> {
223    #[inline]
224    fn into_children(self) -> Option<Vec<NodeBlueprint>> {
225        self
226    }
227}
228
229impl IntoChildren<Option<Vec<NodeBlueprint>>> for Vec<NodeBlueprint> {
230    #[inline]
231    fn into_children(self) -> Option<Vec<NodeBlueprint>> {
232        Some(self)
233    }
234}
235
236impl IntoChildren<Option<Vec<NodeBlueprint>>> for View {
237    #[inline]
238    fn into_children(self) -> Option<Vec<NodeBlueprint>> {
239        Some(self.into_children())
240    }
241}
242
243impl IntoChildren<Option<Vec<NodeBlueprint>>> for NodeBlueprint {
244    #[inline]
245    fn into_children(self) -> Option<Vec<NodeBlueprint>> {
246        Some(self.into_children())
247    }
248}
249
250impl IntoChildren<Option<View>> for Option<View> {
251    #[inline]
252    fn into_children(self) -> Option<View> {
253        self
254    }
255}
256
257impl IntoChildren<Option<View>> for View {
258    #[inline]
259    fn into_children(self) -> Option<View> {
260        Some(self)
261    }
262}
263
264impl IntoChildren<Option<View>> for Vec<NodeBlueprint> {
265    #[inline]
266    fn into_children(self) -> Option<View> {
267        Some(self.into_children())
268    }
269}
270
271impl IntoChildren<Option<View>> for NodeBlueprint {
272    #[inline]
273    fn into_children(self) -> Option<View> {
274        Some(View::new(self))
275    }
276}
277
278impl IntoChildren<Option<NodeBlueprint>> for Option<NodeBlueprint> {
279    #[inline]
280    fn into_children(self) -> Option<NodeBlueprint> {
281        self
282    }
283}
284
285impl IntoChildren<Option<NodeBlueprint>> for NodeBlueprint {
286    #[inline]
287    fn into_children(self) -> Option<NodeBlueprint> {
288        Some(self)
289    }
290}
291
292impl IntoChildren<Option<NodeBlueprint>> for Vec<NodeBlueprint> {
293    #[inline]
294    fn into_children(self) -> Option<NodeBlueprint> {
295        Some(self.into_children())
296    }
297}
298
299impl IntoChildren<Option<NodeBlueprint>> for View {
300    #[inline]
301    fn into_children(self) -> Option<NodeBlueprint> {
302        Some(self.root)
303    }
304}
305
306/// Trait abstracting event handlers accepting `()` or `(Event)`.
307pub trait EventHandlerMarker<Args> {
308    fn call_handler(&self, event: Event);
309}
310
311impl<F: Fn(Event) + 'static> EventHandlerMarker<(Event,)> for F {
312    fn call_handler(&self, event: Event) {
313        (self)(event);
314    }
315}
316
317impl<F: Fn() + 'static> EventHandlerMarker<()> for F {
318    fn call_handler(&self, _event: Event) {
319        (self)();
320    }
321}
322
323impl EventHandlerMarker<()> for Rc<dyn Fn()> {
324    fn call_handler(&self, _event: Event) {
325        (self)();
326    }
327}
328
329impl EventHandlerMarker<(Event,)> for Rc<dyn Fn(Event)> {
330    fn call_handler(&self, event: Event) {
331        (self)(event);
332    }
333}
334
335impl<F: Fn(Event) + 'static> EventHandlerMarker<(Rc<()>, Event)> for Rc<F> {
336    fn call_handler(&self, event: Event) {
337        (self)(event);
338    }
339}
340
341impl<F: Fn() + 'static> EventHandlerMarker<(Rc<()>,)> for Rc<F> {
342    fn call_handler(&self, _event: Event) {
343        (self)();
344    }
345}
346
347impl<Args, F: EventHandlerMarker<Args>> EventHandlerMarker<Args> for Option<F> {
348    fn call_handler(&self, event: Event) {
349        if let Some(ref handler) = self {
350            handler.call_handler(event);
351        }
352    }
353}
354
355/// Trait abstracting input/change value handlers accepting `()` or `(String)`.
356pub trait ValueHandlerMarker<Args> {
357    fn call_handler(&self, val: String);
358}
359
360impl<F: Fn(String) + 'static> ValueHandlerMarker<(String,)> for F {
361    fn call_handler(&self, val: String) {
362        (self)(val);
363    }
364}
365
366impl<F: Fn() + 'static> ValueHandlerMarker<()> for F {
367    fn call_handler(&self, _val: String) {
368        (self)();
369    }
370}
371
372impl ValueHandlerMarker<(String,)> for Rc<dyn Fn(String)> {
373    fn call_handler(&self, val: String) {
374        (self)(val);
375    }
376}
377
378impl ValueHandlerMarker<()> for Rc<dyn Fn()> {
379    fn call_handler(&self, _val: String) {
380        (self)();
381    }
382}
383
384impl<F: Fn(String) + 'static> ValueHandlerMarker<(Rc<()>, String)> for Rc<F> {
385    fn call_handler(&self, val: String) {
386        (self)(val);
387    }
388}
389
390impl<F: Fn() + 'static> ValueHandlerMarker<(Rc<()>,)> for Rc<F> {
391    fn call_handler(&self, _val: String) {
392        (self)();
393    }
394}
395
396impl<Args, F: ValueHandlerMarker<Args>> ValueHandlerMarker<Args> for Option<F> {
397    fn call_handler(&self, val: String) {
398        if let Some(ref handler) = self {
399            handler.call_handler(val);
400        }
401    }
402}
403
404/// DOM element attribute or event listener.
405#[derive(Clone)]
406pub enum Attribute {
407    Property {
408        key: String,
409        value: String,
410    },
411    EventListener {
412        event: EventType,
413        handler: Rc<dyn Fn(Event)>,
414    },
415    DirectStyle(Rc<dyn std::any::Any>),
416    /// Thread-safe type-erased 3D scene handle (e.g. `Arc<strata_render::Scene3D>`) attached to a viewport element.
417    ScenePayload(std::sync::Arc<dyn std::any::Any + Send + Sync>),
418    Entity(EntityId),
419}
420
421impl Attribute {
422    pub fn property(key: impl Into<String>, value: impl Into<String>) -> Self {
423        Self::Property {
424            key: key.into(),
425            value: value.into(),
426        }
427    }
428
429    pub fn direct_style<T: 'static>(style: T) -> Self {
430        Self::DirectStyle(Rc::new(style))
431    }
432
433    pub fn scene_payload<T: Send + Sync + 'static>(payload: T) -> Self {
434        Self::ScenePayload(std::sync::Arc::new(payload))
435    }
436
437    pub fn scene_payload_arc(payload: std::sync::Arc<dyn std::any::Any + Send + Sync>) -> Self {
438        Self::ScenePayload(payload)
439    }
440
441    pub fn entity(id: EntityId) -> Self {
442        Self::Entity(id)
443    }
444
445    pub fn event_listener<Args, F: EventHandlerMarker<Args> + 'static>(
446        event: EventType,
447        handler: F,
448    ) -> Self {
449        Self::EventListener {
450            event,
451            handler: Rc::new(move |e| handler.call_handler(e)),
452        }
453    }
454
455    pub fn value_listener<Args, F: ValueHandlerMarker<Args> + 'static>(
456        event: EventType,
457        handler: F,
458    ) -> Self {
459        Self::EventListener {
460            event,
461            handler: Rc::new(move |e| handler.call_handler(e.value.clone())),
462        }
463    }
464}
465
466impl std::fmt::Debug for Attribute {
467    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
468        match self {
469            Self::Property { key, value } => f
470                .debug_struct("Property")
471                .field("key", key)
472                .field("value", value)
473                .finish(),
474            Self::EventListener { event, .. } => f
475                .debug_struct("EventListener")
476                .field("event", event)
477                .field("handler", &"<callback>")
478                .finish(),
479            Self::DirectStyle(_) => f
480                .debug_tuple("DirectStyle")
481                .field(&"<typed_style>")
482                .finish(),
483            Self::ScenePayload(_) => f.debug_tuple("ScenePayload").field(&"<scene_3d>").finish(),
484            Self::Entity(id) => f.debug_tuple("Entity").field(id).finish(),
485        }
486    }
487}
488
489/// Core reactive blueprint tree representation.
490#[derive(Clone)]
491pub enum NodeBlueprint {
492    Element {
493        tag: Tag,
494        classes: ClassList,
495        attributes: Vec<Attribute>,
496        children: Vec<NodeBlueprint>,
497    },
498    Text(String),
499    DynamicText(Rc<dyn Fn() -> String>),
500    Fragment(Vec<NodeBlueprint>),
501    Empty,
502}
503
504impl std::fmt::Debug for NodeBlueprint {
505    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
506        match self {
507            Self::Element {
508                tag,
509                classes,
510                attributes,
511                children,
512            } => f
513                .debug_struct("Element")
514                .field("tag", tag)
515                .field("classes", classes)
516                .field("attributes", attributes)
517                .field("children", children)
518                .finish(),
519            Self::Text(t) => f.debug_tuple("Text").field(t).finish(),
520            Self::DynamicText(_) => f.debug_tuple("DynamicText").field(&"<dynamic>").finish(),
521            Self::Fragment(c) => f.debug_tuple("Fragment").field(c).finish(),
522            Self::Empty => write!(f, "Empty"),
523        }
524    }
525}
526
527impl Default for NodeBlueprint {
528    #[inline]
529    fn default() -> Self {
530        Self::Empty
531    }
532}
533
534impl NodeBlueprint {
535    pub fn element(
536        tag: Tag,
537        classes: impl Into<ClassList>,
538        attributes: Vec<Attribute>,
539        children: Vec<NodeBlueprint>,
540    ) -> Self {
541        Self::Element {
542            tag,
543            classes: classes.into(),
544            attributes,
545            children,
546        }
547    }
548
549    pub fn element_simple(
550        tag: Tag,
551        classes: impl Into<ClassList>,
552        children: Vec<NodeBlueprint>,
553    ) -> Self {
554        Self::Element {
555            tag,
556            classes: classes.into(),
557            attributes: Vec::new(),
558            children,
559        }
560    }
561
562    pub fn text(content: impl Into<String>) -> Self {
563        Self::Text(content.into())
564    }
565
566    pub fn dynamic_text(f: impl Fn() -> String + 'static) -> Self {
567        Self::DynamicText(Rc::new(f))
568    }
569
570    pub fn fragment(children: Vec<NodeBlueprint>) -> Self {
571        Self::Fragment(children)
572    }
573
574    pub fn empty() -> Self {
575        Self::Empty
576    }
577
578    /// Returns the EntityId assigned to this blueprint element if present.
579    pub fn entity_id(&self) -> Option<EntityId> {
580        match self {
581            Self::Element { attributes, .. } => {
582                for attr in attributes {
583                    if let Attribute::Entity(id) = attr {
584                        if id.is_valid() {
585                            return Some(*id);
586                        }
587                    }
588                }
589                None
590            }
591            _ => None,
592        }
593    }
594
595    /// Assigns or overrides the EntityId for an Element node blueprint.
596    pub fn with_entity_id(mut self, entity_id: EntityId) -> Self {
597        self.set_entity_id(entity_id);
598        self
599    }
600
601    /// Mutably assigns or overrides the EntityId for an Element node blueprint.
602    pub fn set_entity_id(&mut self, entity_id: EntityId) {
603        if let Self::Element { attributes, .. } = self {
604            if let Some(pos) = attributes
605                .iter()
606                .position(|a| matches!(a, Attribute::Entity(_)))
607            {
608                attributes[pos] = Attribute::Entity(entity_id);
609            } else {
610                attributes.push(Attribute::Entity(entity_id));
611            }
612        }
613    }
614
615    /// Iteratively ensures all Element nodes in this blueprint tree have a valid EntityId
616    /// without consuming call-stack frames on deeply nested trees.
617    pub fn ensure_entity_ids(&mut self) {
618        let mut stack: Vec<&mut NodeBlueprint> = vec![self];
619        while let Some(node) = stack.pop() {
620            match node {
621                Self::Element {
622                    attributes,
623                    children,
624                    ..
625                } => {
626                    let has_id = attributes
627                        .iter()
628                        .any(|a| matches!(a, Attribute::Entity(id) if id.is_valid()));
629                    if !has_id {
630                        attributes.push(Attribute::Entity(EntityId::next()));
631                    }
632                    for child in children.iter_mut().rev() {
633                        stack.push(child);
634                    }
635                }
636                Self::Fragment(children) => {
637                    for child in children.iter_mut().rev() {
638                        stack.push(child);
639                    }
640                }
641                _ => {}
642            }
643        }
644    }
645
646    /// Iteratively locates an element blueprint node by its EntityId (O(1) call stack).
647    pub fn find_by_entity_id(&self, target_id: EntityId) -> Option<&NodeBlueprint> {
648        if !target_id.is_valid() {
649            return None;
650        }
651        let mut stack = vec![self];
652        while let Some(node) = stack.pop() {
653            if node.entity_id() == Some(target_id) {
654                return Some(node);
655            }
656            match node {
657                Self::Element { children, .. } | Self::Fragment(children) => {
658                    for child in children.iter().rev() {
659                        stack.push(child);
660                    }
661                }
662                _ => {}
663            }
664        }
665        None
666    }
667
668    /// Iteratively locates a mutable element blueprint node by its EntityId (O(1) call stack).
669    pub fn find_by_entity_id_mut(&mut self, target_id: EntityId) -> Option<&mut NodeBlueprint> {
670        if !target_id.is_valid() {
671            return None;
672        }
673        let mut stack = vec![self];
674        while let Some(node) = stack.pop() {
675            if node.entity_id() == Some(target_id) {
676                return Some(node);
677            }
678            match node {
679                Self::Element { children, .. } | Self::Fragment(children) => {
680                    for child in children.iter_mut().rev() {
681                        stack.push(child);
682                    }
683                }
684                _ => {}
685            }
686        }
687        None
688    }
689
690    /// Returns the DOM node UID from a `data-strata-node-uid` attribute if present.
691    pub fn dom_uid(&self) -> Option<u64> {
692        match self {
693            Self::Element { attributes, .. } => {
694                for attr in attributes {
695                    if let Attribute::Property { key, value } = attr {
696                        if key == "data-strata-node-uid" {
697                            if let Ok(uid) = value.parse::<u64>() {
698                                return Some(uid);
699                            }
700                        }
701                    }
702                }
703                None
704            }
705            _ => None,
706        }
707    }
708
709    /// Iteratively locates an element blueprint node by its DOM node UID (O(1) call stack).
710    pub fn find_by_dom_uid(&self, target_uid: u64) -> Option<&NodeBlueprint> {
711        let mut stack = vec![self];
712        while let Some(node) = stack.pop() {
713            if node.dom_uid() == Some(target_uid) {
714                return Some(node);
715            }
716            match node {
717                Self::Element { children, .. } | Self::Fragment(children) => {
718                    for child in children.iter().rev() {
719                        stack.push(child);
720                    }
721                }
722                _ => {}
723            }
724        }
725        None
726    }
727
728    /// Iteratively locates a mutable element blueprint node by its DOM node UID (O(1) call stack).
729    pub fn find_by_dom_uid_mut(&mut self, target_uid: u64) -> Option<&mut NodeBlueprint> {
730        let mut stack = vec![self];
731        while let Some(node) = stack.pop() {
732            if node.dom_uid() == Some(target_uid) {
733                return Some(node);
734            }
735            match node {
736                Self::Element { children, .. } | Self::Fragment(children) => {
737                    for child in children.iter_mut().rev() {
738                        stack.push(child);
739                    }
740                }
741                _ => {}
742            }
743        }
744        None
745    }
746
747    /// Iteratively calculates the index path to the element blueprint node with matching DOM node UID (O(1) call stack).
748    pub fn find_path_by_dom_uid(&self, target_uid: u64) -> Option<Vec<usize>> {
749        if self.dom_uid() == Some(target_uid) {
750            return Some(Vec::new());
751        }
752        let mut path = Vec::new();
753        let mut stack: Vec<(&[NodeBlueprint], usize)> = Vec::new();
754        match self {
755            Self::Element { children, .. } | Self::Fragment(children) if !children.is_empty() => {
756                stack.push((children.as_slice(), 0));
757            }
758            _ => return None,
759        }
760        while let Some((slice, idx)) = stack.last_mut() {
761            if *idx >= slice.len() {
762                stack.pop();
763                path.pop();
764                continue;
765            }
766            let current_idx = *idx;
767            let child = &slice[current_idx];
768            *idx += 1;
769            path.push(current_idx);
770            if child.dom_uid() == Some(target_uid) {
771                return Some(path);
772            }
773            match child {
774                Self::Element { children, .. } | Self::Fragment(children)
775                    if !children.is_empty() =>
776                {
777                    stack.push((children.as_slice(), 0));
778                }
779                _ => {
780                    path.pop();
781                }
782            }
783        }
784        None
785    }
786
787    /// Iteratively calculates the index path to the element blueprint node with matching EntityId (O(1) call stack).
788    pub fn find_path_by_entity_id(&self, target_id: EntityId) -> Option<Vec<usize>> {
789        if !target_id.is_valid() {
790            return None;
791        }
792        if self.entity_id() == Some(target_id) {
793            return Some(Vec::new());
794        }
795        let mut path = Vec::new();
796        let mut stack: Vec<(&[NodeBlueprint], usize)> = Vec::new();
797        match self {
798            Self::Element { children, .. } | Self::Fragment(children) if !children.is_empty() => {
799                stack.push((children.as_slice(), 0));
800            }
801            _ => return None,
802        }
803        while let Some((slice, idx)) = stack.last_mut() {
804            if *idx >= slice.len() {
805                stack.pop();
806                path.pop();
807                continue;
808            }
809            let current_idx = *idx;
810            let child = &slice[current_idx];
811            *idx += 1;
812            path.push(current_idx);
813            if child.entity_id() == Some(target_id) {
814                return Some(path);
815            }
816            match child {
817                Self::Element { children, .. } | Self::Fragment(children)
818                    if !children.is_empty() =>
819                {
820                    stack.push((children.as_slice(), 0));
821                }
822                _ => {
823                    path.pop();
824                }
825            }
826        }
827        None
828    }
829
830    /// Iteratively flattens nested Fragment nodes within Element children,
831    /// splicing fragment children directly into their parent elements without deep recursion.
832    pub fn flatten_fragments(mut self) -> Self {
833        let mut stack: Vec<&mut NodeBlueprint> = vec![&mut self];
834        while let Some(node) = stack.pop() {
835            let children_opt = match node {
836                Self::Element { children, .. } | Self::Fragment(children) => Some(children),
837                _ => None,
838            };
839            if let Some(children) = children_opt {
840                let needs_flatten = children
841                    .iter()
842                    .any(|c| matches!(c, Self::Fragment(_) | Self::Empty));
843                if needs_flatten {
844                    let old = std::mem::take(children);
845                    let mut flat = Vec::with_capacity(old.len());
846                    let mut splice_stack: Vec<NodeBlueprint> = old.into_iter().rev().collect();
847                    while let Some(mut item) = splice_stack.pop() {
848                        match &mut item {
849                            Self::Fragment(sub) => {
850                                for s in std::mem::take(sub).into_iter().rev() {
851                                    splice_stack.push(s);
852                                }
853                            }
854                            Self::Empty => {}
855                            _ => flat.push(item),
856                        }
857                    }
858                    *children = flat;
859                }
860                for child in children.iter_mut().rev() {
861                    stack.push(child);
862                }
863            }
864        }
865        self
866    }
867
868    fn append_ir_children(
869        graph: &mut UiIrGraph,
870        parent_id: NodeId,
871        children: &[NodeBlueprint],
872        depth: usize,
873    ) {
874        if depth >= 256 {
875            return;
876        }
877        for child in children {
878            match child {
879                NodeBlueprint::Fragment(subchildren) => {
880                    Self::append_ir_children(graph, parent_id, subchildren, depth + 1);
881                }
882                NodeBlueprint::Empty => {}
883                _ => {
884                    let child_id = child.compile_to_ir_depth(graph, depth + 1);
885                    if !child_id.is_null() {
886                        graph.append_child(parent_id, child_id);
887                    }
888                }
889            }
890        }
891    }
892
893    /// Compiles this reactive blueprint tree into a contiguous 64-byte aligned `UiIrGraph`.
894    pub fn compile_to_ir(&self, graph: &mut UiIrGraph) -> NodeId {
895        self.compile_to_ir_depth(graph, 0)
896    }
897
898    fn compile_to_ir_depth(&self, graph: &mut UiIrGraph, depth: usize) -> NodeId {
899        if depth >= 256 {
900            return NodeId::NULL;
901        }
902        match self {
903            Self::Element {
904                tag,
905                classes,
906                attributes,
907                children,
908            } => {
909                let mut ir_tag = tag.to_ir_tag();
910                if classes
911                    .iter()
912                    .any(|c| c == "grid" || c.starts_with("grid-"))
913                {
914                    ir_tag = IrTag::GridContainer;
915                } else if classes
916                    .iter()
917                    .any(|c| c == "flex" || c.starts_with("flex-"))
918                {
919                    ir_tag = IrTag::FlexContainer;
920                } else if classes.iter().any(|c| {
921                    c == "overflow-auto"
922                        || c == "overflow-scroll"
923                        || c == "overflow-y-auto"
924                        || c == "overflow-y-scroll"
925                }) {
926                    ir_tag = IrTag::ScrollView;
927                }
928
929                let mut flags = IrNodeFlags::IS_VISIBLE;
930                for attr in attributes {
931                    if matches!(attr, Attribute::EventListener { .. }) {
932                        flags |= IrNodeFlags::HAS_EVENT_LISTENERS;
933                    }
934                }
935                if classes.iter().any(|c| {
936                    c == "contain-strict" || c == "contain-paint" || c == "overflow-hidden"
937                }) {
938                    flags |= IrNodeFlags::IS_CONTAINMENT_BOUNDARY;
939                }
940
941                let node_id = graph.alloc_node(ir_tag);
942                let memo_hash = Self::compute_hash(ir_tag as u8, classes);
943                if let Some(node) = graph.get_mut(node_id) {
944                    node.flags = flags;
945                    node.memo_hash = memo_hash;
946                }
947
948                Self::append_ir_children(graph, node_id, children, depth);
949                node_id
950            }
951            Self::Text(text) => {
952                let node_id = graph.alloc_node(IrTag::Text);
953                let mut h = 0xcbf29ce484222325u64;
954                for &b in text.as_bytes() {
955                    h ^= b as u64;
956                    h = h.wrapping_mul(0x100000001b3u64);
957                }
958                if let Some(node) = graph.get_mut(node_id) {
959                    node.flags = IrNodeFlags::IS_VISIBLE | IrNodeFlags::IS_TEXT_LEAF;
960                    node.memo_hash = h;
961                }
962                node_id
963            }
964            Self::DynamicText(_) => {
965                let node_id = graph.alloc_node(IrTag::Text);
966                if let Some(node) = graph.get_mut(node_id) {
967                    node.flags = IrNodeFlags::IS_VISIBLE | IrNodeFlags::IS_TEXT_LEAF;
968                }
969                node_id
970            }
971            Self::Fragment(children) => {
972                if children.is_empty() {
973                    return NodeId::NULL;
974                }
975                let node_id = graph.alloc_node(IrTag::ComponentRoot);
976                if let Some(node) = graph.get_mut(node_id) {
977                    node.flags = IrNodeFlags::IS_VISIBLE;
978                }
979                for child in children {
980                    let child_id = child.compile_to_ir_depth(graph, depth + 1);
981                    if !child_id.is_null() {
982                        graph.append_child(node_id, child_id);
983                    }
984                }
985                node_id
986            }
987            Self::Empty => NodeId::NULL,
988        }
989    }
990
991    fn compute_hash(tag_u8: u8, classes: &ClassList) -> u64 {
992        let mut h = 0xcbf29ce484222325u64;
993        h ^= tag_u8 as u64;
994        h = h.wrapping_mul(0x100000001b3u64);
995        for c in classes.iter() {
996            for &b in c.as_bytes() {
997                h ^= b as u64;
998                h = h.wrapping_mul(0x100000001b3u64);
999            }
1000        }
1001        h
1002    }
1003}
1004
1005/// Supported HTML tag variants.
1006#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1007pub enum Tag {
1008    Div,
1009    Span,
1010    Button,
1011    Input,
1012    Select,
1013    Option,
1014    Textarea,
1015    Label,
1016    Form,
1017    Header,
1018    Nav,
1019    Main,
1020    Section,
1021    Aside,
1022    Footer,
1023    H1,
1024    H2,
1025    H3,
1026    H4,
1027    H5,
1028    H6,
1029    P,
1030    Ul,
1031    Ol,
1032    Li,
1033    A,
1034    Img,
1035    Audio,
1036    Video,
1037    Svg,
1038    Path,
1039    Canvas,
1040    Table,
1041    Thead,
1042    Tbody,
1043    Tr,
1044    Th,
1045    Td,
1046    Hr,
1047    Br,
1048    Custom(&'static str),
1049}
1050
1051impl Tag {
1052    /// Maps this DOM tag to its corresponding 1-byte IR tag variant.
1053    pub fn to_ir_tag(self) -> IrTag {
1054        match self {
1055            Tag::Div
1056            | Tag::Main
1057            | Tag::Section
1058            | Tag::Header
1059            | Tag::Footer
1060            | Tag::Nav
1061            | Tag::Aside
1062            | Tag::Form
1063            | Tag::Table
1064            | Tag::Thead
1065            | Tag::Tbody
1066            | Tag::Tr
1067            | Tag::Th
1068            | Tag::Td
1069            | Tag::Ul
1070            | Tag::Ol
1071            | Tag::Li
1072            | Tag::Hr
1073            | Tag::Audio => IrTag::Div,
1074            Tag::Span
1075            | Tag::Label
1076            | Tag::P
1077            | Tag::H1
1078            | Tag::H2
1079            | Tag::H3
1080            | Tag::H4
1081            | Tag::H5
1082            | Tag::H6
1083            | Tag::A
1084            | Tag::Br => IrTag::Span,
1085            Tag::Button => IrTag::Button,
1086            Tag::Input | Tag::Textarea | Tag::Select | Tag::Option => IrTag::Input,
1087            Tag::Img | Tag::Video => IrTag::Image,
1088            Tag::Svg | Tag::Path => IrTag::Svg,
1089            Tag::Canvas => IrTag::Canvas3D,
1090            Tag::Custom(_) => IrTag::Div,
1091        }
1092    }
1093}
1094
1095/// Universal trait converting Rust expressions into `NodeBlueprint` in RSX children.
1096pub trait IntoNodeBlueprint {
1097    fn into_node_blueprint(self) -> NodeBlueprint;
1098}
1099
1100impl IntoNodeBlueprint for NodeBlueprint {
1101    #[inline]
1102    fn into_node_blueprint(self) -> NodeBlueprint {
1103        self
1104    }
1105}
1106
1107impl IntoNodeBlueprint for View {
1108    #[inline]
1109    fn into_node_blueprint(self) -> NodeBlueprint {
1110        self.root
1111    }
1112}
1113
1114impl IntoNodeBlueprint for () {
1115    #[inline]
1116    fn into_node_blueprint(self) -> NodeBlueprint {
1117        NodeBlueprint::Empty
1118    }
1119}
1120
1121impl IntoNodeBlueprint for &str {
1122    #[inline]
1123    fn into_node_blueprint(self) -> NodeBlueprint {
1124        NodeBlueprint::Text(self.to_string())
1125    }
1126}
1127
1128impl IntoNodeBlueprint for String {
1129    #[inline]
1130    fn into_node_blueprint(self) -> NodeBlueprint {
1131        NodeBlueprint::Text(self)
1132    }
1133}
1134
1135impl IntoNodeBlueprint for &String {
1136    #[inline]
1137    fn into_node_blueprint(self) -> NodeBlueprint {
1138        NodeBlueprint::Text(self.clone())
1139    }
1140}
1141
1142impl IntoNodeBlueprint for bool {
1143    #[inline]
1144    fn into_node_blueprint(self) -> NodeBlueprint {
1145        NodeBlueprint::Text(self.to_string())
1146    }
1147}
1148
1149macro_rules! impl_into_node_blueprint_for_num {
1150    ($($t:ty),*) => {
1151        $(
1152            impl IntoNodeBlueprint for $t {
1153                #[inline]
1154                fn into_node_blueprint(self) -> NodeBlueprint {
1155                    NodeBlueprint::Text(self.to_string())
1156                }
1157            }
1158        )*
1159    };
1160}
1161
1162impl_into_node_blueprint_for_num!(
1163    i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64
1164);
1165
1166impl<T: IntoNodeBlueprint> IntoNodeBlueprint for Option<T> {
1167    #[inline]
1168    fn into_node_blueprint(self) -> NodeBlueprint {
1169        match self {
1170            Some(val) => val.into_node_blueprint(),
1171            None => NodeBlueprint::Empty,
1172        }
1173    }
1174}
1175
1176impl<T: IntoNodeBlueprint> IntoNodeBlueprint for Vec<T> {
1177    #[inline]
1178    fn into_node_blueprint(self) -> NodeBlueprint {
1179        let children: Vec<NodeBlueprint> = self
1180            .into_iter()
1181            .map(|item| item.into_node_blueprint())
1182            .collect();
1183        NodeBlueprint::Fragment(children)
1184    }
1185}
1186
1187impl<I, F, T> IntoNodeBlueprint for std::iter::Map<I, F>
1188where
1189    I: Iterator,
1190    F: FnMut(I::Item) -> T,
1191    T: IntoNodeBlueprint,
1192{
1193    #[inline]
1194    fn into_node_blueprint(self) -> NodeBlueprint {
1195        let children: Vec<NodeBlueprint> = self.map(|item| item.into_node_blueprint()).collect();
1196        NodeBlueprint::Fragment(children)
1197    }
1198}
1199
1200impl IntoNodeBlueprint for Rc<dyn Fn() -> String> {
1201    #[inline]
1202    fn into_node_blueprint(self) -> NodeBlueprint {
1203        NodeBlueprint::DynamicText(self)
1204    }
1205}
1206
1207impl<T: std::fmt::Display + Clone + 'static> IntoNodeBlueprint for reactive::Signal<T> {
1208    #[inline]
1209    fn into_node_blueprint(self) -> NodeBlueprint {
1210        NodeBlueprint::DynamicText(Rc::new(move || self.get().to_string()))
1211    }
1212}
1213
1214impl<T: std::fmt::Display + Clone + 'static> IntoNodeBlueprint for &reactive::Signal<T> {
1215    #[inline]
1216    fn into_node_blueprint(self) -> NodeBlueprint {
1217        let sig = self.clone();
1218        NodeBlueprint::DynamicText(Rc::new(move || sig.get().to_string()))
1219    }
1220}
1221
1222impl<T: std::fmt::Display + Clone + 'static> IntoNodeBlueprint for reactive::ReadSignal<T> {
1223    #[inline]
1224    fn into_node_blueprint(self) -> NodeBlueprint {
1225        NodeBlueprint::DynamicText(Rc::new(move || self.get().to_string()))
1226    }
1227}
1228
1229impl<T: std::fmt::Display + Clone + 'static> IntoNodeBlueprint for &reactive::ReadSignal<T> {
1230    #[inline]
1231    fn into_node_blueprint(self) -> NodeBlueprint {
1232        let sig = self.clone();
1233        NodeBlueprint::DynamicText(Rc::new(move || sig.get().to_string()))
1234    }
1235}
1236
1237impl Drop for NodeBlueprint {
1238    fn drop(&mut self) {
1239        let initial = match self {
1240            Self::Element { children, .. } | Self::Fragment(children) if !children.is_empty() => {
1241                std::mem::take(children)
1242            }
1243            _ => return,
1244        };
1245        drop_blueprint_children_iterative(initial);
1246    }
1247}
1248
1249#[inline(never)]
1250fn drop_blueprint_children_iterative(mut stack: Vec<NodeBlueprint>) {
1251    while let Some(mut node) = stack.pop() {
1252        match &mut node {
1253            NodeBlueprint::Element { children, .. } | NodeBlueprint::Fragment(children)
1254                if !children.is_empty() =>
1255            {
1256                stack.append(children);
1257            }
1258            _ => {}
1259        }
1260        // `node` now has empty `children`, so its `Drop` exits immediately on the fast path.
1261    }
1262}
1263
1264#[cfg(test)]
1265mod entity_tests {
1266    use super::*;
1267
1268    #[test]
1269    fn test_node_blueprint_entity_id_assignment_and_lookup() {
1270        let id1 = EntityId::new(101);
1271        let id2 = EntityId::new(102);
1272
1273        let bp = NodeBlueprint::element_simple(
1274            Tag::Div,
1275            "container",
1276            vec![NodeBlueprint::element_simple(
1277                Tag::P,
1278                "child",
1279                vec![NodeBlueprint::text("Hello")],
1280            )
1281            .with_entity_id(id2)],
1282        )
1283        .with_entity_id(id1);
1284
1285        assert_eq!(bp.entity_id(), Some(id1));
1286        let found1 = bp.find_by_entity_id(id1);
1287        assert!(found1.is_some());
1288        assert_eq!(found1.unwrap().entity_id(), Some(id1));
1289
1290        let found2 = bp.find_by_entity_id(id2);
1291        assert!(found2.is_some());
1292        assert_eq!(found2.unwrap().entity_id(), Some(id2));
1293
1294        assert!(bp.find_by_entity_id(EntityId::new(999)).is_none());
1295    }
1296
1297    #[test]
1298    fn test_ensure_entity_ids_preserves_flattening() {
1299        let mut tree = NodeBlueprint::element_simple(
1300            Tag::Div,
1301            "root",
1302            vec![NodeBlueprint::fragment(vec![
1303                NodeBlueprint::element_simple(Tag::Span, "first", vec![]),
1304                NodeBlueprint::element_simple(Tag::Span, "second", vec![]),
1305            ])],
1306        );
1307
1308        tree.ensure_entity_ids();
1309        let root_id = tree.entity_id().unwrap();
1310        assert!(root_id.is_valid());
1311
1312        let flat = tree.flatten_fragments();
1313        assert_eq!(flat.entity_id(), Some(root_id));
1314
1315        if let NodeBlueprint::Element { children, .. } = &flat {
1316            assert_eq!(children.len(), 2);
1317            assert!(children[0].entity_id().is_some());
1318            assert!(children[1].entity_id().is_some());
1319            assert_ne!(children[0].entity_id(), children[1].entity_id());
1320        } else {
1321            panic!("Expected Element node");
1322        }
1323    }
1324
1325    #[test]
1326    fn test_10000_deep_node_blueprint_lookup_and_drop_on_1mb_stack() {
1327        std::thread::Builder::new()
1328            .name("dom-1mb-stack".to_string())
1329            .stack_size(1024 * 1024)
1330            .spawn(|| {
1331                let target_id = EntityId::new(777_777);
1332                let mut cur = NodeBlueprint::element_simple(Tag::Span, "leaf", vec![])
1333                    .with_entity_id(target_id);
1334                for _ in 0..10_000 {
1335                    cur = NodeBlueprint::element_simple(Tag::Div, "wrap", vec![cur]);
1336                }
1337                assert!(cur.find_by_entity_id(target_id).is_some());
1338                let path = cur
1339                    .find_path_by_entity_id(target_id)
1340                    .expect("deep path lookup must succeed");
1341                assert_eq!(path.len(), 10_000);
1342                drop(cur);
1343            })
1344            .expect("spawn 1MB thread")
1345            .join()
1346            .expect("10,000-deep NodeBlueprint lookup & drop must not overflow 1 MiB stack");
1347    }
1348
1349    #[test]
1350    fn test_dom_clipboard_fallback_roundtrip() {
1351        clear_system_clipboard_bridge();
1352        set_clipboard_text("strata clipboard payload");
1353        assert_eq!(
1354            get_clipboard_text().as_deref(),
1355            Some("strata clipboard payload")
1356        );
1357    }
1358}