masonry 0.5.0

Traits and types of the Masonry toolkit.
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
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
// Copyright 2024 the Xilem Authors
// SPDX-License-Identifier: Apache-2.0

use std::{any::TypeId, collections::BTreeMap, mem};

use accesskit::{Node, Role};
use include_doc_path::include_doc_path;
use tracing::{Span, trace_span};

use crate::core::{
    AccessCtx, ChildrenIds, CollectionWidget, LayoutCtx, MeasureCtx, NewWidget, NoAction, PaintCtx,
    PropertiesRef, RegisterCtx, UpdateCtx, UsesProperty, Widget, WidgetId, WidgetMut, WidgetPod,
};
use crate::imaging::Painter;
use crate::kurbo::{Axis, Point, Size};
use crate::layout::{AsUnit, LayoutSize, LenDef, LenReq, Length};
use crate::properties::Gap;
use crate::util::debug_panic;

/// A widget that arranges its children in a grid.
///
/// Children are drawn in index order,
/// i.e. each child is drawn on top of the other children with lower indices.
///
#[doc = concat!(
    "![Grid with buttons of various sizes](",
    include_doc_path!("screenshots/grid_with_changed_spacing.png"),
    ")",
)]
#[derive(Default)]
pub struct Grid {
    children: Vec<Child>,
    columns: Vec<GridTrackSize>,
    rows: Vec<GridTrackSize>,
    needs_placing: bool,
}

#[derive(Debug)]
struct Child {
    widget: WidgetPod<dyn Widget>,
    params: GridParams,

    // these are transient values
    // these do not mean anything if not already initialized within the function
    x: u16,
    y: u16,
}

/// Describes how a grid track (row/column) should be sized.
#[derive(Clone, Copy, PartialEq)]
pub enum GridTrackSize {
    /// At least the minimum intrinsic size of the content and
    /// at most the maximum intrinsic size of the content.
    Auto,

    /// Minimum intrinsic size of the content.
    MinContent,

    /// Maximum intrinsic size of the content
    MaxContent,

    /// Fit content within the given size.
    FitContent(Length),

    /// Fixed at the given size.
    Fixed(Length),

    /// Fixed at the size that is equal to the size of the grid container
    /// times the given parameter.
    ///
    /// The parameter is in normalized percentage, e.g. 0.3, not 30%.
    Percentage(f64),

    /// Fraction of remaining space.
    Fraction(f64),
}

/// Parameters required when adding an item to a [`Grid`] container.
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct GridParams {
    /// Defines which column in the grid the item should start.
    pub col: Option<u16>,

    /// Defines which row in the grid the item should start.
    pub row: Option<u16>,

    /// Defines how many column in the grid the item should occupy.
    pub width: u16,

    /// Defines how many row in the grid the item should occupy.
    pub height: u16,
}

// --- MARK: BUILDERS
impl Grid {
    /// Creates a new grid with no columns or rows.
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a new grid with the given number of columns and rows,
    /// with each row and column sized with [`GridTrackSize::FRACTION`].
    pub fn with_dimensions(columns: usize, rows: usize) -> Self {
        Self {
            columns: vec![GridTrackSize::FRACTION; columns],
            rows: vec![GridTrackSize::FRACTION; rows],
            ..Self::default()
        }
    }

    /// Builder-style method to add a row to the grid.
    pub fn with_row(mut self, row: GridTrackSize) -> Self {
        self.rows.push(row);
        self
    }

    /// Builder-style method to add a column to the grid.
    pub fn with_column(mut self, column: GridTrackSize) -> Self {
        self.columns.push(column);
        self
    }

    /// Builder-style method to add multiple rows to the grid.
    pub fn with_rows(mut self, rows: impl IntoIterator<Item = GridTrackSize>) -> Self {
        self.rows.extend(rows);
        self
    }

    /// Builder-style method to add multiple columns to the grid.
    pub fn with_columns(mut self, columns: impl IntoIterator<Item = GridTrackSize>) -> Self {
        self.columns.extend(columns);
        self
    }

    /// Builder-style method to add a child widget.
    ///
    /// # Panics
    ///
    /// If the `params` refer to a row/column that does not exist, an algorithm similar
    /// to CSS grid's would try to assign an appropriate position to it.
    /// If the algorithm fails, `measure`/`layout` pass would panic in debug mode
    /// and silently ignore this child in release mode.
    pub fn with(mut self, child: NewWidget<impl Widget + ?Sized>, params: GridParams) -> Self {
        let child = Child::new(child, params);
        self.children.push(child);
        self.needs_placing = true;
        self
    }
}

// --- MARK: METHODS
impl Grid {
    fn assign_cell_to_auto_placed_children(&mut self) {
        if !mem::take(&mut self.needs_placing) || self.columns.is_empty() || self.rows.is_empty() {
            return;
        }

        let n_col = self.columns.len();
        let n_row = self.rows.len();
        let mut occupied = vec![false; n_col * n_row];
        let idx = |col: usize, row: usize| row * n_col + col;

        let place = |occupied: &mut [bool], child: &mut Child, col: u16, row: u16| {
            if col + child.params.width > n_col as u16 || row + child.params.height > n_row as u16 {
                debug_panic!("Child {child:?} with position ({col}, {row}) is out of grid bounds");
                return;
            }

            child.x = col;
            child.y = row;

            for row in row..row + child.params.height {
                let start = idx(col as _, row as _);
                occupied[start..start + child.params.width as usize].fill(true);
            }
        };

        // Pass 1: place children with fully explicit position
        for child in &mut self.children {
            if let (Some(col), Some(row)) = (child.params.col, child.params.row) {
                place(&mut occupied, child, col, row);
            }
        }

        // Pass 2: auto-placement
        let mut cursor = (0_usize, 0_usize);

        let place_and_advance =
            |occupied: &mut [bool],
             child: &mut Child,
             col: u16,
             row: u16,
             (cursor_col, cursor_row): &mut (usize, usize)| {
                place(occupied, child, col, row);

                *cursor_col = (col + child.params.width) as usize % n_col;
                *cursor_row = row as usize + (*cursor_col == 0) as usize;
            };

        let mut prefix = Vec::new();
        'child: for child in &mut self.children {
            let width = child.params.width as usize;
            let height = child.params.height as usize;

            match (child.params.col, child.params.row) {
                (Some(_), Some(_)) => continue, // already placed in pass 1
                (Some(col), None) => {
                    let mut consecutive = 0;
                    for row in 0..n_row {
                        let blocked =
                            (col..col + child.params.width).any(|c| occupied[idx(c as _, row)]);
                        if blocked {
                            consecutive = 0;
                            continue;
                        }
                        consecutive += 1;
                        if consecutive == child.params.height {
                            let start_row = row as u16 + 1 - child.params.height;
                            place_and_advance(&mut occupied, child, col, start_row, &mut cursor);
                            continue 'child;
                        }
                    }
                    debug_panic!(
                        "Child {child:?} could not be placed in the grid, no row has enough space",
                    );
                }
                (None, Some(row)) => {
                    let mut consecutive = 0;
                    for col in 0..n_col {
                        let blocked =
                            (row..row + child.params.height).any(|r| occupied[idx(col, r as _)]);
                        if blocked {
                            consecutive = 0;
                            continue;
                        }
                        consecutive += 1;
                        if consecutive == child.params.width {
                            let start_col = col as u16 + 1 - child.params.width;
                            place_and_advance(&mut occupied, child, start_col, row, &mut cursor);
                            continue 'child;
                        }
                    }
                    debug_panic!(
                        "Child {child:?} could not be placed in the grid, no column has enough space",
                    );
                }
                (None, None) => {
                    // build a 2D prefix sum that encodes how many cells above and left of it
                    // (including itself) are occupied
                    //
                    // For example, consider a 4x4 grid:
                    // x | x | x | x
                    // x | _ | _ | x
                    // x | _ | _ | x
                    // x | x | x | x
                    //
                    // It generates the following prefix:
                    // 1 | 2 | 3 | 4
                    // 2 | 3 | 4 | 6
                    // 3 | 4 | 5 | 8
                    // 4 | 6 | 8 | 12

                    prefix.clear();
                    prefix.resize(occupied.len(), 0);
                    for col in 0..self.columns.len() {
                        for row in 0..self.rows.len() {
                            let cell = occupied[idx(col, row)] as u32;
                            let top = (row.checked_sub(1)).map_or(0, |r| prefix[idx(col, r)]);
                            let left = (col.checked_sub(1)).map_or(0, |c| prefix[idx(c, row)]);
                            let diag = (col.checked_sub(1))
                                .zip(row.checked_sub(1))
                                .map_or(0, |(c, r)| prefix[idx(c, r)]);

                            prefix[idx(col, row)] = cell + top + left - diag;
                        }
                    }

                    // query for empty rect
                    //
                    // Now, if a 2x2 child is to be viable at (1, 1) location,
                    // prefix[2, 2] + prefix[0, 0] - prefix[0, 2] - prefix[2, 0]
                    // = 5 + 1 - 3 - 3, must be 0, which it is.
                    //
                    // prefix[2, 2] is the last cell for the child,
                    // prefix[0, 0] is the cell just above and left to the child,
                    // prefix[0, 2] is the cell just above to the child on its last column,
                    // prefix[2, 0] is the cell just left to the child on its last row,
                    for row0 in cursor.1..=(n_row - height) {
                        let start_col = if row0 == cursor.1 { cursor.0 } else { 0 };
                        for col0 in start_col..=(n_col - width) {
                            let col1 = col0 + width - 1;
                            let row1 = row0 + height - 1;

                            let cell = prefix[idx(col1, row1)];
                            let top = (row0.checked_sub(1)).map_or(0, |r| prefix[idx(col1, r)]);
                            let left = (col0.checked_sub(1)).map_or(0, |c| prefix[idx(c, row1)]);
                            let diag = (col0.checked_sub(1))
                                .zip(row0.checked_sub(1))
                                .map_or(0, |(c, r)| prefix[idx(c, r)]);

                            if cell + diag - top - left == 0 {
                                place_and_advance(
                                    &mut occupied,
                                    child,
                                    col0 as _,
                                    row0 as _,
                                    &mut cursor,
                                );
                                continue 'child;
                            }
                        }
                    }

                    debug_panic!("Child {child:?} could not be placed in the grid");
                }
            }
        }
    }

    fn resolve_track_lengths(
        &mut self,
        axis: Axis,
        len_req: LenReq,
        cross_length: Option<Length>,
        gap: Length,
        context_length: Option<Length>,
        is_measuring_only: bool,
        mut compute_length: impl FnMut(
            &mut WidgetPod<dyn Widget + 'static>,
            LenDef,
            LayoutSize,
            Axis,
            Option<Length>,
        ) -> Length,
    ) -> Vec<f64> {
        // This function is a somewhat simplified implementation of track sizing algorithm from
        // the CSS grid spec (https://drafts.csswg.org/css-grid-1/#algo-track-sizing).

        let tracks = match axis {
            Axis::Horizontal => &self.columns,
            Axis::Vertical => &self.rows,
        };

        if tracks.is_empty() {
            return Vec::new();
        }

        // available length for distribution
        // = total_length - gap * (#tracks - 1)
        let context_length = context_length
            .and_then(|l| Length::try_px(l.get() - gap.get() * (tracks.len() - 1) as f64));

        // step 1: auto lengths and initial lengths of tracks
        let (track_auto_lengths, mut track_lengths): (Vec<_>, Vec<_>) = tracks
            .iter()
            .map(|t| match *t {
                // conforms to min-content measure of self
                GridTrackSize::Auto | GridTrackSize::MinContent => (LenDef::MinContent, 0.),
                GridTrackSize::MaxContent | GridTrackSize::Fraction(_) => (LenDef::MaxContent, 0.),
                GridTrackSize::FitContent(limit) => (LenDef::FitContent(limit), 0.),
                GridTrackSize::Fixed(length) => (LenDef::Fixed(length), length.get()),
                GridTrackSize::Percentage(percent) => match len_req {
                    LenReq::FitContent(space) => {
                        let fixed = space.get() * percent;
                        (LenDef::FitContent(fixed.px()), fixed)
                    }
                    _ => match context_length {
                        Some(length) => {
                            let fixed = length.get() * percent;
                            (LenDef::Fixed(fixed.px()), fixed)
                        }
                        _ => (LenDef::MinContent, 0.),
                    },
                },
            })
            .unzip();

        let mut multitrack_lengths = BTreeMap::new();

        // step 2: initialize track lengths
        for child in &mut self.children {
            if child.span(axis) == 1 {
                // if a child spans only a single track, the tracks size accommodates
                // the child if the track size s not fixed.
                let track = child.pos(axis) as usize;
                let auto_length = track_auto_lengths[track];
                if !matches!(auto_length, LenDef::Fixed(_)) {
                    let computed = compute_length(
                        &mut child.widget,
                        auto_length,
                        LayoutSize::NONE,
                        axis,
                        cross_length,
                    );
                    track_lengths[track] = computed.get().max(track_lengths[track]);
                };
            } else {
                let pos = child.pos(axis);
                let span = child.span(axis);

                let start_track = pos as usize;
                let end_track = start_track + span as usize;

                // if a child spans multiple tracks and any of those is a fractional track, skip this step.
                // any computation involving fractional tracks are done in a separate step at the end.
                let Some((min_length, max_length)) = tracks[start_track..end_track]
                    .iter()
                    .all(|t| !matches!(t, GridTrackSize::Fraction(_)))
                    .then(|| multitrack_lengths.entry((span, pos)).or_insert((0., 0.)))
                else {
                    continue;
                };

                let computed_min = compute_length(
                    &mut child.widget,
                    LenDef::MinContent,
                    LayoutSize::NONE,
                    axis,
                    cross_length,
                );
                let computed_max = compute_length(
                    &mut child.widget,
                    LenDef::MaxContent,
                    LayoutSize::NONE,
                    axis,
                    cross_length,
                );

                *min_length = computed_min.get().max(*min_length);
                *max_length = computed_max.get().max(*max_length);
            }
        }

        // step 3: resolve all track lengths (except for fractional tracks)
        for ((span, pos), (min_length, max_length)) in multitrack_lengths {
            let start_track = pos as usize;
            let end_track = start_track + span as usize;

            // count the number of minimally (intrinsically) and maximally sized tracks.
            let [mut n_intrinsic, n_max] = track_auto_lengths[start_track..end_track]
                .iter()
                .map(|auto_length| match auto_length {
                    LenDef::MinContent | LenDef::FitContent(_) => [1_usize, 1],
                    LenDef::MaxContent => [0, 1],
                    LenDef::Fixed(_) => [0, 0],
                })
                .reduce(|[a, b], [c, d]| [a + c, b + d])
                .unwrap_or([0, 0]);
            let length_by_itself = track_lengths[start_track..end_track]
                .iter()
                .copied()
                .sum::<f64>()
                + gap.get() * (span - 1) as f64;

            // min_contrib is how much should be added to the already existing length to align it
            // to the min length of the tracks computed in the previous step (2).
            let mut min_contrib = min_length - length_by_itself;

            // if the tracks are already longer than the min length there is nothing to do.
            while min_contrib > 0. {
                let per_track_min_contrib = min_contrib / n_intrinsic as f64;
                let per_track_max_contrib =
                    per_track_min_contrib + (max_length - min_length) / n_max as f64;

                for (auto_length, length) in track_auto_lengths[start_track..end_track]
                    .iter()
                    .zip(&mut track_lengths[start_track..])
                {
                    match auto_length {
                        LenDef::FitContent(limit)
                            if *length + per_track_min_contrib > limit.get() =>
                        {
                            // if the extended length exceeds limit, extend up to limit and
                            // pull this track off the pool if extendable tracks.
                            min_contrib -= limit.get() - mem::replace(length, limit.get());
                            n_intrinsic -= 1;
                        }
                        LenDef::MinContent | LenDef::FitContent(_) => {
                            *length += per_track_min_contrib;
                            min_contrib -= per_track_min_contrib;
                        }
                        LenDef::MaxContent => {
                            *length += per_track_max_contrib;
                            min_contrib -= per_track_max_contrib;
                        }
                        LenDef::Fixed(_) => {}
                    }
                }
            }
        }

        // step 4: resolve fractional and auto-sized tracks

        let extract_bases_with_fr = |track_lengths: Vec<f64>, fr_unit: f64| {
            tracks
                .iter()
                .zip(track_lengths)
                .map(|(track, length)| match track {
                    GridTrackSize::Fraction(fr) => *fr * fr_unit,
                    _ => length,
                })
                .collect()
        };

        if len_req == LenReq::MinContent {
            // if the grid is required to be min-content, fractional tracks are sized zero.
            return extract_bases_with_fr(track_lengths, 0.);
        }

        if let Some(context_length) = context_length
            && (matches!(len_req, LenReq::FitContent(_)) || !is_measuring_only)
        {
            // if context length is provided and the grid is fit-content sized,
            // distribute the remaining context length after sizing non-fractional tracks
            // between the fractional tracks according to their fractions.
            // if there is no fractional track but there are auto-sized tracks, distribute the space
            // between the auto-sized tracks equally.
            let (occupied_length, total_fr) = tracks
                .iter()
                .zip(&track_lengths)
                .map(|(track, length)| match *track {
                    GridTrackSize::Fraction(fr) => (0., fr),
                    _ => (*length, 0.),
                })
                .reduce(|(a, b), (c, d)| (a + c, b + d))
                .unwrap();

            let leftover_length = context_length.get() - occupied_length;
            if leftover_length <= 0. {
                return track_lengths;
            }

            if total_fr == 0. {
                let n_auto = tracks
                    .iter()
                    .filter(|t| matches!(t, GridTrackSize::Auto))
                    .count();
                if n_auto != 0 {
                    let per_auto_track_ext = leftover_length / n_auto as f64;
                    tracks
                        .iter()
                        .zip(track_lengths)
                        .map(|(track, length)| match track {
                            GridTrackSize::Auto => length + per_auto_track_ext,
                            _ => length,
                        })
                        .collect()
                } else {
                    track_lengths
                }
            } else {
                extract_bases_with_fr(track_lengths, leftover_length / total_fr)
            }
        } else {
            // if context length is not provided or the grid is min/max-content sized,
            // take the maximum of fractional track length from single-track childrens and apply that.
            if let Some(fr_unit) = tracks
                .iter()
                .zip(&track_lengths)
                .filter_map(|(track, length)| match track {
                    GridTrackSize::Fraction(fr) => Some(length / *fr),
                    _ => None,
                })
                .reduce(f64::max)
            {
                extract_bases_with_fr(track_lengths, fr_unit)
            } else {
                track_lengths
            }
        }
    }
}

// --- MARK: IMPL CHILD
impl Child {
    fn new(child: NewWidget<impl Widget + ?Sized>, params: GridParams) -> Self {
        Self {
            widget: child.erased().to_pod(),
            params,

            x: 0,
            y: 0,
        }
    }

    /// Returns the number of cells the child's area spans on the given `axis`.
    fn span(&self, axis: Axis) -> u16 {
        match axis {
            Axis::Horizontal => self.params.width,
            Axis::Vertical => self.params.height,
        }
    }

    fn pos(&self, axis: Axis) -> u16 {
        match axis {
            Axis::Horizontal => self.x,
            Axis::Vertical => self.y,
        }
    }
}

// --- MARK: IMPL GRIDTRACKSIZE
impl GridTrackSize {
    /// *One (1)* Fraction of remaining space.
    pub const FRACTION: Self = Self::Fraction(1.);
}

impl Default for GridTrackSize {
    fn default() -> Self {
        Self::FRACTION
    }
}

// --- MARK: IMPL GRIDPARAMS
impl GridParams {
    /// Creates grid parameters with the defaulted values.
    ///
    /// It sets the cell span to 1×1.
    pub fn new() -> Self {
        Self {
            col: None,
            row: None,
            width: 1,
            height: 1,
        }
    }

    /// Creates grid parameters for the given position.
    ///
    /// It sets the cell span to 1×1.
    pub fn pos(col: u16, row: u16) -> Self {
        Self::new().with_col(col).with_row(row)
    }

    /// Builder-style method to define at which column in the grid the item should start.
    pub fn with_col(mut self, col: u16) -> Self {
        self.col = Some(col);
        self
    }

    /// Builder-style method to define at which row in the grid the item should start.
    pub fn with_row(mut self, row: u16) -> Self {
        self.row = Some(row);
        self
    }

    /// Builder-style method to define at which column and row in the grid the item should start.
    pub fn with_pos(self, col: u16, row: u16) -> Self {
        self.with_col(col).with_row(row)
    }

    /// Builder-style method to define how many column in the grid the item should occupy.
    ///
    /// # Panics
    ///
    /// When debug assertions are on, panics if the width is zero.
    pub fn with_width(mut self, mut width: u16) -> Self {
        if width == 0 {
            debug_panic!(
                "Grid width value should be a positive nonzero number; got {}",
                width
            );
            width = 1;
        }
        self.width = width;
        self
    }

    /// Builder-style method to define how many row in the grid the item should occupy.
    ///
    /// # Panics
    ///
    /// When debug assertions are on, panics if the height is zero.
    pub fn with_height(mut self, mut height: u16) -> Self {
        if height == 0 {
            debug_panic!(
                "Grid height value should be a positive nonzero number; got {}",
                height
            );
            height = 1;
        }
        self.height = height;
        self
    }

    /// Builder-style method to define how many column and row in the grid the item should occupy.
    ///
    /// # Panics
    ///
    /// When debug assertions are on, panics if either the width or the height is zero.
    pub fn with_span(self, width: u16, height: u16) -> Self {
        self.with_width(width).with_height(height)
    }
}

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

// --- MARK: WIDGETMUT
impl Grid {
    /// Sets the column sizes of the grid.
    pub fn set_columns(this: &mut WidgetMut<'_, Self>, columns: Vec<GridTrackSize>) {
        this.widget.columns = columns;
        this.widget.needs_placing = true;
        this.ctx.request_layout();
    }

    /// Sets the row sizes of the grid.
    pub fn set_rows(this: &mut WidgetMut<'_, Self>, rows: Vec<GridTrackSize>) {
        this.widget.rows = rows;
        this.widget.needs_placing = true;
        this.ctx.request_layout();
    }
}

// --- MARK: COLLECTIONWIDGET
impl CollectionWidget<GridParams> for Grid {
    /// Returns the number of children.
    fn len(&self) -> usize {
        self.children.len()
    }

    /// Returns `true` if there are no children.
    fn is_empty(&self) -> bool {
        self.children.is_empty()
    }

    /// Returns a mutable reference to the child widget at the given index.
    ///
    /// # Panics
    ///
    /// Panics if `idx` is out of bounds.
    fn get_mut<'t>(this: &'t mut WidgetMut<'_, Self>, idx: usize) -> WidgetMut<'t, dyn Widget> {
        let child = &mut this.widget.children[idx].widget;
        this.ctx.get_mut(child)
    }

    /// Appends a child widget to the collection.
    fn add(
        this: &mut WidgetMut<'_, Self>,
        child: NewWidget<impl Widget + ?Sized>,
        params: impl Into<GridParams>,
    ) {
        let child = Child::new(child, params.into());
        this.widget.children.push(child);
        this.widget.needs_placing = true;
        this.ctx.children_changed();
    }

    /// Inserts a child widget at the given index.
    ///
    /// # Panics
    ///
    /// Panics if `idx` is larger than the number of children.
    fn insert(
        this: &mut WidgetMut<'_, Self>,
        idx: usize,
        child: NewWidget<impl Widget + ?Sized>,
        params: impl Into<GridParams>,
    ) {
        let child = Child::new(child, params.into());
        this.widget.children.insert(idx, child);
        this.widget.needs_placing = true;
        this.ctx.children_changed();
    }

    /// Replaces the child widget at the given index.
    ///
    /// # Panics
    ///
    /// Panics if `idx` is out of bounds.
    fn set(
        this: &mut WidgetMut<'_, Self>,
        idx: usize,
        child: NewWidget<impl Widget + ?Sized>,
        params: impl Into<GridParams>,
    ) {
        let child = Child::new(child, params.into());
        let old_child = mem::replace(&mut this.widget.children[idx], child);
        this.widget.needs_placing = true;
        this.ctx.remove_child(old_child.widget);
    }

    /// Sets the child params at the given index.
    ///
    /// # Panics
    ///
    /// Panics if `idx` is out of bounds.
    fn set_params(this: &mut WidgetMut<'_, Self>, idx: usize, params: impl Into<GridParams>) {
        let child = &mut this.widget.children[idx];
        child.params = params.into();
        this.widget.needs_placing = true;
        this.ctx.request_layout();
    }

    /// Swaps the index of two children.
    ///
    /// This also swaps the [`GridParams`] `x` and `y` with the other child.
    ///
    /// # Panics
    ///
    /// Panics if `a` or `b` are out of bounds.
    fn swap(this: &mut WidgetMut<'_, Self>, a: usize, b: usize) {
        let (a_x, a_y) = (this.widget.children[a].x, this.widget.children[a].y);
        let (b_x, b_y) = (this.widget.children[b].x, this.widget.children[b].y);

        this.widget.children.swap(a, b);

        (this.widget.children[a].x, this.widget.children[a].y) = (a_x, a_y);
        (this.widget.children[b].x, this.widget.children[b].y) = (b_x, b_y);

        this.widget.needs_placing = true;
        this.ctx.children_changed();
    }

    /// Removes the child at the given index.
    ///
    /// # Panics
    ///
    /// Panics if `idx` is out of bounds.
    fn remove(this: &mut WidgetMut<'_, Self>, idx: usize) {
        let child = this.widget.children.remove(idx);
        this.ctx.remove_child(child.widget);
        this.widget.needs_placing = true;
    }

    /// Removes all children.
    fn clear(this: &mut WidgetMut<'_, Self>) {
        for child in this.widget.children.drain(..) {
            this.ctx.remove_child(child.widget);
        }
        this.widget.needs_placing = true;
    }
}

impl UsesProperty<Gap> for Grid {}

// --- MARK: IMPL WIDGET
impl Widget for Grid {
    type Action = NoAction;

    fn register_children(&mut self, ctx: &mut RegisterCtx<'_>) {
        for child in self.children.iter_mut() {
            ctx.register_child(&mut child.widget);
        }
    }

    fn property_changed(&mut self, ctx: &mut UpdateCtx<'_>, property_type: TypeId) {
        Gap::prop_changed(ctx, property_type);
    }

    fn measure(
        &mut self,
        ctx: &mut MeasureCtx<'_>,
        props: &PropertiesRef<'_>,
        axis: Axis,
        len_req: LenReq,
        cross_length: Option<Length>,
    ) -> Length {
        let cache = ctx.property_cache();
        let gap = props.get::<Gap>(cache);

        let gap_length = gap.gap.get();

        self.assign_cell_to_auto_placed_children();

        let track_lengths = self.resolve_track_lengths(
            axis,
            len_req,
            cross_length,
            gap.gap,
            ctx.context_size().length(axis),
            true,
            |child, auto_length, context_size, axis, cross_length| {
                ctx.compute_length(child, auto_length, context_size, axis, cross_length)
            },
        );

        if track_lengths.is_empty() {
            return 0.px();
        }

        let computed = Length::px(
            gap_length * (track_lengths.len() - 1) as f64 + track_lengths.into_iter().sum::<f64>(),
        );

        match len_req {
            LenReq::FitContent(space) => computed.min(space),
            _ => computed,
        }
    }

    fn layout(&mut self, ctx: &mut LayoutCtx<'_>, props: &PropertiesRef<'_>, size: Size) {
        let cache = ctx.property_cache();
        let gap = props.get::<Gap>(cache);

        let gap_length = gap.gap.get();

        self.assign_cell_to_auto_placed_children();

        let mut resolve_track = |grid: &mut Self, axis: Axis| {
            grid.resolve_track_lengths(
                axis,
                LenReq::FitContent(size.get_coord(axis).px()),
                Some(size.get_coord(axis.cross()).px()),
                gap.gap,
                Some(size.get_coord(axis).px()),
                false,
                |child, auto_length, context_size, axis, cross_length| {
                    ctx.compute_length(child, auto_length, context_size, axis, cross_length)
                },
            )
            .into_iter()
            .scan(0., |offset, length| {
                Some(mem::replace(offset, *offset + length + gap_length))
            })
            .collect::<Vec<_>>()
        };

        let col_offsets = resolve_track(self, Axis::Horizontal);
        let row_offsets = resolve_track(self, Axis::Vertical);

        let mut baselines = None::<(u16, u16, f64, u16, u16, f64)>;

        for child in &mut self.children {
            let col = child.x as usize;
            let row = child.y as usize;
            let width = child.params.width as usize;
            let height = child.params.height as usize;

            if col + width > self.columns.len() || row + height > self.rows.len() {
                continue;
            }

            let size = Size::new(
                col_offsets
                    .get(col + width)
                    .map_or(size.width, |o| o - gap_length)
                    - col_offsets[col],
                row_offsets
                    .get(row + height)
                    .map_or(size.height, |o| o - gap_length)
                    - row_offsets[row],
            )
            .max(Size::ZERO);

            ctx.run_layout(&mut child.widget, size);

            let origin = Point::new(col_offsets[col], row_offsets[row]);
            ctx.place_child(&mut child.widget, origin);

            let (first_baseline, last_baseline) = ctx.child_aligned_baselines(&child.widget);
            let last_row = child.y + child.params.height;

            baselines = Some(match baselines {
                None => (
                    child.x,
                    child.y,
                    origin.y + first_baseline,
                    child.x,
                    last_row,
                    origin.y + last_baseline,
                ),
                Some((mut col0, mut row0, mut base0, mut col1, mut row1, mut base1)) => {
                    if (child.y, child.x) < (row0, col0) {
                        (col0, row0, base0) = (child.x, child.y, origin.y + first_baseline);
                    }
                    if (last_row, child.x) > (row1, col1) {
                        (col1, row1, base1) = (child.x, last_row, origin.y + last_baseline);
                    }
                    (col0, row0, base0, col1, row1, base1)
                }
            });
        }

        if let Some((_, _, first_baseline, _, _, last_baseline)) = baselines {
            ctx.set_baselines(first_baseline, last_baseline);
        } else {
            ctx.clear_baselines();
        }
    }

    fn paint(
        &mut self,
        _ctx: &mut PaintCtx<'_>,
        _props: &PropertiesRef<'_>,
        _painter: &mut Painter<'_>,
    ) {
    }

    fn accessibility_role(&self) -> Role {
        Role::GenericContainer
    }

    fn accessibility(
        &mut self,
        _ctx: &mut AccessCtx<'_>,
        _props: &PropertiesRef<'_>,
        _node: &mut Node,
    ) {
    }

    fn children_ids(&self) -> ChildrenIds {
        self.children
            .iter()
            .map(|child| child.widget.id())
            .collect()
    }

    fn make_trace_span(&self, id: WidgetId) -> Span {
        trace_span!("Grid", id = id.trace())
    }
}

// --- MARK: TESTS
#[cfg(test)]
mod tests {
    use super::*;
    use crate::layout::AsUnit;
    use crate::palette;
    use crate::properties::types::CrossAxisAlignment;
    use crate::properties::{Background, Dimensions, Padding};
    use crate::testing::{TestHarness, assert_render_snapshot};
    use crate::theme::test_property_set;
    use crate::widgets::{Button, Flex, Label};

    #[test]
    fn test_grid_basics() {
        // Start with a 1x1 grid
        let widget = Grid::with_dimensions(1, 1)
            .with(Button::with_text("A").prepare(), GridParams::pos(0, 0))
            .prepare()
            .with_props(Dimensions::STRETCH);
        let mut harness = TestHarness::create_with_size(test_property_set(), widget, (200, 200));
        // Snapshot with the single widget.
        assert_render_snapshot!(harness, "grid_initial_1x1");

        // Expand it to a 4x4 grid
        harness.edit_root_widget(|mut grid| {
            Grid::set_columns(&mut grid, vec![GridTrackSize::FRACTION; 4]);
        });
        assert_render_snapshot!(harness, "grid_expanded_4x1");

        harness.edit_root_widget(|mut grid| {
            Grid::set_rows(&mut grid, vec![GridTrackSize::FRACTION; 4]);
        });
        assert_render_snapshot!(harness, "grid_expanded_4x4");

        // Add a widget that takes up more than one horizontal cell
        harness.edit_root_widget(|mut grid| {
            Grid::add(
                &mut grid,
                Button::with_text("B").prepare(),
                GridParams::pos(1, 0).with_span(3, 1),
            );
        });
        assert_render_snapshot!(harness, "grid_with_horizontal_widget");

        // Add a widget that takes up more than one vertical cell
        harness.edit_root_widget(|mut grid| {
            Grid::add(
                &mut grid,
                Button::with_text("C").prepare(),
                GridParams::pos(0, 1).with_span(1, 3),
            );
        });
        assert_render_snapshot!(harness, "grid_with_vertical_widget");

        // Add a widget that takes up more than one horizontal and vertical cell
        harness.edit_root_widget(|mut grid| {
            Grid::add(
                &mut grid,
                Button::with_text("D").prepare(),
                GridParams::pos(1, 1).with_span(2, 2),
            );
        });
        assert_render_snapshot!(harness, "grid_with_2x2_widget");

        // Change the gap
        harness.edit_root_widget(|mut grid| {
            grid.insert_prop(Gap::new(7.px()));
        });
        assert_render_snapshot!(harness, "grid_with_changed_spacing");
    }

    #[test]
    fn test_widget_removal_and_modification() {
        let widget = Grid::with_dimensions(2, 2)
            .with(Button::with_text("A").prepare(), GridParams::pos(0, 0))
            .prepare();
        let mut harness = TestHarness::create_with_size(test_property_set(), widget, (200, 200));
        // Snapshot with the single widget.
        assert_render_snapshot!(harness, "grid_initial_2x2");

        // Now remove the widget
        harness.edit_root_widget(|mut grid| {
            Grid::remove(&mut grid, 0);
        });
        assert_render_snapshot!(harness, "grid_2x2_with_removed_widget");

        // Add it back
        harness.edit_root_widget(|mut grid| {
            Grid::add(
                &mut grid,
                Button::with_text("A").prepare(),
                GridParams::pos(0, 0),
            );
        });
        assert_render_snapshot!(harness, "grid_initial_2x2"); // Should be back to the original state

        // Test replacement
        harness.edit_root_widget(|mut grid| {
            Grid::remove(&mut grid, 0);
            Grid::add(
                &mut grid,
                Button::with_text("X").prepare(),
                GridParams::pos(0, 0),
            );
        });
        harness.edit_root_widget(|mut grid| {
            Grid::set(
                &mut grid,
                0,
                Button::with_text("A").prepare(),
                GridParams::pos(0, 0),
            );
        });
        assert_render_snapshot!(harness, "grid_initial_2x2"); // Should be back to the original state

        // Change the grid params to position it on the other corner
        harness.edit_root_widget(|mut grid| {
            Grid::set_params(&mut grid, 0, GridParams::pos(1, 1));
        });
        assert_render_snapshot!(harness, "grid_moved_2x2_1");

        // Now make it take up the entire grid
        harness.edit_root_widget(|mut grid| {
            Grid::set_params(&mut grid, 0, GridParams::pos(0, 0).with_span(2, 2));
        });
        assert_render_snapshot!(harness, "grid_moved_2x2_2");
    }

    #[test]
    fn test_widget_order() {
        let widget = Grid::with_dimensions(2, 2)
            .with(Button::with_text("A").prepare(), GridParams::pos(0, 0))
            .prepare();
        let mut harness = TestHarness::create_with_size(test_property_set(), widget, (200, 200));
        // Snapshot with the single widget.
        assert_render_snapshot!(harness, "grid_initial_2x2");

        // Order sets the draw order, so draw a widget over A by adding it after
        harness.edit_root_widget(|mut grid| {
            Grid::add(
                &mut grid,
                Button::with_text("B").prepare(),
                GridParams::pos(0, 0),
            );
        });
        assert_render_snapshot!(harness, "grid_2x2_with_overlapping_b");

        // Draw a widget under the others by putting it at index 0
        // Make it wide enough to see it stick out, with half of it under A and B.
        harness.edit_root_widget(|mut grid| {
            Grid::insert(
                &mut grid,
                0,
                Button::with_text("C").prepare(),
                GridParams::pos(0, 0).with_span(2, 1),
            );
        });
        assert_render_snapshot!(harness, "grid_2x2_with_overlapping_c");
    }

    #[test]
    fn grid_baselines() {
        let grid = Grid::with_dimensions(3, 3)
            .with(
                Label::new("A\nB").prepare().with_props((
                    Padding::from_vh(0.px(), 0.px()),
                    Background::Color(palette::css::ORANGE),
                )),
                GridParams::pos(1, 0),
            )
            .with(
                Label::new("C\nD").prepare().with_props((
                    Padding::from_vh(8.px(), 0.px()),
                    Background::Color(palette::css::DARK_BLUE),
                )),
                GridParams::pos(0, 0).with_span(1, 2),
            )
            .with(
                Label::new("E\nF").prepare().with_props((
                    Padding::from_vh(16.px(), 0.px()),
                    Background::Color(palette::css::DARK_SALMON),
                )),
                GridParams::pos(2, 0).with_span(1, 3),
            )
            .with(
                Label::new("G\nH").prepare().with_props((
                    Padding::from_vh(24.px(), 0.px()),
                    Background::Color(palette::css::DARK_SLATE_BLUE),
                )),
                GridParams::pos(1, 1).with_span(1, 2),
            )
            .prepare()
            .with_props(Dimensions::width(80.px()));

        let root = Flex::row()
            .cross_axis_alignment(CrossAxisAlignment::FirstBaseline)
            .with_fixed(Label::new("Out").prepare())
            .with_fixed(grid)
            .prepare()
            .with_props(Padding::all(10.px()));

        let mut harness = TestHarness::create_with_size(test_property_set(), root, (150, 200));

        assert_render_snapshot!(harness, "grid_baselines_first");

        harness.edit_root_widget(|mut root| {
            Flex::set_cross_axis_alignment(&mut root, CrossAxisAlignment::LastBaseline);
        });

        assert_render_snapshot!(harness, "grid_baselines_last");
    }

    #[test]
    fn grid_nonuniform() {
        let widget = Grid::new()
            .with_columns([
                GridTrackSize::MinContent,
                GridTrackSize::MaxContent,
                GridTrackSize::Fraction(1.),
            ])
            .with_rows([
                GridTrackSize::Auto,
                GridTrackSize::Fixed(30.px()),
                GridTrackSize::Percentage(0.2),
                GridTrackSize::Fraction(2.),
                GridTrackSize::Fraction(1.),
            ])
            .with(
                Label::new("Min Content")
                    .prepare()
                    .with_props(Background::Color(palette::css::CHOCOLATE.with_alpha(0.5))),
                GridParams::new(),
            )
            .with(
                Label::new("Max Content")
                    .prepare()
                    .with_props(Background::Color(palette::css::OLIVE.with_alpha(0.5))),
                GridParams::new(),
            )
            .with(
                Label::new("1×3")
                    .prepare()
                    .with_props(Background::Color(palette::css::ORANGE_RED.with_alpha(0.5))),
                GridParams::pos(2, 0).with_height(3),
            )
            .with(
                Label::new("20px")
                    .prepare()
                    .with_props(Background::Color(palette::css::MAGENTA.with_alpha(0.5))),
                GridParams::new().with_col(1),
            )
            .with(
                Label::new("30%")
                    .prepare()
                    .with_props(Background::Color(palette::css::SEA_GREEN.with_alpha(0.5))),
                GridParams::new(),
            )
            .with(
                Label::new("2×2")
                    .prepare()
                    .with_props(Background::Color(palette::css::AQUAMARINE.with_alpha(0.5))),
                GridParams::pos(1, 2).with_span(2, 2),
            )
            .with(
                Label::new("2fr")
                    .prepare()
                    .with_props(Background::Color(palette::css::PURPLE.with_alpha(0.5))),
                GridParams::new(),
            )
            .with(
                Label::new("1fr")
                    .prepare()
                    .with_props(Background::Color(palette::css::GOLD.with_alpha(0.5))),
                GridParams::new().with_col(2),
            )
            .prepare()
            .with_props(Gap::new(5.px()))
            .with_props(Dimensions::STRETCH);

        let mut harness = TestHarness::create_with_size(test_property_set(), widget, (300, 300));
        assert_render_snapshot!(harness, "grid_nonuniform");
    }

    #[test]
    fn grid_fitcontent_overflow() {
        let widget = Grid::new()
            .with_columns([
                GridTrackSize::MinContent,
                GridTrackSize::FitContent(50.px()),
                GridTrackSize::MinContent,
            ])
            .with_rows([GridTrackSize::Fixed(30.px()); 2])
            .with(
                Label::new("30px")
                    .prepare()
                    .with_props(Dimensions::width(30.px()))
                    .with_props(Background::Color(palette::css::CHOCOLATE.with_alpha(0.5))),
                GridParams::pos(0, 0),
            )
            .with(
                Label::new("40px")
                    .prepare()
                    .with_props(Dimensions::width(40.px()))
                    .with_props(Background::Color(palette::css::BISQUE.with_alpha(0.5))),
                GridParams::pos(1, 0),
            )
            .with(
                Label::new("20px")
                    .prepare()
                    .with_props(Dimensions::width(20.px()))
                    .with_props(Background::Color(palette::css::LIME_GREEN.with_alpha(0.5))),
                GridParams::pos(2, 0),
            )
            .with(
                Label::new("160px")
                    .prepare()
                    .with_props(Dimensions::width(160.px()))
                    .with_props(Background::Color(palette::css::PURPLE.with_alpha(0.5))),
                GridParams::pos(0, 1).with_width(3),
            )
            .prepare()
            .with_props(Gap::new(5.px()))
            .with_props(Dimensions::MIN);

        let mut harness = TestHarness::create_with_size(test_property_set(), widget, (300, 300));
        assert_render_snapshot!(harness, "grid_fitcontent_overflow");
    }
}