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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
use super::*;
use crate::id::NodeId;
use crate::parser::parse_document;

#[test]
fn layout_column() {
    let input = r#"
frame @form {
  w: 800 h: 600
  layout: column gap=10 pad=20

  rect @a { w: 100 h: 40 }
  rect @b { w: 100 h: 30 }
}
"#;
    let graph = parse_document(input).unwrap();
    let viewport = Viewport {
        width: 800.0,
        height: 600.0,
    };
    let bounds = resolve_layout(&graph, viewport);

    let a_idx = graph.index_of(NodeId::intern("a")).unwrap();
    let b_idx = graph.index_of(NodeId::intern("b")).unwrap();

    let a = bounds[&a_idx];
    let b = bounds[&b_idx];

    // Both should be at x = pad (20)
    assert!(
        (a.x - 20.0).abs() < 0.01,
        "a.x should be 20 (pad), got {}",
        a.x
    );
    assert!(
        (b.x - 20.0).abs() < 0.01,
        "b.x should be 20 (pad), got {}",
        b.x
    );

    // The two children should be exactly (height_of_first + gap) apart
    let gap_plus_height = (b.y - a.y).abs();
    // Either a is first (gap = 40 + 10 = 50) or b is first (gap = 30 + 10 = 40)
    assert!(
        (gap_plus_height - 50.0).abs() < 0.01 || (gap_plus_height - 40.0).abs() < 0.01,
        "children should be height+gap apart, got diff = {gap_plus_height}"
    );
}

#[test]
fn layout_center_in_canvas() {
    let input = r#"
rect @box {
  w: 200
  h: 100
}

@box -> center_in: canvas
"#;
    let graph = parse_document(input).unwrap();
    let viewport = Viewport {
        width: 800.0,
        height: 600.0,
    };
    let bounds = resolve_layout(&graph, viewport);

    let idx = graph.index_of(NodeId::intern("box")).unwrap();
    let b = bounds[&idx];

    assert!((b.x - 300.0).abs() < 0.01); // (800 - 200) / 2
    assert!((b.y - 250.0).abs() < 0.01); // (600 - 100) / 2
}

#[test]
fn layout_group_auto_bounds() {
    // Group auto-sizing: group dimensions are computed from children bounding box
    let input = r#"
group @container {
  rect @a { w: 100 h: 40 x: 10 y: 10 }
  rect @b { w: 80 h: 30 x: 10 y: 60 }
}
"#;
    let graph = parse_document(input).unwrap();
    let viewport = Viewport {
        width: 800.0,
        height: 600.0,
    };
    let bounds = resolve_layout(&graph, viewport);

    let container_idx = graph.index_of(NodeId::intern("container")).unwrap();
    let cb = &bounds[&container_idx];

    // Group should auto-size to cover both children
    assert!(cb.width > 0.0, "group width should be positive");
    assert!(cb.height > 0.0, "group height should be positive");
    // Width should be at least the wider child (100px)
    assert!(
        cb.width >= 100.0,
        "group width ({}) should be >= 100",
        cb.width
    );
}

#[test]
fn layout_frame_declared_size() {
    let input = r#"
frame @card {
  w: 480 h: 320
}
"#;
    let graph = parse_document(input).unwrap();
    let viewport = Viewport {
        width: 800.0,
        height: 600.0,
    };
    let bounds = resolve_layout(&graph, viewport);

    let idx = graph.index_of(NodeId::intern("card")).unwrap();
    let b = &bounds[&idx];

    assert_eq!(b.width, 480.0, "frame should use declared width");
    assert_eq!(b.height, 320.0, "frame should use declared height");
}

#[test]
fn layout_nested_group_auto_size() {
    // Nested groups: both outer and inner auto-size to children
    let input = r#"
group @outer {
  group @inner {
rect @a { w: 100 h: 40 x: 0 y: 0 }
rect @b { w: 80 h: 30 x: 0 y: 50 }
  }
  rect @c { w: 120 h: 50 x: 0 y: 100 }
}
"#;
    let graph = parse_document(input).unwrap();
    let viewport = Viewport {
        width: 800.0,
        height: 600.0,
    };
    let bounds = resolve_layout(&graph, viewport);

    let inner_idx = graph.index_of(NodeId::intern("inner")).unwrap();
    let outer_idx = graph.index_of(NodeId::intern("outer")).unwrap();

    let inner = bounds[&inner_idx];
    let outer = bounds[&outer_idx];

    // Inner group: height should cover both children
    assert!(
        inner.height >= 70.0,
        "inner group height ({}) should be >= 70 (children bbox)",
        inner.height
    );

    // Outer group should contain both @inner and @c
    let outer_bottom = outer.y + outer.height;
    assert!(
        outer_bottom >= 150.0,
        "outer bottom ({outer_bottom}) should contain all children"
    );
}

#[test]
fn layout_group_child_inside_column_parent() {
    // Frame with column layout containing a group child
    let input = r#"
frame @wizard {
  w: 480 h: 800
  layout: column gap=0 pad=0

  rect @card {
w: 480 h: 520
  }
}
"#;
    let graph = parse_document(input).unwrap();
    let viewport = Viewport {
        width: 800.0,
        height: 600.0,
    };
    let bounds = resolve_layout(&graph, viewport);

    let wizard_idx = graph.index_of(NodeId::intern("wizard")).unwrap();
    let card_idx = graph.index_of(NodeId::intern("card")).unwrap();

    let wizard = bounds[&wizard_idx];
    let card = bounds[&card_idx];

    // Card should be inside wizard
    assert!(
        card.y >= wizard.y,
        "card.y ({}) must be >= wizard.y ({})",
        card.y,
        wizard.y
    );
}

#[test]
fn layout_column_preserves_document_order() {
    let input = r#"
frame @card {
  w: 800 h: 600
  layout: column gap=12 pad=24

  text @heading "Monthly Revenue" {
font: "Inter" 600 18
  }
  text @amount "$48,250" {
font: "Inter" 700 36
  }
  rect @button { w: 320 h: 44 }
}
"#;
    let graph = parse_document(input).unwrap();
    let viewport = Viewport {
        width: 800.0,
        height: 600.0,
    };
    let bounds = resolve_layout(&graph, viewport);

    let heading = bounds[&graph.index_of(NodeId::intern("heading")).unwrap()];
    let amount = bounds[&graph.index_of(NodeId::intern("amount")).unwrap()];
    let button = bounds[&graph.index_of(NodeId::intern("button")).unwrap()];

    assert!(
        heading.y < amount.y,
        "heading (y={}) must be above amount (y={})",
        heading.y,
        amount.y
    );
    assert!(
        amount.y < button.y,
        "amount (y={}) must be above button (y={})",
        amount.y,
        button.y
    );
    // Heading height should use font size × 1.4 (line-height)
    let expected_heading_h = 18.0 * 1.4;
    assert!(
        (heading.height - expected_heading_h).abs() < 0.01,
        "heading height should be {} (font size × 1.4), got {}",
        expected_heading_h,
        heading.height
    );
    // Amount height should use font size × 1.4 (line-height)
    let expected_amount_h = 36.0 * 1.4;
    assert!(
        (amount.height - expected_amount_h).abs() < 0.01,
        "amount height should be {} (font size × 1.4), got {}",
        expected_amount_h,
        amount.height
    );
}

#[test]
fn layout_dashboard_card_with_center_in() {
    let input = r#"
frame @card {
  w: 800 h: 600
  layout: column gap=12 pad=24
  text @heading "Monthly Revenue" { font: "Inter" 600 18 }
  text @amount "$48,250" { font: "Inter" 700 36 }
  text @change "+12.5% from last month" { font: "Inter" 400 14 }
  rect @chart { w: 320 h: 160 }
  rect @button { w: 320 h: 44 }
}
@card -> center_in: canvas
"#;
    let graph = parse_document(input).unwrap();
    let card_idx = graph.index_of(NodeId::intern("card")).unwrap();

    // graph.children() must return document order regardless of platform
    let children: Vec<_> = graph
        .children(card_idx)
        .iter()
        .map(|idx| graph.graph[*idx].id.as_str().to_string())
        .collect();
    assert_eq!(children[0], "heading", "First child must be heading");
    assert_eq!(children[4], "button", "Last child must be button");

    let viewport = Viewport {
        width: 800.0,
        height: 600.0,
    };
    let bounds = resolve_layout(&graph, viewport);

    let heading = bounds[&graph.index_of(NodeId::intern("heading")).unwrap()];
    let amount = bounds[&graph.index_of(NodeId::intern("amount")).unwrap()];
    let change = bounds[&graph.index_of(NodeId::intern("change")).unwrap()];
    let chart = bounds[&graph.index_of(NodeId::intern("chart")).unwrap()];
    let button = bounds[&graph.index_of(NodeId::intern("button")).unwrap()];
    let card = bounds[&graph.index_of(NodeId::intern("card")).unwrap()];

    // All children must be INSIDE the card
    assert!(
        heading.y >= card.y,
        "heading.y({}) must be >= card.y({})",
        heading.y,
        card.y
    );
    assert!(
        button.y + button.height <= card.y + card.height + 0.1,
        "button bottom({}) must be <= card bottom({})",
        button.y + button.height,
        card.y + card.height
    );

    // Document order preserved after center_in shift
    assert!(
        heading.y < amount.y,
        "heading.y({}) < amount.y({})",
        heading.y,
        amount.y
    );
    assert!(
        amount.y < change.y,
        "amount.y({}) < change.y({})",
        amount.y,
        change.y
    );
    assert!(
        change.y < chart.y,
        "change.y({}) < chart.y({})",
        change.y,
        chart.y
    );
    assert!(
        chart.y < button.y,
        "chart.y({}) < button.y({})",
        chart.y,
        button.y
    );
}

#[test]
fn layout_column_position_constraint_becomes_absolute() {
    // Children with Position constraints inside a column layout become
    // absolutely positioned (Figma-style). They're pulled out of the
    // column flow, while children without Position stay stacked.
    let input = r#"
frame @card {
  w: 800 h: 600
  layout: column gap=10 pad=20

  rect @a { w: 100 h: 40 }
  rect @b {
w: 100 h: 30
x: 500 y: 500
  }
}
"#;
    let graph = parse_document(input).unwrap();
    let viewport = Viewport {
        width: 800.0,
        height: 600.0,
    };
    let bounds = resolve_layout(&graph, viewport);

    let a_idx = graph.index_of(NodeId::intern("a")).unwrap();
    let b_idx = graph.index_of(NodeId::intern("b")).unwrap();
    let card_idx = graph.index_of(NodeId::intern("card")).unwrap();

    let a = bounds[&a_idx];
    let b = bounds[&b_idx];
    let card = bounds[&card_idx];

    // @a stays in column flow: x = card.x + pad (20)
    assert!(
        (a.x - (card.x + 20.0)).abs() < 0.01,
        "a.x ({}) should be card.x + pad ({})",
        a.x,
        card.x + 20.0
    );

    // @b has Position(500, 500) → absolutely positioned at card.x + 500
    assert!(
        (b.x - (card.x + 500.0)).abs() < 0.01,
        "b.x ({}) should be card.x + 500 ({})",
        b.x,
        card.x + 500.0
    );
    assert!(
        (b.y - (card.y + 500.0)).abs() < 0.01,
        "b.y ({}) should be card.y + 500 ({})",
        b.y,
        card.y + 500.0
    );
}

#[test]
fn layout_group_auto_size_contains_all_children() {
    // A free-layout group should auto-size to contain all children,
    // even those with Position constraints that extend beyond others.
    let input = r#"
group @panel {
  rect @a { w: 100 h: 40 }
  rect @b {
w: 80 h: 30
x: 200 y: 150
  }
}
"#;
    let graph = parse_document(input).unwrap();
    let viewport = Viewport {
        width: 800.0,
        height: 600.0,
    };
    let bounds = resolve_layout(&graph, viewport);

    let panel_idx = graph.index_of(NodeId::intern("panel")).unwrap();
    let b_idx = graph.index_of(NodeId::intern("b")).unwrap();

    let panel = bounds[&panel_idx];
    let b = bounds[&b_idx];

    // Panel must contain @b entirely
    assert!(
        panel.x + panel.width >= b.x + b.width,
        "panel right ({}) must contain b right ({})",
        panel.x + panel.width,
        b.x + b.width
    );
    assert!(
        panel.y + panel.height >= b.y + b.height,
        "panel bottom ({}) must contain b bottom ({})",
        panel.y + panel.height,
        b.y + b.height
    );
}

#[test]
fn layout_text_centered_in_rect() {
    let input = r#"
rect @btn {
  w: 320 h: 44
  text @label "View Details" {
font: "Inter" 600 14
  }
}
"#;
    let graph = parse_document(input).unwrap();
    let viewport = Viewport {
        width: 800.0,
        height: 600.0,
    };
    let bounds = resolve_layout(&graph, viewport);

    let btn = bounds[&graph.index_of(NodeId::intern("btn")).unwrap()];
    let label = bounds[&graph.index_of(NodeId::intern("label")).unwrap()];

    // Text should use intrinsic size (hug contents), not fill parent
    assert!(
        label.width < btn.width,
        "text width ({}) should be < parent ({})",
        label.width,
        btn.width
    );
    assert!(
        label.height < btn.height,
        "text height ({}) should be < parent ({})",
        label.height,
        btn.height
    );

    // Text should be centered within parent
    let expected_cx = btn.x + btn.width / 2.0;
    let actual_cx = label.x + label.width / 2.0;
    assert!(
        (actual_cx - expected_cx).abs() < 0.1,
        "text center x ({}) should match parent center ({})",
        actual_cx,
        expected_cx
    );
    let expected_cy = btn.y + btn.height / 2.0;
    let actual_cy = label.y + label.height / 2.0;
    assert!(
        (actual_cy - expected_cy).abs() < 0.1,
        "text center y ({}) should match parent center ({})",
        actual_cy,
        expected_cy
    );
}

#[test]
fn layout_text_in_ellipse_centered() {
    let input = r#"
ellipse @badge {
  rx: 60 ry: 30
  text @count "42" {
font: "Inter" 700 20
  }
}
"#;
    let graph = parse_document(input).unwrap();
    let viewport = Viewport {
        width: 800.0,
        height: 600.0,
    };
    let bounds = resolve_layout(&graph, viewport);

    let badge = bounds[&graph.index_of(NodeId::intern("badge")).unwrap()];
    let count = bounds[&graph.index_of(NodeId::intern("count")).unwrap()];

    // Text should use intrinsic size, not fill the ellipse
    assert!(
        count.width < badge.width,
        "text width ({}) should be < ellipse ({})",
        count.width,
        badge.width
    );

    // Text should be centered within the ellipse bounding box
    let expected_cx = badge.x + badge.width / 2.0;
    let actual_cx = count.x + count.width / 2.0;
    assert!(
        (actual_cx - expected_cx).abs() < 0.1,
        "text center x ({}) should match ellipse center ({})",
        actual_cx,
        expected_cx
    );
    let expected_cy = badge.y + badge.height / 2.0;
    let actual_cy = count.y + count.height / 2.0;
    assert!(
        (actual_cy - expected_cy).abs() < 0.1,
        "text center y ({}) should match ellipse center ({})",
        actual_cy,
        expected_cy
    );
}

#[test]
fn layout_text_explicit_position_not_expanded() {
    let input = r#"
rect @btn {
  w: 320 h: 44
  text @label "OK" {
font: "Inter" 600 14
x: 10 y: 5
  }
}
"#;
    let graph = parse_document(input).unwrap();
    let viewport = Viewport {
        width: 800.0,
        height: 600.0,
    };
    let bounds = resolve_layout(&graph, viewport);

    let btn = bounds[&graph.index_of(NodeId::intern("btn")).unwrap()];
    let label = bounds[&graph.index_of(NodeId::intern("label")).unwrap()];

    // Text with explicit position should NOT be expanded to parent
    assert!(
        label.width < btn.width,
        "text width ({}) should be < parent ({}) when explicit position is set",
        label.width,
        btn.width
    );
}

#[test]
fn layout_text_multiple_children_not_expanded() {
    let input = r#"
rect @card {
  w: 200 h: 100
  text @title "Title" {
font: "Inter" 600 16
  }
  text @subtitle "Sub" {
font: "Inter" 400 12
  }
}
"#;
    let graph = parse_document(input).unwrap();
    let viewport = Viewport {
        width: 800.0,
        height: 600.0,
    };
    let bounds = resolve_layout(&graph, viewport);

    let card = bounds[&graph.index_of(NodeId::intern("card")).unwrap()];
    let title = bounds[&graph.index_of(NodeId::intern("title")).unwrap()];
    let subtitle = bounds[&graph.index_of(NodeId::intern("subtitle")).unwrap()];

    // Multiple children: text width should remain intrinsic (not expanded)
    assert!(
        title.width < card.width,
        "text width ({}) should be < parent ({}) with multiple children",
        title.width,
        card.width
    );

    // Both text children should be auto-centered (multi-child lift)
    let title_cx = title.x + title.width / 2.0;
    let card_cx = card.x + card.width / 2.0;
    assert!(
        (title_cx - card_cx).abs() < 1.0,
        "title center_x ({title_cx}) should ≈ card center_x ({card_cx})"
    );
    let subtitle_cx = subtitle.x + subtitle.width / 2.0;
    assert!(
        (subtitle_cx - card_cx).abs() < 1.0,
        "subtitle center_x ({subtitle_cx}) should ≈ card center_x ({card_cx})"
    );
}

#[test]
fn layout_place_center() {
    let input = r#"
rect @btn {
  w: 200 h: 60
  text @label "Click" {
    place: center
  }
}
"#;
    let graph = parse_document(input).unwrap();
    let bounds = resolve_layout(
        &graph,
        Viewport {
            width: 800.0,
            height: 600.0,
        },
    );

    let btn = bounds[&graph.index_of(NodeId::intern("btn")).unwrap()];
    let label = bounds[&graph.index_of(NodeId::intern("label")).unwrap()];

    let label_cx = label.x + label.width / 2.0;
    let btn_cx = btn.x + btn.width / 2.0;
    assert!(
        (label_cx - btn_cx).abs() < 1.0,
        "place:center h — label_cx={label_cx}, btn_cx={btn_cx}"
    );
    let label_cy = label.y + label.height / 2.0;
    let btn_cy = btn.y + btn.height / 2.0;
    assert!(
        (label_cy - btn_cy).abs() < 1.0,
        "place:center v — label_cy={label_cy}, btn_cy={btn_cy}"
    );
}

#[test]
fn layout_place_top_left() {
    let input = r#"
rect @box {
  w: 200 h: 100
  text @corner "X" { place: top-left }
}
"#;
    let graph = parse_document(input).unwrap();
    let bounds = resolve_layout(
        &graph,
        Viewport {
            width: 800.0,
            height: 600.0,
        },
    );

    let parent = bounds[&graph.index_of(NodeId::intern("box")).unwrap()];
    let child = bounds[&graph.index_of(NodeId::intern("corner")).unwrap()];

    assert!((child.x - parent.x).abs() < 0.01, "top-left x mismatch");
    assert!((child.y - parent.y).abs() < 0.01, "top-left y mismatch");
}

#[test]
fn layout_place_bottom_right() {
    let input = r#"
rect @box {
  w: 200 h: 100
  text @corner "X" { place: bottom-right }
}
"#;
    let graph = parse_document(input).unwrap();
    let bounds = resolve_layout(
        &graph,
        Viewport {
            width: 800.0,
            height: 600.0,
        },
    );

    let parent = bounds[&graph.index_of(NodeId::intern("box")).unwrap()];
    let child = bounds[&graph.index_of(NodeId::intern("corner")).unwrap()];

    let expected_x = parent.x + parent.width - child.width;
    let expected_y = parent.y + parent.height - child.height;
    assert!(
        (child.x - expected_x).abs() < 0.01,
        "bottom-right x mismatch"
    );
    assert!(
        (child.y - expected_y).abs() < 0.01,
        "bottom-right y mismatch"
    );
}

#[test]
fn layout_auto_center_multiple_text_children() {
    let input = r#"
rect @card {
  w: 300 h: 200
  text @heading "Hello" { font: "Inter" 700 24 }
  text @body "World" { font: "Inter" 400 14 }
}
"#;
    let graph = parse_document(input).unwrap();
    let bounds = resolve_layout(
        &graph,
        Viewport {
            width: 800.0,
            height: 600.0,
        },
    );

    let card = bounds[&graph.index_of(NodeId::intern("card")).unwrap()];
    let heading = bounds[&graph.index_of(NodeId::intern("heading")).unwrap()];
    let body = bounds[&graph.index_of(NodeId::intern("body")).unwrap()];
    let card_cx = card.x + card.width / 2.0;

    let heading_cx = heading.x + heading.width / 2.0;
    assert!(
        (heading_cx - card_cx).abs() < 1.0,
        "heading center ({heading_cx}) ≈ card center ({card_cx})"
    );

    let body_cx = body.x + body.width / 2.0;
    assert!(
        (body_cx - card_cx).abs() < 1.0,
        "body center ({body_cx}) ≈ card center ({card_cx})"
    );
}

#[test]
fn layout_text_centered_in_rect_inside_column() {
    // Reproduces demo.fd: text inside rect inside column group
    let input = r#"
group @form {
  layout: column gap=16 pad=32

  rect @email_field {
w: 280 h: 44
text @email_hint "Email" { }
  }

  rect @login_btn {
w: 280 h: 48
text @btn_label "Sign In" { }
  }
}
"#;
    let graph = parse_document(input).unwrap();
    let viewport = Viewport {
        width: 800.0,
        height: 600.0,
    };
    let bounds = resolve_layout(&graph, viewport);

    let email_field = bounds[&graph.index_of(NodeId::intern("email_field")).unwrap()];
    let email_hint = bounds[&graph.index_of(NodeId::intern("email_hint")).unwrap()];
    let login_btn = bounds[&graph.index_of(NodeId::intern("login_btn")).unwrap()];
    let btn_label = bounds[&graph.index_of(NodeId::intern("btn_label")).unwrap()];

    // Text bounds must match parent rect for centering to work
    eprintln!(
        "email_field: x={:.1} y={:.1} w={:.1} h={:.1}",
        email_field.x, email_field.y, email_field.width, email_field.height
    );
    eprintln!(
        "email_hint:  x={:.1} y={:.1} w={:.1} h={:.1}",
        email_hint.x, email_hint.y, email_hint.width, email_hint.height
    );
    eprintln!(
        "login_btn:   x={:.1} y={:.1} w={:.1} h={:.1}",
        login_btn.x, login_btn.y, login_btn.width, login_btn.height
    );
    eprintln!(
        "btn_label:   x={:.1} y={:.1} w={:.1} h={:.1}",
        btn_label.x, btn_label.y, btn_label.width, btn_label.height
    );

    // Text should be centered within parent (hug-contents mode)
    let email_field_cx = email_field.x + email_field.width / 2.0;
    let email_hint_cx = email_hint.x + email_hint.width / 2.0;
    assert!(
        (email_hint_cx - email_field_cx).abs() < 0.1,
        "email_hint center x ({}) should match email_field center x ({})",
        email_hint_cx,
        email_field_cx
    );
    let email_field_cy = email_field.y + email_field.height / 2.0;
    let email_hint_cy = email_hint.y + email_hint.height / 2.0;
    assert!(
        (email_hint_cy - email_field_cy).abs() < 0.1,
        "email_hint center y ({}) should match email_field center y ({})",
        email_hint_cy,
        email_field_cy
    );
    // Text should NOT fill parent — hug contents instead
    assert!(
        email_hint.width < email_field.width,
        "email_hint width ({}) should be < email_field width ({})",
        email_hint.width,
        email_field.width
    );

    let login_btn_cx = login_btn.x + login_btn.width / 2.0;
    let btn_label_cx = btn_label.x + btn_label.width / 2.0;
    assert!(
        (btn_label_cx - login_btn_cx).abs() < 0.1,
        "btn_label center x ({}) should match login_btn center x ({})",
        btn_label_cx,
        login_btn_cx
    );
    let login_btn_cy = login_btn.y + login_btn.height / 2.0;
    let btn_label_cy = btn_label.y + btn_label.height / 2.0;
    assert!(
        (btn_label_cy - login_btn_cy).abs() < 0.1,
        "btn_label center y ({}) should match login_btn center y ({})",
        btn_label_cy,
        login_btn_cy
    );
    assert!(
        btn_label.width < login_btn.width,
        "btn_label width ({}) should be < login_btn width ({})",
        btn_label.width,
        login_btn.width
    );
}

/// Regression test: resolve_subtree preserves existing cached child bounds
/// (via or_insert in Free layout) while re-centering text within new parent.
/// The combination of or_insert + skip resolve() prevents the resize fight.
#[test]
fn resolve_subtree_preserves_cached_bounds_and_recenters() {
    let input = r#"
rect @parent {
  w: 200 h: 100
  text @child "Hello World" {
    font: "Inter" 400 14
  }
}
"#;
    let graph = parse_document(input).unwrap();
    let viewport = Viewport {
        width: 800.0,
        height: 600.0,
    };
    let mut bounds = resolve_layout(&graph, viewport);

    let parent_idx = graph.index_of(NodeId::intern("parent")).unwrap();
    let child_idx = graph.index_of(NodeId::intern("child")).unwrap();

    // Simulate JS-measured text metrics: override child size with specific values
    let js_width = 85.5;
    let js_height = 20.0;
    if let Some(cb) = bounds.get_mut(&child_idx) {
        cb.width = js_width;
        cb.height = js_height;
    }

    // Resize parent from 200→300 and call resolve_subtree
    if let Some(pb) = bounds.get_mut(&parent_idx) {
        pb.width = 300.0;
    }
    resolve_subtree(&graph, parent_idx, &mut bounds, viewport);

    let child_after = bounds[&child_idx];
    let parent_after = bounds[&parent_idx];

    // or_insert preserves the JS-measured sizes
    assert!(
        (child_after.width - js_width).abs() < 0.01,
        "child width ({}) should be preserved at {js_width}",
        child_after.width
    );
    assert!(
        (child_after.height - js_height).abs() < 0.01,
        "child height ({}) should be preserved at {js_height}",
        child_after.height
    );

    // Auto-centering re-centers child within new parent bounds
    let child_cx = child_after.x + child_after.width / 2.0;
    let parent_cx = parent_after.x + parent_after.width / 2.0;
    assert!(
        (child_cx - parent_cx).abs() < 1.0,
        "child center ({child_cx}) should be ≈ new parent center ({parent_cx})"
    );
}

#[test]
fn layout_text_max_width_wraps_height() {
    // Text with max_width should have width clamped to max_width.
    // Height is a single-line placeholder — JS measureText() is the
    // authoritative source for actual wrapped height (KI Lesson #9).
    let input = r#"
text @long "Hello World this is a long sentence that should wrap" {
  font: "Inter" 400 14
  w: 80
}
"#;
    let graph = parse_document(input).unwrap();
    let viewport = Viewport {
        width: 800.0,
        height: 600.0,
    };
    let bounds = resolve_layout(&graph, viewport);

    let idx = graph.index_of(NodeId::intern("long")).unwrap();
    let b = &bounds[&idx];

    // Width should be clamped to max_width (80)
    assert!(
        (b.width - 80.0).abs() < 0.01,
        "text width ({}) should be 80 (max_width)",
        b.width
    );

    // Height should be single-line placeholder (14 * 1.4 = 19.6)
    let single_line = 14.0 * 1.4;
    assert!(
        (b.height - single_line).abs() < 0.01,
        "text height ({}) should be single-line placeholder ({single_line})",
        b.height
    );
}

#[test]
fn layout_free_frame_pad_insets_children() {
    let input = r#"
frame @card {
  w: 400 h: 300
  pad: 20

  rect @child { w: 100 h: 50 }
}
"#;
    let graph = parse_document(input).unwrap();
    let viewport = Viewport {
        width: 800.0,
        height: 600.0,
    };
    let bounds = resolve_layout(&graph, viewport);

    let card = bounds[&graph.index_of(NodeId::intern("card")).unwrap()];
    let child = bounds[&graph.index_of(NodeId::intern("child")).unwrap()];

    // Child default position should be at parent origin + pad
    assert!(
        (child.x - (card.x + 20.0)).abs() < 0.01,
        "child.x ({}) should be card.x + pad ({})",
        child.x,
        card.x + 20.0
    );
    assert!(
        (child.y - (card.y + 20.0)).abs() < 0.01,
        "child.y ({}) should be card.y + pad ({})",
        child.y,
        card.y + 20.0
    );
}

#[test]
fn layout_free_frame_pad_text_centered_in_padded_area() {
    let input = r#"
frame @card {
  w: 400 h: 300
  pad: 40

  text @label "Hello" {
    font: "Inter" 600 14
    place: center
  }
}
"#;
    let graph = parse_document(input).unwrap();
    let viewport = Viewport {
        width: 800.0,
        height: 600.0,
    };
    let bounds = resolve_layout(&graph, viewport);

    let card = bounds[&graph.index_of(NodeId::intern("card")).unwrap()];
    let label = bounds[&graph.index_of(NodeId::intern("label")).unwrap()];

    // Text should be centered within padded area (400-80=320, 300-80=220)
    let content_cx = card.x + 40.0 + (400.0 - 80.0) / 2.0;
    let content_cy = card.y + 40.0 + (300.0 - 80.0) / 2.0;
    let label_cx = label.x + label.width / 2.0;
    let label_cy = label.y + label.height / 2.0;

    assert!(
        (label_cx - content_cx).abs() < 1.0,
        "label center x ({label_cx}) should match padded content center ({content_cx})"
    );
    assert!(
        (label_cy - content_cy).abs() < 1.0,
        "label center y ({label_cy}) should match padded content center ({content_cy})"
    );
}

#[test]
fn layout_free_frame_pad_zero_matches_no_pad() {
    // pad=0 should behave identically to the old Free without pad
    let input = r#"
frame @card {
  w: 400 h: 300
  rect @child { w: 100 h: 50 }
}
"#;
    let graph = parse_document(input).unwrap();
    let viewport = Viewport {
        width: 800.0,
        height: 600.0,
    };
    let bounds = resolve_layout(&graph, viewport);

    let card = bounds[&graph.index_of(NodeId::intern("card")).unwrap()];
    let child = bounds[&graph.index_of(NodeId::intern("child")).unwrap()];

    // Child should be at parent origin (no padding)
    assert!(
        (child.x - card.x).abs() < 0.01,
        "child.x ({}) should equal card.x ({})",
        child.x,
        card.x
    );
    assert!(
        (child.y - card.y).abs() < 0.01,
        "child.y ({}) should equal card.y ({})",
        child.y,
        card.y
    );
}

#[test]
fn layout_text_stays_centered_after_bounds_shrink() {
    // Regression test for: centered text shifts left on click.
    // Simulates what update_text_metrics does: shrinks text bounds
    // to JS-measured size. After shrinking, text must remain centered
    // within the parent shape.
    let input = r#"
rect @btn {
  w: 320 h: 44
  text @label "Sign In" {
    font: "Inter" 600 14
  }
}
"#;
    let graph = parse_document(input).unwrap();
    let viewport = Viewport {
        width: 800.0,
        height: 600.0,
    };
    let mut bounds = resolve_layout(&graph, viewport);

    let btn_idx = graph.index_of(NodeId::intern("btn")).unwrap();
    let label_idx = graph.index_of(NodeId::intern("label")).unwrap();

    let btn = bounds[&btn_idx];

    // Verify initial centering
    let label_before = bounds[&label_idx];
    let initial_cx = label_before.x + label_before.width / 2.0;
    let btn_cx = btn.x + btn.width / 2.0;
    assert!(
        (initial_cx - btn_cx).abs() < 1.0,
        "initial text center ({initial_cx}) should match btn center ({btn_cx})"
    );

    // Simulate update_text_metrics: shrink to measured size
    // "Sign In" at 14px ≈ 50px wide, 19.6px tall (from JS measureText)
    let measured_w = 50.0_f32;
    let measured_h = 19.6_f32;
    if let Some(b) = bounds.get_mut(&label_idx) {
        b.width = measured_w;
        b.height = measured_h;
        // Re-center within parent (this is what update_text_metrics now does)
        b.x = btn.x + (btn.width - measured_w) / 2.0;
        b.y = btn.y + (btn.height - measured_h) / 2.0;
    }

    // Verify text is still centered after shrink
    let label_after = bounds[&label_idx];
    let after_cx = label_after.x + label_after.width / 2.0;
    let after_cy = label_after.y + label_after.height / 2.0;
    let btn_cy = btn.y + btn.height / 2.0;

    assert!(
        (after_cx - btn_cx).abs() < 0.1,
        "after shrink: text center x ({after_cx}) should match btn center ({btn_cx})"
    );
    assert!(
        (after_cy - btn_cy).abs() < 0.1,
        "after shrink: text center y ({after_cy}) should match btn center ({btn_cy})"
    );

    // Verify text bounds are smaller than parent
    assert!(
        label_after.width < btn.width,
        "text width ({}) should be < parent ({})",
        label_after.width,
        btn.width
    );
}