frus-widgets 0.4.0

frus — declarative widget tree
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
//! The **constraint boxes**: widgets whose whole job is to change the size their
//! child is allowed, or made, to be.
//!
//! - [`SizedBox`] — a fixed box, or one that fills, or one that hugs.
//! - [`ConstrainedBox`] — floors and ceilings on either axis.
//! - [`IntrinsicWidth`] / [`IntrinsicHeight`] — a box the size its content would
//!   *like* to be, rather than the size the space on offer suggests.
//! - [`OverflowBox`] — a child laid out to constraints of its own, which it may
//!   exceed, painted over whatever is around it.
//! - [`LimitedBox`] — a ceiling that applies only where the room on offer has no end.
//!
//! The first three are ordinary layout nodes and cost nothing beyond what taffy
//! already does. [`OverflowBox`] is not: its child is laid out **separately**, which
//! is what lets the child be bigger than the box that holds it.

use frus_core::{Alignment, Rect, Scene, Size};
use frus_layout::{Dimension, Style};

use crate::interaction::Status;
use crate::theme::Theme;
use crate::widget::{FillAxes, Widget};

/// A box that **caps its child only where nothing else does**: where the room on offer has no
/// end — down a column's scroll, along a list — the child may take at most `max_width` or
/// `max_height`; where it has one, the box changes nothing.
///
/// ```
/// use frus_widgets::{LimitedBox, Text};
///
/// // A placeholder that asks for all the room, and is 120 px tall in a scrolling list.
/// let _row: LimitedBox<()> = LimitedBox::new(Text::new("Loading")).max_height(120.0);
/// ```
///
/// Without a limit on an axis, that axis is left as it came. The child is never made
/// bigger than it would be: a child that hugs its content still does.
pub struct LimitedBox<Msg = crate::callback::Callback> {
    max: (Option<f32>, Option<f32>),
    children: Vec<Box<dyn Widget<Msg>>>,
}

impl<Msg> LimitedBox<Msg> {
    /// A box around `child`, with no limit yet.
    pub fn new(child: impl Widget<Msg> + 'static) -> Self {
        Self {
            max: (None, None),
            children: vec![Box::new(child)],
        }
    }

    /// The most the child may take across, where the room on offer has no end.
    pub fn max_width(mut self, max: f32) -> Self {
        self.max.0 = Some(max.max(0.0));
        self
    }

    /// The most the child may take down, where the room on offer has no end.
    pub fn max_height(mut self, max: f32) -> Self {
        self.max.1 = Some(max.max(0.0));
        self
    }
}

impl<Msg: Clone> Widget<Msg> for LimitedBox<Msg> {
    fn style(&self) -> Style {
        Style::default()
    }

    fn children(&self) -> &[Box<dyn Widget<Msg>>] {
        &self.children
    }

    fn paint(&self, _bounds: Rect, _status: Status, _theme: &Theme, _scene: &mut Scene) {}

    fn on_click(&self) -> Option<Msg> {
        None
    }

    fn constraints_transform(&self) -> Option<ConstraintsTransform> {
        let rule = |max: Option<f32>| match max {
            Some(max) => AxisConstraint::Limited(max),
            None => AxisConstraint::Loose,
        };
        Some(ConstraintsTransform {
            width: rule(self.max.0),
            height: rule(self.max.1),
            alignment: Alignment::TOP_LEFT,
            report: false,
        })
    }

    fn debug_name(&self) -> &'static str {
        "LimitedBox"
    }
}

/// A box of a given size — or one that fills what it is given, or one that takes
/// only what its child needs.
///
/// `SizedBox::empty()` with a size is also the plainest way to put a gap somewhere
/// that has no gap of its own; with no child it draws nothing at all.
pub struct SizedBox<Msg = crate::callback::Callback> {
    width: Dimension,
    height: Dimension,
    /// The axes it asks all the room on (milestone 599).
    fills: FillAxes,
    children: Vec<Box<dyn Widget<Msg>>>,
}

impl<Msg> SizedBox<Msg> {
    /// An empty box, `Auto` on both axes until a size is set.
    pub fn empty() -> Self {
        Self {
            width: Dimension::Auto,
            height: Dimension::Auto,
            fills: FillAxes::NONE,
            children: Vec::new(),
        }
    }

    /// A box holding `child`, its size still to be chosen.
    pub fn new(child: impl Widget<Msg> + 'static) -> Self {
        let mut boxed = Self::empty();
        boxed.children.push(Box::new(child));
        boxed
    }

    /// A `side`×`side` box holding `child`.
    pub fn square(side: f32, child: impl Widget<Msg> + 'static) -> Self {
        Self::new(child).width(side).height(side)
    }

    /// A box that **fills** the space on offer, on both axes, and hands it to
    /// `child`.
    ///
    /// All of it wherever the parent has it to give: a whole page, a whole card, the width
    /// of a column even inside a scroll. Along a row's or a column's own direction, where
    /// the line is shared with other children, it is only as long as its child; wrap it in
    /// [`Expanded`](crate::Expanded) for the rest of the line.
    pub fn expand(child: impl Widget<Msg> + 'static) -> Self {
        let mut boxed = Self::new(child);
        boxed.fills = FillAxes::BOTH;
        boxed
    }

    /// A box that takes **only what its child needs**, on both axes — the useful
    /// opposite of [`SizedBox::expand`] inside a container that would otherwise
    /// stretch it.
    pub fn shrink(child: impl Widget<Msg> + 'static) -> Self {
        Self::new(child)
    }

    /// Sets the width, in logical pixels.
    pub fn width(self, width: f32) -> Self {
        self.width_dimension(Dimension::Length(width))
    }

    /// Sets the height, in logical pixels.
    pub fn height(self, height: f32) -> Self {
        self.height_dimension(Dimension::Length(height))
    }

    /// Sets the width as a fraction of the parent's (`1.0` = all of it).
    pub fn width_fraction(self, fraction: f32) -> Self {
        self.width_dimension(Dimension::Percent(fraction))
    }

    /// Sets the height as a fraction of the parent's.
    pub fn height_fraction(self, fraction: f32) -> Self {
        self.height_dimension(Dimension::Percent(fraction))
    }

    fn width_dimension(mut self, width: Dimension) -> Self {
        self.width = width;
        self
    }

    fn height_dimension(mut self, height: Dimension) -> Self {
        self.height = height;
        self
    }

    /// Sets the child, replacing any already there.
    pub fn child(mut self, child: impl Widget<Msg> + 'static) -> Self {
        self.children.clear();
        self.children.push(Box::new(child));
        self
    }
}

impl<Msg: Clone> Widget<Msg> for SizedBox<Msg> {
    fn style(&self) -> Style {
        let base = Style {
            width: self.width,
            height: self.height,
            ..Default::default()
        };
        // An expanding box **hands** its child the room it took, as the reference's does
        // with tight constraints: one cell, stretched both ways (milestone 599).
        match self.fills == FillAxes::BOTH {
            true => Style {
                overlap: true,
                align: frus_layout::Align::Stretch,
                ..base
            },
            false => base,
        }
    }

    fn children(&self) -> &[Box<dyn Widget<Msg>>] {
        &self.children
    }

    fn paint(&self, _bounds: Rect, _status: Status, _theme: &Theme, _scene: &mut Scene) {
        // A pure layout widget: it draws nothing of its own.
    }

    fn on_click(&self) -> Option<Msg> {
        None
    }

    /// The room on offer, when it was made to expand. It used to be a percentage of the
    /// parent, which is nothing when the parent is as big as its content: a column inside a
    /// scroll (milestone 599).
    fn fill_axes(&self, _theme: &Theme) -> FillAxes {
        self.fills
    }
}

/// Floors and ceilings on either axis, for a child that would otherwise be free to
/// take any size.
///
/// A floor and a ceiling that are equal make the box **tight**: whatever the child
/// or the space on offer says, that is the size. Set nothing and the box is
/// transparent — it is the constraints that make it worth having, not the box.
pub struct ConstrainedBox<Msg = crate::callback::Callback> {
    min_width: Dimension,
    max_width: Dimension,
    min_height: Dimension,
    max_height: Dimension,
    children: Vec<Box<dyn Widget<Msg>>>,
}

impl<Msg> ConstrainedBox<Msg> {
    /// An unconstrained box holding `child`; the constraints are set from here.
    pub fn new(child: impl Widget<Msg> + 'static) -> Self {
        Self {
            min_width: Dimension::Auto,
            max_width: Dimension::Auto,
            min_height: Dimension::Auto,
            max_height: Dimension::Auto,
            children: vec![Box::new(child)],
        }
    }

    /// The same, for a child that is **already boxed** — what a slot holds once the
    /// caller's type has been erased.
    pub fn new_boxed(child: Box<dyn Widget<Msg>>) -> Self {
        Self {
            min_width: Dimension::Auto,
            max_width: Dimension::Auto,
            min_height: Dimension::Auto,
            max_height: Dimension::Auto,
            children: vec![child],
        }
    }

    /// A box whose floor **is** its ceiling on both axes: exactly `width`×`height`.
    pub fn tight(width: f32, height: f32, child: impl Widget<Msg> + 'static) -> Self {
        Self::new(child)
            .min_width(width)
            .max_width(width)
            .min_height(height)
            .max_height(height)
    }

    /// A box with ceilings only: the child may be anything up to `width`×`height`.
    pub fn loose(width: f32, height: f32, child: impl Widget<Msg> + 'static) -> Self {
        Self::new(child).max_width(width).max_height(height)
    }

    /// The width the box never goes below.
    pub fn min_width(mut self, width: f32) -> Self {
        self.min_width = Dimension::Length(width);
        self
    }

    /// The width the box never goes above.
    pub fn max_width(mut self, width: f32) -> Self {
        self.max_width = Dimension::Length(width);
        self
    }

    /// The height the box never goes below.
    pub fn min_height(mut self, height: f32) -> Self {
        self.min_height = Dimension::Length(height);
        self
    }

    /// The height the box never goes above.
    pub fn max_height(mut self, height: f32) -> Self {
        self.max_height = Dimension::Length(height);
        self
    }
}

impl<Msg: Clone> Widget<Msg> for ConstrainedBox<Msg> {
    fn style(&self) -> Style {
        Style {
            min_width: self.min_width,
            max_width: self.max_width,
            min_height: self.min_height,
            max_height: self.max_height,
            ..Default::default()
        }
    }

    fn children(&self) -> &[Box<dyn Widget<Msg>>] {
        &self.children
    }

    fn paint(&self, _bounds: Rect, _status: Status, _theme: &Theme, _scene: &mut Scene) {}

    fn on_click(&self) -> Option<Msg> {
        None
    }
}

/// Which axis a box takes from its content's **preferred** size rather than from
/// the space on offer.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum IntrinsicAxis {
    /// The width.
    Width,
    /// The height.
    Height,
}

/// A box sized to what its content would **like** to be.
///
/// The usual case: a column of buttons that should all be as wide as the widest
/// label, and no wider. Stretching gives them the whole column; hugging gives each
/// its own width; only an intrinsic width gives them all the widest one.
///
/// It is not free. The content is measured **once more**, unconstrained, before it
/// is laid out for real — which is why it is a widget you reach for deliberately and
/// not a property every box carries. Nested one inside another, the cost multiplies.
pub struct Intrinsic<Msg = crate::callback::Callback> {
    axis: IntrinsicAxis,
    step: Option<f32>,
    children: Vec<Box<dyn Widget<Msg>>>,
}

/// A box as wide as its content would like to be. See [`Intrinsic`].
pub type IntrinsicWidth<Msg> = Intrinsic<Msg>;
/// A box as tall as its content would like to be. See [`Intrinsic`].
pub type IntrinsicHeight<Msg> = Intrinsic<Msg>;

impl<Msg> Intrinsic<Msg> {
    /// A box as **wide** as `child` would like to be.
    pub fn width(child: impl Widget<Msg> + 'static) -> Self {
        Self {
            axis: IntrinsicAxis::Width,
            step: None,
            children: vec![Box::new(child)],
        }
    }

    /// A box as **tall** as `child` would like to be.
    pub fn height(child: impl Widget<Msg> + 'static) -> Self {
        Self {
            axis: IntrinsicAxis::Height,
            step: None,
            children: vec![Box::new(child)],
        }
    }

    /// Rounds the measured size **up** to a multiple of `step`.
    ///
    /// For a box whose width should change in steps rather than continuously — a
    /// label that grows a character at a time makes everything beside it jitter.
    pub fn step(mut self, step: f32) -> Self {
        self.step = (step > 0.0).then_some(step);
        self
    }

    /// The axis this box takes from its content.
    pub fn axis(&self) -> IntrinsicAxis {
        self.axis
    }

    /// Applies the step rounding to a measured extent.
    pub fn quantise(&self, extent: f32) -> f32 {
        match self.step {
            Some(step) => (extent / step).ceil() * step,
            None => extent,
        }
    }
}

impl<Msg: Clone> Widget<Msg> for Intrinsic<Msg> {
    fn style(&self) -> Style {
        // The measured extent is written into this style by `build_layout`, which is
        // the only place with a runtime to measure against.
        Style::default()
    }

    fn children(&self) -> &[Box<dyn Widget<Msg>>] {
        &self.children
    }

    fn paint(&self, _bounds: Rect, _status: Status, _theme: &Theme, _scene: &mut Scene) {}

    fn on_click(&self) -> Option<Msg> {
        None
    }

    fn intrinsic(&self) -> Option<(IntrinsicAxis, Option<f32>)> {
        Some((self.axis, self.step))
    }
}

/// The constraints an [`OverflowBox`] hands its child, and where the result sits.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Overflow {
    /// Width given to the child; `None` = the box's own width.
    pub width: Option<f32>,
    /// Height given to the child; `None` = the box's own height.
    pub height: Option<f32>,
    /// Lay the child out **unconstrained**, at the size it asks for. Overrides the
    /// two above.
    pub unconstrained: bool,
    /// Lay the child out at the box's width and **the height it asks for** (milestone
    /// 595): a paragraph kept at the width it is shown at and allowed to run below the
    /// box. Overrides `height`.
    pub natural_height: bool,
    /// Where the child sits inside the box, and therefore which way it spills.
    pub alignment: Alignment,
}

/// A child laid out to constraints of **its own**, free to be bigger than the box
/// that holds it, and painted over whatever is around it.
///
/// The box itself takes the size it would have taken with no child at all, so
/// nothing around it moves. What changes is the child: it is laid out separately —
/// at a size given here, or at the size it asks for
/// ([`OverflowBox::unconstrained`]) — then anchored in the box and allowed to spill
/// past its edges.
///
/// This is the escape hatch for a background that should bleed past its slot, or a
/// decoration wider than the row it belongs to. It does **not** clip: put a
/// [`crate::ClipRRect`] above it if the spill should stop somewhere.
pub struct OverflowBox<Msg = crate::callback::Callback> {
    overflow: Overflow,
    children: Vec<Box<dyn Widget<Msg>>>,
}

impl<Msg> OverflowBox<Msg> {
    /// A box that lays `child` out to the sizes given by the builders below,
    /// centred; unset axes keep the box's own size.
    pub fn new(child: impl Widget<Msg> + 'static) -> Self {
        Self {
            overflow: Overflow {
                width: None,
                height: None,
                unconstrained: false,
                natural_height: false,
                alignment: Alignment::CENTER,
            },
            children: vec![Box::new(child)],
        }
    }

    /// A box that lets `child` be **whatever size it asks for**, as if nothing were
    /// constraining it, and centres the result.
    pub fn unconstrained(child: impl Widget<Msg> + 'static) -> Self {
        let mut boxed = Self::new(child);
        boxed.overflow.unconstrained = true;
        boxed
    }

    /// The width to lay the child out at.
    pub fn width(mut self, width: f32) -> Self {
        self.overflow.width = Some(width);
        self
    }

    /// The height to lay the child out at.
    pub fn height(mut self, height: f32) -> Self {
        self.overflow.height = Some(height);
        self
    }

    /// Lays the child out at the box's width and **the height it asks for**, however tall
    /// or short the box is (milestone 595).
    pub fn natural_height(mut self) -> Self {
        self.overflow.natural_height = true;
        self
    }

    /// Where the child sits in the box — and so which edges it spills past.
    pub fn alignment(mut self, alignment: Alignment) -> Self {
        self.overflow.alignment = alignment;
        self
    }
}

impl<Msg: Clone> Widget<Msg> for OverflowBox<Msg> {
    fn style(&self) -> Style {
        // The box takes **the largest size it is allowed**, because its child is laid
        // out separately and so contributes nothing to its size. Left to hug, it would
        // collapse to nothing on the main axis, and the child would be anchored to a
        // box of zero width — spilling equally in both directions from a point.
        Style {
            width: Dimension::Percent(1.0),
            height: Dimension::Percent(1.0),
            ..Default::default()
        }
    }

    fn children(&self) -> &[Box<dyn Widget<Msg>>] {
        &self.children
    }

    fn paint(&self, _bounds: Rect, _status: Status, _theme: &Theme, _scene: &mut Scene) {}

    fn on_click(&self) -> Option<Msg> {
        None
    }

    fn overflow_box(&self) -> Option<Overflow> {
        Some(self.overflow)
    }
}

impl Overflow {
    /// The size to lay the child out at, given the box's own, and whether the
    /// measurement should be unconstrained.
    pub(crate) fn child_size(&self, own: Size) -> Size {
        Size::new(
            self.width.unwrap_or(own.width),
            self.height.unwrap_or(own.height),
        )
    }

    /// Where the child's top-left corner goes, given both sizes.
    pub(crate) fn origin(&self, own: Rect, child: Size) -> (f32, f32) {
        (
            own.x + (own.width - child.width) * self.alignment.fraction_x(),
            own.y + (own.height - child.height) * self.alignment.fraction_y(),
        )
    }
}

/// A box of a **stated size** whose child is laid out at another one, and spills.
///
/// The size given here is what the parent sees and what the neighbours make room for.
/// The child is laid out separately — at the size it asks for, or at one stated with
/// [`SizedOverflowBox::child_size`] — anchored in the box by its alignment, and allowed
/// past every edge.
///
/// It is [`OverflowBox`] with the hole given a size: an overflow box fills whatever it is
/// offered, because nothing else could anchor a child that contributes no size, and this
/// is the form for a slot narrower than the space around it — a 24 px gap in a toolbar
/// showing a 40 px control, a caption strip under an image that reaches past both sides.
///
/// It does **not** clip: put a [`crate::ClipRRect`] above it if the spill should stop.
pub struct SizedOverflowBox<Msg = crate::callback::Callback> {
    width: f32,
    height: f32,
    overflow: Overflow,
    children: Vec<Box<dyn Widget<Msg>>>,
}

impl<Msg> SizedOverflowBox<Msg> {
    /// A `width`×`height` box holding `child`, which is laid out at **its own** natural
    /// size and centred.
    pub fn new(width: f32, height: f32, child: impl Widget<Msg> + 'static) -> Self {
        Self {
            width,
            height,
            overflow: Overflow {
                width: None,
                height: None,
                unconstrained: true,
                natural_height: false,
                alignment: Alignment::CENTER,
            },
            children: vec![Box::new(child)],
        }
    }

    /// Lays the child out at a size of its own rather than at the one it asks for.
    pub fn child_size(mut self, width: f32, height: f32) -> Self {
        self.overflow.unconstrained = false;
        self.overflow.width = Some(width);
        self.overflow.height = Some(height);
        self
    }

    /// Where the child sits in the box — and so which edges it spills past.
    pub fn alignment(mut self, alignment: Alignment) -> Self {
        self.overflow.alignment = alignment;
        self
    }
}

impl<Msg: Clone> Widget<Msg> for SizedOverflowBox<Msg> {
    fn style(&self) -> Style {
        Style {
            width: Dimension::Length(self.width),
            height: Dimension::Length(self.height),
            ..Default::default()
        }
    }

    fn children(&self) -> &[Box<dyn Widget<Msg>>] {
        &self.children
    }

    fn paint(&self, _bounds: Rect, _status: Status, _theme: &Theme, _scene: &mut Scene) {}

    fn on_click(&self) -> Option<Msg> {
        None
    }

    fn overflow_box(&self) -> Option<Overflow> {
        Some(self.overflow)
    }

    fn debug_name(&self) -> &'static str {
        "SizedOverflowBox"
    }
}

/// What a [`ConstraintsTransformBox`] does to **one axis** of the space on offer.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AxisConstraint {
    /// As it came: the child is given the room the parent offered.
    AsGiven,
    /// Taken away: the child is asked how big it would like to be, and may come back
    /// bigger than the room there was.
    Unbounded,
    /// A number of its own, whatever was offered.
    Fixed(f32),
    /// The room on offer as **the most** the child may take, not a size it is handed: a
    /// paragraph wraps at it and is then as wide as its longest line. With no room on offer,
    /// as big as it likes (milestone 598).
    Loose,
    /// As [`Loose`](Self::Loose) where the room on offer is bounded; where it is not, at most
    /// this many pixels. What [`LimitedBox`] does (milestone 598).
    Limited(f32),
}

/// What a [`ConstraintsTransformBox`] gives its child, per axis, and what it does about a
/// child that comes back too big.
///
/// It is a small vocabulary rather than an arbitrary function of the space on offer, and
/// that is a decision worth stating. The layout and the paint walk are two passes over the
/// same tree, and only the first is told what the parent offered: by the time the walk lays
/// the child out, the box has been sized to the child and the offer is not recoverable from
/// it. A function of the offer could not be run again there — and a function run again on
/// the wrong input answers plausibly, which is worse than not answering at all. Each of
/// these three **can** be run again: a fixed number is itself, an unbounded axis is a
/// question with no input, and an axis given as it came produced a child of exactly the
/// box's own size.
///
/// The reference's transform is a closure, and every transform the reference itself ships
/// is one of these three.
#[derive(Clone, Copy, Debug)]
pub struct ConstraintsTransform {
    /// What the child is given across.
    pub width: AxisConstraint,
    /// And down.
    pub height: AxisConstraint,
    /// Where a child smaller than the box sits in it.
    pub alignment: Alignment,
    /// Whether a child that came out **bigger** than the box is reported as an overflow —
    /// the yellow and black band, in debug builds. On by default: a box that transforms its
    /// constraints is asking a question about what fits, and a silent answer is no answer.
    pub report: bool,
}

impl ConstraintsTransform {
    /// Feeds what decides the box's geometry to a layout fingerprint (milestone 593): the
    /// rule on each axis and where the child sits. A transform is data, not a closure, so
    /// two frames that hash alike ask the same question of the same child.
    pub(crate) fn layout_hash<H: std::hash::Hasher>(&self, hasher: &mut H) {
        use std::hash::Hash;
        for axis in [self.width, self.height] {
            match axis {
                AxisConstraint::AsGiven => 0u8.hash(hasher),
                AxisConstraint::Unbounded => 1u8.hash(hasher),
                AxisConstraint::Fixed(v) => {
                    2u8.hash(hasher);
                    v.to_bits().hash(hasher);
                }
                AxisConstraint::Loose => 3u8.hash(hasher),
                AxisConstraint::Limited(v) => {
                    4u8.hash(hasher);
                    v.to_bits().hash(hasher);
                }
            }
        }
        self.alignment.x.to_bits().hash(hasher);
        self.alignment.y.to_bits().hash(hasher);
    }

    /// Both axes as they came, which is the transform that does nothing.
    pub fn new() -> Self {
        Self {
            width: AxisConstraint::AsGiven,
            height: AxisConstraint::AsGiven,
            alignment: Alignment::CENTER,
            report: true,
        }
    }

    /// What the child is given across.
    pub fn width(mut self, width: AxisConstraint) -> Self {
        self.width = width;
        self
    }

    /// What the child is given down.
    pub fn height(mut self, height: AxisConstraint) -> Self {
        self.height = height;
        self
    }

    /// Where a child smaller than the box sits in it.
    pub fn alignment(mut self, alignment: Alignment) -> Self {
        self.alignment = alignment;
        self
    }

    /// Whether a child bigger than the box wears a band. Off is what a deliberate spill
    /// wants.
    pub fn report(mut self, report: bool) -> Self {
        self.report = report;
        self
    }
}

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

impl AxisConstraint {
    /// `(extent, free, filled)` for the **measurement**, given what the layout offered on
    /// this axis — `None` being no limit at all. A bounded axis is either **handed** to the
    /// child (`filled`: a child with no size of its own takes it) or only **allowed** (the
    /// most it may take).
    pub(crate) fn offered(self, offer: Option<f32>) -> (f32, bool, bool) {
        match self {
            AxisConstraint::Unbounded => (0.0, true, false),
            AxisConstraint::Fixed(extent) => (extent.max(0.0), false, true),
            AxisConstraint::AsGiven => match offer {
                Some(extent) => (extent.max(0.0), false, true),
                None => (0.0, true, false),
            },
            AxisConstraint::Loose => match offer {
                Some(extent) => (extent.max(0.0), false, false),
                None => (0.0, true, false),
            },
            AxisConstraint::Limited(most) => match offer {
                Some(extent) => (extent.max(0.0), false, false),
                None => (most.max(0.0), false, false),
            },
        }
    }

    /// `(extent, free)` for the **walk**, given the box the measurement produced.
    ///
    /// It answers the same thing the measurement did, from what is left of it: a fixed
    /// number is itself, an unbounded axis is the same question either way, and an axis
    /// given as it came produced a child of the box's own extent — the box being that child
    /// held to what was offered.
    ///
    /// `(extent, free, filled)`, as [`Self::offered`]. A loose or limited axis produced a box
    /// of the child's own extent, and the child is allowed that extent again, not handed it:
    /// a paragraph that wrapped at the room and is as wide as its longest line wraps at that
    /// line the same way.
    pub(crate) fn at(self, own: f32) -> (f32, bool, bool) {
        match self {
            AxisConstraint::Unbounded => (0.0, true, false),
            AxisConstraint::Fixed(extent) => (extent.max(0.0), false, true),
            AxisConstraint::AsGiven => (own.max(0.0), false, true),
            AxisConstraint::Loose | AxisConstraint::Limited(_) => (own.max(0.0), false, false),
        }
    }
}

/// A box that **changes the space on offer** before its child is laid out in it, and is
/// then as big as what came back — never bigger than what it was itself offered.
///
/// This is the general form of the boxes above, and the one they are special cases of: what
/// the child is given, per axis, said in [`AxisConstraint`]. Taking a ceiling away lets the
/// child be its natural size ([`UnconstrainedBox`]); a fixed number lays it out in a room
/// of that size whatever the parent offered.
///
/// ```ignore
/// // "However tall you need to be" — and a band across the box if that was too tall.
/// ConstraintsTransformBox::new(paragraph).height(AxisConstraint::Unbounded)
/// ```
///
/// A child that comes out bigger than the box **overflows it**: painted past the edges, and
/// reported with the debug band. That is the point of the widget — it asks what the space
/// on offer is doing to the content, and answers on the screen. Turn the band off with
/// [`ConstraintsTransformBox::report`] when the spill is deliberate.
pub struct ConstraintsTransformBox<Msg = crate::callback::Callback> {
    transform: ConstraintsTransform,
    children: Vec<Box<dyn Widget<Msg>>>,
}

impl<Msg> ConstraintsTransformBox<Msg> {
    /// A box holding `child`, with both axes still as they came.
    pub fn new(child: impl Widget<Msg> + 'static) -> Self {
        Self {
            transform: ConstraintsTransform::new(),
            children: vec![Box::new(child)],
        }
    }

    /// What the child is given across.
    pub fn width(mut self, width: AxisConstraint) -> Self {
        self.transform.width = width;
        self
    }

    /// What the child is given down.
    pub fn height(mut self, height: AxisConstraint) -> Self {
        self.transform.height = height;
        self
    }

    /// Where a child smaller than the box sits in it.
    pub fn alignment(mut self, alignment: Alignment) -> Self {
        self.transform.alignment = alignment;
        self
    }

    /// Whether a child bigger than the box wears a band.
    pub fn report(mut self, report: bool) -> Self {
        self.transform.report = report;
        self
    }

    /// A box built from a transform prepared elsewhere.
    pub fn with(child: impl Widget<Msg> + 'static, transform: ConstraintsTransform) -> Self {
        Self {
            transform,
            children: vec![Box::new(child)],
        }
    }
}

impl<Msg: Clone> Widget<Msg> for ConstraintsTransformBox<Msg> {
    fn style(&self) -> Style {
        Style::default()
    }

    fn children(&self) -> &[Box<dyn Widget<Msg>>] {
        &self.children
    }

    fn paint(&self, _bounds: Rect, _status: Status, _theme: &Theme, _scene: &mut Scene) {}

    fn on_click(&self) -> Option<Msg> {
        None
    }

    fn constraints_transform(&self) -> Option<ConstraintsTransform> {
        Some(self.transform)
    }

    fn debug_name(&self) -> &'static str {
        "ConstraintsTransformBox"
    }
}

/// Lets its child be its **natural size** even where the parent offers less — and says so
/// when that does not fit.
///
/// The child is laid out as if nothing were constraining it, and the box is as big as the
/// child, up to the space it was itself offered. Where the child fits, nothing is
/// unusual — the box is simply the child's size, hugging it in a place that would have
/// stretched it. Where it does not, the child is painted past the edges and a band says by
/// how much, in debug builds.
///
/// ```ignore
/// // A row of chips that must not be squashed: too many, and the overflow is visible.
/// UnconstrainedBox::new(Flex::row().child(chip_a).child(chip_b))
/// ```
///
/// That visible failure is the point, and the difference between this and [`OverflowBox`],
/// which spills on purpose and quietly. It is [`ConstraintsTransformBox`] with the
/// constraint taken away, and nothing more.
///
/// [`UnconstrainedBox::axis`] frees **one** axis and leaves the other as it was, which is
/// usually what is wanted: a paragraph that may be as tall as it likes is still as wide as
/// its column.
pub struct UnconstrainedBox;

impl UnconstrainedBox {
    /// Frees both axes.
    #[allow(clippy::new_ret_no_self)]
    pub fn new<Msg: Clone + 'static>(
        child: impl Widget<Msg> + 'static,
    ) -> ConstraintsTransformBox<Msg> {
        ConstraintsTransformBox::new(child)
            .width(AxisConstraint::Unbounded)
            .height(AxisConstraint::Unbounded)
    }

    /// Frees the given axis, and leaves the other one as the parent offered it.
    pub fn axis<Msg: Clone + 'static>(
        child: impl Widget<Msg> + 'static,
        axis: crate::scroll::Axis,
    ) -> ConstraintsTransformBox<Msg> {
        let freed = |free: bool| match free {
            true => AxisConstraint::Unbounded,
            false => AxisConstraint::AsGiven,
        };
        ConstraintsTransformBox::new(child)
            .width(freed(axis.free_x()))
            .height(freed(axis.free_y()))
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    use crate::{build_ui, Container, Flex, InspectorNode, Runtime, Text};
    use frus_core::{Color, Primitive};

    const RED: Color = Color {
        r: 1.0,
        g: 0.0,
        b: 0.0,
        a: 1.0,
    };

    /// A child that fills whatever box it is put in, painted red so the tests below
    /// can read that box off the scene. `Align::Stretch` gives it the cross axis;
    /// `flex(1)` gives it the main one.
    fn filler() -> Container<()> {
        Container::new().flex(1.0).color(RED)
    }

    /// The first red rectangle painted.
    fn red_box<W: Widget<()> + 'static>(root: W, available: Size) -> Rect {
        let runtime = Runtime::default();
        let ui = build_ui(&root, available, &runtime, &Theme::dark());
        ui.scene()
            .primitives()
            .iter()
            .find_map(|p| match p {
                Primitive::Rect { rect, color, .. } if color.r > 0.5 && color.g < 0.5 => {
                    Some(*rect)
                }
                _ => None,
            })
            .expect("the red box")
    }

    #[test]
    fn a_ceiling_stops_a_box_that_would_fill() {
        // Stretched by its column, the box would be 400 wide; capped, it is 120.
        let root = Flex::<()>::column()
            .width(400.0)
            .child(ConstrainedBox::new(filler().height(40.0)).max_width(120.0));
        let rect = red_box(root, Size::new(400.0, 200.0));
        assert!((rect.width - 120.0).abs() < 0.5, "capped: {rect:?}");
    }

    #[test]
    fn a_floor_stops_a_box_that_would_hug() {
        // In a row the box hugs its content, which asks for nothing; the floor is
        // the only thing giving it a width.
        let root = Flex::<()>::row()
            .width(400.0)
            .height(60.0)
            .child(ConstrainedBox::new(filler()).min_width(90.0))
            // Along a row the room is the row's to share out: with a neighbour, an empty
            // box is nothing there, as the reference's is (milestone 633). Alone in the row
            // frus gives it the room instead, where the reference would give it none.
            .child(Container::new().width(10.0).height(10.0));
        let rect = red_box(root, Size::new(400.0, 200.0));
        assert!((rect.width - 90.0).abs() < 0.5, "floored: {rect:?}");
    }

    #[test]
    fn a_tight_box_is_that_size_whatever_is_inside_it() {
        let root = Flex::<()>::column()
            .width(400.0)
            .child(ConstrainedBox::tight(75.0, 33.0, filler()));
        let rect = red_box(root, Size::new(400.0, 200.0));
        assert!(
            (rect.width - 75.0).abs() < 0.5 && (rect.height - 33.0).abs() < 0.5,
            "tight: {rect:?}"
        );
    }

    #[test]
    fn a_sized_box_that_expands_takes_everything_on_offer() {
        let root = Flex::<()>::column()
            .width(400.0)
            .height(200.0)
            .child(SizedBox::expand(filler()));
        let rect = red_box(root, Size::new(400.0, 200.0));
        assert!(
            (rect.width - 400.0).abs() < 0.5 && (rect.height - 200.0).abs() < 0.5,
            "expanded: {rect:?}"
        );
    }

    #[test]
    fn a_sized_box_is_the_size_it_was_given() {
        let root = Flex::<()>::column()
            .width(400.0)
            .child(SizedBox::square(64.0, filler()));
        let rect = red_box(root, Size::new(400.0, 200.0));
        assert!(
            (rect.width - 64.0).abs() < 0.5 && (rect.height - 64.0).abs() < 0.5,
            "square: {rect:?}"
        );
    }

    #[test]
    fn an_intrinsic_width_is_what_the_content_wants_not_what_the_column_offers() {
        // Stretched by the 400 px column, the inner block would be 400 wide. Taken
        // intrinsically, it is as wide as the line inside it — and much less.
        let root = Flex::<()>::column().width(400.0).child(Intrinsic::width(
            Flex::<()>::column()
                .child(Text::new("a short line"))
                .child(Container::new().height(10.0).color(RED)),
        ));
        let rect = red_box(root, Size::new(400.0, 200.0));
        assert!(
            rect.width > 1.0 && rect.width < 380.0,
            "the content's width, not the column's: {rect:?}"
        );
    }

    #[test]
    fn an_intrinsic_width_rounds_up_to_its_step() {
        let step = Intrinsic::<()>::width(Container::new()).step(20.0);
        assert_eq!(step.quantise(1.0), 20.0);
        assert_eq!(step.quantise(20.0), 20.0);
        assert_eq!(step.quantise(21.0), 40.0);
        // With no step, the measurement passes through untouched.
        let plain = Intrinsic::<()>::width(Container::new());
        assert_eq!(plain.quantise(21.0), 21.0);
    }

    #[test]
    fn an_overflowing_child_is_bigger_than_its_box_and_centred_on_it() {
        // A 40 px slot holding a 100 px child: it hangs 30 px off either side.
        let root = Flex::<()>::column().width(400.0).child(
            SizedBox::empty()
                .width(40.0)
                .height(40.0)
                .child(OverflowBox::new(filler()).width(100.0).height(100.0)),
        );
        let rect = red_box(root, Size::new(400.0, 200.0));
        assert!(
            (rect.width - 100.0).abs() < 0.5 && (rect.height - 100.0).abs() < 0.5,
            "the child keeps its own size: {rect:?}"
        );
        assert!(
            rect.x < -29.0 && rect.x > -31.0,
            "centred, spilling: {rect:?}"
        );
    }

    #[test]
    fn an_overflow_box_can_anchor_the_spill_to_one_corner() {
        let root = Flex::<()>::column().width(400.0).child(
            SizedBox::empty().width(40.0).height(40.0).child(
                OverflowBox::new(filler())
                    .width(100.0)
                    .height(100.0)
                    .alignment(Alignment::TOP_LEFT),
            ),
        );
        let rect = red_box(root, Size::new(400.0, 200.0));
        assert!(
            rect.x.abs() < 0.5 && rect.y.abs() < 0.5,
            "anchored top-left, spilling right and down: {rect:?}"
        );
    }

    #[test]
    fn the_box_around_an_overflowing_child_does_not_grow() {
        // The neighbour below sits at 40, not at 100: the box did not grow, which is
        // the whole difference between an overflow and a big child.
        let root = Flex::<()>::column()
            .width(400.0)
            .child(
                SizedBox::empty().width(40.0).height(40.0).child(
                    OverflowBox::new(Container::new().flex(1.0))
                        .width(100.0)
                        .height(100.0),
                ),
            )
            .child(Container::new().width(10.0).height(10.0).color(RED));
        let rect = red_box(root, Size::new(400.0, 300.0));
        assert!((rect.y - 40.0).abs() < 0.5, "the neighbour moved: {rect:?}");
    }

    #[test]
    fn an_unconstrained_child_is_the_size_it_asks_for() {
        // The slot is 20 px; the child asks for 90×30 and gets it.
        let root = Flex::<()>::column().width(400.0).child(
            SizedBox::empty()
                .width(20.0)
                .height(20.0)
                .child(OverflowBox::unconstrained(
                    Container::new().width(90.0).height(30.0).color(RED),
                )),
        );
        let rect = red_box(root, Size::new(400.0, 200.0));
        assert!(
            (rect.width - 90.0).abs() < 0.5 && (rect.height - 30.0).abs() < 0.5,
            "unconstrained: {rect:?}"
        );
    }

    /// The scene and the inspector's boxes, for a tree laid out in `available`.
    fn inspected(root: &dyn Widget<()>, available: Size) -> (crate::Ui<()>, Vec<InspectorNode>) {
        crate::build_ui_inspected(root, available, &Runtime::default(), &Theme::dark())
    }

    /// The box the walk gave the widget named `name` — the box itself, which is the thing
    /// these widgets are about and the one thing the scene does not show.
    fn box_named(nodes: &[InspectorNode], name: &str) -> Rect {
        nodes
            .iter()
            .find(|n| n.name == name)
            .unwrap_or_else(|| panic!("no {name} in {}", crate::dump_tree(nodes)))
            .rect
    }

    /// A red box of a stated size — laid out at whatever it is given, and visible.
    fn red(width: f32, height: f32) -> Container<()> {
        Container::new().width(width).height(height).color(RED)
    }

    /// A column that does **not** stretch its children, so a box that hugs can be seen
    /// hugging.
    fn narrow_column(width: f32) -> Flex<()> {
        Flex::<()>::column()
            .width(width)
            .align(frus_layout::Align::Start)
    }

    #[test]
    fn a_child_that_fits_gives_the_unconstrained_box_its_own_size() {
        let root = narrow_column(400.0).child(UnconstrainedBox::new(red(90.0, 30.0)));
        let (ui, nodes) = inspected(&root, Size::new(400.0, 200.0));
        let own = box_named(&nodes, "ConstraintsTransformBox");
        assert!(
            (own.width - 90.0).abs() < 0.5 && (own.height - 30.0).abs() < 0.5,
            "the box is the child's size: {own:?}"
        );
        assert!(ui.overflows().is_empty(), "nothing ran past anything");
    }

    /// The other half, and the reason the widget is worth having: the child keeps the
    /// size it asked for, the box keeps the size it was offered, and the difference is
    /// **reported** rather than quietly absorbed.
    #[test]
    fn an_unconstrained_child_that_does_not_fit_overflows_and_says_so() {
        let root = narrow_column(100.0).child(UnconstrainedBox::new(red(300.0, 20.0)));
        let (ui, nodes) = inspected(&root, Size::new(100.0, 200.0));
        let child = red_box_in(&ui);
        assert!(
            (child.width - 300.0).abs() < 0.5,
            "the child kept its size: {child:?}"
        );
        let own = box_named(&nodes, "ConstraintsTransformBox");
        assert!(
            (own.width - 100.0).abs() < 0.5,
            "the box kept the room it was offered: {own:?}"
        );
        // Centred, it runs past **both** sides, and both are reported: a band on one of
        // them would say the child was a hundred too wide rather than two.
        let spills = ui.overflows();
        let mut sides: Vec<_> = spills.iter().map(|o| (o.side, o.amount)).collect();
        sides.sort_by_key(|(side, _)| format!("{side:?}"));
        assert_eq!(sides.len(), 2, "two edges: {spills:?}");
        assert_eq!(sides[0].0, frus_layout::Side::Left);
        assert_eq!(sides[1].0, frus_layout::Side::Right);
        assert!(
            sides.iter().all(|(_, amount)| (amount - 100.0).abs() < 0.5),
            "a hundred either side: {spills:?}"
        );
    }

    /// One axis freed, the other left as it was: the child is as tall as it likes and no
    /// wider than the column, which is what a paragraph wants.
    #[test]
    fn freeing_one_axis_leaves_the_other_one_alone() {
        let root = narrow_column(100.0).child(UnconstrainedBox::axis(
            Container::new().height(200.0).color(RED),
            crate::scroll::Axis::Vertical,
        ));
        let (ui, _) = inspected(&root, Size::new(100.0, 80.0));
        let child = red_box_in(&ui);
        assert!(
            (child.width - 100.0).abs() < 0.5,
            "held to the column: {child:?}"
        );
        assert!(
            (child.height - 200.0).abs() < 0.5,
            "and as tall as it asked: {child:?}"
        );
    }

    /// Unbounded is only one of the three things an axis can say: this one gives the
    /// child a hundred pixels of room in a column twice that wide, and the box comes back
    /// the size of what it asked for.
    #[test]
    fn a_transform_can_give_the_child_a_room_of_its_own() {
        let root = narrow_column(200.0).child(
            ConstraintsTransformBox::new(Container::new().height(20.0).color(RED))
                .width(AxisConstraint::Fixed(100.0)),
        );
        let (ui, nodes) = inspected(&root, Size::new(200.0, 200.0));
        let child = red_box_in(&ui);
        assert!(
            (child.width - 100.0).abs() < 0.5,
            "the child was laid out in the room it was given: {child:?}"
        );
        assert!((box_named(&nodes, "ConstraintsTransformBox").width - 100.0).abs() < 0.5);
        assert!(ui.overflows().is_empty(), "half of it fits in all of it");
    }

    #[test]
    fn a_sized_overflow_box_reports_one_size_and_lays_its_child_out_at_another() {
        let root = Flex::<()>::column()
            .width(400.0)
            .child(SizedOverflowBox::new(40.0, 40.0, red(100.0, 100.0)));
        let (ui, nodes) = inspected(&root, Size::new(400.0, 300.0));
        let own = box_named(&nodes, "SizedOverflowBox");
        assert!(
            (own.width - 40.0).abs() < 0.5 && (own.height - 40.0).abs() < 0.5,
            "the box is the size it stated: {own:?}"
        );
        let child = red_box_in(&ui);
        assert!(
            (child.width - 100.0).abs() < 0.5,
            "the child is not: {child:?}"
        );
        assert!(
            (child.x + 30.0).abs() < 0.5 && (child.y + 30.0).abs() < 0.5,
            "centred on the box it hangs out of: {child:?}"
        );
    }

    /// The first red rectangle in a finished scene.
    fn red_box_in(ui: &crate::Ui<()>) -> Rect {
        ui.scene()
            .primitives()
            .iter()
            .find_map(|p| match p {
                Primitive::Rect { rect, color, .. } if color.r > 0.5 && color.g < 0.5 => {
                    Some(*rect)
                }
                _ => None,
            })
            .expect("the red box")
    }

    /// A red box that asks for all the room it is given, on both axes: what a centred child
    /// asks for is passed up through its container.
    fn expanding() -> Container<()> {
        Container::new()
            .color(RED)
            .child(crate::Center::new(SizedBox::empty()))
    }

    /// **Where the room has no end**, down a scroll, the limit is the box: a child asking for
    /// all the room is 120 tall, and as wide as the scroll.
    #[test]
    fn a_limited_box_caps_a_child_where_the_room_has_no_end() {
        let root = crate::SingleChildScrollView::<()>::new()
            .width(200.0)
            .height(300.0)
            .child(Flex::column().child(LimitedBox::new(expanding()).max_height(120.0)));
        let rect = red_box(root, Size::new(200.0, 300.0));
        assert!((rect.height - 120.0).abs() < 0.5, "{rect:?}");
        assert!((rect.width - 200.0).abs() < 0.5, "{rect:?}");
    }

    /// **Where the room has an end**, the limit changes nothing: on a page, the same child is
    /// the page.
    #[test]
    fn a_limited_box_leaves_a_bounded_room_alone() {
        let rect = red_box(
            LimitedBox::new(expanding()).max_height(120.0),
            Size::new(200.0, 300.0),
        );
        assert!((rect.height - 300.0).abs() < 0.5, "{rect:?}");
    }

    /// **A child that hugs** still does: the limit is a ceiling, not a size.
    #[test]
    fn a_limited_box_does_not_grow_a_child_that_hugs() {
        let root = crate::SingleChildScrollView::<()>::new()
            .width(200.0)
            .height(300.0)
            .child(
                Flex::column().child(
                    LimitedBox::new(Container::new().width(40.0).height(20.0).color(RED))
                        .max_height(120.0),
                ),
            );
        let rect = red_box(root, Size::new(200.0, 300.0));
        assert!((rect.height - 20.0).abs() < 0.5, "{rect:?}");
        assert!((rect.width - 40.0).abs() < 0.5, "{rect:?}");
    }

    /// **Across**, the same: along a horizontal scroll, a child asking for all the room is as
    /// wide as the limit.
    #[test]
    fn a_limited_box_caps_across_too() {
        let root = crate::SingleChildScrollView::<()>::new()
            .axis(crate::scroll::Axis::Horizontal)
            .width(300.0)
            .height(100.0)
            .child(Flex::row().child(LimitedBox::new(expanding()).max_width(90.0)));
        let rect = red_box(root, Size::new(300.0, 100.0));
        assert!((rect.width - 90.0).abs() < 0.5, "{rect:?}");
    }

    /// **A paragraph wraps at the limit**, along a horizontal scroll where nothing else would
    /// stop it: it is as wide as the limit and several lines tall.
    #[test]
    fn a_paragraph_wraps_at_the_limit() {
        let words = "one two three four five six seven eight nine ten eleven twelve";
        let root = crate::SingleChildScrollView::<()>::new()
            .axis(crate::scroll::Axis::Horizontal)
            .width(300.0)
            .height(200.0)
            .child(
                Flex::row().child(
                    LimitedBox::new(Container::new().color(RED).child(Text::new(words)))
                        .max_width(120.0),
                ),
            );
        let rect = red_box(root, Size::new(300.0, 200.0));
        assert!((rect.width - 120.0).abs() < 0.5, "{rect:?}");
        assert!(rect.height > 50.0, "several lines: {rect:?}");
    }

    /// **Inside a scroll**, the column holding it is as wide as the scroll because the box
    /// asks for it, and the box is that width. It was 0: a percentage of a column that was as
    /// wide as its content.
    #[test]
    fn a_sized_box_that_expands_is_as_wide_as_a_scroll() {
        let root = crate::SingleChildScrollView::<()>::new()
            .width(200.0)
            .height(300.0)
            .child(
                Flex::column().child(SizedBox::expand(Container::new().color(RED)).height(50.0)),
            );
        let rect = red_box(root, Size::new(200.0, 300.0));
        assert!((rect.width - 200.0).abs() < 0.5, "{rect:?}");
        assert!((rect.height - 50.0).abs() < 0.5, "{rect:?}");
    }

    /// **Alone on a page**, it is the page; **beside a label in a row**, it shares the line
    /// and is as wide as its child, after the label.
    #[test]
    fn a_sized_box_that_expands_fills_a_page_and_shares_a_line() {
        let rect = red_box(SizedBox::expand(filler()), Size::new(200.0, 300.0));
        assert!(
            (rect.width - 200.0).abs() < 0.5 && (rect.height - 300.0).abs() < 0.5,
            "{rect:?}"
        );
        let row = Flex::<()>::row()
            .width(300.0)
            .height(100.0)
            .child(Text::new("label").no_wrap())
            .child(SizedBox::expand(Container::new().width(30.0).color(RED)));
        let rect = red_box(row, Size::new(300.0, 100.0));
        assert!((rect.width - 30.0).abs() < 0.5, "{rect:?}");
        assert!((rect.height - 100.0).abs() < 0.5, "{rect:?}");
        assert!(rect.x > 20.0, "after the label: {rect:?}");
    }
}