fd-core 0.1.18

FD (Fast Draft) — core data model, parser, emitter, and layout solver
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
//! Constraint-based layout solver.
//!
//! Converts relative constraints (center_in, offset, fill_parent) into
//! absolute `ResolvedBounds` for each node. Also handles Column/Row/Grid
//! layout modes for groups.

use crate::model::*;
use petgraph::graph::NodeIndex;
use std::collections::HashMap;

/// The canvas (viewport) dimensions.
#[derive(Debug, Clone, Copy)]
pub struct Viewport {
    pub width: f32,
    pub height: f32,
}

impl Default for Viewport {
    fn default() -> Self {
        Self {
            width: 800.0,
            height: 600.0,
        }
    }
}

/// Resolve all node positions in the scene graph.
///
/// Returns a map from `NodeIndex` → `ResolvedBounds` with absolute positions.
pub fn resolve_layout(
    graph: &SceneGraph,
    viewport: Viewport,
) -> HashMap<NodeIndex, ResolvedBounds> {
    let mut bounds: HashMap<NodeIndex, ResolvedBounds> = HashMap::new();

    // Root fills the viewport
    bounds.insert(
        graph.root,
        ResolvedBounds {
            x: 0.0,
            y: 0.0,
            width: viewport.width,
            height: viewport.height,
        },
    );

    // Resolve recursively from root
    resolve_children(graph, graph.root, &mut bounds, viewport);

    // Apply top-level constraints (may override layout-computed positions)
    // We do this by traversing top-down to ensure parent constraints are resolved before children.
    resolve_constraints_top_down(graph, graph.root, &mut bounds, viewport);

    // Final pass: re-compute group auto-sizes after constraints shifted children.
    // This ensures free-layout groups correctly contain children with Position constraints.
    recompute_group_auto_sizes(graph, graph.root, &mut bounds);

    bounds
}

/// Re-resolve only the children of `parent_idx`, using its current bounds.
///
/// This is a lightweight version of `resolve_layout` scoped to one subtree.
/// Used by `ResizeNode` to re-flow column/row/grid children and re-center
/// text during drag, without re-resolving the entire graph.
pub fn resolve_subtree(
    graph: &SceneGraph,
    parent_idx: NodeIndex,
    bounds: &mut HashMap<NodeIndex, ResolvedBounds>,
    viewport: Viewport,
) {
    resolve_children(graph, parent_idx, bounds, viewport);
    resolve_constraints_top_down(graph, parent_idx, bounds, viewport);
    recompute_group_auto_sizes(graph, parent_idx, bounds);
}

fn resolve_constraints_top_down(
    graph: &SceneGraph,
    node_idx: NodeIndex,
    bounds: &mut HashMap<NodeIndex, ResolvedBounds>,
    viewport: Viewport,
) {
    let node = &graph.graph[node_idx];
    for constraint in &node.constraints {
        // Position constraints now apply even inside managed layouts —
        // a moved child becomes "absolutely positioned" within the frame
        // (like Figma's Absolute Position toggle).
        apply_constraint(graph, node_idx, constraint, bounds, viewport);
    }

    for child_idx in graph.children(node_idx) {
        resolve_constraints_top_down(graph, child_idx, bounds, viewport);
    }
}

/// Check whether a node's parent uses a managed layout (Column/Row/Grid).
pub fn is_parent_managed(graph: &SceneGraph, node_idx: NodeIndex) -> bool {
    let parent_idx = match graph.parent(node_idx) {
        Some(p) => p,
        None => return false,
    };
    let parent_node = &graph.graph[parent_idx];
    match &parent_node.kind {
        NodeKind::Frame { layout, .. } => !matches!(layout, LayoutMode::Free { .. }),
        _ => false,
    }
}

/// Bottom-up re-computation of group auto-sizes after all constraints are applied.
fn recompute_group_auto_sizes(
    graph: &SceneGraph,
    node_idx: NodeIndex,
    bounds: &mut HashMap<NodeIndex, ResolvedBounds>,
) {
    // Recurse into children first (bottom-up)
    for child_idx in graph.children(node_idx) {
        recompute_group_auto_sizes(graph, child_idx, bounds);
    }

    let node = &graph.graph[node_idx];
    // Only groups auto-size — frames use declared dimensions
    if !matches!(node.kind, NodeKind::Group) {
        return;
    }

    let children = graph.children(node_idx);
    if children.is_empty() {
        return;
    }

    let mut min_x = f32::MAX;
    let mut min_y = f32::MAX;
    let mut max_x = f32::MIN;
    let mut max_y = f32::MIN;

    for &child_idx in &children {
        if let Some(cb) = bounds.get(&child_idx) {
            min_x = min_x.min(cb.x);
            min_y = min_y.min(cb.y);
            max_x = max_x.max(cb.x + cb.width);
            max_y = max_y.max(cb.y + cb.height);
        }
    }

    if min_x < f32::MAX {
        bounds.insert(
            node_idx,
            ResolvedBounds {
                x: min_x,
                y: min_y,
                width: max_x - min_x,
                height: max_y - min_y,
            },
        );
    }
}

#[allow(clippy::only_used_in_recursion)]
fn resolve_children(
    graph: &SceneGraph,
    parent_idx: NodeIndex,
    bounds: &mut HashMap<NodeIndex, ResolvedBounds>,
    viewport: Viewport,
) {
    let parent_bounds = bounds[&parent_idx];
    let parent_node = &graph.graph[parent_idx];

    let children: Vec<NodeIndex> = graph.children(parent_idx);
    if children.is_empty() {
        return;
    }

    // Determine layout mode
    let layout = match &parent_node.kind {
        NodeKind::Group => LayoutMode::Free { pad: 0.0 }, // Group is always Free
        NodeKind::Frame { layout, .. } => layout.clone(),
        _ => LayoutMode::Free { pad: 0.0 },
    };

    match layout {
        LayoutMode::Column { gap, pad } => {
            let content_width = parent_bounds.width - 2.0 * pad;
            // Filter: children with Position constraints are absolutely positioned
            // within the frame — they don't participate in the column flow.
            let flow_children: Vec<NodeIndex> = children
                .iter()
                .copied()
                .filter(|&ci| {
                    !graph.graph[ci]
                        .constraints
                        .iter()
                        .any(|c| matches!(c, Constraint::Position { .. }))
                })
                .collect();
            // Pass 1: initialize flow children at parent origin + pad
            for &child_idx in &flow_children {
                let child_node = &graph.graph[child_idx];
                let child_size = intrinsic_size(child_node);
                // Stretch text nodes to fill column width (like CSS align-items: stretch)
                let w = if matches!(child_node.kind, NodeKind::Text { .. }) {
                    content_width.max(child_size.0)
                } else {
                    child_size.0
                };
                bounds.insert(
                    child_idx,
                    ResolvedBounds {
                        x: parent_bounds.x + pad,
                        y: parent_bounds.y + pad,
                        width: w,
                        height: child_size.1,
                    },
                );
                resolve_children(graph, child_idx, bounds, viewport);
            }
            // Absolutely-positioned children: initialize from intrinsic_size
            for &child_idx in &children {
                if !flow_children.contains(&child_idx) {
                    let child_size = intrinsic_size(&graph.graph[child_idx]);
                    bounds.entry(child_idx).or_insert(ResolvedBounds {
                        x: parent_bounds.x,
                        y: parent_bounds.y,
                        width: child_size.0,
                        height: child_size.1,
                    });
                    resolve_children(graph, child_idx, bounds, viewport);
                }
            }
            // Pass 2: reposition flow children using resolved sizes
            let mut y = parent_bounds.y + pad;
            for &child_idx in &flow_children {
                let resolved = bounds[&child_idx];
                let dx = (parent_bounds.x + pad) - resolved.x;
                let dy = y - resolved.y;
                if dx.abs() > 0.001 || dy.abs() > 0.001 {
                    shift_subtree(graph, child_idx, dx, dy, bounds);
                }
                y += bounds[&child_idx].height + gap;
            }
        }
        LayoutMode::Row { gap, pad } => {
            // Filter: absolutely-positioned children skip the row flow
            let flow_children: Vec<NodeIndex> = children
                .iter()
                .copied()
                .filter(|&ci| {
                    !graph.graph[ci]
                        .constraints
                        .iter()
                        .any(|c| matches!(c, Constraint::Position { .. }))
                })
                .collect();
            // Pass 1: initialize flow children
            for &child_idx in &flow_children {
                let child_size = intrinsic_size(&graph.graph[child_idx]);
                bounds.insert(
                    child_idx,
                    ResolvedBounds {
                        x: parent_bounds.x + pad,
                        y: parent_bounds.y + pad,
                        width: child_size.0,
                        height: child_size.1,
                    },
                );
                resolve_children(graph, child_idx, bounds, viewport);
            }
            // Absolutely-positioned children
            for &child_idx in &children {
                if !flow_children.contains(&child_idx) {
                    let child_size = intrinsic_size(&graph.graph[child_idx]);
                    bounds.entry(child_idx).or_insert(ResolvedBounds {
                        x: parent_bounds.x,
                        y: parent_bounds.y,
                        width: child_size.0,
                        height: child_size.1,
                    });
                    resolve_children(graph, child_idx, bounds, viewport);
                }
            }
            // Pass 2: reposition flow children
            let mut x = parent_bounds.x + pad;
            for &child_idx in &flow_children {
                let resolved = bounds[&child_idx];
                let dx = x - resolved.x;
                let dy = (parent_bounds.y + pad) - resolved.y;
                if dx.abs() > 0.001 || dy.abs() > 0.001 {
                    shift_subtree(graph, child_idx, dx, dy, bounds);
                }
                x += bounds[&child_idx].width + gap;
            }
        }
        LayoutMode::Grid { cols, gap, pad } => {
            // Filter: absolutely-positioned children skip the grid flow
            let flow_children: Vec<NodeIndex> = children
                .iter()
                .copied()
                .filter(|&ci| {
                    !graph.graph[ci]
                        .constraints
                        .iter()
                        .any(|c| matches!(c, Constraint::Position { .. }))
                })
                .collect();
            // Pass 1: initialize flow children
            for &child_idx in &flow_children {
                let child_size = intrinsic_size(&graph.graph[child_idx]);
                bounds.insert(
                    child_idx,
                    ResolvedBounds {
                        x: parent_bounds.x + pad,
                        y: parent_bounds.y + pad,
                        width: child_size.0,
                        height: child_size.1,
                    },
                );
                resolve_children(graph, child_idx, bounds, viewport);
            }
            // Absolutely-positioned children
            for &child_idx in &children {
                if !flow_children.contains(&child_idx) {
                    let child_size = intrinsic_size(&graph.graph[child_idx]);
                    bounds.entry(child_idx).or_insert(ResolvedBounds {
                        x: parent_bounds.x,
                        y: parent_bounds.y,
                        width: child_size.0,
                        height: child_size.1,
                    });
                    resolve_children(graph, child_idx, bounds, viewport);
                }
            }
            // Pass 2: reposition flow children
            let mut x = parent_bounds.x + pad;
            let mut y = parent_bounds.y + pad;
            let mut col = 0u32;
            let mut row_height = 0.0f32;

            for &child_idx in &flow_children {
                let resolved = bounds[&child_idx];
                let dx = x - resolved.x;
                let dy = y - resolved.y;
                if dx.abs() > 0.001 || dy.abs() > 0.001 {
                    shift_subtree(graph, child_idx, dx, dy, bounds);
                }

                let resolved = bounds[&child_idx];
                row_height = row_height.max(resolved.height);
                col += 1;
                if col >= cols {
                    col = 0;
                    x = parent_bounds.x + pad;
                    y += row_height + gap;
                    row_height = 0.0;
                } else {
                    x += resolved.width + gap;
                }
            }
        }
        LayoutMode::Free { pad } => {
            // Compute padded content area
            let content_x = parent_bounds.x + pad;
            let content_y = parent_bounds.y + pad;
            let content_w = (parent_bounds.width - 2.0 * pad).max(0.0);
            let content_h = (parent_bounds.height - 2.0 * pad).max(0.0);

            // Each child positioned at padded origin by default.
            // Use or_insert to preserve existing cached bounds (e.g. JS-measured
            // text sizes, explicit positions) during resolve_subtree calls.
            for &child_idx in &children {
                let child_size = intrinsic_size(&graph.graph[child_idx]);
                bounds.entry(child_idx).or_insert(ResolvedBounds {
                    x: content_x,
                    y: content_y,
                    width: child_size.0,
                    height: child_size.1,
                });
            }

            let parent_is_shape = matches!(
                parent_node.kind,
                NodeKind::Rect { .. } | NodeKind::Ellipse { .. } | NodeKind::Frame { .. }
            );

            for &child_idx in &children {
                let child_node = &graph.graph[child_idx];
                let has_position = child_node
                    .constraints
                    .iter()
                    .any(|c| matches!(c, Constraint::Position { .. }));

                // Priority 1: explicit `place:` property (uses padded area)
                if let Some((h, v)) = child_node.place {
                    if !has_position && let Some(cb) = bounds.get(&child_idx).copied() {
                        let x = match h {
                            HPlace::Left => content_x,
                            HPlace::Center => content_x + (content_w - cb.width) / 2.0,
                            HPlace::Right => content_x + content_w - cb.width,
                        };
                        let y = match v {
                            VPlace::Top => content_y,
                            VPlace::Middle => content_y + (content_h - cb.height) / 2.0,
                            VPlace::Bottom => content_y + content_h - cb.height,
                        };
                        bounds.insert(child_idx, ResolvedBounds { x, y, ..cb });
                    }
                    continue;
                }

                // Priority 2: auto-center text children in shape parents
                // (no explicit place: and no Position constraint)
                // Uses padded bounds for centering area
                if parent_is_shape
                    && matches!(child_node.kind, NodeKind::Text { .. })
                    && !has_position
                    && let Some(child_b) = bounds.get(&child_idx).copied()
                {
                    let cx = content_x + (content_w - child_b.width) / 2.0;
                    let cy = content_y + (content_h - child_b.height) / 2.0;
                    bounds.insert(
                        child_idx,
                        ResolvedBounds {
                            x: cx,
                            y: cy,
                            width: child_b.width,
                            height: child_b.height,
                        },
                    );
                }
            }
        }
    }

    // Recurse into children (only for Free mode — Column/Row/Grid already recursed in pass 1)
    if matches!(layout, LayoutMode::Free { .. }) {
        for &child_idx in &children {
            resolve_children(graph, child_idx, bounds, viewport);
        }
    }

    // Auto-size groups to the union bounding box of their children
    if matches!(parent_node.kind, NodeKind::Group) && !children.is_empty() {
        let mut min_x = f32::MAX;
        let mut min_y = f32::MAX;
        let mut max_x = f32::MIN;
        let mut max_y = f32::MIN;

        for &child_idx in &children {
            if let Some(cb) = bounds.get(&child_idx) {
                min_x = min_x.min(cb.x);
                min_y = min_y.min(cb.y);
                max_x = max_x.max(cb.x + cb.width);
                max_y = max_y.max(cb.y + cb.height);
            }
        }

        if min_x < f32::MAX {
            bounds.insert(
                parent_idx,
                ResolvedBounds {
                    x: min_x,
                    y: min_y,
                    width: max_x - min_x,
                    height: max_y - min_y,
                },
            );
        }
    }
}

/// Recursively shift a node and all its descendants by (dx, dy).
/// Used after pass 2 repositioning to keep subtree positions consistent.
fn shift_subtree(
    graph: &SceneGraph,
    node_idx: NodeIndex,
    dx: f32,
    dy: f32,
    bounds: &mut HashMap<NodeIndex, ResolvedBounds>,
) {
    if let Some(b) = bounds.get(&node_idx).copied() {
        bounds.insert(
            node_idx,
            ResolvedBounds {
                x: b.x + dx,
                y: b.y + dy,
                ..b
            },
        );
    }
    for child_idx in graph.children(node_idx) {
        shift_subtree(graph, child_idx, dx, dy, bounds);
    }
}

/// Get the intrinsic (declared) size of a node.
fn intrinsic_size(node: &SceneNode) -> (f32, f32) {
    match &node.kind {
        NodeKind::Rect { width, height } => (*width, *height),
        NodeKind::Ellipse { rx, ry } => (*rx * 2.0, *ry * 2.0),
        NodeKind::Text {
            content, max_width, ..
        } => {
            let font_size = node.props.font.as_ref().map_or(14.0, |f| f.size);
            let char_width = font_size * 0.6;
            let total_w = content.chars().count() as f32 * char_width;
            let line_height = font_size * 1.4;
            match max_width {
                // With max_width: return single-line placeholder height.
                // The accurate wrapped height is set by JS measureText()
                // round-trip (KI Lesson #9: heuristics must not fight
                // high-fidelity measurements).
                Some(mw) => (*mw, line_height),
                None => (total_w, line_height),
            }
        }
        NodeKind::Group => (0.0, 0.0), // Auto-sized: computed after children resolve
        NodeKind::Frame { width, height, .. } => (*width, *height),
        NodeKind::Path { .. } => (100.0, 100.0), // Computed from path bounds
        NodeKind::Image { width, height, .. } => (*width, *height),
        NodeKind::Generic => (120.0, 40.0), // Placeholder label box
        NodeKind::Root => (0.0, 0.0),
    }
}

fn apply_constraint(
    graph: &SceneGraph,
    node_idx: NodeIndex,
    constraint: &Constraint,
    bounds: &mut HashMap<NodeIndex, ResolvedBounds>,
    viewport: Viewport,
) {
    let node_bounds = match bounds.get(&node_idx) {
        Some(b) => *b,
        None => return,
    };

    match constraint {
        Constraint::CenterIn(target_id) => {
            let container = if target_id.as_str() == "canvas" {
                ResolvedBounds {
                    x: 0.0,
                    y: 0.0,
                    width: viewport.width,
                    height: viewport.height,
                }
            } else {
                match graph.index_of(*target_id).and_then(|i| bounds.get(&i)) {
                    Some(b) => *b,
                    None => return,
                }
            };

            let cx = container.x + (container.width - node_bounds.width) / 2.0;
            let cy = container.y + (container.height - node_bounds.height) / 2.0;
            let dx = cx - node_bounds.x;
            let dy = cy - node_bounds.y;

            shift_subtree(graph, node_idx, dx, dy, bounds);
        }
        Constraint::Offset { from, dx, dy } => {
            let from_bounds = match graph.index_of(*from).and_then(|i| bounds.get(&i)) {
                Some(b) => *b,
                None => return,
            };
            let target_x = from_bounds.x + dx;
            let target_y = from_bounds.y + dy;
            let sdx = target_x - node_bounds.x;
            let sdy = target_y - node_bounds.y;

            shift_subtree(graph, node_idx, sdx, sdy, bounds);
        }
        Constraint::FillParent { pad } => {
            // Find parent in graph
            let parent_idx = graph
                .graph
                .neighbors_directed(node_idx, petgraph::Direction::Incoming)
                .next();

            if let Some(parent) = parent_idx.and_then(|p| bounds.get(&p).copied()) {
                let target_x = parent.x + pad;
                let target_y = parent.y + pad;
                let new_w = parent.width - 2.0 * pad;
                let new_h = parent.height - 2.0 * pad;
                let dx = target_x - node_bounds.x;
                let dy = target_y - node_bounds.y;

                // Move children with the position shift
                shift_subtree(graph, node_idx, dx, dy, bounds);

                // Apply the resize to the node itself (children keep their sizes)
                if let Some(nb) = bounds.get_mut(&node_idx) {
                    nb.width = new_w;
                    nb.height = new_h;
                }
            }
        }
        Constraint::Position { x, y } => {
            let (px, py) = match graph.parent(node_idx).and_then(|p| bounds.get(&p)) {
                Some(p_bounds) => (p_bounds.x, p_bounds.y),
                None => (0.0, 0.0),
            };
            let target_x = px + *x;
            let target_y = py + *y;
            let dx = target_x - node_bounds.x;
            let dy = target_y - node_bounds.y;

            shift_subtree(graph, node_idx, dx, dy, bounds);
        }
    }
}

#[cfg(test)]
#[path = "layout_tests.rs"]
mod tests;