1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
//! [`Container`]: a decorated box (size, padding, color, rounded corners, border,
//! click) with an optional child.
use frus_core::{
AlignmentGeometry, Border, BorderRadius, BoxBorder, BoxDecoration, BoxShadow, BoxShape, Color,
Curve, DecorationImage, Gradient, Insets, InsetsGeometry, LinearGradient, Rect, Scene, Size,
};
use frus_layout::{Align, Dimension, Justify, Style};
use crate::interaction::Status;
use crate::theme::Theme;
use crate::widget::Widget;
/// An easing curve (smoothstep) to soften the transitions.
fn ease(t: f32) -> f32 {
let t = t.clamp(0.0, 1.0);
t * t * (3.0 - 2.0 * t)
}
/// A decorated rectangular box.
pub struct Container<Msg = crate::callback::Callback> {
width: Dimension,
height: Dimension,
flex_grow: f32,
flex_shrink: f32,
padding: InsetsGeometry,
/// The **outer** margin (around the box, outside the decoration).
margin: InsetsGeometry,
radius: BorderRadius,
/// Clip the child to this box's rounded rectangle.
clip: bool,
/// A decoration painted **over** the child rather than behind it; see
/// [`Container::foreground`].
foreground: Option<BoxDecoration>,
/// The border, side by side (milestone 641).
border: Option<BoxBorder>,
color: Option<Color>,
hover_color: Option<Color>,
pressed_color: Option<Color>,
/// A gradient from the colour towards an end colour, along a direction: kept apart,
/// because its first colour is the container's colour, which may animate.
towards: Option<(Color, [f32; 2])>,
/// A gradient said in full (milestone 644).
gradient: Option<Gradient>,
/// The shadows, painted in order (milestone 641).
shadows: Vec<BoxShadow>,
/// A rectangle or a circle (milestone 641).
shape: BoxShape,
/// A picture over the background, under the border (milestone 645).
image: Option<DecorationImage>,
/// How the background meets what is under the box (milestone 646).
background_blend_mode: Option<frus_core::BlendMode>,
on_click: Option<Msg>,
on_long_press: Option<Msg>,
/// A repaint boundary: it caches the painted subtree (see
/// [`crate::Widget::repaint_boundary`]).
repaint_boundary: bool,
/// A **group** opacity `[0,1]` applied to the whole subtree. `None` = opaque.
opacity: Option<f32>,
/// When the group opacity is **animated**: the transition's `(duration, curve)`.
/// `None` = a fixed opacity, with no transition.
opacity_anim: Option<(f32, Curve)>,
/// When the background is an **animated color**: the transition's `(target,
/// duration, curve)`. `None` = a fixed color.
color_anim: Option<(Color, f32, Curve)>,
/// When the **size** is animated: `(target, duration, curve)` — interpolated at
/// layout time. `None` = a fixed size.
size_anim: Option<(Size, f32, Curve)>,
/// When the **corner radius** is animated: `(target, duration, curve)` —
/// interpolated at paint time. `None` = a fixed radius.
radius_anim: Option<(BorderRadius, f32, Curve)>,
/// When the **padding** is animated: `(duration, curve)` — the target is
/// `self.padding`, interpolated at layout time. `None` = fixed padding.
padding_anim: Option<(f32, Curve)>,
/// `(duration, curve)` of an **animated anchor**; `None` = the anchor is fixed.
alignment_anim: Option<(f32, Curve)>,
/// The child's anchoring within the box, physical or directional (resolved for
/// RTL at render time). `None` = the default flex behaviour, in which the child
/// stretches to fill.
alignment: Option<AlignmentGeometry>,
/// Whether it sizes itself by the reference's rules (`true`), or always by its content —
/// what a widget built on a container that answers the question itself asks for
/// ([`Container::hugging`]).
reference_sizing: bool,
/// The reference's `constraints`: `(min_width, max_width, min_height, max_height)`,
/// each unset where nothing was said.
limits: [Option<f32>; 4],
/// The reference's `transform`, as this framework's three: a shift, a scale and a turn.
shift: Option<(f32, f32)>,
scale: Option<(f32, f32)>,
turn: Option<f32>,
/// The point the scale and the turn are about — the reference's `transformAlignment`.
pivot: frus_core::Alignment,
children: Vec<Box<dyn Widget<Msg>>>,
}
impl<Msg> Container<Msg> {
/// The axes the reference's container takes the room on: every axis it was given no
/// size on, when it has no child or aligns its child.
fn reference_fill(&self) -> crate::widget::FillAxes {
let fills = self.reference_sizing && (self.children.is_empty() || self.alignment.is_some());
crate::widget::FillAxes {
horizontal: fills && matches!(self.width, Dimension::Auto),
vertical: fills && matches!(self.height, Dimension::Auto),
}
}
/// A container sized by its content whatever the reference's rules say: for a widget
/// built on one that decides for itself how much room to take, as [`crate::Aligned`]
/// does with its factors.
pub(crate) fn hugging(mut self) -> Self {
self.reference_sizing = false;
self
}
/// **At least `width` wide** — part of the reference's `constraints`. A width given
/// with [`width`](Self::width) is held within the constraints, as the reference
/// tightens them.
#[must_use]
pub fn min_width(mut self, width: f32) -> Self {
self.limits[0] = Some(width);
self
}
/// **At most `width` wide.**
#[must_use]
pub fn max_width(mut self, width: f32) -> Self {
self.limits[1] = Some(width);
self
}
/// **At least `height` tall.**
#[must_use]
pub fn min_height(mut self, height: f32) -> Self {
self.limits[2] = Some(height);
self
}
/// **At most `height` tall.**
#[must_use]
pub fn max_height(mut self, height: f32) -> Self {
self.limits[3] = Some(height);
self
}
/// **Shifted by `(dx, dy)`** when painted, as the reference's `transform` does: the
/// layout keeps its place and the box and its child are drawn moved.
#[must_use]
pub fn translated(mut self, dx: f32, dy: f32) -> Self {
self.shift = Some((dx, dy));
self
}
/// **Scaled by `(sx, sy)`** when painted, about the
/// [`transform_alignment`](Self::transform_alignment).
#[must_use]
pub fn scaled(mut self, sx: f32, sy: f32) -> Self {
self.scale = Some((sx, sy));
self
}
/// **Turned by `radians`** when painted, about the
/// [`transform_alignment`](Self::transform_alignment).
#[must_use]
pub fn rotated(mut self, radians: f32) -> Self {
self.turn = Some(radians);
self
}
/// **The point a scale and a turn are about**, within the box. Unset, its centre.
#[must_use]
pub fn transform_alignment(mut self, pivot: frus_core::Alignment) -> Self {
self.pivot = pivot;
self
}
/// Creates an empty container (automatic size, no decoration).
pub fn new() -> Self {
Self {
width: Dimension::Auto,
height: Dimension::Auto,
flex_grow: 0.0,
flex_shrink: 0.0,
padding: InsetsGeometry::Physical(Insets::ZERO),
margin: InsetsGeometry::Physical(Insets::ZERO),
radius: BorderRadius::ZERO,
clip: false,
foreground: None,
border: None,
color: None,
hover_color: None,
pressed_color: None,
towards: None,
gradient: None,
shadows: Vec::new(),
shape: BoxShape::Rectangle,
image: None,
background_blend_mode: None,
on_click: None,
on_long_press: None,
repaint_boundary: false,
opacity: None,
opacity_anim: None,
color_anim: None,
size_anim: None,
radius_anim: None,
padding_anim: None,
alignment_anim: None,
alignment: None,
reference_sizing: true,
limits: [None; 4],
shift: None,
scale: None,
turn: None,
pivot: frus_core::Alignment::CENTER,
children: Vec::new(),
}
}
/// The **effective** layout padding: the inner padding plus, when a border is
/// visible, the room it reserves (the content of a bordered box is not eaten by
/// the stroke). The single source for `style()` and for the **target** of an
/// animated padding (`anim_padding`).
fn effective_padding(&self) -> Insets {
self.effective_padding_in(frus_core::TextDirection::Ltr)
}
/// The padding the layout is given — the content's and the border's — for a frame in
/// `direction` (milestone 588: see [`InsetsGeometry::laid_out`]).
fn effective_padding_in(&self, direction: frus_core::TextDirection) -> Insets {
let mut padding = self.padding.laid_out(direction);
// Each side's own width, in the reading direction (milestone 641).
if let Some(border) = self.border {
let w = border.resolve(direction).dimensions();
padding.top += w.top;
padding.right += w.right;
padding.bottom += w.bottom;
padding.left += w.left;
}
padding
}
/// Marks this container as a **repaint boundary**: its subtree is cached and
/// reused for as long as its geometry and its descendants' interaction state
/// stay stable. To be placed around **static** content that would otherwise be
/// repainted on every frame of a neighbouring animation.
pub fn repaint_boundary(mut self) -> Self {
self.repaint_boundary = true;
self
}
/// Sets the width, in logical pixels.
pub fn width(mut self, width: f32) -> Self {
self.width = Dimension::Length(width);
self
}
/// Sets the height, in logical pixels.
pub fn height(mut self, height: f32) -> Self {
self.height = Dimension::Length(height);
self
}
/// Sets the width as a **fraction of the space the parent offers** — `1.0` fills it.
pub fn width_fraction(mut self, fraction: f32) -> Self {
self.width = Dimension::Percent(fraction);
self
}
/// Flex growth factor along the parent's main axis.
pub fn flex(mut self, grow: f32) -> Self {
self.flex_grow = grow;
self
}
/// How much of a row's deficit this box absorbs. The default is `0.0` — the
/// reference's rule, where an inflexible child is never squeezed and a row that does
/// not fit overflows and says so.
///
/// `shrink(1.0)` asks for flexbox's behaviour instead: give way rather than let the
/// row run over. It is the right answer for a box whose size is a preference rather
/// than a requirement, and the wrong one for fixed chrome — an icon button at the end
/// of a row should keep its width however long the label beside it grows.
pub fn shrink(mut self, shrink: f32) -> Self {
self.flex_shrink = shrink;
self
}
/// This box never shrinks — the default said out loud, kept because a layout that
/// depends on it reads better for saying so. See [`Self::shrink`].
pub fn no_shrink(self) -> Self {
self.shrink(0.0)
}
/// Uniform inner padding, in logical pixels.
pub fn padding(mut self, padding: f32) -> Self {
self.padding = InsetsGeometry::Physical(Insets::uniform(padding));
self
}
/// Inner padding per side (top, right, bottom, left).
pub fn padding_each(mut self, top: f32, right: f32, bottom: f32, left: f32) -> Self {
self.padding = InsetsGeometry::Physical(Insets::new(top, right, bottom, left));
self
}
/// Sets the padding from any insets: one number, physical [`Insets`] — whose left stays
/// on the left in a right-to-left script — or [`InsetsDirectional`](frus_core::InsetsDirectional),
/// whose start is the right there.
pub fn padding_insets(mut self, padding: impl Into<InsetsGeometry>) -> Self {
self.padding = padding.into();
self
}
/// Sets the margin from any insets, as [`padding_insets`](Self::padding_insets) does the
/// padding.
pub fn margin_insets(mut self, margin: impl Into<InsetsGeometry>) -> Self {
self.margin = margin.into();
self
}
/// A uniform **outer** margin: space reserved **around** the box — outside the
/// decoration, it pushes the siblings away without growing the background or
/// the border.
pub fn margin(mut self, margin: f32) -> Self {
self.margin = InsetsGeometry::Physical(Insets::uniform(margin));
self
}
/// Outer margin per side (top, right, bottom, left).
pub fn margin_each(mut self, top: f32, right: f32, bottom: f32, left: f32) -> Self {
self.margin = InsetsGeometry::Physical(Insets::new(top, right, bottom, left));
self
}
/// The rounded corner radii: uniform via `f32` (`.radius(10.0)`) or per corner
/// via [`BorderRadius`] (`.radius(BorderRadius::top(12.0))`).
pub fn radius(mut self, radius: impl Into<BorderRadius>) -> Self {
self.radius = radius.into();
self
}
/// **Clips** the child to this box, corners included.
///
/// Off by default, as in the reference: a decoration is painted *behind* a child
/// and does not confine it, so a box with rounded corners leaves an image inside it
/// square unless it is asked. Asking costs a compositing layer, which is why neither
/// framework does it for you.
///
/// [`crate::ClipRRect`] is the same thing without the decoration, and is what to
/// reach for when there is no box to decorate.
pub fn clip(mut self) -> Self {
self.clip = true;
self
}
/// The border: width (in px) and color, the same on all four sides.
pub fn border(mut self, width: f32, color: Color) -> Self {
self.border = (width > 0.0).then(|| Border::new(width, color).into());
self
}
/// **The border, side by side** — a [`Border`] or a
/// [`BorderDirectional`](frus_core::BorderDirectional), each side its own width and colour
/// (milestone 641).
pub fn box_border(mut self, border: impl Into<BoxBorder>) -> Self {
self.border = Some(border.into());
self
}
/// **A rectangle or a circle** (milestone 641). A circle is centred in the box, as wide
/// as its shorter side, and its radius is not read.
pub fn shape(mut self, shape: BoxShape) -> Self {
self.shape = shape;
self
}
/// **The shadows**, painted in order behind the box (milestone 641).
pub fn shadows(mut self, shadows: impl IntoIterator<Item = BoxShadow>) -> Self {
self.shadows = shadows.into_iter().collect();
self
}
/// The background color at rest.
pub fn color(mut self, color: Color) -> Self {
self.color = Some(color);
self
}
/// The background color on hover.
pub fn hover_color(mut self, color: Color) -> Self {
self.hover_color = Some(color);
self
}
/// The background color when pressed.
pub fn pressed_color(mut self, color: Color) -> Self {
self.pressed_color = Some(color);
self
}
/// A linear background gradient (`color` → `end`), with `dir` in `[0,1]²` space
/// (`[0.0, 1.0]` = top→bottom, for instance).
pub fn gradient(mut self, end: Color, dir: [f32; 2]) -> Self {
self.towards = Some((end, dir));
self
}
/// A picture over the background, under the border, clipped to the corners or the
/// circle — fitted, aligned, repeated or sliced as the [`DecorationImage`] says.
pub fn image(mut self, image: DecorationImage) -> Self {
self.image = Some(image);
self
}
/// Blends the background — the colour or the gradient — with what is under the box
/// by `mode` rather than painting it over: a multiply that darkens the picture
/// behind, a colour that tints it, a difference that inverts it.
pub fn background_blend_mode(mut self, mode: frus_core::BlendMode) -> Self {
self.background_blend_mode = Some(mode);
self
}
/// A drop shadow: the `(dx, dy)` offset, the blur radius and the color. Each call adds
/// one, over those already there.
pub fn shadow(mut self, dx: f32, dy: f32, blur: f32, color: Color) -> Self {
self.shadows.push(BoxShadow::new(dx, dy, blur, color));
self
}
/// The message emitted when the container is clicked.
pub fn on_click(mut self, message: impl Into<Msg>) -> Self {
self.on_click = Some(message.into());
self
}
/// The message emitted by a **long press** (a press held without movement). A
/// long press supersedes the click.
pub fn on_long_press(mut self, message: impl Into<Msg>) -> Self {
self.on_long_press = Some(message.into());
self
}
/// Sets the container's child.
pub fn child(mut self, child: impl Widget<Msg> + 'static) -> Self {
self.children.clear();
self.children.push(Box::new(child));
self
}
/// Applies a **group opacity** `[0,1]` to the whole subtree, as one block: the
/// rendering goes through a composited layer, so overlaps are not
/// double-blended. `1.0` = no effect at all.
pub fn opacity(mut self, opacity: f32) -> Self {
self.opacity = Some(opacity.clamp(0.0, 1.0));
self
}
/// Like [`Container::opacity`], but the opacity **animates** toward `opacity` on
/// every change, with `duration` (in seconds) and `curve`. The fade applies to
/// the whole group.
pub fn animated_opacity(mut self, opacity: f32, duration: f32, curve: Curve) -> Self {
self.opacity = Some(opacity.clamp(0.0, 1.0));
self.opacity_anim = Some((duration, curve));
self
}
/// A background whose color **animates** toward `color` on every change, with
/// `duration` (in seconds) and `curve`. The runtime interpolates from the
/// current color; on mount it adopts `color` with no transition. Note: one box
/// shares a single `(duration, curve)` across its animations (opacity, color).
pub fn animated_color(mut self, color: Color, duration: f32, curve: Curve) -> Self {
self.color = Some(color);
self.color_anim = Some((color, duration, curve));
self
}
/// A box whose **size** animates toward `width×height` on every change, with
/// `duration` and `curve`. The interpolated size is injected **at layout time**
/// (the children reposition accordingly). On mount it adopts the target with no
/// transition.
pub fn animated_size(mut self, width: f32, height: f32, duration: f32, curve: Curve) -> Self {
self.width = Dimension::Length(width);
self.height = Dimension::Length(height);
self.size_anim = Some((Size::new(width, height), duration, curve));
self
}
/// A box whose **corner radius** animates toward `radius` on every change, with
/// `duration` and `curve` — the corners morph smoothly. Uniform via `f32`, or
/// per corner via [`BorderRadius`]. On mount it adopts the target with no
/// transition.
pub fn animated_radius(
mut self,
radius: impl Into<BorderRadius>,
duration: f32,
curve: Curve,
) -> Self {
let radius = radius.into();
self.radius = radius;
self.radius_anim = Some((radius, duration, curve));
self
}
/// A box whose (uniform) **inner padding** animates toward `padding` on every
/// change, with `duration` and `curve`. The interpolated padding is injected
/// **at layout time** (the content repositions). On mount it adopts the target
/// with no transition.
pub fn animated_padding(mut self, padding: f32, duration: f32, curve: Curve) -> Self {
self.padding = InsetsGeometry::Physical(Insets::uniform(padding));
self.padding_anim = Some((duration, curve));
self
}
/// A box whose **anchor** animates toward `alignment` on every change, with
/// `duration` and `curve`: the child slides through the free space instead of
/// jumping across it. On mount it adopts the anchor with no transition.
///
/// It interpolates the anchor's own two fractions, so a **directional** anchor stays
/// directional the whole way and mirrors as a whole in a right-to-left script.
pub fn animated_alignment(
mut self,
alignment: impl Into<AlignmentGeometry>,
duration: f32,
curve: Curve,
) -> Self {
self.alignment = Some(alignment.into());
self.alignment_anim = Some((duration, curve));
self
}
/// **Anchors the child** within the box: centred, in a corner, against an edge…
/// Accepts a **physical** anchor ([`Alignment`](frus_core::Alignment)) or a
/// **directional** one
/// ([`AlignmentDirectional`](frus_core::AlignmentDirectional), resolved for RTL
/// at render time) — both through `Into`. By default, with no anchor, the child
/// stretches to fill the container (the flex behaviour); setting an anchor
/// leaves the child at its natural size and positions it.
pub fn alignment(mut self, alignment: impl Into<AlignmentGeometry>) -> Self {
self.alignment = Some(alignment.into());
self
}
/// A decoration painted **over the child** rather than behind it — the reference's
/// `foregroundDecoration`.
///
/// [`Container::decoration`] and every part it is made of go *behind* the content,
/// which is what a background is for and no use at all when the point is that the
/// content does not cover it: an outline over a photograph, a wash across a tile
/// that is out of stock, a sheen over a card. There is no other way to say it short
/// of a [`crate::Stack`].
///
/// It is painted on the container's own box, the same one the background uses, and
/// it is inside anything the container asks for — an opacity fades it with
/// everything else, [`Container::clip`] holds it to the corners.
///
/// One convenience the reference does not have: a foreground that names **no**
/// radius takes the container's, since a square outline over a rounded box is
/// almost always a mistake rather than a request. Set one explicitly — including
/// [`frus_core::BorderRadius::ZERO`] — to say otherwise.
///
/// ```
/// # use frus_widgets::Container;
/// # use frus_core::{Border, BoxDecoration, Color};
/// # let photo = Container::<()>::new();
/// Container::<()>::new()
/// .radius(12.0)
/// .child(photo)
/// .foreground(BoxDecoration::default().border(Border::new(1.0, Color::rgba(0.0, 0.0, 0.0, 0.2))));
/// ```
pub fn foreground(mut self, decoration: BoxDecoration) -> Self {
self.foreground = Some(decoration);
self
}
/// Sets the box's fill, gradient, picture, blend mode, border, shadows and shape from a
/// [`BoxDecoration`](frus_core::BoxDecoration) at once. What the decoration leaves unset
/// changes nothing; the radius and the shape are always adopted.
pub fn decoration(mut self, decoration: BoxDecoration) -> Self {
if let Some(color) = decoration.color {
self.color = Some(color);
}
if let Some(gradient) = decoration.gradient {
self.gradient = Some(gradient);
}
if let Some(image) = decoration.image {
self.image = Some(image);
}
if let Some(mode) = decoration.background_blend_mode {
self.background_blend_mode = Some(mode);
}
if let Some(border) = decoration.border {
self.border = Some(border);
}
self.radius = decoration.radius;
if !decoration.shadows.is_empty() {
self.shadows = decoration.shadows;
}
self.shape = decoration.shape;
self
}
}
impl<Msg> Default for Container<Msg> {
fn default() -> Self {
Self::new()
}
}
impl<Msg> Container<Msg> {
/// The style, with the padding and the margin laid out for `direction`.
fn style_in(&self, direction: frus_core::TextDirection) -> Style {
let mut style = Style {
width: self.width,
height: self.height,
flex_grow: self.flex_grow,
flex_shrink: self.flex_shrink,
padding: self.effective_padding_in(direction),
margin: self.margin.laid_out(direction),
..Default::default()
};
let limit = |v: Option<f32>| v.map_or(Dimension::Auto, Dimension::Length);
style.min_width = limit(self.limits[0]);
style.max_width = limit(self.limits[1]);
style.min_height = limit(self.limits[2]);
style.max_height = limit(self.limits[3]);
// Anchoring the child: taffy is left to place it at the **top left** of the
// content box, at its natural size (Start / Start, no stretching), and the
// walk then offsets it within the free space according to the `Alignment`'s
// fractions (a manual, fractional placement — outside the discrete flex).
if self.alignment.is_some() {
style.justify = Justify::Start;
style.align = Align::Start;
}
style
}
}
impl<Msg: Clone> Widget<Msg> for Container<Msg> {
fn style(&self) -> Style {
self.style_in(frus_core::TextDirection::Ltr)
}
/// The padding and the margin laid out for the reading direction the subtree is in
/// (milestone 588).
fn style_themed(&self, theme: &Theme) -> Style {
self.style_in(theme.direction)
}
fn children(&self) -> &[Box<dyn Widget<Msg>>] {
&self.children
}
fn paint(&self, bounds: Rect, status: Status, theme: &Theme, scene: &mut Scene) {
// A background with an **animated color**: the color the runtime interpolates
// wins (the hover/press interpolation does not apply to an animated background).
// Otherwise two progressions in a row — rest → hover, then that → held. The press
// used to be the one step here that was instant; it is a progression since
// milestone 441, and crossing over from wherever the hover had got to is what
// keeps a pointer that presses mid-fade from jumping backwards first.
let color = if self.color_anim.is_some() {
status.anim_color.or(self.color)
} else {
let settled = match (self.color, self.hover_color) {
(Some(base), Some(hover)) => Some(base.lerp(hover, ease(status.hover_progress))),
_ => self.color,
};
let press = ease(status.press_progress.clamp(0.0, 1.0));
match (settled, self.pressed_color.or(self.hover_color)) {
(Some(from), Some(held)) => Some(from.lerp(held, press)),
// Nothing to cross over *from*: a container with a held colour and no
// resting one at all has no fill to fade, so it appears with the press.
(None, held) if press > 0.0 => held,
(settled, _) => settled,
}
};
// Compose the decoration (background/gradient/border/shadow) and lower it into
// primitives in the fixed order shadow → background → border. The opacity
// (the fade-in) modulates every color.
// An animated radius: the radius the runtime interpolates wins over the fixed one.
let radius = if self.radius_anim.is_some() {
status.anim_radius.unwrap_or(self.radius)
} else {
self.radius
};
// A gradient towards an end colour starts at this frame's colour, along its
// direction: the reference's `begin` and `end`, opposite each other about the centre.
let gradient = self.gradient.clone().or_else(|| {
let (end, dir) = self.towards?;
let start = color?;
Some(Gradient::from(
LinearGradient::new(vec![start, end]).between(
frus_core::Alignment::new(-dir[0], -dir[1]),
frus_core::Alignment::new(dir[0], dir[1]),
),
))
});
let decoration = BoxDecoration {
color,
gradient,
border: self.border,
radius,
shadows: self.shadows.clone(),
shape: self.shape,
image: self.image.clone(),
background_blend_mode: self.background_blend_mode,
};
decoration.paint_into_in(scene, bounds, status.opacity, theme.direction);
}
fn clip_shape(&self) -> Option<frus_core::ClipShape> {
self.clip.then(|| match self.shape {
BoxShape::Rectangle => frus_core::ClipShape::RRect(self.radius.clamped()),
// The ellipse inscribed in the box: the circle, in a square one.
BoxShape::Circle => frus_core::ClipShape::Oval,
})
}
fn foreground(&self, _theme: &Theme) -> Option<BoxDecoration> {
self.foreground.clone().map(|decoration| {
if decoration.radius == frus_core::BorderRadius::ZERO {
decoration.radius(self.radius)
} else {
decoration
}
})
}
fn on_click(&self) -> Option<Msg> {
self.on_click.clone()
}
fn on_long_press(&self) -> Option<Msg> {
self.on_long_press.clone()
}
fn repaint_boundary(&self) -> bool {
self.repaint_boundary
}
fn opacity_group(&self) -> Option<f32> {
self.opacity
}
/// The animated opacity's target (only when `animated_opacity` is set) — this is
/// the value the runtime tweens and the walk reads back for the layer.
fn anim_target(&self) -> Option<f32> {
self.opacity_anim.as_ref().and(self.opacity)
}
fn anim_color(&self) -> Option<Color> {
self.color_anim.as_ref().and(self.color)
}
fn anim_size(&self) -> Option<Size> {
self.size_anim.as_ref().map(|(s, _, _)| *s)
}
fn anim_radius(&self) -> Option<BorderRadius> {
self.radius_anim.as_ref().map(|(r, _, _)| *r)
}
fn anim_padding(&self) -> Option<Insets> {
// The target = the effective padding (content + border), consistent with `style()`.
self.padding_anim.as_ref().map(|_| self.effective_padding())
}
fn alignment_geometry(&self) -> Option<AlignmentGeometry> {
self.alignment
}
fn transform_translate(&self) -> Option<(f32, f32)> {
self.shift
}
fn transform_scale(&self) -> Option<(f32, f32, frus_core::Alignment)> {
self.scale.map(|(sx, sy)| (sx, sy, self.pivot))
}
fn transform_rotate(&self) -> Option<(f32, frus_core::Alignment)> {
self.turn.map(|r| (r, self.pivot))
}
/// **The room on offer**, on each axis it was given no size on, when it has no child
/// or when it aligns its child — the reference's two rules (`container.dart:390`,
/// `:396`). Empty, a container expands to what its parent allows; aligning, it fills
/// its parent and places its child inside. Along a row or a column shared with other
/// children the request is not granted, so it is nothing there, as the reference's
/// `LimitedBox(0)` is in unbounded room. Otherwise it is its child's size.
fn fill_axes(&self, _theme: &Theme) -> crate::widget::FillAxes {
self.reference_fill()
}
fn anim_offset(&self) -> Option<(f32, f32)> {
// The target = the anchor's own fractions, which is what the walk puts back into
// an anchor of the same kind.
self.alignment_anim
.as_ref()
.and(self.alignment)
.map(|a| a.fractions())
}
fn anim_duration(&self) -> f32 {
// One box's animations (opacity/color/size/radius/padding) share a single
// duration (in the order: opacity, color, size, radius, padding).
self.opacity_anim
.as_ref()
.map(|(d, _)| *d)
.or(self.color_anim.as_ref().map(|(_, d, _)| *d))
.or(self.size_anim.as_ref().map(|(_, d, _)| *d))
.or(self.radius_anim.as_ref().map(|(_, d, _)| *d))
.or(self.padding_anim.as_ref().map(|(d, _)| *d))
.or(self.alignment_anim.as_ref().map(|(d, _)| *d))
.unwrap_or(crate::runtime::ANIM_DURATION)
}
fn anim_curve(&self) -> Curve {
self.opacity_anim
.as_ref()
.map(|(_, c)| c.clone())
.or(self.color_anim.as_ref().map(|(_, _, c)| c.clone()))
.or(self.size_anim.as_ref().map(|(_, _, c)| c.clone()))
.or(self.radius_anim.as_ref().map(|(_, _, c)| c.clone()))
.or(self.padding_anim.as_ref().map(|(_, c)| c.clone()))
.or(self.alignment_anim.as_ref().map(|(_, c)| c.clone()))
.unwrap_or(Curve::Linear)
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A box in an over-budget row **keeps its width** — the reference's rule, and the
/// default since milestone 349. Flexbox's default was the opposite, and the smallest
/// fixed thing in the row paid for the whole deficit: milestone 333 found an icon
/// button at 13 px of 40, drawn off the card and out of the hit registry.
///
/// `shrink(1.0)` asks for flexbox's behaviour back, for a box that would rather give
/// way than let the row overflow.
#[test]
fn a_box_in_an_over_budget_row_keeps_its_width() {
use crate::interaction::WidgetId;
use crate::runtime::Runtime;
use crate::theme::Theme;
use crate::Flex;
let widths = |row: &Flex<()>| -> Vec<f32> {
let runtime = Runtime::default();
let theme = Theme::light();
let mut layout = frus_layout::Layout::new();
let node = crate::ui::build_layout(row, WidgetId::ROOT, &runtime, &theme, &mut layout);
layout.compute_filled(node, 100.0, 50.0);
layout
.absolute_rects(node)
.iter()
.skip(1)
.take(2)
.map(|(r, _)| r.width)
.collect()
};
// 120 px of children in 100 px of row. Nobody was asked to give way, so nobody
// does, and the row overflows — which is now visible, striped and labelled.
let row = Flex::row()
.child(Container::<()>::new().width(80.0).height(20.0))
.child(Container::<()>::new().width(40.0).height(20.0));
assert_eq!(
widths(&row),
vec![80.0, 40.0],
"an inflexible child is never squeezed"
);
// Unless it says so, and then the whole deficit is its own.
let giving_way = Flex::row()
.child(Container::<()>::new().width(80.0).height(20.0).shrink(1.0))
.child(Container::<()>::new().width(40.0).height(20.0));
assert_eq!(widths(&giving_way), vec![60.0, 40.0]);
}
/// **A held box crosses over to its pressed colour** (milestone 441) instead of
/// snapping to it. The line that chose it read `Interaction::Pressed` and the comment
/// beside it said "Pressed: instant" — the one step of the rest → hover → held path
/// that was not a progression.
#[test]
fn a_held_box_crosses_over_to_its_pressed_colour() {
use frus_core::Primitive;
let rest = Color::rgb(0.2, 0.2, 0.2);
let held = Color::rgb(0.8, 0.8, 0.8);
let box_: Container<()> = Container::new()
.width(20.0)
.height(20.0)
.color(rest)
.pressed_color(held);
let fill = |press: f32| {
let mut scene = Scene::new();
Widget::<()>::paint(
&box_,
Rect::new(0.0, 0.0, 20.0, 20.0),
Status {
press_progress: press,
..Default::default()
},
&crate::Theme::dark(),
&mut scene,
);
scene
.primitives()
.iter()
.find_map(|p| match p {
Primitive::Rect { color, .. } => Some(*color),
_ => None,
})
.expect("a box paints its background")
};
assert_eq!(fill(0.0), rest, "untouched");
assert_eq!(fill(1.0), held, "held");
let half = fill(0.5).r;
assert!(
half > rest.r && half < held.r,
"half way through the press: {half}"
);
}
/// A `Container` with a group opacity < 1 has its painted subtree wrapped in a
/// [`frus_core::Primitive::Layer`] at that opacity.
#[test]
fn opacity_group_wraps_subtree_in_a_layer() {
use frus_core::{Primitive, Size};
let root: Container<()> = Container::new()
.width(40.0)
.height(40.0)
.color(Color::rgb(1.0, 0.0, 0.0))
.opacity(0.5);
let rt = crate::runtime::Runtime::default();
let theme = crate::Theme::dark();
let ui = crate::ui::build_ui(&root, Size::new(64.0, 64.0), &rt, &theme);
let layer = ui.scene().primitives().iter().find_map(|p| match p {
Primitive::Layer {
opacity,
primitives,
..
} => Some((*opacity, primitives.len())),
_ => None,
});
let (op, n) = layer.expect("a group opacity layer");
assert!((op - 0.5).abs() < 1e-6, "group opacity = {op}");
assert!(
n >= 1,
"the layer wraps the painted content ({n} primitives)"
);
}
/// Full opacity (`1.0`): no layer is emitted (the opaque path, at zero cost).
#[test]
fn full_opacity_emits_no_layer() {
use frus_core::{Primitive, Size};
let root: Container<()> = Container::new()
.width(40.0)
.height(40.0)
.color(Color::rgb(1.0, 0.0, 0.0))
.opacity(1.0);
let rt = crate::runtime::Runtime::default();
let theme = crate::Theme::dark();
let ui = crate::ui::build_ui(&root, Size::new(64.0, 64.0), &rt, &theme);
assert!(
!ui.scene()
.primitives()
.iter()
.any(|p| matches!(p, Primitive::Layer { .. })),
"no layer at full opacity"
);
}
/// `animated_opacity` declares an animated value (the runtime tweens it) with the
/// duration and curve supplied; `opacity` alone does not (a fixed opacity).
#[test]
fn animated_opacity_declares_anim_target() {
let animated: Container<()> = Container::new().animated_opacity(0.0, 0.3, Curve::ease_in());
assert_eq!(Widget::<()>::anim_target(&animated), Some(0.0));
assert_eq!(Widget::<()>::anim_duration(&animated), 0.3);
assert_eq!(Widget::<()>::anim_curve(&animated), Curve::ease_in());
assert_eq!(Widget::<()>::opacity_group(&animated), Some(0.0));
// A fixed opacity: a group, yes, but no animated value.
let fixed: Container<()> = Container::new().opacity(0.5);
assert_eq!(Widget::<()>::anim_target(&fixed), None);
assert_eq!(Widget::<()>::opacity_group(&fixed), Some(0.5));
}
/// An `animated_color` background paints the color the runtime **interpolates**
/// (not the target): mounted at red, transitioning to blue half-way → the
/// background rectangle is about half red, half blue.
#[test]
fn animated_color_paints_the_interpolated_color() {
use frus_core::{Primitive, Size};
let red = Color::rgb(1.0, 0.0, 0.0);
let blue = Color::rgb(0.0, 0.0, 1.0);
let mut rt = crate::runtime::Runtime::default();
let start: Container<()> =
Container::new()
.width(20.0)
.height(20.0)
.animated_color(red, 0.10, Curve::Linear);
rt.advance_colors(&start, 1.0); // montage → rouge
let to_blue: Container<()> =
Container::new()
.width(20.0)
.height(20.0)
.animated_color(blue, 0.10, Curve::Linear);
rt.advance_colors(&to_blue, 0.05); // t = 0.5
let theme = crate::Theme::dark();
let ui = crate::ui::build_ui(&to_blue, Size::new(20.0, 20.0), &rt, &theme);
let color = ui
.scene()
.primitives()
.iter()
.find_map(|p| match p {
Primitive::Rect { color, .. } => Some(*color),
_ => None,
})
.expect("un rectangle de fond");
assert!(
(color.r - 0.5).abs() < 0.1 && (color.b - 0.5).abs() < 0.1,
"the interpolated color is painted: {color:?}"
);
}
/// An `animated_size` **drives the layout**: half-way through (20×20 → 40×40,
/// linear), the background rectangle measures about 30×30 (the interpolated
/// size injected into layout through `effective_style`).
#[test]
fn animated_size_drives_the_layout() {
use frus_core::{Primitive, Size};
let mut rt = crate::runtime::Runtime::default();
let red = Color::rgb(1.0, 0.0, 0.0);
let start: Container<()> =
Container::new()
.color(red)
.animated_size(20.0, 20.0, 0.10, Curve::Linear);
rt.advance_sizes(&start, 1.0); // montage → 20×20
let to_big: Container<()> =
Container::new()
.color(red)
.animated_size(40.0, 40.0, 0.10, Curve::Linear);
rt.advance_sizes(&to_big, 0.05); // t = 0.5 → 30×30
let theme = crate::Theme::dark();
let ui = crate::ui::build_ui(&to_big, Size::new(100.0, 100.0), &rt, &theme);
let rect = ui
.scene()
.primitives()
.iter()
.find_map(|p| match p {
Primitive::Rect { rect, .. } => Some(*rect),
_ => None,
})
.expect("un rectangle de fond");
assert!(
(rect.width - 30.0).abs() < 1.0,
"interpolated width: {}",
rect.width
);
assert!(
(rect.height - 30.0).abs() < 1.0,
"interpolated height: {}",
rect.height
);
}
/// An `animated_radius` paints the **interpolated** radius: mounted at 0,
/// transitioning to 20 half-way → the background rectangle has a radius of ~10.
#[test]
fn animated_radius_paints_the_interpolated_radius() {
use frus_core::{Primitive, Size};
let red = Color::rgb(1.0, 0.0, 0.0);
let mut rt = crate::runtime::Runtime::default();
let sharp: Container<()> = Container::new()
.width(40.0)
.height(40.0)
.color(red)
.animated_radius(0.0, 0.10, Curve::Linear);
rt.advance_radii(&sharp, 1.0); // montage → 0
let round: Container<()> = Container::new()
.width(40.0)
.height(40.0)
.color(red)
.animated_radius(20.0, 0.10, Curve::Linear);
rt.advance_radii(&round, 0.05); // t = 0.5 → 10
let theme = crate::Theme::dark();
let ui = crate::ui::build_ui(&round, Size::new(60.0, 60.0), &rt, &theme);
let radius = ui
.scene()
.primitives()
.iter()
.find_map(|p| match p {
Primitive::Rect { radius, .. } => Some(*radius),
_ => None,
})
.expect("un rectangle de fond");
assert!(
(radius.top_left - 10.0).abs() < 1.0,
"interpolated radius: {}",
radius.top_left
);
}
/// An `animated_padding` **insets the child at layout time**: mounted at 0,
/// transitioning to 20 half-way → the child is inset by ~10 (the interpolated
/// padding).
#[test]
fn animated_padding_insets_the_child_at_layout() {
use frus_core::{Primitive, Size};
let red = Color::rgb(1.0, 0.0, 0.0);
let build = |pad: f32| {
Container::<()>::new()
.width(60.0)
.height(60.0)
.animated_padding(pad, 0.10, Curve::Linear)
.child(Container::new().width(20.0).height(20.0).color(red))
};
let mut rt = crate::runtime::Runtime::default();
rt.advance_paddings(&build(0.0), 1.0); // montage → 0
let bigger = build(20.0);
rt.advance_paddings(&bigger, 0.05); // t = 0.5 → 10
let theme = crate::Theme::dark();
let ui = crate::ui::build_ui(&bigger, Size::new(60.0, 60.0), &rt, &theme);
let rect = ui
.scene()
.primitives()
.iter()
.find_map(|p| match p {
Primitive::Rect { rect, color, .. } if color.r > 0.5 => Some(*rect),
_ => None,
})
.expect("the child's red background");
assert!(
(rect.x - 10.0).abs() < 1.0 && (rect.y - 10.0).abs() < 1.0,
"the child is inset by ~10 by the interpolated padding: {rect:?}"
);
}
/// `alignment(Center)` positions the (20×20) child at the centre of a 100×100 box
/// → its background sits at about (40, 40).
#[test]
fn alignment_centers_the_child() {
use frus_core::{Alignment, Primitive, Size};
let red = Color::rgb(1.0, 0.0, 0.0);
let root: Container<()> = Container::new()
.width(100.0)
.height(100.0)
.alignment(Alignment::CENTER)
.child(Container::new().width(20.0).height(20.0).color(red));
let rt = crate::runtime::Runtime::default();
let theme = crate::Theme::dark();
let ui = crate::ui::build_ui(&root, Size::new(100.0, 100.0), &rt, &theme);
let rect = ui
.scene()
.primitives()
.iter()
.find_map(|p| match p {
Primitive::Rect { rect, color, .. } if color.r > 0.5 => Some(*rect),
_ => None,
})
.expect("the child's red background");
assert!(
(rect.x - 40.0).abs() < 1.0 && (rect.y - 40.0).abs() < 1.0,
"centred: {rect:?}"
);
}
/// `alignment(BottomRight)` anchors the (20×20) child to the bottom-right corner
/// of a 100×100 box → its background sits at about (80, 80).
#[test]
fn alignment_anchors_child_to_a_corner() {
use frus_core::{Alignment, Primitive, Size};
let red = Color::rgb(1.0, 0.0, 0.0);
let root: Container<()> = Container::new()
.width(100.0)
.height(100.0)
.alignment(Alignment::BOTTOM_RIGHT)
.child(Container::new().width(20.0).height(20.0).color(red));
let rt = crate::runtime::Runtime::default();
let theme = crate::Theme::dark();
let ui = crate::ui::build_ui(&root, Size::new(100.0, 100.0), &rt, &theme);
let rect = ui
.scene()
.primitives()
.iter()
.find_map(|p| match p {
Primitive::Rect { rect, color, .. } if color.r > 0.5 => Some(*rect),
_ => None,
})
.expect("the child's red background");
assert!(
(rect.x - 80.0).abs() < 1.0 && (rect.y - 80.0).abs() < 1.0,
"bottom-right corner: {rect:?}"
);
}
/// A **fractional** anchor (outside the nine discrete positions) places the child
/// proportionally: `x = 0.5, y = -0.5` → fractions (0.75, 0.25) → in a 100×100
/// box with a 20×20 child (80×80 free), the background lands at about (60, 20).
/// This is what the discrete flex could not do — and what makes
/// `Tween<Alignment>` visually continuous.
#[test]
fn fractional_alignment_places_child_proportionally() {
use frus_core::{Alignment, Primitive, Size};
let red = Color::rgb(1.0, 0.0, 0.0);
let root: Container<()> = Container::new()
.width(100.0)
.height(100.0)
.alignment(Alignment::new(0.5, -0.5))
.child(Container::new().width(20.0).height(20.0).color(red));
let rt = crate::runtime::Runtime::default();
let theme = crate::Theme::dark();
let ui = crate::ui::build_ui(&root, Size::new(100.0, 100.0), &rt, &theme);
let rect = ui
.scene()
.primitives()
.iter()
.find_map(|p| match p {
Primitive::Rect { rect, color, .. } if color.r > 0.5 => Some(*rect),
_ => None,
})
.expect("the child's red background");
assert!(
(rect.x - 60.0).abs() < 1.0 && (rect.y - 20.0).abs() < 1.0,
"fractionnel : {rect:?}"
);
}
/// A **directional** anchor follows the reading direction: `CENTER_START` places
/// the child on the **left** in LTR, on the **right** in RTL (resolved at render
/// time).
#[test]
fn directional_alignment_flips_the_child_in_rtl() {
use frus_core::{AlignmentDirectional, Primitive, Size};
let red = Color::rgb(1.0, 0.0, 0.0);
let rt = crate::runtime::Runtime::default();
let child_x = |theme: &crate::Theme| {
let root: Container<()> = Container::new()
.width(100.0)
.height(100.0)
.alignment(AlignmentDirectional::CENTER_START)
.child(Container::new().width(20.0).height(20.0).color(red));
let ui = crate::ui::build_ui(&root, Size::new(100.0, 100.0), &rt, theme);
ui.scene()
.primitives()
.iter()
.find_map(|p| match p {
Primitive::Rect { rect, color, .. } if color.r > 0.5 => Some(rect.x),
_ => None,
})
.expect("the child's red background")
};
assert!(
child_x(&crate::Theme::dark()).abs() < 1.0,
"start on the left in LTR"
);
assert!(
(child_x(&crate::Theme::dark().rtl()) - 80.0).abs() < 1.0,
"start on the right in RTL"
);
}
/// `decoration(...)` applies background, radius and border as one block: the
/// background paints the given color and radius, and the border reserves its
/// width at layout time.
/// **A border side by side takes its own room on each side**, a directional one by the
/// reading direction; a circle clips as one; and each shadow said is kept (milestone
/// 641).
#[test]
fn sides_shape_and_shadows_reach_the_box() {
use frus_core::{BorderDirectional, BorderSide, BoxShape, ClipShape, TextDirection};
let sided: Container<()> = Container::new().box_border(BorderDirectional {
start: BorderSide::new(Color::WHITE, 6.0),
top: BorderSide::new(Color::WHITE, 2.0),
..Default::default()
});
assert_eq!(
sided.effective_padding_in(TextDirection::Ltr),
Insets::new(2.0, 0.0, 0.0, 6.0)
);
assert_eq!(
sided.effective_padding_in(TextDirection::Rtl),
Insets::new(2.0, 6.0, 0.0, 0.0)
);
let round: Container<()> = Container::new().shape(BoxShape::Circle).clip();
assert_eq!(Widget::<()>::clip_shape(&round), Some(ClipShape::Oval));
let two: Container<()> = Container::new().shadow(0.0, 1.0, 2.0, Color::BLACK).shadow(
0.0,
4.0,
8.0,
Color::BLACK,
);
assert_eq!(two.shadows.len(), 2, "each call adds one");
let none: Container<()> = Container::new().border(0.0, Color::WHITE);
assert_eq!(none.border, None, "no width, no border");
}
#[test]
fn decoration_applies_composite_fields() {
use frus_core::{BorderRadius, BoxDecoration, Primitive, Size};
let green = Color::rgb(0.0, 1.0, 0.0);
let deco = BoxDecoration {
color: Some(green),
radius: BorderRadius::uniform(8.0),
border: Some(Border::new(2.0, Color::WHITE).into()),
..Default::default()
};
let root: Container<()> = Container::new().width(40.0).height(40.0).decoration(deco);
// The border reserves its width in the layout padding.
assert_eq!(Widget::style(&root).padding, Insets::uniform(2.0));
let rt = crate::runtime::Runtime::default();
let theme = crate::Theme::dark();
let ui = crate::ui::build_ui(&root, Size::new(40.0, 40.0), &rt, &theme);
let (color, radius) = ui
.scene()
.primitives()
.iter()
.find_map(|p| match p {
Primitive::Rect { color, radius, .. } if color.g > 0.5 => Some((*color, *radius)),
_ => None,
})
.expect("the decorated green background");
assert!(color.g > 0.9, "a green background: {color:?}");
assert!(
(radius.top_left - 8.0).abs() < 1e-3,
"rayon composite : {}",
radius.top_left
);
}
/// `margin(...)` reserves space **around** the box: it pushes the siblings away
/// and offsets the background without growing it. In a column, a second child
/// (20 tall) with a margin of 10 starts at `y = 20 (sibling) + 10 (margin)` and
/// is inset by 10 on the left.
#[test]
fn margin_pushes_siblings_and_insets() {
use frus_core::{Primitive, Size};
let red = Color::rgb(1.0, 0.0, 0.0);
let green = Color::rgb(0.0, 1.0, 0.0);
let root = crate::Flex::<()>::column()
.width(100.0)
.child(Container::new().height(20.0).color(red))
.child(Container::new().height(20.0).margin(10.0).color(green));
let rt = crate::runtime::Runtime::default();
let theme = crate::Theme::dark();
let ui = crate::ui::build_ui(&root, Size::new(100.0, 200.0), &rt, &theme);
let rect = ui
.scene()
.primitives()
.iter()
.find_map(|p| match p {
Primitive::Rect { rect, color, .. } if color.g > 0.5 && color.r < 0.5 => {
Some(*rect)
}
_ => None,
})
.expect("the 2nd child's green background");
assert!(
(rect.y - 30.0).abs() < 0.5 && (rect.x - 10.0).abs() < 0.5,
"margin: pushed to y=30, inset to x=10: {rect:?}"
);
assert!(
(rect.height - 20.0).abs() < 0.5,
"the margin does not grow the box: {rect:?}"
);
}
#[test]
fn visible_border_reserves_layout_padding() {
// A visible border: the layout padding reserves its width.
let bordered: Container<()> = Container::new().padding(4.0).border(2.0, Color::WHITE);
assert_eq!(Widget::style(&bordered).padding, Insets::uniform(6.0));
// With no border (or an invisible one): the padding is unchanged.
let plain: Container<()> = Container::new().padding(4.0);
assert_eq!(Widget::style(&plain).padding, Insets::uniform(4.0));
let invisible: Container<()> = Container::new()
.padding(4.0)
.border(2.0, Color::TRANSPARENT);
assert_eq!(Widget::style(&invisible).padding, Insets::uniform(4.0));
}
}
#[cfg(test)]
mod clip_tests {
use super::*;
use crate::{build_ui, Runtime, Size};
use frus_core::Primitive;
fn layers(root: &Container<()>) -> Vec<frus_core::ClipShape> {
let ui = build_ui(
root,
Size::new(100.0, 100.0),
&Runtime::default(),
&Theme::default(),
);
ui.scene()
.primitives()
.iter()
.filter_map(|p| match p {
Primitive::Layer { clip_shape, .. } => Some(clip_shape.clone()),
_ => None,
})
.collect()
}
/// Off by default, as in the reference: a decoration is painted behind a child and
/// does not confine it.
#[test]
fn a_rounded_box_does_not_clip_unless_asked() {
let plain = Container::<()>::new()
.width(100.0)
.height(100.0)
.radius(12.0)
.color(Color::rgb(1.0, 0.0, 0.0))
.child(Container::<()>::new().width(100.0).height(100.0));
assert!(layers(&plain).is_empty(), "no compositing layer");
}
/// Asked, it wraps its child in a layer clipped to its own corners.
#[test]
fn clip_confines_the_child_to_the_corners() {
let clipped = Container::<()>::new()
.width(100.0)
.height(100.0)
.radius(12.0)
.clip()
.color(Color::rgb(1.0, 0.0, 0.0))
.child(Container::<()>::new().width(100.0).height(100.0));
let shapes = layers(&clipped);
assert_eq!(shapes.len(), 1);
match &shapes[0] {
frus_core::ClipShape::RRect(r) => assert_eq!(r.top_left, 12.0),
other => panic!("a rounded rectangle, not {other:?}"),
}
}
}
#[cfg(test)]
mod foreground_tests {
use super::*;
use crate::{build_ui, Runtime, Size};
use frus_core::{Primitive, Scene};
const BACK: Color = Color::rgb(1.0, 0.0, 0.0);
const CHILD: Color = Color::rgb(0.0, 1.0, 0.0);
const OVER: Color = Color::rgb(0.0, 0.0, 1.0);
fn scene(root: &Container<()>) -> Scene {
build_ui(
root,
Size::new(100.0, 100.0),
&Runtime::default(),
&Theme::default(),
)
.scene()
.clone()
}
/// The order the three coloured boxes came out in, by their colour.
fn order(root: &Container<()>) -> Vec<Color> {
scene(root)
.primitives()
.iter()
.filter_map(|p| match p {
Primitive::Rect { color, .. } if *color == BACK || *color == CHILD => Some(*color),
Primitive::Rect {
border_color,
border_width,
..
} if *border_width > 0.0 && *border_color == OVER => Some(OVER),
_ => None,
})
.collect()
}
fn card() -> Container<()> {
Container::<()>::new()
.width(100.0)
.height(100.0)
.color(BACK)
.child(
Container::<()>::new()
.width(100.0)
.height(100.0)
.color(CHILD),
)
}
/// Nothing is painted over a child unless a foreground asks for it.
#[test]
fn nothing_paints_over_the_child_by_default() {
assert_eq!(order(&card()), vec![BACK, CHILD]);
}
/// The whole point: after the child, not before it. A background could not say this.
#[test]
fn a_foreground_paints_after_the_child() {
let card = card().foreground(BoxDecoration::default().border(Border::new(2.0, OVER)));
assert_eq!(order(&card), vec![BACK, CHILD, OVER]);
}
/// It uses the container's own box, the same one the background does.
#[test]
fn it_covers_the_container_s_own_box() {
let card = card()
.padding(10.0)
.foreground(BoxDecoration::default().border(Border::new(2.0, OVER)));
let over = scene(&card)
.primitives()
.iter()
.find_map(|p| match p {
Primitive::Rect {
border_color,
border_width,
rect,
..
} if *border_width > 0.0 && *border_color == OVER => Some(*rect),
_ => None,
})
.expect("the foreground is painted");
assert_eq!((over.width, over.height), (100.0, 100.0));
}
/// A foreground that names no radius takes the container's: a square outline over a
/// rounded box is a mistake far more often than a request.
#[test]
fn a_silent_foreground_wears_the_container_s_corners() {
let card = card()
.radius(12.0)
.foreground(BoxDecoration::default().border(Border::new(2.0, OVER)));
assert_eq!(
Widget::<()>::foreground(&card, &Theme::default())
.unwrap()
.radius,
BorderRadius::uniform(12.0),
"resolved against the container on the way out"
);
}
/// Said explicitly, the foreground's own radius stands.
#[test]
fn an_explicit_radius_is_left_alone() {
let card = card().radius(12.0).foreground(
BoxDecoration::default()
.border(Border::new(2.0, OVER))
.radius(4.0),
);
assert_eq!(
Widget::<()>::foreground(&card, &Theme::default())
.unwrap()
.radius,
BorderRadius::uniform(4.0)
);
}
}
/// The reference's container rules (milestone 633): `container.dart:387`.
#[cfg(test)]
mod reference_tests {
use super::*;
use crate::{build_ui_inspected, Center, Flex, Runtime, Text};
fn rect_of(root: &dyn Widget<()>, size: Size, nth: usize) -> Rect {
let (_, nodes) = build_ui_inspected(root, size, &Runtime::default(), &Theme::dark());
nodes
.iter()
.filter(|n| n.name == "Container")
.nth(nth)
.map(|n| n.rect)
.expect("a container")
}
/// **Empty, a container takes the room its parent allows** — inside a centre, all of
/// it — and **along a row shared with others it is nothing**, the reference's
/// `LimitedBox(0)` in unbounded room.
#[test]
fn an_empty_container_takes_the_room_allowed() {
let size = Size::new(300.0, 200.0);
let alone = Center::new(Container::<()>::new().color(Color::rgb8(1, 2, 3)));
assert_eq!(rect_of(&alone, size, 0), Rect::new(0.0, 0.0, 300.0, 200.0));
let row = Flex::<()>::row()
.width(300.0)
.height(50.0)
.child(Container::new().color(Color::rgb8(1, 2, 3)))
.child(Container::new().width(10.0).height(10.0));
let empty = rect_of(&row, size, 0);
assert_eq!(
(empty.width, empty.height),
(0.0, 50.0),
"nothing along, the row across"
);
}
/// **Aligning, it fills its parent and places its child inside**; otherwise it is its
/// child's size.
#[test]
fn an_aligning_container_fills_its_parent() {
let size = Size::new(300.0, 200.0);
let aligned = Center::new(
Container::<()>::new()
.alignment(frus_core::Alignment::BOTTOM_RIGHT)
.child(Container::new().width(20.0).height(10.0)),
);
assert_eq!(
rect_of(&aligned, size, 0),
Rect::new(0.0, 0.0, 300.0, 200.0)
);
assert_eq!(
rect_of(&aligned, size, 1),
Rect::new(280.0, 190.0, 20.0, 10.0)
);
let hugging = Center::new(Container::<()>::new().child(Text::new("Hi")));
let hug = rect_of(&hugging, size, 0);
assert!(hug.width < 40.0 && hug.height < 30.0, "{hug:?}");
}
/// **Constraints**, which hold a width given with them (the reference's `tighten`).
#[test]
fn constraints_hold_the_box() {
let size = Size::new(300.0, 200.0);
let floored = Center::new(
Container::<()>::new()
.min_width(80.0)
.min_height(30.0)
.child(Text::new("Hi")),
);
let r = rect_of(&floored, size, 0);
assert_eq!((r.width, r.height), (80.0, 30.0));
let capped = Center::new(
Container::<()>::new()
.width(500.0)
.max_width(120.0)
.height(10.0),
);
assert_eq!(rect_of(&capped, size, 0).width, 120.0);
// Empty, a ceiling caps the room it takes.
let ceiling = Center::new(Container::<()>::new().max_width(50.0).max_height(40.0));
let r = rect_of(&ceiling, size, 0);
assert_eq!((r.width, r.height), (50.0, 40.0));
}
/// **A transform is painted, not laid out**, about the transform alignment.
#[test]
fn a_transform_is_about_its_alignment() {
let c = Container::<()>::new()
.width(40.0)
.height(20.0)
.translated(5.0, 6.0)
.scaled(2.0, 3.0)
.rotated(0.5)
.transform_alignment(frus_core::Alignment::TOP_LEFT);
assert_eq!(Widget::<()>::transform_translate(&c), Some((5.0, 6.0)));
assert_eq!(
Widget::<()>::transform_scale(&c),
Some((2.0, 3.0, frus_core::Alignment::TOP_LEFT))
);
assert_eq!(
Widget::<()>::transform_rotate(&c),
Some((0.5, frus_core::Alignment::TOP_LEFT))
);
let plain = Container::<()>::new().scaled(2.0, 2.0);
assert_eq!(
Widget::<()>::transform_scale(&plain).map(|t| t.2),
Some(frus_core::Alignment::CENTER),
"about the centre unless told"
);
}
}