retroglyph-ui 0.5.0

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
//! Constraint-based `Rect` splitter for multi-panel UIs.
//!
//! [`split_v`]/[`split_h`] split a [`Rect`] into stacked rows or side-by-side columns from a
//! slice of [`Constraint`]s; that pair plus `Constraint` is the whole entry point for the plain
//! case. Spacing and leftover-space placement are opt-in knobs on [`Layout`] instead of separate
//! named functions:
//!
//! ```
//! use retroglyph_core::grid::Rect;
//! use retroglyph_ui::layout::{Constraint, Flex, Layout};
//!
//! let area = Rect::new(0, 0, 20, 10);
//! let panes = Layout::vertical([Constraint::Fixed(1), Constraint::Fill(1)])
//!     .spacing(1)
//!     .flex(Flex::Center)
//!     .split(area);
//! assert_eq!(panes.len(), 2);
//! ```
//!
//! [`Layout::spacing`] carves a fixed-cell gap (or [`Spacing::Overlap`]) between every adjacent
//! pair of panes, without the caller having to interleave `Constraint::Fixed(spacing)` gap
//! constraints and filter them back out by hand; [`Layout::split_with_gaps`] returns those gap
//! rects alongside the content panes so a caller can draw dividers in them without recomputing
//! the gap positions. [`Layout::flex`] controls where leftover space goes once constraints are
//! resolved; see [`Flex`].
//!
//! 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).
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]
    }
}

/// A flexible pane (`Fill`/`Min`/`Max`) tracked by `solve` while distributing the remainder.
///
/// `pane` is the constraint's index in the original slice, so records can be freely reordered
/// (e.g. sorted by `frac`) without losing track of which pane each record belongs to.
#[derive(Clone, Copy, Default)]
struct Flexible {
    pane: usize,
    weight: u16,
    cap: Option<u16>,
    share: u32,
    frac: u32,
}

/// 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<Flexible, STACK_CAP> = SmallBuf::with_capacity(constraints.len());
    for (i, c) in constraints.iter().enumerate() {
        match c {
            Constraint::Fill(weight) => flexible.push(Flexible {
                pane: i,
                weight: *weight,
                cap: None,
                ..Flexible::default()
            }),
            Constraint::Min(_) => flexible.push(Flexible {
                pane: i,
                weight: 1,
                cap: None,
                ..Flexible::default()
            }),
            Constraint::Max(cap) => flexible.push(Flexible {
                pane: i,
                weight: 1,
                cap: Some(*cap),
                ..Flexible::default()
            }),
            Constraint::Fixed(_) | Constraint::Percent(_) | Constraint::Ratio(_, _) => {}
        }
    }
    if !flexible.is_empty() {
        let remainder = total.saturating_sub(used);
        let total_weight: u32 = flexible.iter().map(|f| u32::from(f.weight)).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 floor_sum: u32 = 0;
            for f in flexible.iter_mut() {
                let product = u32::from(remainder) * u32::from(f.weight);
                f.share = product / total_weight;
                f.frac = product % total_weight;
                floor_sum += f.share;
            }
            let mut leftover = u32::from(remainder).saturating_sub(floor_sum);
            flexible.sort_unstable_by(|a, b| b.frac.cmp(&a.frac).then(a.pane.cmp(&b.pane)));
            for f in flexible.iter_mut() {
                if leftover == 0 {
                    break;
                }
                f.share += 1;
                leftover -= 1;
            }
            for f in flexible.iter() {
                // `f.share` 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 = f.share as u16;
                let grown = sizes[f.pane].saturating_add(share);
                sizes[f.pane] = f.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::layout::{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 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::layout::{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()
}

/// 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 [`Layout::spacing`] accepts either a bare cell count or a [`Spacing`] directly.
#[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)
    }
}

/// The axis length to solve `count` panes' [`Constraint`]s against once [`Layout::spacing`] is
/// set: `total` with `count - 1` gaps of `spacing.cells()` reserved out ([`Spacing::Space`]) or
/// handed back in ([`Spacing::Overlap`]).
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),
    }
}

/// 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. Used by [`Layout::split_with_gaps`].
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)
}

/// 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; set via [`Layout::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 `Layout`'s internal resolve
/// step.
///
/// 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
}

/// Which axis a [`Layout`] splits along.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Axis {
    Vertical,
    Horizontal,
}

/// Builder for [`split_v`]/[`split_h`] with optional spacing and leftover-space placement.
///
/// `Layout::vertical`/[`Layout::horizontal`] take the [`Constraint`]s (anything that converts to
/// a `Vec<Constraint>`: an array literal, a `Vec`, or a `Box<[Constraint]>`); [`Layout::spacing`]
/// and [`Layout::flex`] are optional chained calls that default to no spacing and
/// [`Flex::Start`](Flex::default), matching plain [`split_v`]/[`split_h`]. [`Layout::split`]
/// resolves the panes; [`Layout::split_with_gaps`] also returns the gap [`Rect`]s a caller would
/// draw dividers into, the same pair [`split_h`]-with-spacing used to return.
///
/// # Examples
///
/// ```
/// use retroglyph_core::grid::Rect;
/// use retroglyph_ui::layout::{Constraint, Flex, Layout};
///
/// let area = Rect::new(0, 0, 20, 10);
/// let panes = Layout::vertical([Constraint::Fixed(1), Constraint::Fill(1)])
///     .spacing(1)
///     .flex(Flex::Center)
///     .split(area);
/// assert_eq!(panes.len(), 2);
/// ```
#[derive(Clone, Debug)]
pub struct Layout {
    axis: Axis,
    constraints: Vec<Constraint>,
    spacing: Spacing,
    flex: Flex,
}

impl Layout {
    /// Split into stacked rows top-to-bottom, like [`split_v`].
    #[must_use]
    pub fn vertical(constraints: impl Into<Vec<Constraint>>) -> Self {
        Self {
            axis: Axis::Vertical,
            constraints: constraints.into(),
            spacing: Spacing::Space(0),
            flex: Flex::Start,
        }
    }

    /// Split into columns left-to-right, like [`split_h`].
    #[must_use]
    pub fn horizontal(constraints: impl Into<Vec<Constraint>>) -> Self {
        Self {
            axis: Axis::Horizontal,
            constraints: constraints.into(),
            spacing: Spacing::Space(0),
            flex: Flex::Start,
        }
    }

    /// Carve a fixed-cell gap (or [`Spacing::Overlap`]) between every adjacent pair of panes; see
    /// [`Spacing`]. Defaults to no spacing, matching plain [`split_v`]/[`split_h`].
    #[must_use]
    pub fn spacing(mut self, spacing: impl Into<Spacing>) -> Self {
        self.spacing = spacing.into();
        self
    }

    /// Control where leftover space is placed once constraints are resolved; see [`Flex`].
    /// Defaults to [`Flex::Start`], matching plain [`split_v`]/[`split_h`].
    #[must_use]
    pub const fn flex(mut self, flex: Flex) -> Self {
        self.flex = flex;
        self
    }

    /// Resolve each pane's offset and size along the split axis: `axis_len` after
    /// [`spacing`](Self::spacing) is reserved/handed back, [`solve`]d against `constraints`, then
    /// [`place`]d per [`flex`](Self::flex), with the per-pane spacing delta folded back in.
    fn resolve(&self, axis_len: u16) -> (Vec<u16>, Vec<u16>) {
        let gap = if self.constraints.len() >= 2 {
            self.spacing.cells()
        } else {
            0
        };
        let total = if gap == 0 {
            axis_len
        } else {
            spaced_total(axis_len, self.constraints.len(), self.spacing)
        };
        let sizes = solve(total, &self.constraints);
        let mut offsets: Vec<u16> = place(total, &sizes, self.flex).to_vec();
        if gap != 0 {
            for (i, offset) in offsets.iter_mut().enumerate() {
                // `i` is a pane index in one layout split, nowhere near `u16::MAX` in any
                // realistic UI.
                #[allow(clippy::cast_possible_truncation)]
                let delta = gap.saturating_mul(i as u16);
                *offset = match self.spacing {
                    Spacing::Space(_) => offset.saturating_add(delta),
                    Spacing::Overlap(_) => offset.saturating_sub(delta),
                };
            }
        }
        (offsets, sizes.to_vec())
    }

    /// Split `area` into panes along [`vertical`](Self::vertical)/[`horizontal`](Self::horizontal)
    /// per the builder's constraints, spacing, and flex.
    ///
    /// Never panics, for the same reason as [`split_v`]/[`split_h`].
    #[must_use]
    pub fn split(&self, area: Rect) -> Vec<Rect> {
        match self.axis {
            Axis::Vertical => {
                let (offsets, sizes) = self.resolve(area.height());
                offsets
                    .iter()
                    .zip(sizes.iter())
                    .map(|(&y, &h)| {
                        Rect::new(area.left(), area.top().saturating_add(y), area.width(), h)
                    })
                    .collect()
            }
            Axis::Horizontal => {
                let (offsets, sizes) = self.resolve(area.width());
                offsets
                    .iter()
                    .zip(sizes.iter())
                    .map(|(&x, &w)| {
                        Rect::new(area.left().saturating_add(x), area.top(), w, area.height())
                    })
                    .collect()
            }
        }
    }

    /// Split `area` like [`split`](Self::split), and also return the gap [`Rect`]s between every
    /// adjacent pair of panes carved out by [`spacing`](Self::spacing).
    ///
    /// 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 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. `gaps` is empty with fewer than two panes or zero spacing/overlap.
    ///
    /// # Examples
    ///
    /// ```
    /// use retroglyph_core::grid::Rect;
    /// use retroglyph_ui::layout::{Constraint, Layout};
    ///
    /// let area = Rect::new(0, 0, 59, 6);
    /// let (panes, gaps) = Layout::horizontal([Constraint::Fill(1); 3])
    ///     .spacing(1)
    ///     .split_with_gaps(area);
    /// 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));
    /// ```
    #[must_use]
    pub fn split_with_gaps(&self, area: Rect) -> (Vec<Rect>, Vec<Rect>) {
        let panes = self.split(area);
        if self.spacing.cells() == 0 || panes.len() < 2 {
            return (panes, Vec::new());
        }
        let gaps = match self.axis {
            Axis::Vertical => panes
                .windows(2)
                .map(|w| {
                    let (gy, gh) = spacer_span(w[0].top(), w[0].height(), self.spacing);
                    Rect::new(area.left(), gy, area.width(), gh)
                })
                .collect(),
            Axis::Horizontal => panes
                .windows(2)
                .map(|w| {
                    let (gx, gw) = spacer_span(w[0].left(), w[0].width(), self.spacing);
                    Rect::new(gx, area.top(), gw, area.height())
                })
                .collect(),
        };
        (panes, gaps)
    }
}

/// 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)]
#[non_exhaustive]
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::layout::{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 (ax, ay) = match resolved {
        Side::Above => (anchor.left(), anchor.top().saturating_sub(height)),
        Side::Below => (anchor.left(), anchor.bottom()),
        Side::Left => (anchor.left().saturating_sub(width), anchor.top()),
        Side::Right => (anchor.right(), anchor.top()),
    };
    let x = ax
        .min(bounds.right().saturating_sub(width))
        .max(bounds.left());
    let y = ay
        .min(bounds.bottom().saturating_sub(height))
        .max(bounds.top());

    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 tied_fractional_shares_go_to_the_earlier_pane_first() {
        let area = Rect::new(0, 0, 20, 1);
        // Fill(1), Min(1), Fill(1): weight pool is 1+1+1=3, remainder is 20.
        // Ideal shares are 20/3 ~= 6.67 each, so all three fracs tie at 2/3;
        // floors are 6, 6, 6 (sum 18), leaving 2 leftover cells that must go
        // to the two EARLIEST panes in `pane` order (index 0 then 1), not to
        // whichever pane a hash/sort happened to place first.
        let panes = split_h(
            area,
            &[Constraint::Fill(1), Constraint::Min(1), Constraint::Fill(1)],
        );
        let widths: Vec<u16> = panes.iter().map(Rect::width).collect();
        assert_eq!(widths, vec![7, 7, 6]);
        assert_eq!(widths.iter().sum::<u16>(), 20);
    }

    #[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 = Layout::vertical(constraints).flex(Flex::Start).split(area);
        assert_eq!(legacy, flexed);
    }

    #[test]
    fn flex_end_pushes_leftover_before_the_panes() {
        let area = Rect::new(0, 0, 10, 10);
        let panes = Layout::vertical([Constraint::Fixed(2), Constraint::Fixed(2)])
            .flex(Flex::End)
            .split(area);
        // 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 = Layout::vertical([Constraint::Fixed(4)])
            .flex(Flex::Center)
            .split(area);
        // 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 = Layout::horizontal([Constraint::Fixed(2), Constraint::Fixed(2)])
            .flex(Flex::SpaceBetween)
            .split(area);
        // 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 = Layout::horizontal([Constraint::Fixed(3)])
            .flex(Flex::SpaceAround)
            .split(area);
        // 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) = Layout::horizontal([
            Constraint::Fill(1),
            Constraint::Fill(1),
            Constraint::Fill(1),
        ])
        .spacing(1)
        .split_with_gaps(area);
        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, _) = Layout::horizontal([Constraint::Percent(50), Constraint::Percent(50)])
            .spacing(10)
            .split_with_gaps(area);
        let widths: Vec<u16> = panes.iter().map(Rect::width).collect();
        assert_eq!(widths, vec![45, 45]);

        let (panes, _) = Layout::horizontal([Constraint::Ratio(1, 2), Constraint::Ratio(1, 2)])
            .spacing(10)
            .split_with_gaps(area);
        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!(
            Layout::horizontal([Constraint::Fill(1)])
                .spacing(1)
                .split_with_gaps(area),
            (split_h(area, &[Constraint::Fill(1)]), Vec::new())
        );
        assert_eq!(
            Layout::horizontal([Constraint::Fill(1), Constraint::Fill(1)])
                .spacing(0)
                .split_with_gaps(area),
            (
                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) = Layout::vertical([
            Constraint::Fill(1),
            Constraint::Fill(1),
            Constraint::Fill(1),
        ])
        .spacing(1)
        .split_with_gaps(area);
        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) = Layout::horizontal([Constraint::Fill(1), Constraint::Fill(1)])
            .spacing(Spacing::Overlap(1))
            .split_with_gaps(area);
        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) = Layout::vertical([Constraint::Fill(1); 3])
            .spacing(Spacing::Overlap(1))
            .split_with_gaps(area);
        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!(
            Layout::horizontal([Constraint::Fill(1)])
                .spacing(Spacing::Overlap(1))
                .split_with_gaps(area),
            (split_h(area, &[Constraint::Fill(1)]), Vec::new())
        );
        assert_eq!(
            Layout::horizontal([Constraint::Fill(1), Constraint::Fill(1)])
                .spacing(Spacing::Overlap(0))
                .split_with_gaps(area),
            (
                split_h(area, &[Constraint::Fill(1), Constraint::Fill(1)]),
                Vec::new()
            )
        );
    }

    #[test]
    fn spacing_and_flex_compose() {
        // Center-flexed with a 1-cell gap: the two panes fill 9 of the 10 available cells
        // (10 minus the one gap cell), leaving 1 cell of slack split around them by `Flex::Center`,
        // then the gap is threaded back in between the panes.
        let area = Rect::new(0, 0, 10, 1);
        let panes = Layout::horizontal([Constraint::Fixed(4), Constraint::Fixed(4)])
            .spacing(1)
            .flex(Flex::Center)
            .split(area);
        assert_eq!(panes[0].left(), 0);
        assert_eq!(panes[0].right(), 4);
        assert_eq!(panes[1].left(), 5);
        assert_eq!(panes[1].right(), 9);
    }

    #[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 layout_split_matches_plain_split_v_and_split_h() {
        let v_area = Rect::new(0, 0, 20, 10);
        let v_constraints = [
            Constraint::Fixed(1),
            Constraint::Fill(1),
            Constraint::Fixed(1),
        ];
        assert_eq!(
            Layout::vertical(v_constraints).split(v_area),
            split_v(v_area, &v_constraints)
        );

        let h_area = Rect::new(0, 0, 100, 5);
        let h_constraints = [Constraint::Percent(30), Constraint::Fill(1)];
        assert_eq!(
            Layout::horizontal(h_constraints).split(h_area),
            split_h(h_area, &h_constraints)
        );
    }
}