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