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    /// Organizational container (like Figma Group).
416    /// Auto-sizes to children, no own styles or layout modes.
417    Group,
418
419    /// Frame — visible container with explicit size and optional clipping.
420    /// Like a Figma frame: has fill/stroke, declared dimensions, clips overflow.
421    Frame {
422        width: f32,
423        height: f32,
424        clip: bool,
425        layout: LayoutMode,
426    },
427
428    /// Rectangle.
429    Rect { width: f32, height: f32 },
430
431    /// Ellipse / circle.
432    Ellipse { rx: f32, ry: f32 },
433
434    /// Freeform path (pen tool output).
435    Path { commands: Vec<PathCmd> },
436
437    /// Text label.
438    Text { content: String },
439}
440
441impl NodeKind {
442    /// Return the FD format keyword for this node kind.
443    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/// A single node in the scene graph.
458#[derive(Debug, Clone, Serialize, Deserialize)]
459pub struct SceneNode {
460    /// The node's ID (e.g. `@login_form`). Anonymous nodes get auto-IDs.
461    pub id: NodeId,
462
463    /// What kind of element this is.
464    pub kind: NodeKind,
465
466    /// Inline style overrides on this node.
467    pub style: Style,
468
469    /// Named theme references (`use: base_text`).
470    pub use_styles: SmallVec<[NodeId; 2]>,
471
472    /// Constraint-based positioning.
473    pub constraints: SmallVec<[Constraint; 2]>,
474
475    /// Animations attached to this node.
476    pub animations: SmallVec<[AnimKeyframe; 2]>,
477
478    /// Structured annotations (`spec { ... }` block).
479    pub annotations: Vec<Annotation>,
480
481    /// Line comments (`# text`) that appeared before this node in the source.
482    /// Preserved across parse/emit round-trips so format passes don't delete them.
483    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// ─── Scene Graph ─────────────────────────────────────────────────────────
502
503/// The complete FD document — a DAG of `SceneNode` values.
504///
505/// Edges go from parent → child. Style definitions are stored separately
506/// in a hashmap for lookup by name.
507#[derive(Debug, Clone)]
508pub struct SceneGraph {
509    /// The underlying directed graph.
510    pub graph: StableDiGraph<SceneNode, ()>,
511
512    /// The root node index.
513    pub root: NodeIndex,
514
515    /// Named theme definitions (`theme base_text { ... }`).
516    pub styles: HashMap<NodeId, Style>,
517
518    /// Index from NodeId → NodeIndex for fast lookup.
519    pub id_index: HashMap<NodeId, NodeIndex>,
520
521    /// Visual edges (connections between nodes).
522    pub edges: Vec<Edge>,
523
524    /// File imports with namespace aliases.
525    pub imports: Vec<Import>,
526
527    /// Explicit child ordering set by `sort_nodes`.
528    /// When present for a parent, `children()` returns this order
529    /// instead of the default `NodeIndex` sort.
530    pub sorted_child_order: HashMap<NodeIndex, Vec<NodeIndex>>,
531}
532
533impl SceneGraph {
534    /// Create a new empty scene graph with a root node.
535    #[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    /// Add a node as a child of `parent`. Returns the new node's index.
556    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    /// Remove a node safely, keeping the `id_index` synchronized.
565    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    /// Look up a node by its `@id`.
574    pub fn get_by_id(&self, id: NodeId) -> Option<&SceneNode> {
575        self.id_index.get(&id).map(|idx| &self.graph[*idx])
576    }
577
578    /// Look up a node mutably by its `@id`.
579    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    /// Get the index for a NodeId.
587    pub fn index_of(&self, id: NodeId) -> Option<NodeIndex> {
588        self.id_index.get(&id).copied()
589    }
590
591    /// Get the parent index of a node.
592    pub fn parent(&self, idx: NodeIndex) -> Option<NodeIndex> {
593        self.graph
594            .neighbors_directed(idx, petgraph::Direction::Incoming)
595            .next()
596    }
597
598    /// Reparent a node to a new parent.
599    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    /// Get children of a node in document (insertion) order.
609    ///
610    /// Sorts by `NodeIndex` so the result is deterministic regardless of
611    /// how `petgraph` iterates its adjacency list on different targets
612    /// (native vs WASM).
613    pub fn children(&self, idx: NodeIndex) -> Vec<NodeIndex> {
614        // If an explicit sort order was set (by sort_nodes), use it
615        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    /// Move a child one step backward in z-order (swap with previous sibling).
628    /// Returns true if the z-order changed.
629    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; // already at back
641        }
642        // Rebuild edges in swapped order
643        self.rebuild_child_order(parent, &siblings, pos, pos - 1)
644    }
645
646    /// Move a child one step forward in z-order (swap with next sibling).
647    /// Returns true if the z-order changed.
648    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; // already at front
660        }
661        self.rebuild_child_order(parent, &siblings, pos, pos + 1)
662    }
663
664    /// Move a child to the back of z-order (first child).
665    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    /// Move a child to the front of z-order (last child).
682    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    /// Rebuild child edges, moving child at `from` to `to` position.
700    fn rebuild_child_order(
701        &mut self,
702        parent: NodeIndex,
703        siblings: &[NodeIndex],
704        from: usize,
705        to: usize,
706    ) -> bool {
707        // Remove all edges from parent to children
708        for &sib in siblings {
709            if let Some(edge) = self.graph.find_edge(parent, sib) {
710                self.graph.remove_edge(edge);
711            }
712        }
713        // Build new order
714        let mut new_order: Vec<NodeIndex> = siblings.to_vec();
715        let child = new_order.remove(from);
716        new_order.insert(to, child);
717        // Re-add edges in new order
718        for &sib in &new_order {
719            self.graph.add_edge(parent, sib, ());
720        }
721        true
722    }
723
724    /// Define a named style.
725    pub fn define_style(&mut self, name: NodeId, style: Style) {
726        self.styles.insert(name, style);
727    }
728
729    /// Resolve a node's effective style (merging `use` references + inline overrides + active animations).
730    pub fn resolve_style(&self, node: &SceneNode, active_triggers: &[AnimTrigger]) -> Style {
731        let mut resolved = Style::default();
732
733        // Apply referenced styles in order
734        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        // Apply inline overrides (take precedence)
741        merge_style(&mut resolved, &node.style);
742
743        // Apply active animation state overrides
744        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    /// Rebuild the `id_index` (needed after deserialization).
762    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    /// Resolve an edge's effective style (merging `use` references + inline overrides + active animations).
771    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    /// Figma-style target bubbling: if the leaf is inside a Group that isn't
798    /// already selected, return the outermost unselected Group. Otherwise
799    /// return the leaf directly.
800    ///
801    /// This gives "first click selects group, second click drills in" behavior.
802    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 this group is already selected, stop bubbling — let inner target through
816                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    /// Check if `ancestor_id` is a parent/grandparent/etc. of `descendant_id`.
828    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
855/// Merge `src` style into `dst`, overwriting only `Some` fields.
856fn 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// ─── Resolved positions (output of layout solver) ────────────────────────
888
889/// Resolved absolute bounding box after constraint solving.
890#[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    /// Check if this bounds intersects with a rectangle (AABB overlap).
908    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); // #RRGGBBAA
945    }
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        // Fill comes from base style
978        assert!(resolved.fill.is_some());
979        // Font comes from inline override
980        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        // Node with use: centered + inline override of text_align to Right
998        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        // Horizontal should be overridden to Right
1009        assert_eq!(resolved.text_align, Some(TextAlign::Right));
1010        // Vertical should come from base style (Middle)
1011        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        // Root -> Group -> Rect
1019        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        // No selection → bubbles up to group
1035        assert_eq!(sg.effective_target(rect_id, &[]), group_id);
1036        // Group already selected → drills into leaf
1037        assert_eq!(sg.effective_target(rect_id, &[group_id]), rect_id);
1038        // Rect itself selected → returns rect (no group above is selected)
1039        // but group is NOT selected, so it bubbles to group
1040        assert_eq!(sg.effective_target(rect_id, &[rect_id]), group_id);
1041        // Group itself (no parent group) → returns group directly
1042        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        // Root -> group_outer -> group_inner -> rect_leaf
1050        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        // No selection → bubbles to outermost group
1069        assert_eq!(sg.effective_target(leaf_id, &[]), outer_id);
1070        // Outer selected → drill to inner group (next unselected group)
1071        assert_eq!(sg.effective_target(leaf_id, &[outer_id]), inner_id);
1072        // Both groups selected → drill to leaf
1073        assert_eq!(sg.effective_target(leaf_id, &[outer_id, inner_id]), leaf_id);
1074        // Only inner selected, outer NOT → inner is selected so we drill into child (leaf)
1075        // The walk-up hits inner first, sees it's selected, breaks — returns leaf
1076        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        // Root -> Rect (no group)
1084        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        // No group parent → returns leaf directly
1095        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        // Root -> Group -> Rect
1103        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        // Group is ancestor of rect
1128        assert!(sg.is_ancestor_of(group_id, rect_id));
1129        // Root is ancestor of rect (grandparent)
1130        assert!(sg.is_ancestor_of(NodeId::intern("root"), rect_id));
1131        // Rect is NOT ancestor of group
1132        assert!(!sg.is_ancestor_of(rect_id, group_id));
1133        // Self is NOT ancestor of self
1134        assert!(!sg.is_ancestor_of(group_id, group_id));
1135        // Other is not ancestor of rect (sibling)
1136        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        // Without press trigger: scale should be None
1162        let resolved = sg.resolve_style(&node, &[]);
1163        assert!(resolved.scale.is_none());
1164
1165        // With press trigger: scale should be 0.97
1166        let resolved = sg.resolve_style(&node, &[AnimTrigger::Press]);
1167        assert_eq!(resolved.scale, Some(0.97));
1168        // Fill should still be present
1169        assert!(resolved.fill.is_some());
1170    }
1171}