1use crate::id::NodeId;
10use petgraph::graph::NodeIndex;
11use petgraph::stable_graph::StableDiGraph;
12use serde::{Deserialize, Serialize};
13use smallvec::SmallVec;
14use std::collections::HashMap;
15
16#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
20pub struct Color {
21 pub r: f32,
22 pub g: f32,
23 pub b: f32,
24 pub a: f32,
25}
26
27pub fn hex_val(c: u8) -> Option<u8> {
29 match c {
30 b'0'..=b'9' => Some(c - b'0'),
31 b'a'..=b'f' => Some(c - b'a' + 10),
32 b'A'..=b'F' => Some(c - b'A' + 10),
33 _ => None,
34 }
35}
36
37impl Color {
38 pub const fn rgba(r: f32, g: f32, b: f32, a: f32) -> Self {
39 Self { r, g, b, a }
40 }
41
42 pub fn from_hex(hex: &str) -> Option<Self> {
45 let hex = hex.strip_prefix('#').unwrap_or(hex);
46 let bytes = hex.as_bytes();
47
48 match bytes.len() {
49 3 => {
50 let r = hex_val(bytes[0])?;
51 let g = hex_val(bytes[1])?;
52 let b = hex_val(bytes[2])?;
53 Some(Self::rgba(
54 (r * 17) as f32 / 255.0,
55 (g * 17) as f32 / 255.0,
56 (b * 17) as f32 / 255.0,
57 1.0,
58 ))
59 }
60 4 => {
61 let r = hex_val(bytes[0])?;
62 let g = hex_val(bytes[1])?;
63 let b = hex_val(bytes[2])?;
64 let a = hex_val(bytes[3])?;
65 Some(Self::rgba(
66 (r * 17) as f32 / 255.0,
67 (g * 17) as f32 / 255.0,
68 (b * 17) as f32 / 255.0,
69 (a * 17) as f32 / 255.0,
70 ))
71 }
72 6 => {
73 let r = hex_val(bytes[0])? << 4 | hex_val(bytes[1])?;
74 let g = hex_val(bytes[2])? << 4 | hex_val(bytes[3])?;
75 let b = hex_val(bytes[4])? << 4 | hex_val(bytes[5])?;
76 Some(Self::rgba(
77 r as f32 / 255.0,
78 g as f32 / 255.0,
79 b as f32 / 255.0,
80 1.0,
81 ))
82 }
83 8 => {
84 let r = hex_val(bytes[0])? << 4 | hex_val(bytes[1])?;
85 let g = hex_val(bytes[2])? << 4 | hex_val(bytes[3])?;
86 let b = hex_val(bytes[4])? << 4 | hex_val(bytes[5])?;
87 let a = hex_val(bytes[6])? << 4 | hex_val(bytes[7])?;
88 Some(Self::rgba(
89 r as f32 / 255.0,
90 g as f32 / 255.0,
91 b as f32 / 255.0,
92 a as f32 / 255.0,
93 ))
94 }
95 _ => None,
96 }
97 }
98
99 pub fn to_hex(&self) -> String {
101 let r = (self.r * 255.0).round() as u8;
102 let g = (self.g * 255.0).round() as u8;
103 let b = (self.b * 255.0).round() as u8;
104 let a = (self.a * 255.0).round() as u8;
105 if a == 255 {
106 format!("#{r:02X}{g:02X}{b:02X}")
107 } else {
108 format!("#{r:02X}{g:02X}{b:02X}{a:02X}")
109 }
110 }
111}
112
113#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct GradientStop {
116 pub offset: f32, pub color: Color,
118}
119
120#[derive(Debug, Clone, Serialize, Deserialize)]
122pub enum Paint {
123 Solid(Color),
124 LinearGradient {
125 angle: f32, stops: Vec<GradientStop>,
127 },
128 RadialGradient {
129 stops: Vec<GradientStop>,
130 },
131}
132
133#[derive(Debug, Clone, Serialize, Deserialize)]
136pub struct Stroke {
137 pub paint: Paint,
138 pub width: f32,
139 pub cap: StrokeCap,
140 pub join: StrokeJoin,
141}
142
143#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
144pub enum StrokeCap {
145 Butt,
146 Round,
147 Square,
148}
149
150#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
151pub enum StrokeJoin {
152 Miter,
153 Round,
154 Bevel,
155}
156
157impl Default for Stroke {
158 fn default() -> Self {
159 Self {
160 paint: Paint::Solid(Color::rgba(0.0, 0.0, 0.0, 1.0)),
161 width: 1.0,
162 cap: StrokeCap::Butt,
163 join: StrokeJoin::Miter,
164 }
165 }
166}
167
168#[derive(Debug, Clone, Serialize, Deserialize)]
171pub struct FontSpec {
172 pub family: String,
173 pub weight: u16, pub size: f32,
175}
176
177impl Default for FontSpec {
178 fn default() -> Self {
179 Self {
180 family: "Inter".into(),
181 weight: 400,
182 size: 14.0,
183 }
184 }
185}
186
187#[derive(Debug, Clone, Serialize, Deserialize)]
191pub enum PathCmd {
192 MoveTo(f32, f32),
193 LineTo(f32, f32),
194 QuadTo(f32, f32, f32, f32), CubicTo(f32, f32, f32, f32, f32, f32), Close,
197}
198
199#[derive(Debug, Clone, Serialize, Deserialize)]
202pub struct Shadow {
203 pub offset_x: f32,
204 pub offset_y: f32,
205 pub blur: f32,
206 pub color: Color,
207}
208
209#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
213pub enum TextAlign {
214 Left,
215 #[default]
216 Center,
217 Right,
218}
219
220#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
222pub enum TextVAlign {
223 Top,
224 #[default]
225 Middle,
226 Bottom,
227}
228
229#[derive(Debug, Clone, Default, Serialize, Deserialize)]
231pub struct Style {
232 pub fill: Option<Paint>,
233 pub stroke: Option<Stroke>,
234 pub font: Option<FontSpec>,
235 pub corner_radius: Option<f32>,
236 pub opacity: Option<f32>,
237 pub shadow: Option<Shadow>,
238
239 pub text_align: Option<TextAlign>,
241 pub text_valign: Option<TextVAlign>,
243
244 pub scale: Option<f32>,
246}
247
248#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
252pub enum AnimTrigger {
253 Hover,
254 Press,
255 Enter, Custom(String),
257}
258
259#[derive(Debug, Clone, Serialize, Deserialize)]
261pub enum Easing {
262 Linear,
263 EaseIn,
264 EaseOut,
265 EaseInOut,
266 Spring,
267 CubicBezier(f32, f32, f32, f32),
268}
269
270#[derive(Debug, Clone, Serialize, Deserialize)]
272pub struct AnimKeyframe {
273 pub trigger: AnimTrigger,
274 pub duration_ms: u32,
275 pub easing: Easing,
276 pub properties: AnimProperties,
277}
278
279#[derive(Debug, Clone, Default, Serialize, Deserialize)]
281pub struct AnimProperties {
282 pub fill: Option<Paint>,
283 pub opacity: Option<f32>,
284 pub scale: Option<f32>,
285 pub rotate: Option<f32>, pub translate: Option<(f32, f32)>,
287}
288
289#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
294pub enum Annotation {
295 Description(String),
297 Accept(String),
299 Status(String),
301 Priority(String),
303 Tag(String),
305}
306
307#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
311pub struct Import {
312 pub path: String,
314 pub namespace: String,
316}
317
318#[derive(Debug, Clone, Serialize, Deserialize)]
322pub enum Constraint {
323 CenterIn(NodeId),
325 Offset { from: NodeId, dx: f32, dy: f32 },
327 FillParent { pad: f32 },
329 Position { x: f32, y: f32 },
332}
333
334#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
338pub enum ArrowKind {
339 #[default]
340 None,
341 Start,
342 End,
343 Both,
344}
345
346#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
348pub enum CurveKind {
349 #[default]
350 Straight,
351 Smooth,
352 Step,
353}
354
355#[derive(Debug, Clone, Serialize, Deserialize)]
357pub struct Edge {
358 pub id: NodeId,
359 pub from: NodeId,
360 pub to: NodeId,
361 pub label: Option<String>,
362 pub style: Style,
363 pub use_styles: SmallVec<[NodeId; 2]>,
364 pub arrow: ArrowKind,
365 pub curve: CurveKind,
366 pub annotations: Vec<Annotation>,
367 pub animations: SmallVec<[AnimKeyframe; 2]>,
368 pub flow: Option<FlowAnim>,
369 pub label_offset: Option<(f32, f32)>,
371}
372
373#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
375pub enum FlowKind {
376 Pulse,
378 Dash,
380}
381
382#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
384pub struct FlowAnim {
385 pub kind: FlowKind,
386 pub duration_ms: u32,
387}
388
389#[derive(Debug, Clone, Default, Serialize, Deserialize)]
391pub enum LayoutMode {
392 #[default]
394 Free,
395 Column { gap: f32, pad: f32 },
397 Row { gap: f32, pad: f32 },
399 Grid { cols: u32, gap: f32, pad: f32 },
401}
402
403#[derive(Debug, Clone, Serialize, Deserialize)]
407pub enum NodeKind {
408 Root,
410
411 Generic,
414
415 Group,
418
419 Frame {
422 width: f32,
423 height: f32,
424 clip: bool,
425 layout: LayoutMode,
426 },
427
428 Rect { width: f32, height: f32 },
430
431 Ellipse { rx: f32, ry: f32 },
433
434 Path { commands: Vec<PathCmd> },
436
437 Text { content: String },
439}
440
441impl NodeKind {
442 pub fn kind_name(&self) -> &'static str {
444 match self {
445 Self::Root => "root",
446 Self::Generic => "generic",
447 Self::Group => "group",
448 Self::Frame { .. } => "frame",
449 Self::Rect { .. } => "rect",
450 Self::Ellipse { .. } => "ellipse",
451 Self::Path { .. } => "path",
452 Self::Text { .. } => "text",
453 }
454 }
455}
456
457#[derive(Debug, Clone, Serialize, Deserialize)]
459pub struct SceneNode {
460 pub id: NodeId,
462
463 pub kind: NodeKind,
465
466 pub style: Style,
468
469 pub use_styles: SmallVec<[NodeId; 2]>,
471
472 pub constraints: SmallVec<[Constraint; 2]>,
474
475 pub animations: SmallVec<[AnimKeyframe; 2]>,
477
478 pub annotations: Vec<Annotation>,
480
481 pub comments: Vec<String>,
484}
485
486impl SceneNode {
487 pub fn new(id: NodeId, kind: NodeKind) -> Self {
488 Self {
489 id,
490 kind,
491 style: Style::default(),
492 use_styles: SmallVec::new(),
493 constraints: SmallVec::new(),
494 animations: SmallVec::new(),
495 annotations: Vec::new(),
496 comments: Vec::new(),
497 }
498 }
499}
500
501#[derive(Debug, Clone)]
508pub struct SceneGraph {
509 pub graph: StableDiGraph<SceneNode, ()>,
511
512 pub root: NodeIndex,
514
515 pub styles: HashMap<NodeId, Style>,
517
518 pub id_index: HashMap<NodeId, NodeIndex>,
520
521 pub edges: Vec<Edge>,
523
524 pub imports: Vec<Import>,
526
527 pub sorted_child_order: HashMap<NodeIndex, Vec<NodeIndex>>,
531}
532
533impl SceneGraph {
534 #[must_use]
536 pub fn new() -> Self {
537 let mut graph = StableDiGraph::new();
538 let root_node = SceneNode::new(NodeId::intern("root"), NodeKind::Root);
539 let root = graph.add_node(root_node);
540
541 let mut id_index = HashMap::new();
542 id_index.insert(NodeId::intern("root"), root);
543
544 Self {
545 graph,
546 root,
547 styles: HashMap::new(),
548 id_index,
549 edges: Vec::new(),
550 imports: Vec::new(),
551 sorted_child_order: HashMap::new(),
552 }
553 }
554
555 pub fn add_node(&mut self, parent: NodeIndex, node: SceneNode) -> NodeIndex {
557 let id = node.id;
558 let idx = self.graph.add_node(node);
559 self.graph.add_edge(parent, idx, ());
560 self.id_index.insert(id, idx);
561 idx
562 }
563
564 pub fn remove_node(&mut self, idx: NodeIndex) -> Option<SceneNode> {
566 let removed = self.graph.remove_node(idx);
567 if let Some(removed_node) = &removed {
568 self.id_index.remove(&removed_node.id);
569 }
570 removed
571 }
572
573 pub fn get_by_id(&self, id: NodeId) -> Option<&SceneNode> {
575 self.id_index.get(&id).map(|idx| &self.graph[*idx])
576 }
577
578 pub fn get_by_id_mut(&mut self, id: NodeId) -> Option<&mut SceneNode> {
580 self.id_index
581 .get(&id)
582 .copied()
583 .map(|idx| &mut self.graph[idx])
584 }
585
586 pub fn index_of(&self, id: NodeId) -> Option<NodeIndex> {
588 self.id_index.get(&id).copied()
589 }
590
591 pub fn parent(&self, idx: NodeIndex) -> Option<NodeIndex> {
593 self.graph
594 .neighbors_directed(idx, petgraph::Direction::Incoming)
595 .next()
596 }
597
598 pub fn reparent_node(&mut self, child: NodeIndex, new_parent: NodeIndex) {
600 if let Some(old_parent) = self.parent(child)
601 && let Some(edge) = self.graph.find_edge(old_parent, child)
602 {
603 self.graph.remove_edge(edge);
604 }
605 self.graph.add_edge(new_parent, child, ());
606 }
607
608 pub fn children(&self, idx: NodeIndex) -> Vec<NodeIndex> {
614 if let Some(order) = self.sorted_child_order.get(&idx) {
616 return order.clone();
617 }
618
619 let mut children: Vec<NodeIndex> = self
620 .graph
621 .neighbors_directed(idx, petgraph::Direction::Outgoing)
622 .collect();
623 children.sort();
624 children
625 }
626
627 pub fn send_backward(&mut self, child: NodeIndex) -> bool {
630 let parent = match self.parent(child) {
631 Some(p) => p,
632 None => return false,
633 };
634 let siblings = self.children(parent);
635 let pos = match siblings.iter().position(|&s| s == child) {
636 Some(p) => p,
637 None => return false,
638 };
639 if pos == 0 {
640 return false; }
642 self.rebuild_child_order(parent, &siblings, pos, pos - 1)
644 }
645
646 pub fn bring_forward(&mut self, child: NodeIndex) -> bool {
649 let parent = match self.parent(child) {
650 Some(p) => p,
651 None => return false,
652 };
653 let siblings = self.children(parent);
654 let pos = match siblings.iter().position(|&s| s == child) {
655 Some(p) => p,
656 None => return false,
657 };
658 if pos >= siblings.len() - 1 {
659 return false; }
661 self.rebuild_child_order(parent, &siblings, pos, pos + 1)
662 }
663
664 pub fn send_to_back(&mut self, child: NodeIndex) -> bool {
666 let parent = match self.parent(child) {
667 Some(p) => p,
668 None => return false,
669 };
670 let siblings = self.children(parent);
671 let pos = match siblings.iter().position(|&s| s == child) {
672 Some(p) => p,
673 None => return false,
674 };
675 if pos == 0 {
676 return false;
677 }
678 self.rebuild_child_order(parent, &siblings, pos, 0)
679 }
680
681 pub fn bring_to_front(&mut self, child: NodeIndex) -> bool {
683 let parent = match self.parent(child) {
684 Some(p) => p,
685 None => return false,
686 };
687 let siblings = self.children(parent);
688 let pos = match siblings.iter().position(|&s| s == child) {
689 Some(p) => p,
690 None => return false,
691 };
692 let last = siblings.len() - 1;
693 if pos == last {
694 return false;
695 }
696 self.rebuild_child_order(parent, &siblings, pos, last)
697 }
698
699 fn rebuild_child_order(
701 &mut self,
702 parent: NodeIndex,
703 siblings: &[NodeIndex],
704 from: usize,
705 to: usize,
706 ) -> bool {
707 for &sib in siblings {
709 if let Some(edge) = self.graph.find_edge(parent, sib) {
710 self.graph.remove_edge(edge);
711 }
712 }
713 let mut new_order: Vec<NodeIndex> = siblings.to_vec();
715 let child = new_order.remove(from);
716 new_order.insert(to, child);
717 for &sib in &new_order {
719 self.graph.add_edge(parent, sib, ());
720 }
721 true
722 }
723
724 pub fn define_style(&mut self, name: NodeId, style: Style) {
726 self.styles.insert(name, style);
727 }
728
729 pub fn resolve_style(&self, node: &SceneNode, active_triggers: &[AnimTrigger]) -> Style {
731 let mut resolved = Style::default();
732
733 for style_id in &node.use_styles {
735 if let Some(base) = self.styles.get(style_id) {
736 merge_style(&mut resolved, base);
737 }
738 }
739
740 merge_style(&mut resolved, &node.style);
742
743 for anim in &node.animations {
745 if active_triggers.contains(&anim.trigger) {
746 if anim.properties.fill.is_some() {
747 resolved.fill = anim.properties.fill.clone();
748 }
749 if anim.properties.opacity.is_some() {
750 resolved.opacity = anim.properties.opacity;
751 }
752 if anim.properties.scale.is_some() {
753 resolved.scale = anim.properties.scale;
754 }
755 }
756 }
757
758 resolved
759 }
760
761 pub fn rebuild_index(&mut self) {
763 self.id_index.clear();
764 for idx in self.graph.node_indices() {
765 let id = self.graph[idx].id;
766 self.id_index.insert(id, idx);
767 }
768 }
769
770 pub fn resolve_style_for_edge(&self, edge: &Edge, active_triggers: &[AnimTrigger]) -> Style {
772 let mut resolved = Style::default();
773 for style_id in &edge.use_styles {
774 if let Some(base) = self.styles.get(style_id) {
775 merge_style(&mut resolved, base);
776 }
777 }
778 merge_style(&mut resolved, &edge.style);
779
780 for anim in &edge.animations {
781 if active_triggers.contains(&anim.trigger) {
782 if anim.properties.fill.is_some() {
783 resolved.fill = anim.properties.fill.clone();
784 }
785 if anim.properties.opacity.is_some() {
786 resolved.opacity = anim.properties.opacity;
787 }
788 if anim.properties.scale.is_some() {
789 resolved.scale = anim.properties.scale;
790 }
791 }
792 }
793
794 resolved
795 }
796
797 pub fn effective_target(&self, leaf_id: NodeId, selected: &[NodeId]) -> NodeId {
803 let mut current_idx = match self.index_of(leaf_id) {
804 Some(idx) => idx,
805 None => return leaf_id,
806 };
807 let mut group_target = leaf_id;
808
809 while let Some(parent_idx) = self.parent(current_idx) {
810 let parent = &self.graph[parent_idx];
811 if matches!(parent.kind, NodeKind::Root) {
812 break;
813 }
814 if matches!(parent.kind, NodeKind::Group) {
815 if selected.contains(&parent.id) {
817 break;
818 }
819 group_target = parent.id;
820 }
821 current_idx = parent_idx;
822 }
823
824 group_target
825 }
826
827 pub fn is_ancestor_of(&self, ancestor_id: NodeId, descendant_id: NodeId) -> bool {
829 if ancestor_id == descendant_id {
830 return false;
831 }
832 let mut current_idx = match self.index_of(descendant_id) {
833 Some(idx) => idx,
834 None => return false,
835 };
836 while let Some(parent_idx) = self.parent(current_idx) {
837 if self.graph[parent_idx].id == ancestor_id {
838 return true;
839 }
840 if matches!(self.graph[parent_idx].kind, NodeKind::Root) {
841 break;
842 }
843 current_idx = parent_idx;
844 }
845 false
846 }
847}
848
849impl Default for SceneGraph {
850 fn default() -> Self {
851 Self::new()
852 }
853}
854
855fn merge_style(dst: &mut Style, src: &Style) {
857 if src.fill.is_some() {
858 dst.fill = src.fill.clone();
859 }
860 if src.stroke.is_some() {
861 dst.stroke = src.stroke.clone();
862 }
863 if src.font.is_some() {
864 dst.font = src.font.clone();
865 }
866 if src.corner_radius.is_some() {
867 dst.corner_radius = src.corner_radius;
868 }
869 if src.opacity.is_some() {
870 dst.opacity = src.opacity;
871 }
872 if src.shadow.is_some() {
873 dst.shadow = src.shadow.clone();
874 }
875
876 if src.text_align.is_some() {
877 dst.text_align = src.text_align;
878 }
879 if src.text_valign.is_some() {
880 dst.text_valign = src.text_valign;
881 }
882 if src.scale.is_some() {
883 dst.scale = src.scale;
884 }
885}
886
887#[derive(Debug, Clone, Copy, Default, PartialEq)]
891pub struct ResolvedBounds {
892 pub x: f32,
893 pub y: f32,
894 pub width: f32,
895 pub height: f32,
896}
897
898impl ResolvedBounds {
899 pub fn contains(&self, px: f32, py: f32) -> bool {
900 px >= self.x && px <= self.x + self.width && py >= self.y && py <= self.y + self.height
901 }
902
903 pub fn center(&self) -> (f32, f32) {
904 (self.x + self.width / 2.0, self.y + self.height / 2.0)
905 }
906
907 pub fn intersects_rect(&self, rx: f32, ry: f32, rw: f32, rh: f32) -> bool {
909 self.x < rx + rw
910 && self.x + self.width > rx
911 && self.y < ry + rh
912 && self.y + self.height > ry
913 }
914}
915
916#[cfg(test)]
917mod tests {
918 use super::*;
919
920 #[test]
921 fn scene_graph_basics() {
922 let mut sg = SceneGraph::new();
923 let rect = SceneNode::new(
924 NodeId::intern("box1"),
925 NodeKind::Rect {
926 width: 100.0,
927 height: 50.0,
928 },
929 );
930 let idx = sg.add_node(sg.root, rect);
931
932 assert!(sg.get_by_id(NodeId::intern("box1")).is_some());
933 assert_eq!(sg.children(sg.root).len(), 1);
934 assert_eq!(sg.children(sg.root)[0], idx);
935 }
936
937 #[test]
938 fn color_hex_roundtrip() {
939 let c = Color::from_hex("#6C5CE7").unwrap();
940 assert_eq!(c.to_hex(), "#6C5CE7");
941
942 let c2 = Color::from_hex("#FF000080").unwrap();
943 assert!((c2.a - 128.0 / 255.0).abs() < 0.01);
944 assert!(c2.to_hex().len() == 9); }
946
947 #[test]
948 fn style_merging() {
949 let mut sg = SceneGraph::new();
950 sg.define_style(
951 NodeId::intern("base"),
952 Style {
953 fill: Some(Paint::Solid(Color::rgba(0.0, 0.0, 0.0, 1.0))),
954 font: Some(FontSpec {
955 family: "Inter".into(),
956 weight: 400,
957 size: 14.0,
958 }),
959 ..Default::default()
960 },
961 );
962
963 let mut node = SceneNode::new(
964 NodeId::intern("txt"),
965 NodeKind::Text {
966 content: "hi".into(),
967 },
968 );
969 node.use_styles.push(NodeId::intern("base"));
970 node.style.font = Some(FontSpec {
971 family: "Inter".into(),
972 weight: 700,
973 size: 24.0,
974 });
975
976 let resolved = sg.resolve_style(&node, &[]);
977 assert!(resolved.fill.is_some());
979 let f = resolved.font.unwrap();
981 assert_eq!(f.weight, 700);
982 assert_eq!(f.size, 24.0);
983 }
984
985 #[test]
986 fn style_merging_align() {
987 let mut sg = SceneGraph::new();
988 sg.define_style(
989 NodeId::intern("centered"),
990 Style {
991 text_align: Some(TextAlign::Center),
992 text_valign: Some(TextVAlign::Middle),
993 ..Default::default()
994 },
995 );
996
997 let mut node = SceneNode::new(
999 NodeId::intern("overridden"),
1000 NodeKind::Text {
1001 content: "hello".into(),
1002 },
1003 );
1004 node.use_styles.push(NodeId::intern("centered"));
1005 node.style.text_align = Some(TextAlign::Right);
1006
1007 let resolved = sg.resolve_style(&node, &[]);
1008 assert_eq!(resolved.text_align, Some(TextAlign::Right));
1010 assert_eq!(resolved.text_valign, Some(TextVAlign::Middle));
1012 }
1013
1014 #[test]
1015 fn test_effective_target_bubbles_to_group() {
1016 let mut sg = SceneGraph::new();
1017
1018 let group_id = NodeId::intern("my_group");
1020 let rect_id = NodeId::intern("my_rect");
1021
1022 let group = SceneNode::new(group_id, NodeKind::Group);
1023 let rect = SceneNode::new(
1024 rect_id,
1025 NodeKind::Rect {
1026 width: 10.0,
1027 height: 10.0,
1028 },
1029 );
1030
1031 let group_idx = sg.add_node(sg.root, group);
1032 sg.add_node(group_idx, rect);
1033
1034 assert_eq!(sg.effective_target(rect_id, &[]), group_id);
1036 assert_eq!(sg.effective_target(rect_id, &[group_id]), rect_id);
1038 assert_eq!(sg.effective_target(rect_id, &[rect_id]), group_id);
1041 assert_eq!(sg.effective_target(group_id, &[]), group_id);
1043 }
1044
1045 #[test]
1046 fn test_effective_target_nested_groups() {
1047 let mut sg = SceneGraph::new();
1048
1049 let outer_id = NodeId::intern("group_outer");
1051 let inner_id = NodeId::intern("group_inner");
1052 let leaf_id = NodeId::intern("rect_leaf");
1053
1054 let outer = SceneNode::new(outer_id, NodeKind::Group);
1055 let inner = SceneNode::new(inner_id, NodeKind::Group);
1056 let leaf = SceneNode::new(
1057 leaf_id,
1058 NodeKind::Rect {
1059 width: 50.0,
1060 height: 50.0,
1061 },
1062 );
1063
1064 let outer_idx = sg.add_node(sg.root, outer);
1065 let inner_idx = sg.add_node(outer_idx, inner);
1066 sg.add_node(inner_idx, leaf);
1067
1068 assert_eq!(sg.effective_target(leaf_id, &[]), outer_id);
1070 assert_eq!(sg.effective_target(leaf_id, &[outer_id]), inner_id);
1072 assert_eq!(sg.effective_target(leaf_id, &[outer_id, inner_id]), leaf_id);
1074 assert_eq!(sg.effective_target(leaf_id, &[inner_id]), leaf_id);
1077 }
1078
1079 #[test]
1080 fn test_effective_target_no_group() {
1081 let mut sg = SceneGraph::new();
1082
1083 let rect_id = NodeId::intern("standalone_rect");
1085 let rect = SceneNode::new(
1086 rect_id,
1087 NodeKind::Rect {
1088 width: 10.0,
1089 height: 10.0,
1090 },
1091 );
1092 sg.add_node(sg.root, rect);
1093
1094 assert_eq!(sg.effective_target(rect_id, &[]), rect_id);
1096 }
1097
1098 #[test]
1099 fn test_is_ancestor_of() {
1100 let mut sg = SceneGraph::new();
1101
1102 let group_id = NodeId::intern("grp");
1104 let rect_id = NodeId::intern("r1");
1105 let other_id = NodeId::intern("other");
1106
1107 let group = SceneNode::new(group_id, NodeKind::Group);
1108 let rect = SceneNode::new(
1109 rect_id,
1110 NodeKind::Rect {
1111 width: 10.0,
1112 height: 10.0,
1113 },
1114 );
1115 let other = SceneNode::new(
1116 other_id,
1117 NodeKind::Rect {
1118 width: 5.0,
1119 height: 5.0,
1120 },
1121 );
1122
1123 let group_idx = sg.add_node(sg.root, group);
1124 sg.add_node(group_idx, rect);
1125 sg.add_node(sg.root, other);
1126
1127 assert!(sg.is_ancestor_of(group_id, rect_id));
1129 assert!(sg.is_ancestor_of(NodeId::intern("root"), rect_id));
1131 assert!(!sg.is_ancestor_of(rect_id, group_id));
1133 assert!(!sg.is_ancestor_of(group_id, group_id));
1135 assert!(!sg.is_ancestor_of(other_id, rect_id));
1137 }
1138
1139 #[test]
1140 fn test_resolve_style_scale_animation() {
1141 let sg = SceneGraph::new();
1142
1143 let mut node = SceneNode::new(
1144 NodeId::intern("btn"),
1145 NodeKind::Rect {
1146 width: 100.0,
1147 height: 40.0,
1148 },
1149 );
1150 node.style.fill = Some(Paint::Solid(Color::rgba(1.0, 0.0, 0.0, 1.0)));
1151 node.animations.push(AnimKeyframe {
1152 trigger: AnimTrigger::Press,
1153 duration_ms: 100,
1154 easing: Easing::EaseOut,
1155 properties: AnimProperties {
1156 scale: Some(0.97),
1157 ..Default::default()
1158 },
1159 });
1160
1161 let resolved = sg.resolve_style(&node, &[]);
1163 assert!(resolved.scale.is_none());
1164
1165 let resolved = sg.resolve_style(&node, &[AnimTrigger::Press]);
1167 assert_eq!(resolved.scale, Some(0.97));
1168 assert!(resolved.fill.is_some());
1170 }
1171}