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