Skip to main content

fd_core/
model.rs

1//! Core scene-graph data model for FD documents.
2//!
3//! The document is a DAG (Directed Acyclic Graph) where nodes represent
4//! visual elements (shapes, text, groups) and edges represent parent→child
5//! containment. Styles and animations are attached to nodes. Layout is
6//! constraint-based — relationships are preferred over raw positions.
7//! `Position { x, y }` is the escape hatch for drag-placed or pinned nodes.
8
9use 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// ─── Colors & Paint ──────────────────────────────────────────────────────
17
18/// RGBA color. Stored as 4 × f32 [0.0, 1.0].
19#[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
27/// Helper to parse a single hex digit.
28pub 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    /// Parse a hex color string: `#RGB`, `#RGBA`, `#RRGGBB`, `#RRGGBBAA`.
43    /// The string may optionally start with `#`.
44    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    /// Emit as shortest valid hex string.
100    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/// A gradient stop.
114#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct GradientStop {
116    pub offset: f32, // 0.0 .. 1.0
117    pub color: Color,
118}
119
120/// Fill or stroke paint.
121#[derive(Debug, Clone, Serialize, Deserialize)]
122pub enum Paint {
123    Solid(Color),
124    LinearGradient {
125        angle: f32, // degrees
126        stops: Vec<GradientStop>,
127    },
128    RadialGradient {
129        stops: Vec<GradientStop>,
130    },
131}
132
133// ─── Stroke ──────────────────────────────────────────────────────────────
134
135#[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// ─── Font / Text ─────────────────────────────────────────────────────────
169
170#[derive(Debug, Clone, Serialize, Deserialize)]
171pub struct FontSpec {
172    pub family: String,
173    pub weight: u16, // 100..900
174    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// ─── Path data ───────────────────────────────────────────────────────────
188
189/// A single path command (SVG-like but simplified).
190#[derive(Debug, Clone, Serialize, Deserialize)]
191pub enum PathCmd {
192    MoveTo(f32, f32),
193    LineTo(f32, f32),
194    QuadTo(f32, f32, f32, f32),            // control, end
195    CubicTo(f32, f32, f32, f32, f32, f32), // c1, c2, end
196    Close,
197}
198
199// ─── Shadow ──────────────────────────────────────────────────────────────
200
201#[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// ─── Styling ─────────────────────────────────────────────────────────────
210
211/// Horizontal text alignment.
212#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
213pub enum TextAlign {
214    Left,
215    #[default]
216    Center,
217    Right,
218}
219
220/// Vertical text alignment.
221#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
222pub enum TextVAlign {
223    Top,
224    #[default]
225    Middle,
226    Bottom,
227}
228
229/// A reusable theme set that nodes can reference via `use: theme_name`.
230#[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    /// Horizontal text alignment (default: Center).
240    pub text_align: Option<TextAlign>,
241    /// Vertical text alignment (default: Middle).
242    pub text_valign: Option<TextVAlign>,
243
244    /// Scale factor applied during rendering (from animations).
245    pub scale: Option<f32>,
246}
247
248// ─── Animation ───────────────────────────────────────────────────────────
249
250/// The trigger for an animation.
251#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
252pub enum AnimTrigger {
253    Hover,
254    Press,
255    Enter, // viewport enter
256    Custom(String),
257}
258
259/// Easing function.
260#[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/// A property animation keyframe.
271#[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/// Animatable property overrides.
280#[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>, // degrees
286    pub translate: Option<(f32, f32)>,
287}
288
289// ─── Annotations ─────────────────────────────────────────────────────────
290
291/// Structured annotation attached to a scene node.
292/// Parsed from `spec { ... }` blocks in the FD format.
293#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
294pub enum Annotation {
295    /// Freeform description: `spec { "User auth entry point" }`
296    Description(String),
297    /// Acceptance criterion: `spec { accept: "validates email on blur" }`
298    Accept(String),
299    /// Status: `spec { status: todo }` (values: todo, doing, done, blocked)
300    Status(String),
301    /// Priority: `spec { priority: high }`
302    Priority(String),
303    /// Tag: `spec { tag: auth }`
304    Tag(String),
305}
306
307// ─── Imports ─────────────────────────────────────────────────────────────
308
309/// A file import declaration: `import "path.fd" as namespace`.
310#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
311pub struct Import {
312    /// Relative file path, e.g. "components/buttons.fd".
313    pub path: String,
314    /// Namespace alias, e.g. "buttons".
315    pub namespace: String,
316}
317
318// ─── Layout Constraints ──────────────────────────────────────────────────
319
320/// Constraint-based layout — no absolute coordinates in the format.
321#[derive(Debug, Clone, Serialize, Deserialize)]
322pub enum Constraint {
323    /// Center this node within a target (e.g. `canvas` or another node).
324    CenterIn(NodeId),
325    /// Position relative: dx, dy from a reference node.
326    Offset { from: NodeId, dx: f32, dy: f32 },
327    /// Fill the parent with optional padding.
328    FillParent { pad: f32 },
329    /// Parent-relative position (used for drag-placed or pinned nodes).
330    /// Resolved as `parent.x + x`, `parent.y + y` by the layout solver.
331    Position { x: f32, y: f32 },
332}
333
334// ─── Edges (connections between nodes) ───────────────────────────────────
335
336/// Arrow head placement on an edge.
337#[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/// How the edge path is drawn between two nodes.
347#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
348pub enum CurveKind {
349    #[default]
350    Straight,
351    Smooth,
352    Step,
353}
354
355/// A visual connection between two nodes.
356#[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    /// Offset of the edge label from the midpoint, set when label is dragged.
370    pub label_offset: Option<(f32, f32)>,
371}
372
373/// Flow animation kind — continuous motion along the edge path.
374#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
375pub enum FlowKind {
376    /// A glowing dot traveling from → to on a loop.
377    Pulse,
378    /// Marching dashes along the edge (stroke-dashoffset animation).
379    Dash,
380}
381
382/// A flow animation attached to an edge.
383#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
384pub struct FlowAnim {
385    pub kind: FlowKind,
386    pub duration_ms: u32,
387}
388
389/// Group layout mode (for children arrangement).
390#[derive(Debug, Clone, Default, Serialize, Deserialize)]
391pub enum LayoutMode {
392    /// Free / absolute positioning of children.
393    #[default]
394    Free,
395    /// Column (vertical stack).
396    Column { gap: f32, pad: f32 },
397    /// Row (horizontal stack).
398    Row { gap: f32, pad: f32 },
399    /// Grid layout.
400    Grid { cols: u32, gap: f32, pad: f32 },
401}
402
403// ─── Scene Graph Nodes ───────────────────────────────────────────────────
404
405/// The node kinds in the scene DAG.
406#[derive(Debug, Clone, Serialize, Deserialize)]
407pub enum NodeKind {
408    /// Root of the document.
409    Root,
410
411    /// Generic placeholder — no visual shape assigned yet.
412    /// Used for spec-only nodes: `@login_btn { spec "CTA" }`
413    Generic,
414
415    /// Group / frame — contains children.
416    Group { layout: LayoutMode },
417
418    /// Frame — visible container with explicit size and optional clipping.
419    /// Like a Figma frame: has fill/stroke, declared dimensions, clips overflow.
420    Frame {
421        width: f32,
422        height: f32,
423        clip: bool,
424        layout: LayoutMode,
425    },
426
427    /// Rectangle.
428    Rect { width: f32, height: f32 },
429
430    /// Ellipse / circle.
431    Ellipse { rx: f32, ry: f32 },
432
433    /// Freeform path (pen tool output).
434    Path { commands: Vec<PathCmd> },
435
436    /// Text label.
437    Text { content: String },
438}
439
440impl NodeKind {
441    /// Return the FD format keyword for this node kind.
442    pub fn kind_name(&self) -> &'static str {
443        match self {
444            Self::Root => "root",
445            Self::Generic => "generic",
446            Self::Group { .. } => "group",
447            Self::Frame { .. } => "frame",
448            Self::Rect { .. } => "rect",
449            Self::Ellipse { .. } => "ellipse",
450            Self::Path { .. } => "path",
451            Self::Text { .. } => "text",
452        }
453    }
454}
455
456/// A single node in the scene graph.
457#[derive(Debug, Clone, Serialize, Deserialize)]
458pub struct SceneNode {
459    /// The node's ID (e.g. `@login_form`). Anonymous nodes get auto-IDs.
460    pub id: NodeId,
461
462    /// What kind of element this is.
463    pub kind: NodeKind,
464
465    /// Inline style overrides on this node.
466    pub style: Style,
467
468    /// Named theme references (`use: base_text`).
469    pub use_styles: SmallVec<[NodeId; 2]>,
470
471    /// Constraint-based positioning.
472    pub constraints: SmallVec<[Constraint; 2]>,
473
474    /// Animations attached to this node.
475    pub animations: SmallVec<[AnimKeyframe; 2]>,
476
477    /// Structured annotations (`spec { ... }` block).
478    pub annotations: Vec<Annotation>,
479
480    /// Line comments (`# text`) that appeared before this node in the source.
481    /// Preserved across parse/emit round-trips so format passes don't delete them.
482    pub comments: Vec<String>,
483}
484
485impl SceneNode {
486    pub fn new(id: NodeId, kind: NodeKind) -> Self {
487        Self {
488            id,
489            kind,
490            style: Style::default(),
491            use_styles: SmallVec::new(),
492            constraints: SmallVec::new(),
493            animations: SmallVec::new(),
494            annotations: Vec::new(),
495            comments: Vec::new(),
496        }
497    }
498}
499
500// ─── Scene Graph ─────────────────────────────────────────────────────────
501
502/// The complete FD document — a DAG of `SceneNode` values.
503///
504/// Edges go from parent → child. Style definitions are stored separately
505/// in a hashmap for lookup by name.
506#[derive(Debug, Clone)]
507pub struct SceneGraph {
508    /// The underlying directed graph.
509    pub graph: StableDiGraph<SceneNode, ()>,
510
511    /// The root node index.
512    pub root: NodeIndex,
513
514    /// Named theme definitions (`theme base_text { ... }`).
515    pub styles: HashMap<NodeId, Style>,
516
517    /// Index from NodeId → NodeIndex for fast lookup.
518    pub id_index: HashMap<NodeId, NodeIndex>,
519
520    /// Visual edges (connections between nodes).
521    pub edges: Vec<Edge>,
522
523    /// File imports with namespace aliases.
524    pub imports: Vec<Import>,
525
526    /// Explicit child ordering set by `sort_nodes`.
527    /// When present for a parent, `children()` returns this order
528    /// instead of the default `NodeIndex` sort.
529    pub sorted_child_order: HashMap<NodeIndex, Vec<NodeIndex>>,
530}
531
532impl SceneGraph {
533    /// Create a new empty scene graph with a root node.
534    #[must_use]
535    pub fn new() -> Self {
536        let mut graph = StableDiGraph::new();
537        let root_node = SceneNode::new(NodeId::intern("root"), NodeKind::Root);
538        let root = graph.add_node(root_node);
539
540        let mut id_index = HashMap::new();
541        id_index.insert(NodeId::intern("root"), root);
542
543        Self {
544            graph,
545            root,
546            styles: HashMap::new(),
547            id_index,
548            edges: Vec::new(),
549            imports: Vec::new(),
550            sorted_child_order: HashMap::new(),
551        }
552    }
553
554    /// Add a node as a child of `parent`. Returns the new node's index.
555    pub fn add_node(&mut self, parent: NodeIndex, node: SceneNode) -> NodeIndex {
556        let id = node.id;
557        let idx = self.graph.add_node(node);
558        self.graph.add_edge(parent, idx, ());
559        self.id_index.insert(id, idx);
560        idx
561    }
562
563    /// Remove a node safely, keeping the `id_index` synchronized.
564    pub fn remove_node(&mut self, idx: NodeIndex) -> Option<SceneNode> {
565        let removed = self.graph.remove_node(idx);
566        if let Some(removed_node) = &removed {
567            self.id_index.remove(&removed_node.id);
568        }
569        removed
570    }
571
572    /// Look up a node by its `@id`.
573    pub fn get_by_id(&self, id: NodeId) -> Option<&SceneNode> {
574        self.id_index.get(&id).map(|idx| &self.graph[*idx])
575    }
576
577    /// Look up a node mutably by its `@id`.
578    pub fn get_by_id_mut(&mut self, id: NodeId) -> Option<&mut SceneNode> {
579        self.id_index
580            .get(&id)
581            .copied()
582            .map(|idx| &mut self.graph[idx])
583    }
584
585    /// Get the index for a NodeId.
586    pub fn index_of(&self, id: NodeId) -> Option<NodeIndex> {
587        self.id_index.get(&id).copied()
588    }
589
590    /// Get the parent index of a node.
591    pub fn parent(&self, idx: NodeIndex) -> Option<NodeIndex> {
592        self.graph
593            .neighbors_directed(idx, petgraph::Direction::Incoming)
594            .next()
595    }
596
597    /// Reparent a node to a new parent.
598    pub fn reparent_node(&mut self, child: NodeIndex, new_parent: NodeIndex) {
599        if let Some(old_parent) = self.parent(child)
600            && let Some(edge) = self.graph.find_edge(old_parent, child)
601        {
602            self.graph.remove_edge(edge);
603        }
604        self.graph.add_edge(new_parent, child, ());
605    }
606
607    /// Get children of a node in document (insertion) order.
608    ///
609    /// Sorts by `NodeIndex` so the result is deterministic regardless of
610    /// how `petgraph` iterates its adjacency list on different targets
611    /// (native vs WASM).
612    pub fn children(&self, idx: NodeIndex) -> Vec<NodeIndex> {
613        // If an explicit sort order was set (by sort_nodes), use it
614        if let Some(order) = self.sorted_child_order.get(&idx) {
615            return order.clone();
616        }
617
618        let mut children: Vec<NodeIndex> = self
619            .graph
620            .neighbors_directed(idx, petgraph::Direction::Outgoing)
621            .collect();
622        children.sort();
623        children
624    }
625
626    /// Move a child one step backward in z-order (swap with previous sibling).
627    /// Returns true if the z-order changed.
628    pub fn send_backward(&mut self, child: NodeIndex) -> bool {
629        let parent = match self.parent(child) {
630            Some(p) => p,
631            None => return false,
632        };
633        let siblings = self.children(parent);
634        let pos = match siblings.iter().position(|&s| s == child) {
635            Some(p) => p,
636            None => return false,
637        };
638        if pos == 0 {
639            return false; // already at back
640        }
641        // Rebuild edges in swapped order
642        self.rebuild_child_order(parent, &siblings, pos, pos - 1)
643    }
644
645    /// Move a child one step forward in z-order (swap with next sibling).
646    /// Returns true if the z-order changed.
647    pub fn bring_forward(&mut self, child: NodeIndex) -> bool {
648        let parent = match self.parent(child) {
649            Some(p) => p,
650            None => return false,
651        };
652        let siblings = self.children(parent);
653        let pos = match siblings.iter().position(|&s| s == child) {
654            Some(p) => p,
655            None => return false,
656        };
657        if pos >= siblings.len() - 1 {
658            return false; // already at front
659        }
660        self.rebuild_child_order(parent, &siblings, pos, pos + 1)
661    }
662
663    /// Move a child to the back of z-order (first child).
664    pub fn send_to_back(&mut self, child: NodeIndex) -> bool {
665        let parent = match self.parent(child) {
666            Some(p) => p,
667            None => return false,
668        };
669        let siblings = self.children(parent);
670        let pos = match siblings.iter().position(|&s| s == child) {
671            Some(p) => p,
672            None => return false,
673        };
674        if pos == 0 {
675            return false;
676        }
677        self.rebuild_child_order(parent, &siblings, pos, 0)
678    }
679
680    /// Move a child to the front of z-order (last child).
681    pub fn bring_to_front(&mut self, child: NodeIndex) -> bool {
682        let parent = match self.parent(child) {
683            Some(p) => p,
684            None => return false,
685        };
686        let siblings = self.children(parent);
687        let pos = match siblings.iter().position(|&s| s == child) {
688            Some(p) => p,
689            None => return false,
690        };
691        let last = siblings.len() - 1;
692        if pos == last {
693            return false;
694        }
695        self.rebuild_child_order(parent, &siblings, pos, last)
696    }
697
698    /// Rebuild child edges, moving child at `from` to `to` position.
699    fn rebuild_child_order(
700        &mut self,
701        parent: NodeIndex,
702        siblings: &[NodeIndex],
703        from: usize,
704        to: usize,
705    ) -> bool {
706        // Remove all edges from parent to children
707        for &sib in siblings {
708            if let Some(edge) = self.graph.find_edge(parent, sib) {
709                self.graph.remove_edge(edge);
710            }
711        }
712        // Build new order
713        let mut new_order: Vec<NodeIndex> = siblings.to_vec();
714        let child = new_order.remove(from);
715        new_order.insert(to, child);
716        // Re-add edges in new order
717        for &sib in &new_order {
718            self.graph.add_edge(parent, sib, ());
719        }
720        true
721    }
722
723    /// Define a named style.
724    pub fn define_style(&mut self, name: NodeId, style: Style) {
725        self.styles.insert(name, style);
726    }
727
728    /// Resolve a node's effective style (merging `use` references + inline overrides + active animations).
729    pub fn resolve_style(&self, node: &SceneNode, active_triggers: &[AnimTrigger]) -> Style {
730        let mut resolved = Style::default();
731
732        // Apply referenced styles in order
733        for style_id in &node.use_styles {
734            if let Some(base) = self.styles.get(style_id) {
735                merge_style(&mut resolved, base);
736            }
737        }
738
739        // Apply inline overrides (take precedence)
740        merge_style(&mut resolved, &node.style);
741
742        // Apply active animation state overrides
743        for anim in &node.animations {
744            if active_triggers.contains(&anim.trigger) {
745                if anim.properties.fill.is_some() {
746                    resolved.fill = anim.properties.fill.clone();
747                }
748                if anim.properties.opacity.is_some() {
749                    resolved.opacity = anim.properties.opacity;
750                }
751                if anim.properties.scale.is_some() {
752                    resolved.scale = anim.properties.scale;
753                }
754            }
755        }
756
757        resolved
758    }
759
760    /// Rebuild the `id_index` (needed after deserialization).
761    pub fn rebuild_index(&mut self) {
762        self.id_index.clear();
763        for idx in self.graph.node_indices() {
764            let id = self.graph[idx].id;
765            self.id_index.insert(id, idx);
766        }
767    }
768
769    /// Resolve an edge's effective style (merging `use` references + inline overrides + active animations).
770    pub fn resolve_style_for_edge(&self, edge: &Edge, active_triggers: &[AnimTrigger]) -> Style {
771        let mut resolved = Style::default();
772        for style_id in &edge.use_styles {
773            if let Some(base) = self.styles.get(style_id) {
774                merge_style(&mut resolved, base);
775            }
776        }
777        merge_style(&mut resolved, &edge.style);
778
779        for anim in &edge.animations {
780            if active_triggers.contains(&anim.trigger) {
781                if anim.properties.fill.is_some() {
782                    resolved.fill = anim.properties.fill.clone();
783                }
784                if anim.properties.opacity.is_some() {
785                    resolved.opacity = anim.properties.opacity;
786                }
787                if anim.properties.scale.is_some() {
788                    resolved.scale = anim.properties.scale;
789                }
790            }
791        }
792
793        resolved
794    }
795
796    /// Figma-style target bubbling: if the leaf is inside a Group that isn't
797    /// already selected, return the outermost unselected Group. Otherwise
798    /// return the leaf directly.
799    ///
800    /// This gives "first click selects group, second click drills in" behavior.
801    pub fn effective_target(&self, leaf_id: NodeId, selected: &[NodeId]) -> NodeId {
802        let mut current_idx = match self.index_of(leaf_id) {
803            Some(idx) => idx,
804            None => return leaf_id,
805        };
806        let mut group_target = leaf_id;
807
808        while let Some(parent_idx) = self.parent(current_idx) {
809            let parent = &self.graph[parent_idx];
810            if matches!(parent.kind, NodeKind::Root) {
811                break;
812            }
813            if matches!(parent.kind, NodeKind::Group { .. }) {
814                // If this group is already selected, stop bubbling — let inner target through
815                if selected.contains(&parent.id) {
816                    break;
817                }
818                group_target = parent.id;
819            }
820            current_idx = parent_idx;
821        }
822
823        group_target
824    }
825
826    /// Check if `ancestor_id` is a parent/grandparent/etc. of `descendant_id`.
827    pub fn is_ancestor_of(&self, ancestor_id: NodeId, descendant_id: NodeId) -> bool {
828        if ancestor_id == descendant_id {
829            return false;
830        }
831        let mut current_idx = match self.index_of(descendant_id) {
832            Some(idx) => idx,
833            None => return false,
834        };
835        while let Some(parent_idx) = self.parent(current_idx) {
836            if self.graph[parent_idx].id == ancestor_id {
837                return true;
838            }
839            if matches!(self.graph[parent_idx].kind, NodeKind::Root) {
840                break;
841            }
842            current_idx = parent_idx;
843        }
844        false
845    }
846}
847
848impl Default for SceneGraph {
849    fn default() -> Self {
850        Self::new()
851    }
852}
853
854/// Merge `src` style into `dst`, overwriting only `Some` fields.
855fn merge_style(dst: &mut Style, src: &Style) {
856    if src.fill.is_some() {
857        dst.fill = src.fill.clone();
858    }
859    if src.stroke.is_some() {
860        dst.stroke = src.stroke.clone();
861    }
862    if src.font.is_some() {
863        dst.font = src.font.clone();
864    }
865    if src.corner_radius.is_some() {
866        dst.corner_radius = src.corner_radius;
867    }
868    if src.opacity.is_some() {
869        dst.opacity = src.opacity;
870    }
871    if src.shadow.is_some() {
872        dst.shadow = src.shadow.clone();
873    }
874
875    if src.text_align.is_some() {
876        dst.text_align = src.text_align;
877    }
878    if src.text_valign.is_some() {
879        dst.text_valign = src.text_valign;
880    }
881    if src.scale.is_some() {
882        dst.scale = src.scale;
883    }
884}
885
886// ─── Resolved positions (output of layout solver) ────────────────────────
887
888/// Resolved absolute bounding box after constraint solving.
889#[derive(Debug, Clone, Copy, Default, PartialEq)]
890pub struct ResolvedBounds {
891    pub x: f32,
892    pub y: f32,
893    pub width: f32,
894    pub height: f32,
895}
896
897impl ResolvedBounds {
898    pub fn contains(&self, px: f32, py: f32) -> bool {
899        px >= self.x && px <= self.x + self.width && py >= self.y && py <= self.y + self.height
900    }
901
902    pub fn center(&self) -> (f32, f32) {
903        (self.x + self.width / 2.0, self.y + self.height / 2.0)
904    }
905
906    /// Check if this bounds intersects with a rectangle (AABB overlap).
907    pub fn intersects_rect(&self, rx: f32, ry: f32, rw: f32, rh: f32) -> bool {
908        self.x < rx + rw
909            && self.x + self.width > rx
910            && self.y < ry + rh
911            && self.y + self.height > ry
912    }
913}
914
915#[cfg(test)]
916mod tests {
917    use super::*;
918
919    #[test]
920    fn scene_graph_basics() {
921        let mut sg = SceneGraph::new();
922        let rect = SceneNode::new(
923            NodeId::intern("box1"),
924            NodeKind::Rect {
925                width: 100.0,
926                height: 50.0,
927            },
928        );
929        let idx = sg.add_node(sg.root, rect);
930
931        assert!(sg.get_by_id(NodeId::intern("box1")).is_some());
932        assert_eq!(sg.children(sg.root).len(), 1);
933        assert_eq!(sg.children(sg.root)[0], idx);
934    }
935
936    #[test]
937    fn color_hex_roundtrip() {
938        let c = Color::from_hex("#6C5CE7").unwrap();
939        assert_eq!(c.to_hex(), "#6C5CE7");
940
941        let c2 = Color::from_hex("#FF000080").unwrap();
942        assert!((c2.a - 128.0 / 255.0).abs() < 0.01);
943        assert!(c2.to_hex().len() == 9); // #RRGGBBAA
944    }
945
946    #[test]
947    fn style_merging() {
948        let mut sg = SceneGraph::new();
949        sg.define_style(
950            NodeId::intern("base"),
951            Style {
952                fill: Some(Paint::Solid(Color::rgba(0.0, 0.0, 0.0, 1.0))),
953                font: Some(FontSpec {
954                    family: "Inter".into(),
955                    weight: 400,
956                    size: 14.0,
957                }),
958                ..Default::default()
959            },
960        );
961
962        let mut node = SceneNode::new(
963            NodeId::intern("txt"),
964            NodeKind::Text {
965                content: "hi".into(),
966            },
967        );
968        node.use_styles.push(NodeId::intern("base"));
969        node.style.font = Some(FontSpec {
970            family: "Inter".into(),
971            weight: 700,
972            size: 24.0,
973        });
974
975        let resolved = sg.resolve_style(&node, &[]);
976        // Fill comes from base style
977        assert!(resolved.fill.is_some());
978        // Font comes from inline override
979        let f = resolved.font.unwrap();
980        assert_eq!(f.weight, 700);
981        assert_eq!(f.size, 24.0);
982    }
983
984    #[test]
985    fn style_merging_align() {
986        let mut sg = SceneGraph::new();
987        sg.define_style(
988            NodeId::intern("centered"),
989            Style {
990                text_align: Some(TextAlign::Center),
991                text_valign: Some(TextVAlign::Middle),
992                ..Default::default()
993            },
994        );
995
996        // Node with use: centered + inline override of text_align to Right
997        let mut node = SceneNode::new(
998            NodeId::intern("overridden"),
999            NodeKind::Text {
1000                content: "hello".into(),
1001            },
1002        );
1003        node.use_styles.push(NodeId::intern("centered"));
1004        node.style.text_align = Some(TextAlign::Right);
1005
1006        let resolved = sg.resolve_style(&node, &[]);
1007        // Horizontal should be overridden to Right
1008        assert_eq!(resolved.text_align, Some(TextAlign::Right));
1009        // Vertical should come from base style (Middle)
1010        assert_eq!(resolved.text_valign, Some(TextVAlign::Middle));
1011    }
1012
1013    #[test]
1014    fn test_effective_target_bubbles_to_group() {
1015        let mut sg = SceneGraph::new();
1016
1017        // Root -> Group -> Rect
1018        let group_id = NodeId::intern("my_group");
1019        let rect_id = NodeId::intern("my_rect");
1020
1021        let group = SceneNode::new(
1022            group_id,
1023            NodeKind::Group {
1024                layout: LayoutMode::Free,
1025            },
1026        );
1027        let rect = SceneNode::new(
1028            rect_id,
1029            NodeKind::Rect {
1030                width: 10.0,
1031                height: 10.0,
1032            },
1033        );
1034
1035        let group_idx = sg.add_node(sg.root, group);
1036        sg.add_node(group_idx, rect);
1037
1038        // No selection → bubbles up to group
1039        assert_eq!(sg.effective_target(rect_id, &[]), group_id);
1040        // Group already selected → drills into leaf
1041        assert_eq!(sg.effective_target(rect_id, &[group_id]), rect_id);
1042        // Rect itself selected → returns rect (no group above is selected)
1043        // but group is NOT selected, so it bubbles to group
1044        assert_eq!(sg.effective_target(rect_id, &[rect_id]), group_id);
1045        // Group itself (no parent group) → returns group directly
1046        assert_eq!(sg.effective_target(group_id, &[]), group_id);
1047    }
1048
1049    #[test]
1050    fn test_effective_target_nested_groups() {
1051        let mut sg = SceneGraph::new();
1052
1053        // Root -> group_outer -> group_inner -> rect_leaf
1054        let outer_id = NodeId::intern("group_outer");
1055        let inner_id = NodeId::intern("group_inner");
1056        let leaf_id = NodeId::intern("rect_leaf");
1057
1058        let outer = SceneNode::new(
1059            outer_id,
1060            NodeKind::Group {
1061                layout: LayoutMode::Free,
1062            },
1063        );
1064        let inner = SceneNode::new(
1065            inner_id,
1066            NodeKind::Group {
1067                layout: LayoutMode::Free,
1068            },
1069        );
1070        let leaf = SceneNode::new(
1071            leaf_id,
1072            NodeKind::Rect {
1073                width: 50.0,
1074                height: 50.0,
1075            },
1076        );
1077
1078        let outer_idx = sg.add_node(sg.root, outer);
1079        let inner_idx = sg.add_node(outer_idx, inner);
1080        sg.add_node(inner_idx, leaf);
1081
1082        // No selection → bubbles to outermost group
1083        assert_eq!(sg.effective_target(leaf_id, &[]), outer_id);
1084        // Outer selected → drill to inner group (next unselected group)
1085        assert_eq!(sg.effective_target(leaf_id, &[outer_id]), inner_id);
1086        // Both groups selected → drill to leaf
1087        assert_eq!(sg.effective_target(leaf_id, &[outer_id, inner_id]), leaf_id);
1088        // Only inner selected, outer NOT → inner is selected so we drill into child (leaf)
1089        // The walk-up hits inner first, sees it's selected, breaks — returns leaf
1090        assert_eq!(sg.effective_target(leaf_id, &[inner_id]), leaf_id);
1091    }
1092
1093    #[test]
1094    fn test_effective_target_no_group() {
1095        let mut sg = SceneGraph::new();
1096
1097        // Root -> Rect (no group)
1098        let rect_id = NodeId::intern("standalone_rect");
1099        let rect = SceneNode::new(
1100            rect_id,
1101            NodeKind::Rect {
1102                width: 10.0,
1103                height: 10.0,
1104            },
1105        );
1106        sg.add_node(sg.root, rect);
1107
1108        // No group parent → returns leaf directly
1109        assert_eq!(sg.effective_target(rect_id, &[]), rect_id);
1110    }
1111
1112    #[test]
1113    fn test_is_ancestor_of() {
1114        let mut sg = SceneGraph::new();
1115
1116        // Root -> Group -> Rect
1117        let group_id = NodeId::intern("grp");
1118        let rect_id = NodeId::intern("r1");
1119        let other_id = NodeId::intern("other");
1120
1121        let group = SceneNode::new(
1122            group_id,
1123            NodeKind::Group {
1124                layout: LayoutMode::Free,
1125            },
1126        );
1127        let rect = SceneNode::new(
1128            rect_id,
1129            NodeKind::Rect {
1130                width: 10.0,
1131                height: 10.0,
1132            },
1133        );
1134        let other = SceneNode::new(
1135            other_id,
1136            NodeKind::Rect {
1137                width: 5.0,
1138                height: 5.0,
1139            },
1140        );
1141
1142        let group_idx = sg.add_node(sg.root, group);
1143        sg.add_node(group_idx, rect);
1144        sg.add_node(sg.root, other);
1145
1146        // Group is ancestor of rect
1147        assert!(sg.is_ancestor_of(group_id, rect_id));
1148        // Root is ancestor of rect (grandparent)
1149        assert!(sg.is_ancestor_of(NodeId::intern("root"), rect_id));
1150        // Rect is NOT ancestor of group
1151        assert!(!sg.is_ancestor_of(rect_id, group_id));
1152        // Self is NOT ancestor of self
1153        assert!(!sg.is_ancestor_of(group_id, group_id));
1154        // Other is not ancestor of rect (sibling)
1155        assert!(!sg.is_ancestor_of(other_id, rect_id));
1156    }
1157
1158    #[test]
1159    fn test_resolve_style_scale_animation() {
1160        let sg = SceneGraph::new();
1161
1162        let mut node = SceneNode::new(
1163            NodeId::intern("btn"),
1164            NodeKind::Rect {
1165                width: 100.0,
1166                height: 40.0,
1167            },
1168        );
1169        node.style.fill = Some(Paint::Solid(Color::rgba(1.0, 0.0, 0.0, 1.0)));
1170        node.animations.push(AnimKeyframe {
1171            trigger: AnimTrigger::Press,
1172            duration_ms: 100,
1173            easing: Easing::EaseOut,
1174            properties: AnimProperties {
1175                scale: Some(0.97),
1176                ..Default::default()
1177            },
1178        });
1179
1180        // Without press trigger: scale should be None
1181        let resolved = sg.resolve_style(&node, &[]);
1182        assert!(resolved.scale.is_none());
1183
1184        // With press trigger: scale should be 0.97
1185        let resolved = sg.resolve_style(&node, &[AnimTrigger::Press]);
1186        assert_eq!(resolved.scale, Some(0.97));
1187        // Fill should still be present
1188        assert!(resolved.fill.is_some());
1189    }
1190}