cvkg-layout 0.2.4

Cyber Viking Kvasir Graph (CVKG) - High-fidelity agentic UI framework
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
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
//! # CVKG Agentic Development Guidelines (v1.2)
//!
//! All AI agents contributing to this crate MUST follow ALL seven rules:
//!
//! ── Karpathy Guidelines (1–4) ────────────────────────────────────────────
//! 1. THINK FIRST     — State assumptions. Surface ambiguity. Push back on complexity.
//! 2. STAY SIMPLE     — Minimum code. No speculative features. No unasked-for abstractions.
//! 3. BE SURGICAL     — Touch only what's required. Own your orphans. Don't improve neighbors.
//! 4. VERIFY GOALS    — Turn tasks into checkable criteria. Loop until they pass. Never commit broken.
//!
//! ── CVKG Extended Protocols (5–7) ────────────────────────────────────────
//! 5. TRIPLE-PASS     — Read the target, its surrounding context, and its full call graph
//                      at least THREE TIMES before making any edit or revision.
//! 6. COMMENT ALL     — Every major pub fn, unsafe block, and non-trivial algorithm in
//                      every .rs/.ts/.h/.wgsl file MUST have a descriptive doc comment.
//                      Comments describe WHY and WHAT CONTRACT, not HOW mechanically.
//! 7. MONITOR LOOPS   — Check every tool call / command for progress every 30 seconds.
//                      After 3 consecutive identical failures, stop, write BLOCKED.md,
//                      and move to unblocked work. Never silently accept a broken state.
//!
//! Sources:
//   Karpathy: https://github.com/multica-ai/andrej-karpathy-skills
//   CVKG Extended: Section 2 of the CVKG Design Specification

use cvkg_core::{Alignment, Distribution, LayoutCache, LayoutView, Rect, Size, SizeProposal};
pub use cvkg_core::layout::EdgeInsets;

/// HStack - lays out children horizontally
pub struct HStack {
    spacing: f32,
    alignment: Alignment,
    distribution: Distribution,
}

impl HStack {
    /// Create a new HStack with the given spacing, alignment, and distribution
    pub fn new(spacing: f32, alignment: Alignment, distribution: Distribution) -> Self {
        Self {
            spacing,
            alignment,
            distribution,
        }
    }

    /// Compute the layout rects for children without placing them.
    pub fn compute_layout(
        spacing: f32,
        alignment: Alignment,
        distribution: Distribution,
        bounds: Rect,
        subviews: &[&dyn LayoutView],
        cache: &mut LayoutCache,
    ) -> Vec<Rect> {
        let n = subviews.len();
        if n == 0 {
            return Vec::new();
        }

        let mut rects = vec![Rect::zero(); n];
        let mut child_sizes = Vec::with_capacity(n);
        let mut total_fixed_width = 0.0;
        let mut total_flex_weight = 0.0;
        let mut flex_indices = Vec::new();

        // Pass 1: Categorize children and measure fixed ones
        for (i, child) in subviews.iter().enumerate() {
            let weight = child.flex_weight();
            if weight > 0.0 {
                total_flex_weight += weight;
                flex_indices.push(i);
                child_sizes.push(Size::ZERO); // Placeholder
            } else {
                let desired = child.size_that_fits(
                    SizeProposal::new(Some(bounds.width), Some(bounds.height)),
                    &[],
                    cache,
                );
                child_sizes.push(desired);
                total_fixed_width += desired.width;
            }
        }

        let total_spacing = spacing * (n - 1) as f32;
        let available_for_flex = (bounds.width - total_fixed_width - total_spacing).max(0.0);

        // Pass 2: Measure and size flexible children
        for &idx in &flex_indices {
            let weight = subviews[idx].flex_weight();
            let flex_width = (weight / total_flex_weight) * available_for_flex;
            let desired = subviews[idx].size_that_fits(
                SizeProposal::new(Some(flex_width), Some(bounds.height)),
                &[],
                cache,
            );
            // Flexible children take the width assigned by flex, but height can still be intrinsic or frame-constrained
            child_sizes[idx] = Size {
                width: flex_width,
                height: desired.height,
            };
        }

        let content_width = if total_flex_weight > 0.0 {
            bounds.width - total_spacing
        } else {
            total_fixed_width
        } + total_spacing;

        let (mut x, actual_spacing) = match distribution {
            Distribution::Leading | Distribution::Fill if total_flex_weight > 0.0 => {
                (bounds.x, spacing)
            }
            Distribution::Leading | Distribution::Fill => (bounds.x, spacing),
            Distribution::Trailing => (bounds.x + bounds.width - content_width, spacing),
            Distribution::Center => (bounds.x + (bounds.width - content_width) / 2.0, spacing),
            Distribution::SpaceBetween => {
                let s = if n > 1 {
                    (bounds.width - (total_fixed_width + available_for_flex)) / (n - 1) as f32
                } else {
                    0.0
                };
                (bounds.x, s)
            }
            _ => (bounds.x, spacing), // Simplification for mixed flex/distribution
        };

        for i in 0..n {
            let size = child_sizes[i];
            let y = match alignment {
                Alignment::Top => bounds.y,
                Alignment::Bottom => bounds.y + bounds.height - size.height,
                _ => bounds.y + (bounds.height - size.height) / 2.0,
            };

            rects[i] = Rect {
                x,
                y,
                width: size.width,
                height: size.height,
            };
            x += size.width + actual_spacing;
        }
        rects
    }
}

impl LayoutView for HStack {
    fn size_that_fits(
        &self,
        proposal: SizeProposal,
        subviews: &[&dyn LayoutView],
        cache: &mut LayoutCache,
    ) -> Size {
        let mut width = 0.0f32;
        let mut height = 0.0f32;

        for (i, child) in subviews.iter().enumerate() {
            let child_size = child.size_that_fits(proposal, &[], cache);
            width += child_size.width;
            height = height.max(child_size.height);

            if i < subviews.len() - 1 {
                width += self.spacing;
            }
        }

        Size {
            width: proposal.width.unwrap_or(width),
            height: proposal.height.unwrap_or(height),
        }
    }

    fn place_subviews(
        &self,
        bounds: Rect,
        subviews: &mut [&mut dyn LayoutView],
        cache: &mut LayoutCache,
    ) {
        let views: Vec<&dyn LayoutView> =
            subviews.iter().map(|v| &**v as &dyn LayoutView).collect();
        let rects = Self::compute_layout(
            self.spacing,
            self.alignment,
            self.distribution,
            bounds,
            &views,
            cache,
        );

        for (child, rect) in subviews.iter_mut().zip(rects) {
            child.place_subviews(rect, &mut [], cache);
        }
    }
}

/// VStack - lays out children vertically
pub struct VStack {
    spacing: f32,
    alignment: Alignment,
    distribution: Distribution,
}

impl VStack {
    /// Create a new VStack with the given spacing, alignment, and distribution
    pub fn new(spacing: f32, alignment: Alignment, distribution: Distribution) -> Self {
        Self {
            spacing,
            alignment,
            distribution,
        }
    }

    /// Compute the layout rects for children without placing them.
    pub fn compute_layout(
        spacing: f32,
        alignment: Alignment,
        distribution: Distribution,
        bounds: Rect,
        subviews: &[&dyn LayoutView],
        cache: &mut LayoutCache,
    ) -> Vec<Rect> {
        let n = subviews.len();
        if n == 0 {
            return Vec::new();
        }

        let mut rects = vec![Rect::zero(); n];
        let mut child_sizes = Vec::with_capacity(n);
        let mut total_fixed_height = 0.0;
        let mut total_flex_weight = 0.0;
        let mut flex_indices = Vec::new();

        // Pass 1: Categorize children and measure fixed ones
        for (i, child) in subviews.iter().enumerate() {
            let weight = child.flex_weight();
            if weight > 0.0 {
                total_flex_weight += weight;
                flex_indices.push(i);
                child_sizes.push(Size::ZERO); // Placeholder
            } else {
                let desired = child.size_that_fits(
                    SizeProposal::new(Some(bounds.width), Some(bounds.height)),
                    &[],
                    cache,
                );
                child_sizes.push(desired);
                total_fixed_height += desired.height;
            }
        }

        let total_spacing = spacing * (n - 1) as f32;
        let available_for_flex = (bounds.height - total_fixed_height - total_spacing).max(0.0);

        // Pass 2: Measure and size flexible children
        for &idx in &flex_indices {
            let weight = subviews[idx].flex_weight();
            let flex_height = (weight / total_flex_weight) * available_for_flex;
            let desired = subviews[idx].size_that_fits(
                SizeProposal::new(Some(bounds.width), Some(flex_height)),
                &[],
                cache,
            );
            child_sizes[idx] = Size {
                width: desired.width,
                height: flex_height,
            };
        }

        let content_height = if total_flex_weight > 0.0 {
            bounds.height - total_spacing
        } else {
            total_fixed_height
        } + total_spacing;

        let (mut y, actual_spacing) = match distribution {
            Distribution::Leading | Distribution::Fill if total_flex_weight > 0.0 => {
                (bounds.y, spacing)
            }
            Distribution::Leading | Distribution::Fill => (bounds.y, spacing),
            Distribution::Trailing => (bounds.y + bounds.height - content_height, spacing),
            Distribution::Center => (bounds.y + (bounds.height - content_height) / 2.0, spacing),
            Distribution::SpaceBetween => {
                let s = if n > 1 {
                    (bounds.height - (total_fixed_height + available_for_flex)) / (n - 1) as f32
                } else {
                    0.0
                };
                (bounds.y, s)
            }
            _ => (bounds.y, spacing),
        };

        for i in 0..n {
            let size = child_sizes[i];
            let x = match alignment {
                Alignment::Leading => bounds.x,
                Alignment::Trailing => bounds.x + bounds.width - size.width,
                _ => bounds.x + (bounds.width - size.width) / 2.0,
            };

            rects[i] = Rect {
                x,
                y,
                width: size.width,
                height: size.height,
            };
            y += size.height + actual_spacing;
        }
        rects
    }
}

impl LayoutView for VStack {
    fn size_that_fits(
        &self,
        proposal: SizeProposal,
        subviews: &[&dyn LayoutView],
        cache: &mut LayoutCache,
    ) -> Size {
        let mut width = 0.0f32;
        let mut height = 0.0f32;

        for (i, child) in subviews.iter().enumerate() {
            let child_size = child.size_that_fits(proposal, &[], cache);
            width = width.max(child_size.width);
            height += child_size.height;

            if i < subviews.len() - 1 {
                height += self.spacing;
            }
        }

        Size {
            width: proposal.width.unwrap_or(width),
            height: proposal.height.unwrap_or(height),
        }
    }

    fn place_subviews(
        &self,
        bounds: Rect,
        subviews: &mut [&mut dyn LayoutView],
        cache: &mut LayoutCache,
    ) {
        let views: Vec<&dyn LayoutView> =
            subviews.iter().map(|v| &**v as &dyn LayoutView).collect();
        let rects = Self::compute_layout(
            self.spacing,
            self.alignment,
            self.distribution,
            bounds,
            &views,
            cache,
        );

        for (child, rect) in subviews.iter_mut().zip(rects) {
            child.place_subviews(rect, &mut [], cache);
        }
    }
}

/// ZStack - lays out children on top of each other
pub struct ZStack {}

impl Default for ZStack {
    fn default() -> Self {
        Self::new()
    }
}

impl ZStack {
    /// Create a new ZStack
    pub fn new() -> Self {
        Self {}
    }
}

impl LayoutView for ZStack {
    fn size_that_fits(
        &self,
        proposal: SizeProposal,
        subviews: &[&dyn LayoutView],
        cache: &mut LayoutCache,
    ) -> Size {
        // For ZStack, we want the maximum width and height of all children
        let mut width = 0.0f32;
        let mut height = 0.0f32;

        for child in subviews.iter() {
            let child_size = child.size_that_fits(proposal, &[], cache);
            width = width.max(child_size.width);
            height = height.max(child_size.height);
        }

        Size { width, height }
    }

    fn place_subviews(
        &self,
        bounds: Rect,
        subviews: &mut [&mut dyn LayoutView],
        cache: &mut LayoutCache,
    ) {
        // In ZStack, all children get the same bounds (they stack on top of each other)
        for child in subviews.iter_mut() {
            child.place_subviews(bounds, &mut [], cache);
        }
    }
}

/// Spacer - a layout view that expands to fill available space
pub struct Spacer;

impl LayoutView for Spacer {
    fn size_that_fits(
        &self,
        proposal: SizeProposal,
        _subviews: &[&dyn LayoutView],
        _cache: &mut LayoutCache,
    ) -> Size {
        Size {
            width: proposal.width.unwrap_or(0.0),
            height: proposal.height.unwrap_or(0.0),
        }
    }

    fn place_subviews(
        &self,
        _bounds: Rect,
        _subviews: &mut [&mut dyn LayoutView],
        _cache: &mut LayoutCache,
    ) {
    }
}

/// Flex - a container that distributes space among its children flexibly
pub struct Flex {
    pub orientation: cvkg_core::Orientation,
    pub spacing: f32,
}

impl Flex {
    pub fn new(orientation: cvkg_core::Orientation, spacing: f32) -> Self {
        Self {
            orientation,
            spacing,
        }
    }
}

impl LayoutView for Flex {
    fn size_that_fits(
        &self,
        proposal: SizeProposal,
        _subviews: &[&dyn LayoutView],
        _cache: &mut LayoutCache,
    ) -> Size {
        Size {
            width: proposal.width.unwrap_or(100.0),
            height: proposal.height.unwrap_or(100.0),
        }
    }

    fn place_subviews(
        &self,
        bounds: Rect,
        subviews: &mut [&mut dyn LayoutView],
        cache: &mut LayoutCache,
    ) {
        if subviews.is_empty() {
            return;
        }

        let n = subviews.len() as f32;
        match self.orientation {
            cvkg_core::Orientation::Horizontal => {
                let total_spacing = self.spacing * (n - 1.0);
                let item_width = (bounds.width - total_spacing) / n;
                for (i, child) in subviews.iter_mut().enumerate() {
                    let child_rect = Rect {
                        x: bounds.x + i as f32 * (item_width + self.spacing),
                        y: bounds.y,
                        width: item_width,
                        height: bounds.height,
                    };
                    child.place_subviews(child_rect, &mut [], cache);
                }
            }
            cvkg_core::Orientation::Vertical => {
                let total_spacing = self.spacing * (n - 1.0);
                let item_height = (bounds.height - total_spacing) / n;
                for (i, child) in subviews.iter_mut().enumerate() {
                    let child_rect = Rect {
                        x: bounds.x,
                        y: bounds.y + i as f32 * (item_height + self.spacing),
                        width: bounds.width,
                        height: item_height,
                    };
                    child.place_subviews(child_rect, &mut [], cache);
                }
            }
        }
    }
}

/// Track sizing strategy for a single grid track (row or column).
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum GridTrack {
    /// Exact pixel size.
    Fixed(f32),
    /// Proportional weight compared to other flex tracks.
    Flex(f32),
    /// Size based on the intrinsic size of the grid item.
    Auto,
    /// Size clamped between minimum and maximum bounds.
    MinMax(f32, f32),
}

/// A layout engine that computes coordinates for children positioned in a 2D grid.
pub struct Grid {
    /// Column track sizing rules.
    pub columns: Vec<GridTrack>,
    /// Row track sizing rules.
    pub rows: Vec<GridTrack>,
    /// Empty space between columns.
    pub column_gap: f32,
    /// Empty space between rows.
    pub row_gap: f32,
}

impl Grid {
    /// Creates a new Grid layout engine.
    pub fn new(
        columns: Vec<GridTrack>,
        rows: Vec<GridTrack>,
        column_gap: f32,
        row_gap: f32,
    ) -> Self {
        Self {
            columns,
            rows,
            column_gap,
            row_gap,
        }
    }

    /// Computes the rects for children based on track sizing and grid placements.
    pub fn compute_layout_rects(
        &self,
        bounds: Rect,
        subviews: &[&dyn LayoutView],
        placements: &[Option<cvkg_core::GridPlacement>],
        cache: &mut LayoutCache,
    ) -> Vec<Rect> {
        let col_count = self.columns.len();
        let row_count = self.rows.len();
        if col_count == 0 || row_count == 0 || subviews.is_empty() {
            return vec![Rect::zero(); subviews.len()];
        }

        let mut rects = vec![Rect::zero(); subviews.len()];

        // 1. Resolve placements for all children.
        // If a child has no placement, auto-position it in the next available cell in row-major order.
        let mut resolved_placements = Vec::with_capacity(subviews.len());
        let mut occupied = vec![vec![false; col_count]; row_count];

        for &opt_placement in placements.iter() {
            let placement = if let Some(p) = opt_placement {
                let resolved_col = if p.column < 0 {
                    (col_count as i32 + p.column).max(0) as usize
                } else {
                    p.column as usize
                };
                let resolved_row = if p.row < 0 {
                    (row_count as i32 + p.row).max(0) as usize
                } else {
                    p.row as usize
                };
                cvkg_core::GridPlacement {
                    column: resolved_col as i32,
                    column_span: p.column_span.max(1),
                    row: resolved_row as i32,
                    row_span: p.row_span.max(1),
                }
            } else {
                // Find next unoccupied cell
                let mut found_col = 0;
                let mut found_row = 0;
                let mut found = false;
                for (r, row) in occupied.iter().enumerate() {
                    for (c, cell) in row.iter().enumerate() {
                        if !*cell {
                            found_col = c;
                            found_row = r;
                            found = true;
                            break;
                        }
                    }
                    if found {
                        break;
                    }
                }
                cvkg_core::GridPlacement {
                    column: found_col as i32,
                    column_span: 1,
                    row: found_row as i32,
                    row_span: 1,
                }
            };

            // Mark occupied cells
            let start_r = (placement.row as usize).min(row_count - 1);
            let end_r = (start_r + placement.row_span as usize).min(row_count);
            let start_c = (placement.column as usize).min(col_count - 1);
            let end_c = (start_c + placement.column_span as usize).min(col_count);
            for row in occupied.iter_mut().take(end_r).skip(start_r) {
                for cell in row.iter_mut().take(end_c).skip(start_c) {
                    *cell = true;
                }
            }

            resolved_placements.push(placement);
        }

        // 2. Measure content sizes of children (for Auto and MinMax sizing).
        // For simplicity, we calculate the sizes of Auto and MinMax tracks based on children that span a single track.
        let mut col_content_widths = vec![0.0f32; col_count];
        let mut row_content_heights = vec![0.0f32; row_count];

        for (i, &placement) in resolved_placements.iter().enumerate() {
            let child = subviews[i];
            let size = child.size_that_fits(
                SizeProposal::new(Some(bounds.width), Some(bounds.height)),
                &[],
                cache,
            );

            if placement.column_span == 1 {
                let c = placement.column as usize;
                if c < col_count {
                    col_content_widths[c] = col_content_widths[c].max(size.width);
                }
            }
            if placement.row_span == 1 {
                let r = placement.row as usize;
                if r < row_count {
                    row_content_heights[r] = row_content_heights[r].max(size.height);
                }
            }
        }

        // 3. Resolve Column widths
        let total_col_gaps = self.column_gap * (col_count - 1) as f32;
        let mut remaining_width = (bounds.width - total_col_gaps).max(0.0);
        let mut total_flex_weight_col = 0.0f32;
        let mut col_widths = vec![0.0f32; col_count];

        for (c, track) in self.columns.iter().enumerate() {
            match track {
                GridTrack::Fixed(w) => {
                    col_widths[c] = *w;
                    remaining_width = (remaining_width - *w).max(0.0);
                }
                GridTrack::Auto => {
                    let w = col_content_widths[c];
                    col_widths[c] = w;
                    remaining_width = (remaining_width - w).max(0.0);
                }
                GridTrack::MinMax(min, max) => {
                    let w = col_content_widths[c].clamp(*min, *max);
                    col_widths[c] = w;
                    remaining_width = (remaining_width - w).max(0.0);
                }
                GridTrack::Flex(weight) => {
                    total_flex_weight_col += *weight;
                }
            }
        }

        if total_flex_weight_col > 0.0 {
            for (c, track) in self.columns.iter().enumerate() {
                if let GridTrack::Flex(weight) = track {
                    col_widths[c] = (*weight / total_flex_weight_col) * remaining_width;
                }
            }
        }

        // 4. Resolve Row heights
        let total_row_gaps = self.row_gap * (row_count - 1) as f32;
        let mut remaining_height = (bounds.height - total_row_gaps).max(0.0);
        let mut total_flex_weight_row = 0.0f32;
        let mut row_heights = vec![0.0f32; row_count];

        for (r, track) in self.rows.iter().enumerate() {
            match track {
                GridTrack::Fixed(h) => {
                    row_heights[r] = *h;
                    remaining_height = (remaining_height - *h).max(0.0);
                }
                GridTrack::Auto => {
                    let h = row_content_heights[r];
                    row_heights[r] = h;
                    remaining_height = (remaining_height - h).max(0.0);
                }
                GridTrack::MinMax(min, max) => {
                    let h = row_content_heights[r].clamp(*min, *max);
                    row_heights[r] = h;
                    remaining_height = (remaining_height - h).max(0.0);
                }
                GridTrack::Flex(weight) => {
                    total_flex_weight_row += *weight;
                }
            }
        }

        if total_flex_weight_row > 0.0 {
            for (r, track) in self.rows.iter().enumerate() {
                if let GridTrack::Flex(weight) = track {
                    row_heights[r] = (*weight / total_flex_weight_row) * remaining_height;
                }
            }
        }

        // 5. Compute grid line coordinates
        let mut col_positions = vec![0.0f32; col_count + 1];
        let mut x_acc = bounds.x;
        for c in 0..col_count {
            col_positions[c] = x_acc;
            x_acc += col_widths[c] + self.column_gap;
        }
        col_positions[col_count] = x_acc - self.column_gap;

        let mut row_positions = vec![0.0f32; row_count + 1];
        let mut y_acc = bounds.y;
        for r in 0..row_count {
            row_positions[r] = y_acc;
            y_acc += row_heights[r] + self.row_gap;
        }
        row_positions[row_count] = y_acc - self.row_gap;

        // 6. Compute child rects based on placement and spans
        for i in 0..subviews.len() {
            let placement = resolved_placements[i];
            let c_start = (placement.column as usize).min(col_count - 1);
            let c_end = (c_start + placement.column_span as usize).min(col_count);
            let r_start = (placement.row as usize).min(row_count - 1);
            let r_end = (r_start + placement.row_span as usize).min(row_count);

            let child_x = col_positions[c_start];
            let child_y = row_positions[r_start];

            // Width spans tracks and gaps:
            let child_w = if c_end > c_start {
                col_widths[c_start..c_end].iter().sum::<f32>()
                    + self.column_gap * (c_end - c_start - 1) as f32
            } else {
                0.0
            };

            let child_h = if r_end > r_start {
                row_heights[r_start..r_end].iter().sum::<f32>()
                    + self.row_gap * (r_end - r_start - 1) as f32
            } else {
                0.0
            };

            rects[i] = Rect {
                x: child_x,
                y: child_y,
                width: child_w,
                height: child_h,
            };
        }

        rects
    }
}

impl LayoutView for Grid {
    fn size_that_fits(
        &self,
        proposal: SizeProposal,
        _subviews: &[&dyn LayoutView],
        _cache: &mut LayoutCache,
    ) -> Size {
        Size {
            width: proposal.width.unwrap_or(200.0),
            height: proposal.height.unwrap_or(200.0),
        }
    }

    fn place_subviews(
        &self,
        bounds: Rect,
        subviews: &mut [&mut dyn LayoutView],
        cache: &mut LayoutCache,
    ) {
        let views: Vec<&dyn LayoutView> =
            subviews.iter().map(|v| &**v as &dyn LayoutView).collect();
        let placements = vec![None; subviews.len()];
        let rects = self.compute_layout_rects(bounds, &views, &placements, cache);

        for (child, rect) in subviews.iter_mut().zip(rects) {
            child.place_subviews(rect, &mut [], cache);
        }
    }
}

// =============================================================================
// PADDING
// =============================================================================

/// A layout view that adds padding around its child.
pub struct Padding {
    pub insets: EdgeInsets,
}

impl Padding {
    pub fn new(insets: EdgeInsets) -> Self {
        Self { insets }
    }

    pub fn uniform(value: f32) -> Self {
        Self {
            insets: EdgeInsets::all(value),
        }
    }

    pub fn symmetric(horizontal: f32, vertical: f32) -> Self {
        Self {
            insets: EdgeInsets {
                top: vertical,
                bottom: vertical,
                leading: horizontal,
                trailing: horizontal,
            },
        }
    }
}

impl LayoutView for Padding {
    fn size_that_fits(
        &self,
        proposal: SizeProposal,
        subviews: &[&dyn LayoutView],
        cache: &mut LayoutCache,
    ) -> Size {
        let inner_proposal = SizeProposal::new(
            proposal
                .width
                .map(|w| (w - self.insets.leading - self.insets.trailing).max(0.0)),
            proposal
                .height
                .map(|h| (h - self.insets.top - self.insets.bottom).max(0.0)),
        );
        let child_size = if subviews.is_empty() {
            Size::ZERO
        } else {
            subviews[0].size_that_fits(inner_proposal, &[], cache)
        };
        Size {
            width: child_size.width + self.insets.leading + self.insets.trailing,
            height: child_size.height + self.insets.top + self.insets.bottom,
        }
    }

    fn place_subviews(
        &self,
        bounds: Rect,
        subviews: &mut [&mut dyn LayoutView],
        cache: &mut LayoutCache,
    ) {
        let inner = Rect {
            x: bounds.x + self.insets.leading,
            y: bounds.y + self.insets.top,
            width: (bounds.width - self.insets.leading - self.insets.trailing).max(0.0),
            height: (bounds.height - self.insets.top - self.insets.bottom).max(0.0),
        };
        for child in subviews.iter_mut() {
            child.place_subviews(inner, &mut [], cache);
        }
    }
}

// =============================================================================
// SAFE AREA
// =============================================================================

/// A layout view that respects safe area insets (notches, status bars).
pub struct SafeArea {
    pub edges: SafeAreaEdges,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SafeAreaEdges {
    pub top: bool,
    pub bottom: bool,
    pub leading: bool,
    pub trailing: bool,
}

impl Default for SafeAreaEdges {
    fn default() -> Self {
        Self {
            top: true,
            bottom: true,
            leading: false,
            trailing: false,
        }
    }
}

impl SafeArea {
    pub fn all() -> Self {
        Self {
            edges: SafeAreaEdges {
                top: true,
                bottom: true,
                leading: true,
                trailing: true,
            },
        }
    }

    pub fn vertical() -> Self {
        Self {
            edges: SafeAreaEdges::default(),
        }
    }

    fn insets(&self) -> EdgeInsets {
        EdgeInsets {
            top: if self.edges.top { 44.0 } else { 0.0 },
            bottom: if self.edges.bottom { 34.0 } else { 0.0 },
            leading: if self.edges.leading { 0.0 } else { 0.0 },
            trailing: if self.edges.trailing { 0.0 } else { 0.0 },
        }
    }
}

impl LayoutView for SafeArea {
    fn size_that_fits(
        &self,
        proposal: SizeProposal,
        subviews: &[&dyn LayoutView],
        cache: &mut LayoutCache,
    ) -> Size {
        Padding::new(self.insets()).size_that_fits(proposal, subviews, cache)
    }

    fn place_subviews(
        &self,
        bounds: Rect,
        subviews: &mut [&mut dyn LayoutView],
        cache: &mut LayoutCache,
    ) {
        Padding::new(self.insets()).place_subviews(bounds, subviews, cache);
    }
}

// =============================================================================
// ASPECT RATIO
// =============================================================================

/// Constrains a child to a specific aspect ratio.
pub struct AspectRatio {
    pub ratio: f32,
}

impl AspectRatio {
    pub fn new(ratio: f32) -> Self {
        Self {
            ratio: ratio.max(0.01),
        }
    }

    pub fn square() -> Self {
        Self::new(1.0)
    }

    pub fn widescreen() -> Self {
        Self::new(16.0 / 9.0)
    }

    pub fn portrait() -> Self {
        Self::new(9.0 / 16.0)
    }

    fn fitted_size(&self, proposal: SizeProposal) -> Size {
        let max_w = proposal.width.unwrap_or(f32::MAX);
        let max_h = proposal.height.unwrap_or(f32::MAX);
        let w = max_w;
        let h = w / self.ratio;
        if h <= max_h {
            return Size { width: w, height: h };
        }
        Size {
            width: max_h * self.ratio,
            height: max_h,
        }
    }
}

impl LayoutView for AspectRatio {
    fn size_that_fits(
        &self,
        proposal: SizeProposal,
        subviews: &[&dyn LayoutView],
        cache: &mut LayoutCache,
    ) -> Size {
        if subviews.is_empty() {
            return self.fitted_size(proposal);
        }
        let child = subviews[0];
        let child_size = child.size_that_fits(
            SizeProposal::new(Some(f32::MAX), Some(f32::MAX)),
            &[],
            cache,
        );
        let intrinsic_ratio = child_size.width / child_size.height.max(0.01);
        if (intrinsic_ratio - self.ratio).abs() < 0.01 {
            return self.fitted_size(proposal);
        }
        let fit = self.fitted_size(proposal);
        let child_w = fit.width.min(child_size.width);
        let child_h = child_w / intrinsic_ratio;
        let final_h = child_h.min(fit.height);
        let final_w = final_h * intrinsic_ratio;
        Size { width: final_w, height: final_h }
    }

    fn place_subviews(
        &self,
        bounds: Rect,
        subviews: &mut [&mut dyn LayoutView],
        cache: &mut LayoutCache,
    ) {
        let fit = self.fitted_size(SizeProposal::new(Some(bounds.width), Some(bounds.height)));
        let x = bounds.x + (bounds.width - fit.width) * 0.5;
        let y = bounds.y + (bounds.height - fit.height) * 0.0;
        let inner = Rect {
            x,
            y,
            width: fit.width,
            height: fit.height,
        };
        for child in subviews.iter_mut() {
            child.place_subviews(inner, &mut [], cache);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    struct MockView {
        size: Size,
        flex: f32,
    }

    impl LayoutView for MockView {
        fn size_that_fits(
            &self,
            _p: SizeProposal,
            _s: &[&dyn LayoutView],
            _c: &mut LayoutCache,
        ) -> Size {
            self.size
        }
        fn place_subviews(&self, _b: Rect, _s: &mut [&mut dyn LayoutView], _c: &mut LayoutCache) {}
        fn flex_weight(&self) -> f32 {
            self.flex
        }
    }

    #[test]
    fn test_hstack_basic() {
        let v1 = MockView {
            size: Size {
                width: 50.0,
                height: 50.0,
            },
            flex: 0.0,
        };
        let v2 = MockView {
            size: Size {
                width: 100.0,
                height: 100.0,
            },
            flex: 0.0,
        };
        let views: Vec<&dyn LayoutView> = vec![&v1, &v2];
        let mut cache = LayoutCache::new();
        let bounds = Rect {
            x: 0.0,
            y: 0.0,
            width: 300.0,
            height: 200.0,
        };

        let rects = HStack::compute_layout(
            10.0,
            Alignment::Center,
            Distribution::Leading,
            bounds,
            &views,
            &mut cache,
        );

        assert_eq!(rects.len(), 2);
        assert_eq!(
            rects[0],
            Rect {
                x: 0.0,
                y: 75.0,
                width: 50.0,
                height: 50.0
            }
        );
        assert_eq!(
            rects[1],
            Rect {
                x: 60.0,
                y: 50.0,
                width: 100.0,
                height: 100.0
            }
        );
    }

    #[test]
    fn test_vstack_flex() {
        let v1 = MockView {
            size: Size {
                width: 100.0,
                height: 50.0,
            },
            flex: 0.0,
        };
        let v2 = MockView {
            size: Size {
                width: 100.0,
                height: 0.0,
            },
            flex: 1.0,
        }; // Flex
        let views: Vec<&dyn LayoutView> = vec![&v1, &v2];
        let mut cache = LayoutCache::new();
        let bounds = Rect {
            x: 0.0,
            y: 0.0,
            width: 200.0,
            height: 160.0,
        };

        let rects = VStack::compute_layout(
            10.0,
            Alignment::Leading,
            Distribution::Fill,
            bounds,
            &views,
            &mut cache,
        );

        assert_eq!(rects.len(), 2);
        assert_eq!(
            rects[0],
            Rect {
                x: 0.0,
                y: 0.0,
                width: 100.0,
                height: 50.0
            }
        );
        assert_eq!(
            rects[1],
            Rect {
                x: 0.0,
                y: 60.0,
                width: 100.0,
                height: 100.0
            }
        ); // 160 - 50 - 10 = 100
    }

    #[test]
    fn test_grid_layout() {
        let v1 = MockView {
            size: Size::ZERO,
            flex: 0.0,
        };
        let v2 = MockView {
            size: Size::ZERO,
            flex: 0.0,
        };
        let v3 = MockView {
            size: Size::ZERO,
            flex: 0.0,
        };
        let views: Vec<&dyn LayoutView> = vec![&v1, &v2, &v3];
        let mut cache = LayoutCache::new();
        let bounds = Rect {
            x: 0.0,
            y: 0.0,
            width: 210.0,
            height: 210.0,
        };

        let grid = Grid::new(
            vec![GridTrack::Fixed(100.0), GridTrack::Fixed(100.0)],
            vec![GridTrack::Fixed(100.0), GridTrack::Fixed(100.0)],
            10.0,
            10.0,
        );
        let placements = vec![
            Some(cvkg_core::GridPlacement {
                column: 0,
                column_span: 1,
                row: 0,
                row_span: 1,
            }),
            Some(cvkg_core::GridPlacement {
                column: 1,
                column_span: 1,
                row: 0,
                row_span: 1,
            }),
            Some(cvkg_core::GridPlacement {
                column: 0,
                column_span: 1,
                row: 1,
                row_span: 1,
            }),
        ];

        let rects = grid.compute_layout_rects(bounds, &views, &placements, &mut cache);

        assert_eq!(rects.len(), 3);
        assert_eq!(
            rects[0],
            Rect {
                x: 0.0,
                y: 0.0,
                width: 100.0,
                height: 100.0
            }
        );
        assert_eq!(
            rects[1],
            Rect {
                x: 110.0,
                y: 0.0,
                width: 100.0,
                height: 100.0
            }
        );
        assert_eq!(
            rects[2],
            Rect {
                x: 0.0,
                y: 110.0,
                width: 100.0,
                height: 100.0
            }
        );
    }
}