retroglyph-ui 0.4.1

Immediate-mode terminal UI toolkit for retroglyph: widgets, layout, input/focus, theming, and animation
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
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
//! Constraint-based `Rect` splitter for multi-panel UIs.
//!
//! Splits a [`Rect`] into stacked rows ([`split_v`]) or side-by-side columns
//! ([`split_h`]) according to a slice of [`Constraint`]s. [`split_h_spaced`]/[`split_v_spaced`]
//! do the same but also carve a fixed-cell gap between every adjacent pair of panes, without the
//! caller having to interleave `Constraint::Fixed(spacing)` gap constraints and filter them back
//! out by hand; they return the gap rects alongside the content panes so a caller can draw
//! dividers in them without recomputing the gap positions.
//!
//! Every `split_*` function has a const-generic `split_*_n` sibling ([`split_v_n`]/[`split_h_n`],
//! plus the `_flex`/`_spaced` combinations) that takes `[Constraint; N]` and returns `[Rect; N]`
//! instead of allocating a `Vec<Rect>`: useful for a fixed pane count re-split every frame, and
//! the array return type lets a caller destructure (`let [header, body] = split_v_n(area, [..]);`)
//! instead of indexing into a `Vec` that can silently drift out of sync with the constraint list.
//!
//! The solver sums the [`Fixed`](Constraint::Fixed), [`Percent`](Constraint::Percent), and
//! [`Ratio`](Constraint::Ratio) amounts, then distributes whatever remains across the
//! [`Fill`](Constraint::Fill),
//! [`Min`](Constraint::Min), and [`Max`](Constraint::Max) panes in proportion to their
//! weight: a `Fill(w)` pane claims a share proportional to `w` relative
//! to the other flexible panes, while [`Min`](Constraint::Min) and [`Max`](Constraint::Max)
//! panes always weigh 1. `Fill(1)` (equivalent to every pane weighing 1) reproduces plain
//! equal distribution. Sizes are clamped so the panes never spill past `area`. This is a
//! single sequential pass, not an iterative constraint solver: a [`Max`](Constraint::Max)
//! pane that is capped below its share does not redistribute the excess to other panes, so
//! leftover space can remain unclaimed (see [`Flex`] for how that leftover is placed via
//! [`split_v_flex`]/[`split_h_flex`]).
use alloc::vec::Vec;

use retroglyph_core::grid::{HasSize, Rect, Size};

/// How a single pane claims space along the split axis.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Constraint {
    /// An exact number of cells.
    Fixed(u16),
    /// A percentage (0–100) of the axis length.
    Percent(u16),
    /// A proportional share of the axis length, `numerator / denominator`, without picking
    /// an arbitrary [`Fill`](Self::Fill) weight. Resolves like [`Percent`](Self::Percent): a
    /// fixed size computed up front, not a weighted share of the remainder. A zero
    /// `denominator` resolves to zero rather than panicking.
    Ratio(u16, u16),
    /// Claim a share of whatever space the fixed/percent panes leave, proportional to
    /// `weight` relative to the other [`Fill`](Self::Fill)/[`Min`](Self::Min)/[`Max`](Self::Max)
    /// panes in the same split ([`Min`](Self::Min)/[`Max`](Self::Max) panes always weigh 1).
    /// `Fill(1)` reproduces plain equal distribution across an all-`Fill` split; a weight of
    /// 0 claims no share of the remainder.
    Fill(u16),
    /// Like [`Fill`](Self::Fill), but guarantees at least this many cells even if the axis
    /// is too small for every pane to get its share, and always weighs 1.
    Min(u16),
    /// Like [`Fill`](Self::Fill), but never grows past this many cells (any share past the
    /// cap is left unclaimed rather than redistributed), and always weighs 1.
    Max(u16),
}

impl Constraint {
    /// Resolve this constraint's base size against `total` axis length.
    /// [`Fill`](Self::Fill) and [`Max`](Self::Max) resolve to zero here;
    /// [`Min`](Self::Min) reserves its floor up front like [`Fixed`](Self::Fixed).
    /// Flexible sizes are filled in later by [`solve`].
    fn base(self, total: u16) -> u16 {
        match self {
            Self::Fixed(n) | Self::Min(n) => n.min(total),
            Self::Percent(p) => {
                let p = u32::from(p.min(100));
                // `p` is clamped to `0..=100`, so `total * p / 100 <= total`, itself a `u16`.
                #[allow(clippy::cast_possible_truncation)]
                {
                    (u32::from(total) * p / 100) as u16
                }
            }
            Self::Ratio(num, den) => {
                if den == 0 {
                    0
                } else {
                    // `num / den` can exceed 1 (e.g. `Ratio(3, 2)`), so the result is clamped to
                    // `total` rather than relying on the ratio alone to stay in range.
                    #[allow(clippy::cast_possible_truncation)]
                    {
                        (u32::from(total) * u32::from(num) / u32::from(den)).min(u32::from(total))
                            as u16
                    }
                }
            }
            Self::Fill(_) | Self::Max(_) => 0,
        }
    }
}

/// Constraint counts at or below this stay on the stack in [`SmallBuf`]; larger splits fall back
/// to a heap `Vec`. Chosen comfortably above a typical multi-panel layout (a header, a handful of
/// flexible content panes, a status bar) while staying correct for arbitrarily many panes: see
/// the `layout_solve` benchmark's 100-pane case, which exercises the heap fallback.
const STACK_CAP: usize = 8;

/// A small buffer that stays inline on the stack for up to `N` items and only allocates on the
/// heap past that. `solve` uses this for its scratch buffers (pane sizes, the flexible-pane
/// index/weight/cap list, and the largest-remainder distribution pass) so that the common case of
/// a handful of panes per split (called several times per frame by multi-panel UIs) does not
/// pay for a heap allocation at all.
enum SmallBuf<T: Copy + Default, const N: usize> {
    Stack([T; N], usize),
    Heap(Vec<T>),
}

impl<T: Copy + Default, const N: usize> SmallBuf<T, N> {
    /// Create a buffer able to hold `cap` items without reallocating: inline on the stack if
    /// `cap` fits within `N`, otherwise a heap `Vec` pre-sized to `cap`.
    fn with_capacity(cap: usize) -> Self {
        if cap <= N {
            Self::Stack([T::default(); N], 0)
        } else {
            Self::Heap(Vec::with_capacity(cap))
        }
    }

    /// Append `value`.
    ///
    /// # Panics
    ///
    /// Panics if the buffer is the `Stack` variant and already holds `N` items: callers must
    /// size `with_capacity` to the true upper bound of pushes, as `solve` does.
    fn push(&mut self, value: T) {
        match self {
            Self::Stack(buf, len) => {
                buf[*len] = value;
                *len += 1;
            }
            Self::Heap(vec) => vec.push(value),
        }
    }
}

impl<T: Copy + Default, const N: usize> core::ops::Deref for SmallBuf<T, N> {
    type Target = [T];

    fn deref(&self) -> &[T] {
        match self {
            Self::Stack(buf, len) => &buf[..*len],
            Self::Heap(vec) => vec,
        }
    }
}

impl<T: Copy + Default, const N: usize> core::ops::DerefMut for SmallBuf<T, N> {
    fn deref_mut(&mut self) -> &mut [T] {
        match self {
            Self::Stack(buf, len) => &mut buf[..*len],
            Self::Heap(vec) => vec,
        }
    }
}

impl<T: Copy + Default, const N: usize> core::ops::Index<usize> for SmallBuf<T, N> {
    type Output = T;

    fn index(&self, idx: usize) -> &T {
        &(**self)[idx]
    }
}

impl<T: Copy + Default, const N: usize> core::ops::IndexMut<usize> for SmallBuf<T, N> {
    fn index_mut(&mut self, idx: usize) -> &mut T {
        &mut (**self)[idx]
    }
}

/// Compute the length of each pane along an axis of `total` cells.
fn solve(total: u16, constraints: &[Constraint]) -> SmallBuf<u16, STACK_CAP> {
    let mut sizes: SmallBuf<u16, STACK_CAP> = SmallBuf::with_capacity(constraints.len());
    for c in constraints {
        sizes.push(c.base(total));
    }

    // Clamp the fixed/percent sum so it never exceeds the axis. If it does,
    // shave from the tail so earlier panes keep their requested size.
    let mut used: u16 = 0;
    for size in sizes.iter_mut() {
        let room = total.saturating_sub(used);
        *size = (*size).min(room);
        used += *size;
    }

    // Distribute the remainder across the Fill, Min, and Max panes in proportion to
    // their weight (Fill(w) weighs w; Min/Max always weigh 1). Min panes add their
    // share on top of the floor already reserved above; Max panes start at zero and
    // are capped at their declared value (any share past the cap is simply left
    // unclaimed, not redistributed).
    let mut flexible: SmallBuf<(usize, u16, Option<u16>), STACK_CAP> =
        SmallBuf::with_capacity(constraints.len());
    for (i, c) in constraints.iter().enumerate() {
        match c {
            Constraint::Fill(weight) => flexible.push((i, *weight, None)),
            Constraint::Min(_) => flexible.push((i, 1, None)),
            Constraint::Max(cap) => flexible.push((i, 1, Some(*cap))),
            Constraint::Fixed(_) | Constraint::Percent(_) | Constraint::Ratio(_, _) => {}
        }
    }
    if !flexible.is_empty() {
        let remainder = total.saturating_sub(used);
        let total_weight: u32 = flexible.iter().map(|&(_, w, _)| u32::from(w)).sum();
        if let Some(total_weight) = core::num::NonZeroU32::new(total_weight) {
            // Largest-remainder method: give every pane the integer floor of its
            // proportional share, then hand out the leftover cells one at a time to
            // the panes with the largest fractional remainder (ties -> earlier pane
            // first). For equal weights every fraction ties, so this reduces to the
            // original round-robin-from-the-front behavior exactly.
            let mut shares: SmallBuf<u32, STACK_CAP> = SmallBuf::with_capacity(flexible.len());
            let mut fracs: SmallBuf<u32, STACK_CAP> = SmallBuf::with_capacity(flexible.len());
            let mut floor_sum: u32 = 0;
            for &(_, weight, _) in flexible.iter() {
                let product = u32::from(remainder) * u32::from(weight);
                let share = product / total_weight;
                fracs.push(product % total_weight);
                shares.push(share);
                floor_sum += share;
            }
            let mut leftover = u32::from(remainder).saturating_sub(floor_sum);
            let mut order: SmallBuf<usize, STACK_CAP> = SmallBuf::with_capacity(flexible.len());
            for idx in 0..flexible.len() {
                order.push(idx);
            }
            order.sort_by(|&a, &b| fracs[b].cmp(&fracs[a]).then(a.cmp(&b)));
            for &idx in order.iter() {
                if leftover == 0 {
                    break;
                }
                shares[idx] += 1;
                leftover -= 1;
            }
            for (k, &(i, _, cap)) in flexible.iter().enumerate() {
                // `shares[k]` is an integer share of `remainder` (a `u16` widened to `u32`), so it
                // can never exceed `remainder` itself and fits back in a `u16`.
                #[allow(clippy::cast_possible_truncation)]
                let share = shares[k] as u16;
                let grown = sizes[i].saturating_add(share);
                sizes[i] = cap.map_or(grown, |max| grown.min(max));
            }
        }
    }

    sizes
}

/// Const-generic sibling of [`solve`]: same algorithm, but sized to `N` at compile time, so
/// every scratch buffer is a plain `[T; N]` on the stack and there is no [`SmallBuf`] heap
/// fallback to worry about, whatever `N` is. Used by [`split_v_n`]/[`split_h_n`] and their
/// `_flex`/`_spaced` siblings.
fn solve_n<const N: usize>(total: u16, constraints: &[Constraint; N]) -> [u16; N] {
    let mut sizes = [0u16; N];
    for (i, c) in constraints.iter().enumerate() {
        sizes[i] = c.base(total);
    }

    // Clamp the fixed/percent sum so it never exceeds the axis, same as `solve`.
    let mut used: u16 = 0;
    for size in &mut sizes {
        let room = total.saturating_sub(used);
        *size = (*size).min(room);
        used += *size;
    }

    // Same largest-remainder distribution as `solve`, but into fixed-size `[T; N]` scratch
    // (at most `N` panes can be flexible, so `N` is always enough room).
    let mut flexible: [(usize, u16, Option<u16>); N] = [(0, 0, None); N];
    let mut flex_len = 0usize;
    for (i, c) in constraints.iter().enumerate() {
        match c {
            Constraint::Fill(weight) => {
                flexible[flex_len] = (i, *weight, None);
                flex_len += 1;
            }
            Constraint::Min(_) => {
                flexible[flex_len] = (i, 1, None);
                flex_len += 1;
            }
            Constraint::Max(cap) => {
                flexible[flex_len] = (i, 1, Some(*cap));
                flex_len += 1;
            }
            Constraint::Fixed(_) | Constraint::Percent(_) | Constraint::Ratio(_, _) => {}
        }
    }
    if flex_len > 0 {
        let remainder = total.saturating_sub(used);
        let total_weight: u32 = flexible[..flex_len]
            .iter()
            .map(|&(_, w, _)| u32::from(w))
            .sum();
        if let Some(total_weight) = core::num::NonZeroU32::new(total_weight) {
            let mut shares = [0u32; N];
            let mut fracs = [0u32; N];
            let mut floor_sum: u32 = 0;
            for (k, &(_, weight, _)) in flexible[..flex_len].iter().enumerate() {
                let product = u32::from(remainder) * u32::from(weight);
                let share = product / total_weight;
                fracs[k] = product % total_weight;
                shares[k] = share;
                floor_sum += share;
            }
            let mut leftover = u32::from(remainder).saturating_sub(floor_sum);
            let mut order = [0usize; N];
            for (idx, slot) in order[..flex_len].iter_mut().enumerate() {
                *slot = idx;
            }
            order[..flex_len].sort_by(|&a, &b| fracs[b].cmp(&fracs[a]).then(a.cmp(&b)));
            for &idx in &order[..flex_len] {
                if leftover == 0 {
                    break;
                }
                shares[idx] += 1;
                leftover -= 1;
            }
            for (k, &(i, _, cap)) in flexible[..flex_len].iter().enumerate() {
                // `shares[k]` is an integer share of `remainder` (a `u16` widened to `u32`), so
                // it can never exceed `remainder` itself and fits back in a `u16`.
                #[allow(clippy::cast_possible_truncation)]
                let share = shares[k] as u16;
                let grown = sizes[i].saturating_add(share);
                sizes[i] = cap.map_or(grown, |max| grown.min(max));
            }
        }
    }

    sizes
}

/// Split `area` into stacked rows top-to-bottom.
///
/// Returns one [`Rect`] per constraint; empty panes (zero height) are still
/// returned so indices line up with `constraints`.
///
/// Never panics: a degenerate `area` (zero height, zero width, or both) resolves every
/// constraint to a zero-height pane via [`saturating_sub`](u16::saturating_sub) arithmetic
/// rather than under/overflowing, and an empty `constraints` slice simply returns an empty
/// `Vec`.
///
/// # Examples
///
/// ```
/// use retroglyph_core::grid::Rect;
/// use retroglyph_ui::{Constraint, split_v};
///
/// let area = Rect::new(0, 0, 20, 10);
/// let panes = split_v(area, &[Constraint::Fixed(1), Constraint::Fill(1), Constraint::Fixed(1)]);
/// assert_eq!(panes.iter().map(Rect::height).collect::<Vec<_>>(), vec![1, 8, 1]);
/// ```
#[must_use]
pub fn split_v(area: Rect, constraints: &[Constraint]) -> Vec<Rect> {
    let sizes = solve(area.height(), constraints);
    let mut y = area.top();
    sizes
        .iter()
        .copied()
        .map(|h| {
            let rect = Rect::new(area.left(), y, area.width(), h);
            y = y.saturating_add(h);
            rect
        })
        .collect()
}

/// Split `area` into stacked rows top-to-bottom, like [`split_v`], but sized to a compile-time
/// pane count `N`: takes `[Constraint; N]` and returns `[Rect; N]` instead of allocating a `Vec`.
///
/// The array length ties the constraint count to the return type, so a caller that destructures
/// the result (`let [header, body, footer] = split_v_n(area, [..]);`) gets a compile error if it
/// adds or removes a constraint without updating the destructuring pattern, rather than a
/// silently out-of-sync index into a `Vec`. Never allocates, for any `N`.
///
/// Never panics, for the same reason as [`split_v`].
///
/// # Examples
///
/// ```
/// use retroglyph_core::grid::Rect;
/// use retroglyph_ui::{Constraint, split_v_n};
///
/// let area = Rect::new(0, 0, 20, 10);
/// let [header, body, footer] =
///     split_v_n(area, [Constraint::Fixed(1), Constraint::Fill(1), Constraint::Fixed(1)]);
/// assert_eq!((header.height(), body.height(), footer.height()), (1, 8, 1));
/// ```
#[must_use]
pub fn split_v_n<const N: usize>(area: Rect, constraints: [Constraint; N]) -> [Rect; N] {
    let sizes = solve_n(area.height(), &constraints);
    let mut y = area.top();
    core::array::from_fn(|i| {
        let h = sizes[i];
        let rect = Rect::new(area.left(), y, area.width(), h);
        y = y.saturating_add(h);
        rect
    })
}

/// Split `area` into columns left-to-right.
///
/// Returns one [`Rect`] per constraint; empty panes (zero width) are still
/// returned so indices line up with `constraints`.
///
/// Never panics, for the same reason as [`split_v`]: a degenerate `area` resolves every
/// constraint to a zero-width pane instead of under/overflowing, and an empty `constraints`
/// slice returns an empty `Vec`.
///
/// # Examples
///
/// ```
/// use retroglyph_core::grid::Rect;
/// use retroglyph_ui::{Constraint, split_h};
///
/// let area = Rect::new(0, 0, 100, 5);
/// let panes = split_h(area, &[Constraint::Percent(30), Constraint::Fill(1)]);
/// assert_eq!(panes.iter().map(Rect::width).collect::<Vec<_>>(), vec![30, 70]);
/// ```
#[must_use]
pub fn split_h(area: Rect, constraints: &[Constraint]) -> Vec<Rect> {
    let sizes = solve(area.width(), constraints);
    let mut x = area.left();
    sizes
        .iter()
        .copied()
        .map(|w| {
            let rect = Rect::new(x, area.top(), w, area.height());
            x = x.saturating_add(w);
            rect
        })
        .collect()
}

/// Split `area` into columns left-to-right, like [`split_h`], but sized to a compile-time pane
/// count `N`: takes `[Constraint; N]` and returns `[Rect; N]` instead of allocating a `Vec`.
///
/// See [`split_v_n`] for why the array-sized signature is worth it over indexing a `Vec`. Never
/// allocates, for any `N`; never panics, for the same reason as [`split_h`].
///
/// # Examples
///
/// ```
/// use retroglyph_core::grid::Rect;
/// use retroglyph_ui::{Constraint, split_h_n};
///
/// let area = Rect::new(0, 0, 100, 5);
/// let [left, right] = split_h_n(area, [Constraint::Percent(30), Constraint::Fill(1)]);
/// assert_eq!((left.width(), right.width()), (30, 70));
/// ```
#[must_use]
pub fn split_h_n<const N: usize>(area: Rect, constraints: [Constraint; N]) -> [Rect; N] {
    let sizes = solve_n(area.width(), &constraints);
    let mut x = area.left();
    core::array::from_fn(|i| {
        let w = sizes[i];
        let rect = Rect::new(x, area.top(), w, area.height());
        x = x.saturating_add(w);
        rect
    })
}

/// How adjacent panes relate along the split axis in a `_spaced` split: a fixed gap between
/// them, or a shared, overlapping edge.
///
/// A plain `u16` (the historic `spacing` parameter) converts to [`Space`](Self::Space) via
/// [`From`], so existing callers of [`split_h_spaced`]/[`split_v_spaced`]/[`split_h_n_spaced`]/
/// [`split_v_n_spaced`] keep compiling unchanged.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Spacing {
    /// Carve out a fixed `n`-cell gap between every adjacent pair of panes. The gap comes out
    /// of the area before constraints are resolved, so [`Fill`](Constraint::Fill)/
    /// [`Percent`](Constraint::Percent) panes share only what's left after every gap is
    /// reserved. No-op with fewer than two panes or `n == 0`.
    Space(u16),
    /// Shift every pane back by `n` cells so it overlaps the trailing edge of the previous
    /// pane, e.g. so two adjacent bordered panels can share one line of border instead of each
    /// drawing its own (ratatui's `Spacing::Overlap`). Purely geometric: retroglyph does not
    /// merge the overlapping cells' contents, so whichever pane is drawn last wins on the
    /// shared cells. No-op with fewer than two panes or `n == 0`.
    Overlap(u16),
}

impl Spacing {
    /// The gap/overlap cell count, regardless of which variant this is.
    const fn cells(self) -> u16 {
        match self {
            Self::Space(n) | Self::Overlap(n) => n,
        }
    }
}

impl From<u16> for Spacing {
    /// A plain cell count is a gap, matching the historic `u16` spacing parameter.
    fn from(n: u16) -> Self {
        Self::Space(n)
    }
}

/// Split `area` into columns left-to-right, like [`split_h`], but with a `spacing`-cell gap or
/// overlap between every adjacent pair of panes; see [`Spacing`].
///
/// `spacing`'s cell count is reserved from (for [`Spacing::Space`]) or added back to (for
/// [`Spacing::Overlap`]) `area` before `constraints` are resolved, so
/// [`Fill`](Constraint::Fill)/[`Percent`](Constraint::Percent) panes share only what's left
/// after every gap is reserved, or the full extra room an overlap frees up. No-op (falls back
/// to [`split_h`], with an empty gap `Vec`) with fewer than two panes or zero spacing/overlap.
///
/// Returns `(panes, gaps)`: `gaps` has one entry between every adjacent pair of panes (so
/// `constraints.len() - 1` gaps, none leading or trailing), in the same left-to-right order as
/// `panes`. For [`Spacing::Space`] a gap rect is the empty cell(s) between the two panes it
/// separates; for [`Spacing::Overlap`] it is the shared cell(s) both adjacent panes draw over
/// (whichever pane is drawn last wins there), which is exactly the region a caller would want to
/// draw a shared border into.
///
/// # Examples
///
/// ```
/// use retroglyph_core::grid::Rect;
/// use retroglyph_ui::{Constraint, Spacing, split_h_spaced};
///
/// let area = Rect::new(0, 0, 59, 6);
/// let (panes, gaps) = split_h_spaced(area, &[Constraint::Fill(1); 3], 1);
/// assert_eq!(panes.iter().map(Rect::width).collect::<Vec<_>>(), vec![19, 19, 19]);
/// assert_eq!(panes[1].left(), panes[0].right() + 1); // one gap cell between panes
/// assert_eq!(gaps.len(), 2); // one gap between each adjacent pair of panes
/// assert_eq!(gaps[0], Rect::new(19, 0, 1, 6));
///
/// let (panes, gaps) = split_h_spaced(area, &[Constraint::Fill(1); 2], Spacing::Overlap(1));
/// assert_eq!(panes[1].left(), panes[0].right() - 1); // panes share one border column
/// assert_eq!(gaps[0], Rect::new(panes[0].right() - 1, 0, 1, 6)); // the shared column
/// ```
#[must_use]
pub fn split_h_spaced(
    area: Rect,
    constraints: &[Constraint],
    spacing: impl Into<Spacing>,
) -> (Vec<Rect>, Vec<Rect>) {
    let spacing = spacing.into();
    if spacing.cells() == 0 || constraints.len() < 2 {
        return (split_h(area, constraints), Vec::new());
    }
    let sizes = solve(
        spaced_total(area.width(), constraints.len(), spacing),
        constraints,
    );
    let mut x = area.left();
    let mut panes = Vec::with_capacity(sizes.len());
    let mut gaps = Vec::with_capacity(sizes.len().saturating_sub(1));
    let last = sizes.len().saturating_sub(1);
    for (i, w) in sizes.iter().copied().enumerate() {
        panes.push(Rect::new(x, area.top(), w, area.height()));
        if i < last {
            let (gx, gw) = spacer_span(x, w, spacing);
            gaps.push(Rect::new(gx, area.top(), gw, area.height()));
        }
        x = step(x, w, spacing);
    }
    (panes, gaps)
}

/// Split `area` into stacked rows top-to-bottom, like [`split_v`], but with a `spacing`-cell gap
/// or overlap between every adjacent pair of panes; see [`Spacing`].
///
/// See [`split_h_spaced`] for the full behavior, including the shape and meaning of the returned
/// `(panes, gaps)`; this is the same operation along the vertical axis.
#[must_use]
pub fn split_v_spaced(
    area: Rect,
    constraints: &[Constraint],
    spacing: impl Into<Spacing>,
) -> (Vec<Rect>, Vec<Rect>) {
    let spacing = spacing.into();
    if spacing.cells() == 0 || constraints.len() < 2 {
        return (split_v(area, constraints), Vec::new());
    }
    let sizes = solve(
        spaced_total(area.height(), constraints.len(), spacing),
        constraints,
    );
    let mut y = area.top();
    let mut panes = Vec::with_capacity(sizes.len());
    let mut gaps = Vec::with_capacity(sizes.len().saturating_sub(1));
    let last = sizes.len().saturating_sub(1);
    for (i, h) in sizes.iter().copied().enumerate() {
        panes.push(Rect::new(area.left(), y, area.width(), h));
        if i < last {
            let (gy, gh) = spacer_span(y, h, spacing);
            gaps.push(Rect::new(area.left(), gy, area.width(), gh));
        }
        y = step(y, h, spacing);
    }
    (panes, gaps)
}

/// The axis length to solve `count` panes' [`Constraint`]s against for a `_spaced` split: `total`
/// with `count - 1` gaps of `spacing.cells()` reserved out ([`Spacing::Space`]) or handed back in
/// ([`Spacing::Overlap`]). Shared by the `Vec`-returning and array-returning `_spaced` splits.
const fn spaced_total(total: u16, count: usize, spacing: Spacing) -> u16 {
    // `count` is the number of panes in one layout split, nowhere near `u16::MAX` in any
    // realistic UI, and callers only reach here with `count >= 2`.
    #[allow(clippy::cast_possible_truncation)]
    let gaps = count as u16 - 1;
    let delta = spacing.cells().saturating_mul(gaps);
    match spacing {
        Spacing::Space(_) => total.saturating_sub(delta),
        Spacing::Overlap(_) => total.saturating_add(delta),
    }
}

/// Advance a `_spaced` split's cursor past a pane of size `size` starting at `pos`, leaving a
/// [`Spacing::Space`] gap or eating into the next pane by a [`Spacing::Overlap`] amount.
const fn step(pos: u16, size: u16, spacing: Spacing) -> u16 {
    match spacing {
        Spacing::Space(n) => pos.saturating_add(size).saturating_add(n),
        Spacing::Overlap(n) => pos.saturating_add(size).saturating_sub(n),
    }
}

/// The gap rect's start position and length along the split axis, trailing the pane of `size`
/// cells starting at `pos`. For [`Spacing::Space`] this is the empty `n`-cell run right after the
/// pane; for [`Spacing::Overlap`] it is the pane's own trailing `n` cells, which the next pane
/// draws over. Shared by every `_spaced` split, `Vec`- and array-returning alike.
const fn spacer_span(pos: u16, size: u16, spacing: Spacing) -> (u16, u16) {
    let n = spacing.cells();
    let start = match spacing {
        Spacing::Space(_) => pos.saturating_add(size),
        Spacing::Overlap(_) => pos.saturating_add(size).saturating_sub(n),
    };
    (start, n)
}

/// Split `area` into columns left-to-right, like [`split_h_n`], but with a `spacing`-cell gap or
/// overlap between every adjacent pair of panes, like [`split_h_spaced`]; see [`Spacing`].
///
/// Reserves or hands back `spacing.cells() * (N - 1)` cells up front (equivalent to
/// [`split_h_spaced`]) and solves the remaining panes against what's left, so
/// [`Fill`](Constraint::Fill)/[`Percent`](Constraint::Percent) panes share only the space after
/// every gap is reserved, same as [`split_h_spaced`]. No-op (falls back to [`split_h_n`], with an
/// empty gap `Vec`) with fewer than two panes or zero spacing/overlap.
///
/// Returns `(panes, gaps)`, same meaning as [`split_h_spaced`]'s return value: `panes` is the
/// array of `N` content panes (never allocates, unlike the `Vec`-returning [`split_h_spaced`]),
/// and `gaps` is a `Vec` of the `N - 1` gap rects between them. `gaps` is a `Vec` rather than a
/// second const-generic array because its length (`N - 1`) is not expressible as a fixed-size
/// array tied to `N` on stable Rust.
///
/// # Examples
///
/// ```
/// use retroglyph_core::grid::Rect;
/// use retroglyph_ui::{Constraint, split_h_n_spaced};
///
/// let area = Rect::new(0, 0, 59, 6);
/// let ([a, b, c], gaps) = split_h_n_spaced(area, [Constraint::Fill(1); 3], 1);
/// assert_eq!((a.width(), b.width(), c.width()), (19, 19, 19));
/// assert_eq!(b.left(), a.right() + 1);
/// assert_eq!(gaps.len(), 2);
/// ```
#[must_use]
pub fn split_h_n_spaced<const N: usize>(
    area: Rect,
    constraints: [Constraint; N],
    spacing: impl Into<Spacing>,
) -> ([Rect; N], Vec<Rect>) {
    let spacing = spacing.into();
    if spacing.cells() == 0 || N < 2 {
        return (split_h_n(area, constraints), Vec::new());
    }
    let sizes = solve_n(spaced_total(area.width(), N, spacing), &constraints);
    let mut x = area.left();
    let mut gaps = Vec::with_capacity(N.saturating_sub(1));
    let panes = core::array::from_fn(|i| {
        let w = sizes[i];
        let rect = Rect::new(x, area.top(), w, area.height());
        if i + 1 < N {
            let (gx, gw) = spacer_span(x, w, spacing);
            gaps.push(Rect::new(gx, area.top(), gw, area.height()));
        }
        x = step(x, w, spacing);
        rect
    });
    (panes, gaps)
}

/// Split `area` into stacked rows top-to-bottom, like [`split_v_n`], but with a `spacing`-cell
/// gap or overlap between every adjacent pair of panes, like [`split_v_spaced`]; see [`Spacing`].
///
/// See [`split_h_n_spaced`] for the full behavior, including why `gaps` is a `Vec` rather than a
/// second const-generic array; this is the same operation along the vertical axis.
#[must_use]
pub fn split_v_n_spaced<const N: usize>(
    area: Rect,
    constraints: [Constraint; N],
    spacing: impl Into<Spacing>,
) -> ([Rect; N], Vec<Rect>) {
    let spacing = spacing.into();
    if spacing.cells() == 0 || N < 2 {
        return (split_v_n(area, constraints), Vec::new());
    }
    let sizes = solve_n(spaced_total(area.height(), N, spacing), &constraints);
    let mut y = area.top();
    let mut gaps = Vec::with_capacity(N.saturating_sub(1));
    let panes = core::array::from_fn(|i| {
        let h = sizes[i];
        let rect = Rect::new(area.left(), y, area.width(), h);
        if i + 1 < N {
            let (gy, gh) = spacer_span(y, h, spacing);
            gaps.push(Rect::new(area.left(), gy, area.width(), gh));
        }
        y = step(y, h, spacing);
        rect
    });
    (panes, gaps)
}

/// How leftover space is placed along the split axis, once [`Constraint`]s
/// are resolved.
///
/// Only matters when the resolved pane sizes sum to less than `area`'s
/// length; passed to [`split_v_flex`]/[`split_h_flex`].
///
/// [`split_v`]/[`split_h`] always behave like [`Start`](Self::Start): any
/// leftover space trails after the last pane, unclaimed. This matches their
/// existing documented behavior, so adding `Flex` does not change them.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Flex {
    /// Panes are packed at the start of the area; leftover space trails
    /// after the last pane. The default, and what [`split_v`]/[`split_h`] use.
    #[default]
    Start,
    /// Panes are packed at the end of the area; leftover space leads before
    /// the first pane.
    End,
    /// Leftover space is split evenly before and after the panes.
    Center,
    /// Leftover space is distributed as gaps between panes (none before the
    /// first or after the last). No-op with fewer than two panes.
    SpaceBetween,
    /// Leftover space is distributed as equal-width gaps around every pane,
    /// including before the first and after the last.
    SpaceAround,
}

/// Compute each pane's starting offset along an axis of `total` cells for
/// the resolved `sizes`, per `flex`. Companion to [`solve`]; used by
/// [`split_v_flex`]/[`split_h_flex`].
///
/// Returns a [`SmallBuf`], not a `Vec`, so the common small-split case does not pay for a heap
/// allocation here either (same rationale as `solve`'s scratch buffers).
fn place(total: u16, sizes: &[u16], flex: Flex) -> SmallBuf<u16, STACK_CAP> {
    let content: u16 = sizes.iter().fold(0u16, |a, &b| a.saturating_add(b));
    let slack = total.saturating_sub(content);
    let n = sizes.len();
    let mut offsets: SmallBuf<u16, STACK_CAP> = SmallBuf::with_capacity(n);

    let packed_from = |start: u16, offsets: &mut SmallBuf<u16, STACK_CAP>| {
        let mut pos = start;
        for &s in sizes {
            offsets.push(pos);
            pos = pos.saturating_add(s);
        }
    };

    match flex {
        Flex::End => packed_from(slack, &mut offsets),
        Flex::Center => packed_from(slack / 2, &mut offsets),
        Flex::SpaceBetween if n > 1 => {
            // `n` is the number of panes in one layout split, nowhere near `u16::MAX` in any
            // realistic UI.
            #[allow(clippy::cast_possible_truncation)]
            let gaps = n as u16 - 1;
            let gap = slack / gaps;
            let mut extra = slack % gaps;
            let mut pos = 0;
            for (i, &s) in sizes.iter().enumerate() {
                offsets.push(pos);
                pos = pos.saturating_add(s);
                if i + 1 < n {
                    pos = pos.saturating_add(gap + u16::from(extra > 0));
                    extra = extra.saturating_sub(1);
                }
            }
        }
        Flex::Start | Flex::SpaceBetween => packed_from(0, &mut offsets),
        Flex::SpaceAround => {
            // `n` is the number of panes in one layout split, nowhere near `u16::MAX` in any
            // realistic UI.
            #[allow(clippy::cast_possible_truncation)]
            let gaps = n as u16 + 1;
            let unit = slack / gaps;
            let mut extra = slack % gaps;
            let mut pos = unit + u16::from(extra > 0);
            extra = extra.saturating_sub(u16::from(extra > 0));
            for &s in sizes {
                offsets.push(pos);
                pos = pos.saturating_add(s);
                pos = pos.saturating_add(unit + u16::from(extra > 0));
                extra = extra.saturating_sub(u16::from(extra > 0));
            }
        }
    }

    offsets
}

/// Const-generic sibling of [`place`], used by [`split_v_n_flex`]/[`split_h_n_flex`]. Same
/// algorithm, but into a fixed-size `[u16; N]` so it never allocates, for any `N`.
fn place_n<const N: usize>(total: u16, sizes: &[u16; N], flex: Flex) -> [u16; N] {
    let content: u16 = sizes.iter().fold(0u16, |a, &b| a.saturating_add(b));
    let slack = total.saturating_sub(content);
    let mut offsets = [0u16; N];

    let packed_from = |start: u16, offsets: &mut [u16; N]| {
        let mut pos = start;
        for (o, &s) in offsets.iter_mut().zip(sizes.iter()) {
            *o = pos;
            pos = pos.saturating_add(s);
        }
    };

    match flex {
        Flex::End => packed_from(slack, &mut offsets),
        Flex::Center => packed_from(slack / 2, &mut offsets),
        Flex::SpaceBetween if N > 1 => {
            // `N` is the number of panes in one layout split, nowhere near `u16::MAX` in any
            // realistic UI.
            #[allow(clippy::cast_possible_truncation)]
            let gaps = N as u16 - 1;
            let gap = slack / gaps;
            let mut extra = slack % gaps;
            let mut pos = 0;
            for (i, &s) in sizes.iter().enumerate() {
                offsets[i] = pos;
                pos = pos.saturating_add(s);
                if i + 1 < N {
                    pos = pos.saturating_add(gap + u16::from(extra > 0));
                    extra = extra.saturating_sub(1);
                }
            }
        }
        Flex::Start | Flex::SpaceBetween => packed_from(0, &mut offsets),
        Flex::SpaceAround => {
            // `N` is the number of panes in one layout split, nowhere near `u16::MAX` in any
            // realistic UI.
            #[allow(clippy::cast_possible_truncation)]
            let gaps = N as u16 + 1;
            let unit = slack / gaps;
            let mut extra = slack % gaps;
            let mut pos = unit + u16::from(extra > 0);
            extra = extra.saturating_sub(u16::from(extra > 0));
            for (i, &s) in sizes.iter().enumerate() {
                offsets[i] = pos;
                pos = pos.saturating_add(s);
                pos = pos.saturating_add(unit + u16::from(extra > 0));
                extra = extra.saturating_sub(u16::from(extra > 0));
            }
        }
    }

    offsets
}

/// Split `area` into stacked rows top-to-bottom, like [`split_v`], but with
/// explicit control over how leftover space is placed via [`Flex`].
///
/// Never panics, for the same reason as [`split_v`]: every offset is computed with
/// [`saturating_add`](u16::saturating_add)/[`saturating_sub`](u16::saturating_sub).
#[must_use]
pub fn split_v_flex(area: Rect, constraints: &[Constraint], flex: Flex) -> Vec<Rect> {
    let sizes = solve(area.height(), constraints);
    let offsets = place(area.height(), &sizes, flex);
    offsets
        .iter()
        .copied()
        .zip(sizes.iter().copied())
        .map(|(y, h)| Rect::new(area.left(), area.top().saturating_add(y), area.width(), h))
        .collect()
}

/// Split `area` into stacked rows top-to-bottom, like [`split_v_n`], but with explicit control
/// over how leftover space is placed via [`Flex`], like [`split_v_flex`].
///
/// Never allocates, for any `N`; never panics, for the same reason as [`split_v_flex`].
#[must_use]
pub fn split_v_n_flex<const N: usize>(
    area: Rect,
    constraints: [Constraint; N],
    flex: Flex,
) -> [Rect; N] {
    let sizes = solve_n(area.height(), &constraints);
    let offsets = place_n(area.height(), &sizes, flex);
    core::array::from_fn(|i| {
        Rect::new(
            area.left(),
            area.top().saturating_add(offsets[i]),
            area.width(),
            sizes[i],
        )
    })
}

/// Split `area` into columns left-to-right, like [`split_h`], but with
/// explicit control over how leftover space is placed via [`Flex`].
///
/// Never panics, for the same reason as [`split_h`]: every offset is computed with
/// [`saturating_add`](u16::saturating_add)/[`saturating_sub`](u16::saturating_sub).
#[must_use]
pub fn split_h_flex(area: Rect, constraints: &[Constraint], flex: Flex) -> Vec<Rect> {
    let sizes = solve(area.width(), constraints);
    let offsets = place(area.width(), &sizes, flex);
    offsets
        .iter()
        .copied()
        .zip(sizes.iter().copied())
        .map(|(x, w)| Rect::new(area.left().saturating_add(x), area.top(), w, area.height()))
        .collect()
}

/// Split `area` into columns left-to-right, like [`split_h_n`], but with explicit control over
/// how leftover space is placed via [`Flex`], like [`split_h_flex`].
///
/// Never allocates, for any `N`; never panics, for the same reason as [`split_h_flex`].
#[must_use]
pub fn split_h_n_flex<const N: usize>(
    area: Rect,
    constraints: [Constraint; N],
    flex: Flex,
) -> [Rect; N] {
    let sizes = solve_n(area.width(), &constraints);
    let offsets = place_n(area.width(), &sizes, flex);
    core::array::from_fn(|i| {
        Rect::new(
            area.left().saturating_add(offsets[i]),
            area.top(),
            sizes[i],
            area.height(),
        )
    })
}

/// Compute a `width`×`height` [`Rect`] centered within `screen`.
///
/// `width`/`height` are clamped down to `screen`'s own dimensions if larger,
/// so the result never extends past `screen`'s edges: a modal, dialog, or
/// tooltip box built from this is always fully on-screen, even on a
/// terminal too small to fit the box's requested size. Pure layout math: no
/// drawing, no `Terminal`. Pairs with `panel`/`modal` in `retroglyph-ui`
/// (the `draw` module) for a centered, bordered box.
///
/// Never panics: the clamp and centering offsets are computed with saturating arithmetic, so a
/// zero-size `screen`, `width`, or `height` resolves to a zero-size or edge-pinned rect instead
/// of under/overflowing.
#[must_use]
pub fn centered_rect(screen: Rect, width: u16, height: u16) -> Rect {
    let width = width.min(screen.width());
    let height = height.min(screen.height());
    let x = screen.left().saturating_add((screen.width() - width) / 2);
    let y = screen.top().saturating_add((screen.height() - height) / 2);
    Rect::new(x, y, width, height)
}

/// Which side of an anchor rect a panel prefers to open on, for [`anchored_rect`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Side {
    /// Open above the anchor (panel's bottom edge touches the anchor's top edge).
    Above,
    /// Open below the anchor (panel's top edge touches the anchor's bottom edge). The usual
    /// choice for a dropdown under a menu label or a field.
    Below,
    /// Open to the left of the anchor (panel's right edge touches the anchor's left edge).
    Left,
    /// Open to the right of the anchor (panel's left edge touches the anchor's right edge).
    Right,
}

impl Side {
    /// The side to fall back to when this side doesn't have room, per [`anchored_rect`].
    const fn opposite(self) -> Self {
        match self {
            Self::Above => Self::Below,
            Self::Below => Self::Above,
            Self::Left => Self::Right,
            Self::Right => Self::Left,
        }
    }
}

/// Place a `size` panel adjacent to `anchor`, preferring `side`, flipping to the opposite side
/// when there isn't room, and clamped to stay within `bounds`.
///
/// `side` decides which edge of `anchor` the panel opens from: [`Side::Below`]/[`Side::Above`]
/// place the panel's left edge at `anchor`'s left edge and stack it vertically off `anchor`'s
/// bottom/top edge; [`Side::Right`]/[`Side::Left`] place the panel's top edge at `anchor`'s top
/// edge and lay it out horizontally off `anchor`'s right/left edge. If the preferred side doesn't
/// have enough room within `bounds` (the panel's far edge would fall outside `bounds` on that
/// axis) but the opposite side does, the panel opens on the opposite side instead; if neither
/// side has room, the preferred side is kept and clamped like the fitting case. Once a side is
/// chosen, the panel is clamped along the perpendicular axis so it never runs past `bounds`'
/// edges: this is the three-line clamp a hand-rolled dropdown would otherwise repeat
/// (`x.min(bounds.right() - width).max(bounds.left())`), applied to whichever axis `side` didn't
/// already pin.
///
/// `size` is clamped down to `bounds`' own dimensions if larger, so the result is always fully
/// within `bounds`, the same guarantee [`centered_rect`] makes for a centered box.
///
/// Pure layout math: no drawing, no `Terminal`. Callers still own sizing (deciding `size` from
/// content, with a floor/ceiling) and overflow (scrolling when content is taller than the
/// resulting rect); this only answers where the rect goes.
///
/// Never panics: every offset is computed with saturating arithmetic, so a degenerate `anchor`,
/// `size`, or `bounds` (zero width/height, or `anchor` outside `bounds`) resolves to a clamped,
/// zero-size-or-larger rect instead of under/overflowing.
///
/// # Examples
///
/// ```
/// use retroglyph_core::grid::{Rect, Size};
/// use retroglyph_ui::{Side, anchored_rect};
///
/// let bounds = Rect::new(0, 0, 40, 20);
/// let anchor = Rect::new(5, 5, 10, 1); // e.g. a menu label
/// let rect = anchored_rect(anchor, Size::new(12, 4), Side::Below, bounds);
/// assert_eq!(rect, Rect::new(5, 6, 12, 4));
/// ```
#[must_use]
pub fn anchored_rect(anchor: Rect, size: Size, preferred: Side, bounds: Rect) -> Rect {
    let width = size.width().min(bounds.width());
    let height = size.height().min(bounds.height());

    // `checked_sub` (not `saturating_sub`): a saturated 0 would make an anchor too close to
    // `bounds`' start edge for `height`/`width` look like it fits with room to spare.
    let fits = |candidate: Side| match candidate {
        Side::Above => {
            anchor.top() <= bounds.bottom()
                && anchor
                    .top()
                    .checked_sub(height)
                    .is_some_and(|t| t >= bounds.top())
        }
        Side::Below => anchor.bottom().saturating_add(height) <= bounds.bottom(),
        Side::Left => {
            anchor.left() <= bounds.right()
                && anchor
                    .left()
                    .checked_sub(width)
                    .is_some_and(|l| l >= bounds.left())
        }
        Side::Right => anchor.right().saturating_add(width) <= bounds.right(),
    };
    let resolved = if fits(preferred) || !fits(preferred.opposite()) {
        preferred
    } else {
        preferred.opposite()
    };

    let (x, y) = match resolved {
        Side::Above => {
            let x = anchor
                .left()
                .min(bounds.right().saturating_sub(width))
                .max(bounds.left());
            let y = anchor
                .top()
                .saturating_sub(height)
                .min(bounds.bottom().saturating_sub(height))
                .max(bounds.top());
            (x, y)
        }
        Side::Below => {
            let x = anchor
                .left()
                .min(bounds.right().saturating_sub(width))
                .max(bounds.left());
            let y = anchor
                .bottom()
                .min(bounds.bottom().saturating_sub(height))
                .max(bounds.top());
            (x, y)
        }
        Side::Left => {
            let x = anchor
                .left()
                .saturating_sub(width)
                .min(bounds.right().saturating_sub(width))
                .max(bounds.left());
            let y = anchor
                .top()
                .min(bounds.bottom().saturating_sub(height))
                .max(bounds.top());
            (x, y)
        }
        Side::Right => {
            let x = anchor
                .right()
                .min(bounds.right().saturating_sub(width))
                .max(bounds.left());
            let y = anchor
                .top()
                .min(bounds.bottom().saturating_sub(height))
                .max(bounds.top());
            (x, y)
        }
    };

    Rect::new(x, y, width, height)
}

#[cfg(test)]
mod tests {
    use alloc::vec;

    use super::*;

    #[test]
    fn vertical_split_sums_and_clamps() {
        let area = Rect::new(0, 0, 20, 10);
        let panes = split_v(
            area,
            &[
                Constraint::Fixed(1),
                Constraint::Fill(1),
                Constraint::Fixed(1),
            ],
        );
        assert_eq!(panes.len(), 3);
        // Heights: 1 + 8 + 1 = 10, exactly filling the area.
        assert_eq!(panes[0].height(), 1);
        assert_eq!(panes[1].height(), 8);
        assert_eq!(panes[2].height(), 1);
        // Panes are contiguous and never exceed the area bottom.
        assert_eq!(panes[0].top(), 0);
        assert_eq!(panes[1].top(), 1);
        assert_eq!(panes[2].top(), 9);
        assert_eq!(panes[2].bottom(), area.bottom());
        // Width is preserved across all panes.
        for p in &panes {
            assert_eq!(p.width(), 20);
        }
    }

    #[test]
    fn horizontal_percent_and_fill() {
        let area = Rect::new(0, 0, 100, 5);
        let panes = split_h(area, &[Constraint::Percent(30), Constraint::Fill(1)]);
        assert_eq!(panes[0].width(), 30);
        assert_eq!(panes[1].width(), 70);
        assert_eq!(panes[0].left(), 0);
        assert_eq!(panes[1].left(), 30);
        assert_eq!(panes[1].right(), area.right());
    }

    #[test]
    fn horizontal_ratio_and_fill() {
        let area = Rect::new(0, 0, 100, 5);
        let panes = split_h(area, &[Constraint::Ratio(3, 10), Constraint::Fill(1)]);
        assert_eq!(panes[0].width(), 30);
        assert_eq!(panes[1].width(), 70);
    }

    #[test]
    fn ratio_zero_denominator_resolves_to_zero() {
        let area = Rect::new(0, 0, 100, 5);
        let panes = split_h(area, &[Constraint::Ratio(1, 0), Constraint::Fill(1)]);
        assert_eq!(panes[0].width(), 0);
        assert_eq!(panes[1].width(), 100);
    }

    #[test]
    fn ratio_over_one_clamps_to_total() {
        let area = Rect::new(0, 0, 100, 5);
        let panes = split_h(area, &[Constraint::Ratio(3, 2)]);
        assert_eq!(panes[0].width(), 100);
    }

    #[test]
    fn fill_remainder_distributes_evenly() {
        let area = Rect::new(0, 0, 10, 1);
        // 10 cells across 3 fills: 4, 3, 3 (leftover goes to the front).
        let panes = split_h(
            area,
            &[
                Constraint::Fill(1),
                Constraint::Fill(1),
                Constraint::Fill(1),
            ],
        );
        let widths: Vec<u16> = panes.iter().map(Rect::width).collect();
        assert_eq!(widths, vec![4, 3, 3]);
        assert_eq!(widths.iter().sum::<u16>(), 10);
    }

    #[test]
    fn oversized_fixed_is_clamped() {
        let area = Rect::new(0, 0, 5, 3);
        // Requested 10 + 10 but only 5 columns exist: first takes all, rest zero.
        let panes = split_h(area, &[Constraint::Fixed(10), Constraint::Fixed(10)]);
        assert_eq!(panes[0].width(), 5);
        assert_eq!(panes[1].width(), 0);
        // No pane extends past the area.
        for p in &panes {
            assert!(p.right() <= area.right());
        }
    }

    #[test]
    fn no_fill_leaves_gap() {
        let area = Rect::new(0, 0, 10, 4);
        let panes = split_v(area, &[Constraint::Fixed(2), Constraint::Fixed(2)]);
        // Only 4 of 10 rows consumed; that is fine, panes still fit.
        assert_eq!(panes[0].height(), 2);
        assert_eq!(panes[1].height(), 2);
        assert_eq!(panes[1].bottom(), 4);
    }

    #[test]
    fn min_gets_at_least_its_floor_plus_a_share() {
        let area = Rect::new(0, 0, 10, 1);
        // Min(3) and Fill both get an equal share (5 each) of the full 10
        // cells, since Min's floor is reserved up front and then also
        // shares in distributing the remaining 7: Min ends up with
        // 3 (floor) + 4 (share, rounded up) = 7, Fill gets the other 3.
        let panes = split_h(area, &[Constraint::Min(3), Constraint::Fill(1)]);
        let widths: Vec<u16> = panes.iter().map(Rect::width).collect();
        assert_eq!(widths, vec![7, 3]);
        assert_eq!(widths.iter().sum::<u16>(), 10);
    }

    #[test]
    fn min_floor_holds_when_share_would_be_smaller() {
        let area = Rect::new(0, 0, 10, 1);
        // Three flexible panes would each get ~3, but Min(4) guarantees 4:
        // its floor (4) plus an equal share of the remaining 6 across all
        // three (2 each) gives Min(4) a total of 6, leaving 2 each for the
        // two Fill panes.
        let panes = split_h(
            area,
            &[Constraint::Min(4), Constraint::Fill(1), Constraint::Fill(1)],
        );
        let widths: Vec<u16> = panes.iter().map(Rect::width).collect();
        assert_eq!(widths[0], 6);
        assert_eq!(widths[1], 2);
        assert_eq!(widths[2], 2);
        assert_eq!(widths.iter().sum::<u16>(), 10);
    }

    #[test]
    fn max_caps_its_share_and_leaves_the_rest_unclaimed() {
        let area = Rect::new(0, 0, 10, 1);
        // Fill and Max(2) would each get 5; Max(2) is capped, and its extra
        // 3 cells are left unclaimed (no redistribution), not given to Fill.
        let panes = split_h(area, &[Constraint::Fill(1), Constraint::Max(2)]);
        let widths: Vec<u16> = panes.iter().map(Rect::width).collect();
        assert_eq!(widths, vec![5, 2]);
        assert_eq!(widths.iter().sum::<u16>(), 7);
    }

    #[test]
    fn weighted_fill_splits_proportionally() {
        let area = Rect::new(0, 0, 12, 1);
        // Fill(2) claims twice the share of Fill(1): 4 and 8 of 12.
        let panes = split_h(area, &[Constraint::Fill(1), Constraint::Fill(2)]);
        let widths: Vec<u16> = panes.iter().map(Rect::width).collect();
        assert_eq!(widths, vec![4, 8]);
        assert_eq!(widths.iter().sum::<u16>(), 12);
    }

    #[test]
    fn weighted_fill_at_weight_one_matches_equal_distribution() {
        let area = Rect::new(0, 0, 10, 1);
        // Every pane weighing the same value (not just 1) still divides
        // evenly, since distribution is by weight *ratio*, not magnitude.
        let panes = split_h(
            area,
            &[
                Constraint::Fill(5),
                Constraint::Fill(5),
                Constraint::Fill(5),
            ],
        );
        let widths: Vec<u16> = panes.iter().map(Rect::width).collect();
        assert_eq!(widths, vec![4, 3, 3]);
        assert_eq!(widths.iter().sum::<u16>(), 10);
    }

    #[test]
    fn weighted_fill_leftover_goes_to_the_largest_fractional_share() {
        let area = Rect::new(0, 0, 10, 1);
        // Ideal shares are 30/7 ~= 4.29, 20/7 ~= 2.86, 20/7 ~= 2.86. Floors are
        // 4, 2, 2 (sum 8); the 2 leftover cells go to the panes with the
        // largest fractional remainder, in this case the two Fill(2)s tied
        // ahead of Fill(3), not to the first pane in the slice.
        let panes = split_h(
            area,
            &[
                Constraint::Fill(3),
                Constraint::Fill(2),
                Constraint::Fill(2),
            ],
        );
        let widths: Vec<u16> = panes.iter().map(Rect::width).collect();
        assert_eq!(widths, vec![4, 3, 3]);
        assert_eq!(widths.iter().sum::<u16>(), 10);
    }

    #[test]
    fn fill_weight_zero_claims_no_share_of_the_remainder() {
        let area = Rect::new(0, 0, 10, 1);
        let panes = split_h(area, &[Constraint::Fill(0), Constraint::Fill(1)]);
        let widths: Vec<u16> = panes.iter().map(Rect::width).collect();
        assert_eq!(widths, vec![0, 10]);
    }

    #[test]
    fn all_fill_weights_zero_leaves_the_remainder_unclaimed() {
        let area = Rect::new(0, 0, 10, 1);
        let panes = split_h(area, &[Constraint::Fill(0), Constraint::Fill(0)]);
        let widths: Vec<u16> = panes.iter().map(Rect::width).collect();
        assert_eq!(widths, vec![0, 0]);
    }

    #[test]
    fn weighted_fill_mixes_with_min_and_max_at_weight_one() {
        let area = Rect::new(0, 0, 20, 1);
        // Fill(3) claims 3 parts of the 6-way weight pool (3 + 1 + 1 + 1 = 6);
        // Min(2) and Max(10) each claim 1 part like before. Remainder after
        // Min's floor: 20 - 2 = 18, split 3:1:1:1 -> 9, 3, 3, 3; Min ends at
        // 2 + 3 = 5.
        let panes = split_h(
            area,
            &[
                Constraint::Fill(3),
                Constraint::Min(2),
                Constraint::Fill(1),
                Constraint::Max(10),
            ],
        );
        let widths: Vec<u16> = panes.iter().map(Rect::width).collect();
        assert_eq!(widths, vec![9, 5, 3, 3]);
        assert_eq!(widths.iter().sum::<u16>(), 20);
    }

    #[test]
    fn flex_start_matches_split_v() {
        let area = Rect::new(0, 0, 10, 4);
        let constraints = [Constraint::Fixed(2), Constraint::Fixed(2)];
        let legacy = split_v(area, &constraints);
        let flexed = split_v_flex(area, &constraints, Flex::Start);
        assert_eq!(legacy, flexed);
    }

    #[test]
    fn flex_end_pushes_leftover_before_the_panes() {
        let area = Rect::new(0, 0, 10, 10);
        let panes = split_v_flex(
            area,
            &[Constraint::Fixed(2), Constraint::Fixed(2)],
            Flex::End,
        );
        // 6 rows of slack lead before the first pane.
        assert_eq!(panes[0].top(), 6);
        assert_eq!(panes[1].top(), 8);
        assert_eq!(panes[1].bottom(), 10);
    }

    #[test]
    fn flex_center_splits_leftover_around_the_panes() {
        let area = Rect::new(0, 0, 10, 10);
        let panes = split_v_flex(area, &[Constraint::Fixed(4)], Flex::Center);
        // 6 rows of slack, 3 leading before the single pane.
        assert_eq!(panes[0].top(), 3);
        assert_eq!(panes[0].bottom(), 7);
    }

    #[test]
    fn flex_space_between_puts_leftover_between_panes_only() {
        let area = Rect::new(0, 0, 10, 1);
        let panes = split_h_flex(
            area,
            &[Constraint::Fixed(2), Constraint::Fixed(2)],
            Flex::SpaceBetween,
        );
        // 6 cells of slack become a single gap between the two panes.
        assert_eq!(panes[0].left(), 0);
        assert_eq!(panes[0].right(), 2);
        assert_eq!(panes[1].left(), 8);
        assert_eq!(panes[1].right(), 10);
    }

    #[test]
    fn flex_space_around_puts_equal_gaps_at_both_edges() {
        let area = Rect::new(0, 0, 9, 1);
        let panes = split_h_flex(area, &[Constraint::Fixed(3)], Flex::SpaceAround);
        // 6 cells of slack split into 2 gaps (before and after) of 3 each.
        assert_eq!(panes[0].left(), 3);
        assert_eq!(panes[0].right(), 6);
    }

    #[test]
    fn spaced_split_carves_out_gaps_between_panes() {
        let area = Rect::new(0, 0, 59, 6);
        let (panes, gaps) = split_h_spaced(
            area,
            &[
                Constraint::Fill(1),
                Constraint::Fill(1),
                Constraint::Fill(1),
            ],
            1,
        );
        assert_eq!(panes.len(), 3);
        let widths: Vec<u16> = panes.iter().map(Rect::width).collect();
        assert_eq!(widths, vec![19, 19, 19]);
        // Adjacent panes are separated by exactly one gap cell, not touching.
        assert_eq!(panes[1].left(), panes[0].right() + 1);
        assert_eq!(panes[2].left(), panes[1].right() + 1);
        // One gap rect between each adjacent pair of panes, filling exactly the empty cell.
        assert_eq!(gaps.len(), 2);
        assert_eq!(
            gaps[0],
            Rect::new(panes[0].right(), area.top(), 1, area.height())
        );
        assert_eq!(
            gaps[1],
            Rect::new(panes[1].right(), area.top(), 1, area.height())
        );
    }

    #[test]
    fn spaced_split_resolves_percent_against_the_post_gap_axis() {
        let area = Rect::new(0, 0, 100, 1);
        let (panes, _) = split_h_spaced(
            area,
            &[Constraint::Percent(50), Constraint::Percent(50)],
            10,
        );
        let widths: Vec<u16> = panes.iter().map(Rect::width).collect();
        assert_eq!(widths, vec![45, 45]);

        let (panes, _) = split_h_spaced(
            area,
            &[Constraint::Ratio(1, 2), Constraint::Ratio(1, 2)],
            10,
        );
        let widths: Vec<u16> = panes.iter().map(Rect::width).collect();
        assert_eq!(widths, vec![45, 45]);
    }

    #[test]
    fn spaced_split_falls_back_with_one_pane_or_no_spacing() {
        let area = Rect::new(0, 0, 10, 1);
        assert_eq!(
            split_h_spaced(area, &[Constraint::Fill(1)], 1),
            (split_h(area, &[Constraint::Fill(1)]), Vec::new())
        );
        assert_eq!(
            split_h_spaced(area, &[Constraint::Fill(1), Constraint::Fill(1)], 0),
            (
                split_h(area, &[Constraint::Fill(1), Constraint::Fill(1)]),
                Vec::new()
            )
        );
    }

    #[test]
    fn vertical_spaced_split_matches_horizontal_shape() {
        let area = Rect::new(0, 0, 6, 59);
        let (panes, gaps) = split_v_spaced(
            area,
            &[
                Constraint::Fill(1),
                Constraint::Fill(1),
                Constraint::Fill(1),
            ],
            1,
        );
        let heights: Vec<u16> = panes.iter().map(Rect::height).collect();
        assert_eq!(heights, vec![19, 19, 19]);
        assert_eq!(panes[1].top(), panes[0].bottom() + 1);
        assert_eq!(gaps.len(), 2);
        assert_eq!(
            gaps[0],
            Rect::new(area.left(), panes[0].bottom(), area.width(), 1)
        );
    }

    #[test]
    fn overlap_spacing_shares_one_edge_cell_between_panes() {
        let area = Rect::new(0, 0, 60, 6);
        let (panes, gaps) = split_h_spaced(
            area,
            &[Constraint::Fill(1), Constraint::Fill(1)],
            Spacing::Overlap(1),
        );
        assert_eq!(panes.len(), 2);
        // The panes claim the full area between them and share exactly one column.
        assert_eq!(panes[0].left(), area.left());
        assert_eq!(panes[1].right(), area.right());
        assert_eq!(panes[1].left(), panes[0].right() - 1);
        // The gap rect is the shared column both panes draw over.
        assert_eq!(gaps.len(), 1);
        assert_eq!(
            gaps[0],
            Rect::new(panes[0].right() - 1, area.top(), 1, area.height())
        );
    }

    #[test]
    fn overlap_spacing_works_vertically_and_with_more_than_two_panes() {
        let area = Rect::new(0, 0, 6, 61);
        let (panes, gaps) = split_v_spaced(area, &[Constraint::Fill(1); 3], Spacing::Overlap(1));
        assert_eq!(panes.len(), 3);
        assert_eq!(panes[0].top(), area.top());
        assert_eq!(panes[2].bottom(), area.bottom());
        assert_eq!(panes[1].top(), panes[0].bottom() - 1);
        assert_eq!(panes[2].top(), panes[1].bottom() - 1);
        assert_eq!(gaps.len(), 2);
    }

    #[test]
    fn overlap_spacing_falls_back_with_one_pane_or_zero_overlap() {
        let area = Rect::new(0, 0, 10, 1);
        assert_eq!(
            split_h_spaced(area, &[Constraint::Fill(1)], Spacing::Overlap(1)),
            (split_h(area, &[Constraint::Fill(1)]), Vec::new())
        );
        assert_eq!(
            split_h_spaced(
                area,
                &[Constraint::Fill(1), Constraint::Fill(1)],
                Spacing::Overlap(0)
            ),
            (
                split_h(area, &[Constraint::Fill(1), Constraint::Fill(1)]),
                Vec::new()
            )
        );
    }

    #[test]
    fn split_h_n_spaced_matches_split_h_spaced_with_overlap() {
        let area = Rect::new(0, 0, 60, 6);
        let constraints = [Constraint::Fill(1); 2];
        let (vec_panes, vec_gaps) = split_h_spaced(area, &constraints, Spacing::Overlap(1));
        let ([a, b], gaps) = split_h_n_spaced(area, constraints, Spacing::Overlap(1));
        assert_eq!(vec_panes, vec![a, b]);
        assert_eq!(vec_gaps, gaps);
    }

    #[test]
    fn centered_rect_centers_within_the_screen() {
        let screen = Rect::new(0, 0, 20, 10);
        let r = centered_rect(screen, 10, 4);
        assert_eq!(r, Rect::new(5, 3, 10, 4));
    }

    #[test]
    fn centered_rect_clamps_to_the_screen_size_when_larger() {
        let screen = Rect::new(0, 0, 20, 10);
        let r = centered_rect(screen, 100, 100);
        assert_eq!(r, Rect::new(0, 0, 20, 10));
    }

    #[test]
    fn centered_rect_respects_a_non_origin_screen() {
        let screen = Rect::new(5, 5, 20, 10);
        let r = centered_rect(screen, 10, 4);
        assert_eq!(r, Rect::new(10, 8, 10, 4));
    }

    #[test]
    fn centered_rect_does_not_overflow_on_a_far_off_screen() {
        // retroglyph#729: `screen.left() + (screen.width() - width) / 2` used to overflow `u16`
        // once `screen.left()` was large enough, even though `width`/`height` themselves fit.
        let screen = Rect::new(50_000, 0, 40_000, 10);
        let r = centered_rect(screen, 10, 4);
        assert_eq!(r, Rect::new(u16::MAX, 3, 10, 4));
    }

    #[test]
    fn anchored_rect_opens_below_when_preferred() {
        let bounds = Rect::new(0, 0, 40, 20);
        let anchor = Rect::new(5, 5, 10, 1);
        let r = anchored_rect(anchor, Size::new(12, 4), Side::Below, bounds);
        assert_eq!(r, Rect::new(5, 6, 12, 4));
    }

    #[test]
    fn anchored_rect_opens_above_when_preferred() {
        let bounds = Rect::new(0, 0, 40, 20);
        let anchor = Rect::new(5, 10, 10, 1);
        let r = anchored_rect(anchor, Size::new(12, 4), Side::Above, bounds);
        assert_eq!(r, Rect::new(5, 6, 12, 4));
    }

    #[test]
    fn anchored_rect_flips_below_to_above_when_there_is_no_room_below() {
        let bounds = Rect::new(0, 0, 40, 20);
        // Anchor near the bottom: no room for a 4-tall panel below, but there is above.
        let anchor = Rect::new(5, 18, 10, 1);
        let r = anchored_rect(anchor, Size::new(12, 4), Side::Below, bounds);
        assert_eq!(r, Rect::new(5, 14, 12, 4));
    }

    #[test]
    fn anchored_rect_flips_above_to_below_when_there_is_no_room_above() {
        let bounds = Rect::new(0, 0, 40, 20);
        // Anchor near the top: no room for a 4-tall panel above, but there is below.
        let anchor = Rect::new(5, 1, 10, 1);
        let r = anchored_rect(anchor, Size::new(12, 4), Side::Above, bounds);
        assert_eq!(r, Rect::new(5, 2, 12, 4));
    }

    #[test]
    fn anchored_rect_keeps_preferred_side_when_neither_side_has_room() {
        let bounds = Rect::new(0, 0, 40, 3);
        let anchor = Rect::new(5, 1, 10, 1);
        // Neither above nor below fits the panel (bounds is only 3 rows tall); the panel's
        // height is itself first clamped down to bounds.height() (3), stays on the preferred
        // Below side, and its clamped-height rect is then pulled up to fit inside bounds.
        let r = anchored_rect(anchor, Size::new(12, 4), Side::Below, bounds);
        assert_eq!(r, Rect::new(5, 0, 12, 3));
    }

    #[test]
    fn anchored_rect_clamps_to_the_right_bounds_edge() {
        let bounds = Rect::new(0, 0, 20, 20);
        // Anchor near the right edge: a 12-wide panel starting at anchor.left() (15) would run
        // past bounds.right() (20), so it's pulled left to stay inside.
        let anchor = Rect::new(15, 5, 4, 1);
        let r = anchored_rect(anchor, Size::new(12, 4), Side::Below, bounds);
        assert_eq!(r, Rect::new(8, 6, 12, 4));
    }

    #[test]
    fn anchored_rect_clamps_to_the_left_bounds_edge() {
        // A non-origin bounds so an anchor can sit to the left of bounds.left() itself.
        let bounds = Rect::new(5, 0, 20, 20);
        let anchor = Rect::new(2, 5, 2, 1);
        let r = anchored_rect(anchor, Size::new(12, 4), Side::Below, bounds);
        assert_eq!(r, Rect::new(5, 6, 12, 4));
    }

    #[test]
    fn anchored_rect_opens_to_the_right_and_clamps_vertically() {
        let bounds = Rect::new(0, 0, 40, 10);
        // Anchor near the bottom: a 6-tall panel starting at anchor.top() would run past
        // bounds.bottom(), so it's pulled up to stay inside.
        let anchor = Rect::new(5, 8, 6, 1);
        let r = anchored_rect(anchor, Size::new(8, 6), Side::Right, bounds);
        assert_eq!(r, Rect::new(11, 4, 8, 6));
    }

    #[test]
    fn anchored_rect_opens_to_the_left() {
        let bounds = Rect::new(0, 0, 40, 10);
        let anchor = Rect::new(20, 2, 6, 1);
        let r = anchored_rect(anchor, Size::new(8, 4), Side::Left, bounds);
        assert_eq!(r, Rect::new(12, 2, 8, 4));
    }

    #[test]
    fn anchored_rect_above_stays_within_bounds_for_an_anchor_below_them() {
        let bounds = Rect::new(0, 0, 40, 10);
        // Anchor scrolled far below bounds (e.g. a list row scrolled past the viewport).
        let anchor = Rect::new(5, 50, 10, 1);
        let r = anchored_rect(anchor, Size::new(12, 4), Side::Above, bounds);
        assert!(r.top() >= bounds.top() && r.bottom() <= bounds.bottom());
    }

    #[test]
    fn anchored_rect_left_stays_within_bounds_for_an_anchor_right_of_them() {
        let bounds = Rect::new(0, 0, 10, 10);
        // Anchor scrolled far right of bounds.
        let anchor = Rect::new(50, 2, 2, 1);
        let r = anchored_rect(anchor, Size::new(4, 2), Side::Left, bounds);
        assert!(r.left() >= bounds.left() && r.right() <= bounds.right());
    }

    #[test]
    fn anchored_rect_clamps_size_down_to_bounds() {
        let bounds = Rect::new(0, 0, 10, 10);
        let anchor = Rect::new(2, 2, 2, 1);
        let r = anchored_rect(anchor, Size::new(100, 100), Side::Below, bounds);
        assert_eq!(r.width(), 10);
        assert_eq!(r.height(), 10);
        assert!(r.left() >= bounds.left() && r.right() <= bounds.right());
        assert!(r.top() >= bounds.top() && r.bottom() <= bounds.bottom());
    }

    #[test]
    fn anchored_rect_handles_a_zero_size_bounds() {
        let bounds = Rect::new(3, 3, 0, 0);
        let anchor = Rect::new(3, 3, 0, 0);
        let r = anchored_rect(anchor, Size::new(5, 5), Side::Below, bounds);
        assert_eq!(r, Rect::new(3, 3, 0, 0));
    }

    /// `solve`'s internal `SmallBuf` scratch buffers stay on the stack for up to `STACK_CAP`
    /// (8) items and fall back to the heap past that; this covers a constraint count past the
    /// cap (all-`Fixed`, so `sizes` alone crosses into the heap path) and asserts the result is
    /// identical in shape to what an all-`Vec` implementation would produce: every pane keeps its
    /// requested size and the total exactly fills the area.
    #[test]
    fn split_beyond_stack_cap_matches_small_case_behavior() {
        let panes = 20; // > STACK_CAP, and far below u16::MAX
        #[allow(clippy::cast_possible_truncation)]
        let panes_u16 = panes as u16;
        let area = Rect::new(0, 0, panes_u16, 1);
        let constraints = vec![Constraint::Fixed(1); panes];
        let widths: Vec<u16> = split_h(area, &constraints)
            .iter()
            .map(Rect::width)
            .collect();
        assert_eq!(widths, vec![1u16; panes]);
        assert_eq!(widths.iter().sum::<u16>(), panes_u16);
    }

    /// Same as above, but exercises the flexible-pane path (`flexible`/`shares`/`fracs`/`order`
    /// scratch buffers) past `STACK_CAP` by mixing every `Constraint` kind across enough panes
    /// that the flexible subset alone also crosses the stack cap.
    #[test]
    fn weighted_fill_beyond_stack_cap_matches_small_case_proportions() {
        let area = Rect::new(0, 0, 100, 1);
        // 20 Fill(1) panes: same proportional-split logic as the 2/3-pane cases above, just at
        // a pane count that forces every scratch buffer in `solve` onto the heap.
        let constraints = vec![Constraint::Fill(1); 20];
        let widths: Vec<u16> = split_h(area, &constraints)
            .iter()
            .map(Rect::width)
            .collect();
        assert_eq!(widths.len(), 20);
        assert_eq!(widths.iter().sum::<u16>(), 100);
        // Equal weights distribute as evenly as integer division allows: every width is 5.
        assert!(widths.iter().all(|&w| w == 5));
    }

    #[test]
    fn split_v_n_matches_split_v() {
        let area = Rect::new(0, 0, 20, 10);
        let constraints = [
            Constraint::Fixed(1),
            Constraint::Fill(1),
            Constraint::Fixed(1),
        ];
        let vec_panes = split_v(area, &constraints);
        let [a, b, c] = split_v_n(area, constraints);
        assert_eq!(vec_panes, vec![a, b, c]);
    }

    #[test]
    fn split_h_n_matches_split_h() {
        let area = Rect::new(0, 0, 100, 5);
        let constraints = [Constraint::Percent(30), Constraint::Fill(1)];
        let vec_panes = split_h(area, &constraints);
        let [left, right] = split_h_n(area, constraints);
        assert_eq!(vec_panes, vec![left, right]);
    }

    #[test]
    fn split_v_n_destructures_by_compile_time_count() {
        let area = Rect::new(0, 0, 12, 12);
        let [header, body, footer] = split_v_n(
            area,
            [
                Constraint::Fixed(2),
                Constraint::Fill(1),
                Constraint::Fixed(2),
            ],
        );
        assert_eq!(header.height(), 2);
        assert_eq!(body.height(), 8);
        assert_eq!(footer.height(), 2);
        assert_eq!(header.top(), 0);
        assert_eq!(body.top(), 2);
        assert_eq!(footer.top(), 10);
    }

    #[test]
    fn split_h_n_flex_matches_split_h_flex() {
        let area = Rect::new(0, 0, 10, 1);
        let constraints = [Constraint::Fixed(2), Constraint::Fixed(2)];
        let vec_panes = split_h_flex(area, &constraints, Flex::SpaceBetween);
        let [a, b] = split_h_n_flex(area, constraints, Flex::SpaceBetween);
        assert_eq!(vec_panes, vec![a, b]);
    }

    #[test]
    fn split_v_n_flex_matches_split_v_flex() {
        let area = Rect::new(0, 0, 10, 10);
        let constraints = [Constraint::Fixed(2), Constraint::Fixed(2)];
        let vec_panes = split_v_flex(area, &constraints, Flex::End);
        let [a, b] = split_v_n_flex(area, constraints, Flex::End);
        assert_eq!(vec_panes, vec![a, b]);
    }

    #[test]
    fn split_h_n_spaced_matches_split_h_spaced() {
        let area = Rect::new(0, 0, 59, 6);
        let constraints = [Constraint::Fill(1); 3];
        let (vec_panes, vec_gaps) = split_h_spaced(area, &constraints, 1);
        let ([a, b, c], gaps) = split_h_n_spaced(area, constraints, 1);
        assert_eq!(vec_panes, vec![a, b, c]);
        assert_eq!(vec_gaps, gaps);
    }

    #[test]
    fn split_v_n_spaced_matches_split_v_spaced() {
        let area = Rect::new(0, 0, 6, 59);
        let constraints = [Constraint::Fill(1); 3];
        let (vec_panes, vec_gaps) = split_v_spaced(area, &constraints, 1);
        let ([a, b, c], gaps) = split_v_n_spaced(area, constraints, 1);
        assert_eq!(vec_panes, vec![a, b, c]);
        assert_eq!(vec_gaps, gaps);
    }

    #[test]
    fn split_h_n_spaced_falls_back_with_one_pane_or_no_spacing() {
        let area = Rect::new(0, 0, 10, 1);
        assert_eq!(
            split_h_n_spaced(area, [Constraint::Fill(1)], 1),
            ([split_h_n(area, [Constraint::Fill(1)])[0]], Vec::new())
        );
        let constraints = [Constraint::Fill(1), Constraint::Fill(1)];
        assert_eq!(
            split_h_n_spaced(area, constraints, 0),
            (split_h_n(area, constraints), Vec::new())
        );
    }

    /// `solve_n` never falls back to the heap, unlike `solve`'s `SmallBuf`; this covers a pane
    /// count past `STACK_CAP` to confirm that holds true and produces the same result `solve`
    /// would.
    #[test]
    fn split_h_n_beyond_stack_cap_matches_split_h() {
        let area = Rect::new(0, 0, 20, 1);
        let constraints = [Constraint::Fixed(1); 20];
        let vec_panes = split_h(area, &constraints);
        let arr_panes = split_h_n(area, constraints);
        assert_eq!(vec_panes, arr_panes.to_vec());
    }
}