1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
// Copyright 2018 the Xilem Authors and the Druid Authors
// SPDX-License-Identifier: Apache-2.0
use std::any::TypeId;
use accesskit::{Node, Role};
use include_doc_path::include_doc_path;
use tracing::{Span, trace_span};
use crate::core::{
AccessCtx, ChildrenIds, CollectionWidget, LayoutCtx, MeasureCtx, NewWidget, NoAction, PaintCtx,
PropertiesRef, RegisterCtx, UpdateCtx, UsesProperty, Widget, WidgetId, WidgetMut, WidgetPod,
};
use crate::imaging::Painter;
use crate::kurbo::{Axis, Size};
use crate::layout::{AsUnit, LayoutSize, LenDef, LenReq, Length};
use crate::properties::Gap;
use crate::properties::types::{CrossAxisAlignment, MainAxisAlignment};
use crate::util::Sanitize;
/// A container with either horizontal or vertical layout.
///
/// This widget is the foundation of most layouts, and is highly configurable.
///
/// Every child has a `Flex` specific configuration in the form of [`FlexParams`].
/// This configuration sets the flex factor, the basis, and the cross axis alignment.
///
/// The basis determines the starting size of each child. For fixed children this will default to
/// [`FlexBasis::Auto`] which means that they will be at their preferred size.
/// Flexible children, that is children with a flex factor greater than zero,
/// will default to [`FlexBasis::Zero`] and thus fully depend on extra space distribution.
///
/// Once all the bases have been resolved, all the remaining free space will get
/// distributed among its children based on everyone's share of the sum of all flex factors.
/// Fixed children have a flex factor of zero, so they don't get anything and stay at their basis.
/// Flexible children will get extra space on top of their basis.
///
/// If there is at least one flexible child, it will use up all the extra space.
/// However, if there are only fixed children and there is extra space,
/// then that gets distributed according to [`MainAxisAlignment`].
///
/// There is currently no fine-grained support for flex grow or flex shrink.
/// Instead every child gets their size decided in one shot, as described above.
///
#[doc = concat!(
",
")",
)]
pub struct Flex {
direction: Axis,
cross_alignment: CrossAxisAlignment,
main_alignment: MainAxisAlignment,
children: Vec<Child>,
}
/// The initial size of a [`Flex`] child before extra space distribution.
///
/// Children are ensured this initial size and if there is any extra space left,
/// that remaining space gets divided among the children based on their flex factors.
#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub enum FlexBasis {
/// Automatically determine the basis based on how the child wants to be sized.
///
/// If the child has no defined size, then its `MaxContent` will be measured.
///
/// # Performance
///
/// If used in combination with a non-zero flex factor it will cause
/// an additional measurement pass on this child during [`Flex`]'s layout.
#[default]
Auto,
/// Always use a zero basis for the child, regardless of its sizing wishes.
Zero,
}
/// Optional parameters for an item in a [`Flex`] container (row or column).
///
/// Generally, when you would like to add a flexible child to a container,
/// you can simply call [`with`](Flex::with) or [`add`](Flex::add),
/// passing the child and the desired flex factor as a `f64`, which has an impl of
/// `Into<FlexParams>`.
///
/// The flex factor must be finite and non-negative.
///
/// You can also add spacers and flexible spacers using e.g. [`with_spacer`](Flex::with_spacer).
/// Spacers are children which take up space but don't paint anything.
#[derive(Default, Debug, Copy, Clone, PartialEq)]
pub struct FlexParams {
flex: f64,
basis: Option<FlexBasis>,
alignment: Option<CrossAxisAlignment>,
}
/// Returns the in-effect basis.
///
/// Either unwraps the given `basis`, or gives a reasonable default.
///
/// `FlexBasis::Auto` if `flex` is zero and `FlexBasis::Zero` otherwise.
fn effective_basis(basis: Option<FlexBasis>, flex: f64) -> FlexBasis {
basis.unwrap_or(if flex == 0. {
FlexBasis::Auto
} else {
FlexBasis::Zero
})
}
// TODO: Remove these ephemeral scratch spaces, they are a real foot-gun.
// Currently it's fine because we always write to them before reading.
// However, having the compiler enforce that by using a local variable would be much better.
// Problems arise if e.g. measure() writes and then layout() reads-before-writing.
enum Child {
Widget {
widget: WidgetPod<dyn Widget>,
alignment: Option<CrossAxisAlignment>,
flex: f64,
basis: Option<FlexBasis>,
/// Ephemeral resolved basis.
///
/// It is a logic error to read this value before writing to it in the same method.
basis_resolved: Length,
},
Spacer {
flex: f64,
basis: Length,
/// Ephemeral resolved basis.
///
/// It is a logic error to read this value before writing to it in the same method.
basis_resolved: Length,
/// Ephemeral resolved length.
///
/// It is a logic error to read this value before writing to it in the same method.
length_resolved: Length,
},
}
// --- MARK: BUILDERS
impl Flex {
/// Creates a new `Flex` oriented along the provided axis.
pub fn for_axis(axis: Axis) -> Self {
Self {
direction: axis,
children: Vec::new(),
cross_alignment: CrossAxisAlignment::Center,
main_alignment: MainAxisAlignment::Start,
}
}
/// Creates a new horizontal container.
///
/// The child widgets are laid out horizontally, from left to right.
///
pub fn row() -> Self {
Self::for_axis(Axis::Horizontal)
}
/// Creates a new vertical container.
///
/// The child widgets are laid out vertically, from top to bottom.
pub fn column() -> Self {
Self::for_axis(Axis::Vertical)
}
/// Builder-style method for specifying the children's [`CrossAxisAlignment`].
pub fn cross_axis_alignment(mut self, alignment: CrossAxisAlignment) -> Self {
self.cross_alignment = alignment;
self
}
/// Builder-style method for specifying the children's [`MainAxisAlignment`].
pub fn main_axis_alignment(mut self, alignment: MainAxisAlignment) -> Self {
self.main_alignment = alignment;
self
}
/// Builder-style variant of [`Flex::add_fixed`].
///
/// Convenient for assembling a group of widgets in a single expression.
pub fn with_fixed(mut self, child: NewWidget<impl Widget + ?Sized>) -> Self {
let child = new_child(0., child.erased().to_pod());
self.children.push(child);
self
}
/// Builder-style method to add a flexible child to the container.
pub fn with(
mut self,
child: NewWidget<impl Widget + ?Sized>,
params: impl Into<FlexParams>,
) -> Self {
let child = new_child(params, child.erased().to_pod());
self.children.push(child);
self
}
/// Builder-style method for adding a fixed-size spacer child to the container.
///
/// A good default is [`DEFAULT_SPACER_LEN`](crate::theme::DEFAULT_SPACER_LEN).
pub fn with_fixed_spacer(mut self, len: Length) -> Self {
let new_child = Child::Spacer {
flex: 0.,
basis: len,
basis_resolved: Length::ZERO,
length_resolved: Length::ZERO,
};
self.children.push(new_child);
self
}
/// Builder-style method for adding a `flex` spacer child to the container.
///
/// The `flex` factor must be finite and non-negative.
/// Non-finite or negative flex factor will fall back to zero with a logged warning.
///
/// # Panics
///
/// Panics if `flex` is non-finite or negative and debug assertions are enabled.
pub fn with_spacer(mut self, flex: f64) -> Self {
let flex = flex.sanitize("spacer flex factor");
let new_child = Child::Spacer {
flex,
basis: Length::ZERO,
basis_resolved: Length::ZERO,
length_resolved: Length::ZERO,
};
self.children.push(new_child);
self
}
}
// --- MARK: WIDGETMUT
impl Flex {
/// Sets the flex direction (see [`Axis`]).
pub fn set_direction(this: &mut WidgetMut<'_, Self>, direction: Axis) {
this.widget.direction = direction;
this.ctx.request_layout();
}
/// Sets the children's [`CrossAxisAlignment`].
pub fn set_cross_axis_alignment(this: &mut WidgetMut<'_, Self>, alignment: CrossAxisAlignment) {
this.widget.cross_alignment = alignment;
this.ctx.request_layout();
}
/// Sets the children's [`MainAxisAlignment`].
pub fn set_main_axis_alignment(this: &mut WidgetMut<'_, Self>, alignment: MainAxisAlignment) {
this.widget.main_alignment = alignment;
this.ctx.request_layout();
}
/// Adds a non-flex child widget.
///
/// See also [`with_fixed`].
///
/// [`with_fixed`]: Flex::with_fixed
pub fn add_fixed(this: &mut WidgetMut<'_, Self>, child: NewWidget<impl Widget + ?Sized>) {
let child = new_child(0., child.erased().to_pod());
this.widget.children.push(child);
this.ctx.children_changed();
}
/// Adds an empty spacer child with the given size.
///
/// A good default is [`DEFAULT_SPACER_LEN`](crate::theme::DEFAULT_SPACER_LEN).
pub fn add_fixed_spacer(this: &mut WidgetMut<'_, Self>, len: Length) {
let new_child = Child::Spacer {
flex: 0.,
basis: len,
basis_resolved: Length::ZERO,
length_resolved: Length::ZERO,
};
this.widget.children.push(new_child);
this.ctx.request_layout();
}
/// Adds an empty spacer child with a specific `flex` factor.
///
/// The `flex` factor must be finite and non-negative.
/// Non-finite or negative flex factor will fall back to zero with a logged warning.
///
/// # Panics
///
/// Panics if `flex` is non-finite or negative and debug assertions are enabled.
pub fn add_spacer(this: &mut WidgetMut<'_, Self>, flex: f64) {
let flex = flex.sanitize("spacer flex factor");
let new_child = Child::Spacer {
flex,
basis: Length::ZERO,
basis_resolved: Length::ZERO,
length_resolved: Length::ZERO,
};
this.widget.children.push(new_child);
this.ctx.request_layout();
}
/// Inserts a non-flex child widget at the given index.
///
/// # Panics
///
/// Panics if `idx` is larger than the number of children.
pub fn insert_fixed(
this: &mut WidgetMut<'_, Self>,
idx: usize,
child: NewWidget<impl Widget + ?Sized>,
) {
let child = new_child(0., child.erased().to_pod());
this.widget.children.insert(idx, child);
this.ctx.children_changed();
}
/// Inserts an empty spacer child with the given size at the given index.
///
/// A good default is [`DEFAULT_SPACER_LEN`](crate::theme::DEFAULT_SPACER_LEN).
pub fn insert_fixed_spacer(this: &mut WidgetMut<'_, Self>, idx: usize, len: Length) {
let new_child = Child::Spacer {
flex: 0.,
basis: len,
basis_resolved: Length::ZERO,
length_resolved: Length::ZERO,
};
this.widget.children.insert(idx, new_child);
this.ctx.request_layout();
}
/// Adds an empty spacer child with a specific `flex` factor.
///
/// The `flex` factor must be finite and non-negative.
/// Non-finite or negative flex factor will fall back to zero with a logged warning.
///
/// # Panics
///
/// Panics if `flex` is non-finite or negative and debug assertions are enabled.
///
/// Panics if `idx` is larger than the number of children.
pub fn insert_spacer(this: &mut WidgetMut<'_, Self>, idx: usize, flex: f64) {
let flex = flex.sanitize("spacer flex factor");
let new_child = Child::Spacer {
flex,
basis: Length::ZERO,
basis_resolved: Length::ZERO,
length_resolved: Length::ZERO,
};
this.widget.children.insert(idx, new_child);
this.ctx.request_layout();
}
/// Replaces the child widget at the given index with a new non-flex one.
///
/// # Panics
///
/// Panics if `idx` is out of bounds.
pub fn set_fixed(
this: &mut WidgetMut<'_, Self>,
idx: usize,
child: NewWidget<impl Widget + ?Sized>,
) {
let child = new_child(0., child.erased().to_pod());
let old_child = std::mem::replace(&mut this.widget.children[idx], child);
if let Child::Widget { widget, .. } = old_child {
this.ctx.remove_child(widget);
}
this.ctx.children_changed();
}
/// Replaces the child widget at the given index with an empty spacer.
///
/// A good default is [`DEFAULT_SPACER_LEN`](crate::theme::DEFAULT_SPACER_LEN).
///
/// # Panics
///
/// Panics if `idx` is out of bounds.
pub fn set_fixed_spacer(this: &mut WidgetMut<'_, Self>, idx: usize, len: Length) {
let new_child = Child::Spacer {
flex: 0.,
basis: len,
basis_resolved: Length::ZERO,
length_resolved: Length::ZERO,
};
let old_child = std::mem::replace(&mut this.widget.children[idx], new_child);
if let Child::Widget { widget, .. } = old_child {
this.ctx.remove_child(widget);
}
this.ctx.request_layout();
}
/// Replaces the child widget at the given index
/// with an empty spacer with a specific `flex` factor.
///
/// The `flex` factor must be finite and non-negative.
/// Non-finite or negative flex factor will fall back to zero with a logged warning.
///
/// # Panics
///
/// Panics if `flex` is non-finite or negative and debug assertions are enabled.
///
/// Panics if `idx` is out of bounds.
pub fn set_spacer(this: &mut WidgetMut<'_, Self>, idx: usize, flex: f64) {
let flex = flex.sanitize("spacer flex factor");
let new_child = Child::Spacer {
flex,
basis: Length::ZERO,
basis_resolved: Length::ZERO,
length_resolved: Length::ZERO,
};
let old_child = std::mem::replace(&mut this.widget.children[idx], new_child);
if let Child::Widget { widget, .. } = old_child {
this.ctx.remove_child(widget);
}
this.ctx.request_layout();
}
}
// --- MARK: COLLECTIONWIDGET
impl CollectionWidget<FlexParams> for Flex {
/// Returns the number of children (widgets and spacers).
fn len(&self) -> usize {
self.children.len()
}
/// Returns `true` if there are no children (widgets or spacers).
fn is_empty(&self) -> bool {
self.children.is_empty()
}
/// Returns a mutable reference to the child widget at the given index.
///
/// # Panics
///
/// Panics if `idx` is out of bounds.
///
/// Panics if `idx` contains a spacer instead of a widget.
fn get_mut<'t>(this: &'t mut WidgetMut<'_, Self>, idx: usize) -> WidgetMut<'t, dyn Widget> {
let child = match &mut this.widget.children[idx] {
Child::Widget { widget, .. } => widget,
Child::Spacer { .. } => panic!("The provided Flex idx contains a spacer"),
};
this.ctx.get_mut(child)
}
/// Appends a child widget to the collection.
fn add(
this: &mut WidgetMut<'_, Self>,
child: NewWidget<impl Widget + ?Sized>,
params: impl Into<FlexParams>,
) {
let child = child.erased().to_pod();
let child = new_child(params, child);
this.widget.children.push(child);
this.ctx.children_changed();
}
/// Inserts a child widget at the given index.
///
/// # Panics
///
/// Panics if `idx` is larger than the number of children.
fn insert(
this: &mut WidgetMut<'_, Self>,
idx: usize,
child: NewWidget<impl Widget + ?Sized>,
params: impl Into<FlexParams>,
) {
let child = child.erased().to_pod();
let child = new_child(params, child);
this.widget.children.insert(idx, child);
this.ctx.children_changed();
}
/// Replaces the child widget at the given index.
///
/// # Panics
///
/// Panics if `idx` is out of bounds.
fn set(
this: &mut WidgetMut<'_, Self>,
idx: usize,
child: NewWidget<impl Widget + ?Sized>,
params: impl Into<FlexParams>,
) {
let child = child.erased().to_pod();
let child = new_child(params, child);
let old_child = std::mem::replace(&mut this.widget.children[idx], child);
if let Child::Widget { widget, .. } = old_child {
this.ctx.remove_child(widget);
}
this.ctx.children_changed();
}
/// Sets the child params at the given index.
///
/// # Panics
///
/// Panics if `idx` is out of bounds.
///
/// Panics if `idx` contains a spacer instead of a widget.
fn set_params(this: &mut WidgetMut<'_, Self>, idx: usize, params: impl Into<FlexParams>) {
let child = &mut this.widget.children[idx];
let child_val = std::mem::replace(
child,
Child::Spacer {
flex: 0.,
basis: Length::ZERO,
basis_resolved: Length::ZERO,
length_resolved: Length::ZERO,
},
);
let widget = match child_val {
Child::Widget { widget, .. } => widget,
Child::Spacer { .. } => {
panic!("Can't update flex parameters of a spacer element");
}
};
let new_child = new_child(params, widget);
*child = new_child;
this.ctx.children_changed();
}
/// Swaps the index of two children.
///
/// # Panics
///
/// Panics if `a` or `b` are out of bounds.
fn swap(this: &mut WidgetMut<'_, Self>, a: usize, b: usize) {
this.widget.children.swap(a, b);
this.ctx.children_changed();
}
/// Removes the child at the given index.
///
/// # Panics
///
/// Panics if `idx` is out of bounds.
fn remove(this: &mut WidgetMut<'_, Self>, idx: usize) {
let child = this.widget.children.remove(idx);
if let Child::Widget { widget, .. } = child {
this.ctx.remove_child(widget);
} else {
// We need to explicitly request layout in case of spacer removal
this.ctx.request_layout();
}
}
/// Removes all children.
fn clear(this: &mut WidgetMut<'_, Self>) {
if !this.widget.children.is_empty() {
for child in this.widget.children.drain(..) {
if let Child::Widget { widget, .. } = child {
this.ctx.remove_child(widget);
}
}
// We need to explicitly request layout in case we had any spacers
this.ctx.request_layout();
}
}
}
// --- MARK: OTHER IMPLS
impl FlexParams {
/// Creates custom `FlexParams` with a specific `flex` factor,
/// and optionally with [`FlexBasis`] and [`CrossAxisAlignment`].
///
/// You likely only need to create these manually if you need to specify
/// a custom basis or alignment; if you only need to use a custom `flex` factor you
/// can pass an `f64` to any of the functions that take `FlexParams`.
///
/// The `flex` factor must be finite and non-negative.
/// Non-finite or negative flex factor will fall back to zero with a logged warning.
///
/// By default, the widget uses either [`FlexBasis::Auto`] or [`FlexBasis::Zero`],
/// depending on whether the flex factor is zero or not.
///
/// By default, the widget uses the alignment of its parent [`Flex`] container.
///
/// # Panics
///
/// Panics if `flex` is non-finite or negative and debug assertions are enabled.
pub fn new(
flex: f64,
basis: impl Into<Option<FlexBasis>>,
alignment: impl Into<Option<CrossAxisAlignment>>,
) -> Self {
let flex = flex.sanitize("flex factor");
Self {
flex,
basis: basis.into(),
alignment: alignment.into(),
}
}
}
impl From<f64> for FlexParams {
fn from(flex: f64) -> Self {
Self::new(flex, None, None)
}
}
impl From<CrossAxisAlignment> for FlexParams {
fn from(alignment: CrossAxisAlignment) -> Self {
Self {
alignment: Some(alignment),
..Default::default()
}
}
}
impl Child {
fn is_widget(&self) -> bool {
matches!(self, Self::Widget { .. })
}
fn widget_mut(&mut self) -> Option<&mut WidgetPod<dyn Widget>> {
match self {
Self::Widget { widget, .. } => Some(widget),
_ => None,
}
}
fn widget(&self) -> Option<&WidgetPod<dyn Widget>> {
match self {
Self::Widget { widget, .. } => Some(widget),
_ => None,
}
}
}
/// Creates a new [`Child::Widget`].
fn new_child(params: impl Into<FlexParams>, child: WidgetPod<dyn Widget>) -> Child {
let params = params.into();
Child::Widget {
widget: child,
alignment: params.alignment,
flex: params.flex,
basis: params.basis,
basis_resolved: Length::ZERO,
}
}
/// Calculates `(space_before, space_between)` from the `extra` space given the `child_count`.
fn get_spacing(alignment: MainAxisAlignment, extra: f64, child_count: usize) -> (f64, f64) {
#![expect(clippy::needless_late_init, reason = "Readability")]
let space_before;
let space_between;
match alignment {
_ if child_count == 0 => {
space_before = 0.;
space_between = 0.;
}
MainAxisAlignment::Start => {
space_before = 0.;
space_between = 0.;
}
MainAxisAlignment::End => {
space_before = extra;
space_between = 0.;
}
MainAxisAlignment::Center => {
space_before = extra / 2.;
space_between = 0.;
}
MainAxisAlignment::SpaceBetween => {
let equal_space = extra / (child_count - 1).max(1) as f64;
space_before = 0.;
space_between = equal_space;
}
MainAxisAlignment::SpaceEvenly => {
let equal_space = extra / (child_count + 1) as f64;
space_before = equal_space;
space_between = equal_space;
}
MainAxisAlignment::SpaceAround => {
let equal_space = extra / (2 * child_count) as f64;
space_before = equal_space;
space_between = equal_space * 2.;
}
}
(space_before, space_between)
}
impl UsesProperty<Gap> for Flex {}
// --- MARK: IMPL WIDGET
impl Widget for Flex {
type Action = NoAction;
fn register_children(&mut self, ctx: &mut RegisterCtx<'_>) {
for child in self.children.iter_mut().filter_map(|x| x.widget_mut()) {
ctx.register_child(child);
}
}
fn property_changed(&mut self, ctx: &mut UpdateCtx<'_>, property_type: TypeId) {
Gap::prop_changed(ctx, property_type);
}
fn measure(
&mut self,
ctx: &mut MeasureCtx<'_>,
props: &PropertiesRef<'_>,
// The usual axis input has been named measure_axis here,
// to make it harder to use it in the wrong context by accident.
measure_axis: Axis,
len_req: LenReq,
// The usual cross_length input has been named perp_length here,
// to remove the collision with flex cross, which might not match.
perp_length: Option<Length>,
) -> Length {
let perp = measure_axis.cross();
let main = self.direction;
let cross = main.cross();
let cache = ctx.property_cache();
let gap = props.get::<Gap>(cache);
let gap_length = gap.gap.get();
let gap_count = self.children.len().saturating_sub(1);
let (main_space, cross_space) = if perp == main {
(perp_length, None)
} else {
(None, perp_length)
};
let context_size = LayoutSize::maybe(perp, perp_length);
let (len_req, min_result) = match len_req {
LenReq::MinContent | LenReq::MaxContent => (len_req, Length::ZERO),
// We always want to use up all offered space but may need even more,
// so we implement FitContent as space.max(MinContent).
LenReq::FitContent(space) => (LenReq::MinContent, space),
};
// We can skip resolving bases if we don't know the main space when measuring cross.
// That is because in that code path we don't ever read the resolved basis.
let skip_resolving_bases = measure_axis == cross && main_space.is_none();
// Resolve bases
if !skip_resolving_bases {
// Basis is always resolved with a MaxContent fallback
let main_auto = LenDef::MaxContent;
for child in &mut self.children {
match child {
Child::Widget {
widget,
flex,
basis,
basis_resolved,
..
} => match effective_basis(*basis, *flex) {
FlexBasis::Auto => {
*basis_resolved = ctx.compute_length(
widget,
main_auto,
context_size,
main,
cross_space,
);
}
FlexBasis::Zero => {
// TODO: When min/max constraints become a real thing,
// then need to account for them here.
*basis_resolved = Length::ZERO;
}
},
Child::Spacer {
basis,
basis_resolved,
..
} => {
*basis_resolved = *basis;
}
}
}
}
let mut length = Length::ZERO;
if measure_axis == main {
// Calculate the main axis length
// Find the largest desired flex fraction
let mut flex_fraction: f64 = 0.;
let main_auto = len_req.into();
for child in &mut self.children {
let desired_flex_fraction = match child {
Child::Widget {
widget,
flex,
basis,
..
} => {
if *flex > 0. {
match effective_basis(*basis, *flex) {
FlexBasis::Auto => {
// Auto basis is always MaxContent, so this child doesn't want
// any extra flex space regardless if the request is Min or Max.
0.
}
FlexBasis::Zero => {
let child_length = ctx.compute_length(
widget,
main_auto,
context_size,
main,
cross_space,
);
// Flexible children with a zero basis want to reach
// their target length purely with flex space.
child_length.get() / *flex
}
}
} else {
// Inflexible children remain at their basis size,
// and don't want any extra flex space.
0.
}
}
Child::Spacer { .. } => {
// Spacer basis fully covers its preferred size,
// so spacers don't want any extra flex space.
0.
}
};
flex_fraction = flex_fraction.max(desired_flex_fraction);
}
// Calculate the total space needed for all children
let total_space_needed = self
.children
.iter()
.map(|child| match child {
Child::Widget {
flex,
basis_resolved,
..
}
| Child::Spacer {
flex,
basis_resolved,
..
} => basis_resolved.get() + *flex * flex_fraction,
})
.sum::<f64>();
length = length.saturating_add(total_space_needed.px());
// Add all the gap lengths
let gap_lengths = gap_count as f64 * gap_length;
length = length.saturating_add(gap_lengths.px());
} else {
// Calculate the cross axis length
// If we know the main axis space then we can distribute it to children.
// This is important, because some widgets need it for accurate measurement.
// For example text uses it to set max advance.
let flex_fraction = main_space.map(|mut main_space| {
// Sum flex factors and subtract bases from main space.
let mut flex_sum = 0.;
for child in &mut self.children {
match child {
Child::Widget {
flex,
basis_resolved,
..
}
| Child::Spacer {
flex,
basis_resolved,
..
} => {
flex_sum += *flex;
main_space = main_space.saturating_sub(*basis_resolved);
}
}
}
// Subtract gap lengths
let gap_lengths = gap_count as f64 * gap_length;
main_space = main_space.saturating_sub(gap_lengths.px());
// Calculate the flex fraction, i.e. the amount of space per one flex factor
if flex_sum > 0. {
main_space.get() / flex_sum
} else {
0.
}
});
// Calculate the total space needed for all children
for child in &mut self.children {
match child {
Child::Widget {
widget,
flex,
basis_resolved,
..
} => {
let child_main_length = flex_fraction.map(|flex_fraction| {
basis_resolved.saturating_add((*flex * flex_fraction).px())
});
let cross_auto = len_req.into();
let child_cross_length = ctx.compute_length(
widget,
cross_auto,
context_size,
cross,
child_main_length,
);
length = length.max(child_cross_length);
}
// Spacers don't contribute to cross length
Child::Spacer { .. } => (),
}
}
// Gaps don't contribute to the cross axis
}
min_result.max(length)
}
fn layout(&mut self, ctx: &mut LayoutCtx<'_>, props: &PropertiesRef<'_>, size: Size) {
let cache = ctx.property_cache();
let gap = props.get::<Gap>(cache);
let gap_length = gap.gap.get();
let gap_count = self.children.len().saturating_sub(1);
let main = self.direction;
let cross = main.cross();
let cross_space = size.get_coord(cross).px();
let mut main_space = (size.get_coord(main) - gap_count as f64 * gap_length)
.max(0.)
.px();
let mut flex_sum = 0.;
// Helper function to calculate child size when main length is decided
let compute_child_size =
|ctx: &mut LayoutCtx<'_>,
child: &mut WidgetPod<dyn Widget + 'static>,
child_main_length: Length,
alignment: &Option<CrossAxisAlignment>| {
let cross_auto = match alignment.unwrap_or(self.cross_alignment) {
// Cross stretch is merely an auto fallback, not an immediate choice.
// That means that an explicit child length will override it, matching web.
CrossAxisAlignment::Stretch => LenDef::Fixed(cross_space),
_ => LenDef::FitContent(cross_space),
};
let child_cross_length = ctx.compute_length(
child,
cross_auto,
size.into(),
cross,
Some(child_main_length),
);
main.pack_size(child_main_length.get(), child_cross_length.get())
};
// Sum flex factors, resolve bases, subtract bases from main space,
// and lay out inflexible widgets.
for child in &mut self.children {
match child {
Child::Widget {
widget,
alignment,
flex,
basis,
basis_resolved,
} => {
match effective_basis(*basis, *flex) {
FlexBasis::Auto => {
// Basis is always resolved with a MaxContent fallback
let main_auto = LenDef::MaxContent;
*basis_resolved = ctx.compute_length(
widget,
main_auto,
size.into(),
main,
Some(cross_space),
);
main_space = main_space.saturating_sub(*basis_resolved);
}
FlexBasis::Zero => {
// TODO: When min/max constraints become a real thing,
// then need to account for them here, and also
// subtract the result for main_space.
*basis_resolved = Length::ZERO;
}
}
if *flex == 0. {
let child_main_length = *basis_resolved;
let child_size =
compute_child_size(ctx, widget, child_main_length, alignment);
ctx.run_layout(widget, child_size);
} else {
flex_sum += *flex;
}
}
Child::Spacer {
flex,
basis,
basis_resolved,
length_resolved,
} => {
*basis_resolved = *basis;
main_space = main_space.saturating_sub(*basis_resolved);
if *flex == 0. {
*length_resolved = *basis_resolved;
} else {
flex_sum += *flex;
}
}
}
}
// Calculate the flex fraction, i.e. the amount of space per one flex factor
let flex_fraction = if flex_sum > 0. {
main_space.get() / flex_sum
} else {
0.
};
// Offer the available space to flexible children
for child in &mut self.children {
match child {
Child::Widget {
widget,
alignment,
flex,
basis_resolved,
..
} if *flex > 0. => {
// Currently we just decide the space distribution in one go.
// When Flex gets configurable grow/shrink support,
// and min/max style constraints get implemented,
// this distribution will need to evolve into a looped solver.
let child_main_length =
basis_resolved.saturating_add((*flex * flex_fraction).px());
let child_size = compute_child_size(ctx, widget, child_main_length, alignment);
ctx.run_layout(widget, child_size);
main_space = main_space
.saturating_sub(child_main_length.saturating_sub(*basis_resolved));
}
Child::Spacer {
flex,
basis_resolved,
length_resolved,
..
} if *flex > 0. => {
let child_main_length =
basis_resolved.saturating_add((*flex * flex_fraction).px());
*length_resolved = child_main_length;
main_space =
main_space.saturating_sub(length_resolved.saturating_sub(*basis_resolved));
}
_ => (),
}
}
// We only distribute free space around widgets, not spacers.
let widget_count = self
.children
.iter()
.filter(|child| child.is_widget())
.count();
let (space_before, space_between) =
get_spacing(self.main_alignment, main_space.get(), widget_count);
// Determine the shared cross alignment baselines.
// As we currently only support the horizontal-tb writing mode, we do it only for rows.
let mut alignment_ascent: Option<f64> = None;
let mut alignment_descent: Option<f64> = None;
if main == Axis::Horizontal {
for child in &self.children {
match child {
Child::Widget {
widget, alignment, ..
} => {
let alignment = alignment.unwrap_or(self.cross_alignment);
match alignment {
CrossAxisAlignment::FirstBaseline => {
let (first_baseline, _) = ctx.child_layout_baselines(widget);
alignment_ascent = Some(
alignment_ascent
.unwrap_or(first_baseline)
.max(first_baseline),
);
}
CrossAxisAlignment::LastBaseline => {
let (_, last_baseline) = ctx.child_layout_baselines(widget);
let child_size = ctx.child_size(widget);
let descent = child_size.get_coord(cross) - last_baseline;
alignment_descent =
Some(alignment_descent.unwrap_or(descent).max(descent));
}
_ => (),
}
}
_ => (),
}
}
}
// Distribute free space and place children
let mut main_offset = space_before;
let mut previous_was_widget = false;
for child in &mut self.children {
match child {
Child::Widget {
widget, alignment, ..
} => {
if previous_was_widget {
main_offset += space_between;
}
let child_size = ctx.child_size(widget);
let alignment = alignment.unwrap_or(self.cross_alignment);
let child_origin_cross = match alignment {
CrossAxisAlignment::FirstBaseline if main == Axis::Horizontal => {
let (first_baseline, _) = ctx.child_layout_baselines(widget);
alignment_ascent.unwrap() - first_baseline
}
CrossAxisAlignment::LastBaseline if main == Axis::Horizontal => {
let (_, last_baseline) = ctx.child_layout_baselines(widget);
let descent = child_size.get_coord(cross) - last_baseline;
let end_gap = alignment_descent.unwrap() - descent;
let cross_unused = cross_space.get() - child_size.get_coord(cross);
cross_unused - end_gap
}
_ => {
let cross_unused = cross_space.get() - child_size.get_coord(cross);
alignment.offset(cross_unused)
}
};
let child_origin = main.pack_point(main_offset, child_origin_cross);
ctx.place_child(widget, child_origin);
main_offset += child_size.get_coord(main);
main_offset += gap_length;
previous_was_widget = true;
}
Child::Spacer {
length_resolved, ..
} => {
main_offset += length_resolved.get();
main_offset += gap_length;
previous_was_widget = false;
}
}
}
// Derive the container's own baselines.
// The logic here aims to fairly closely match the CSS Flexbox spec.
match (alignment_ascent, alignment_descent) {
// If there is both a first baseline and a last baseline alignment group,
// then use the corresponding shared alignment baselines as our own.
(Some(ascent), Some(descent)) => {
let first_baseline = ascent;
let last_baseline = size.get_coord(cross) - descent;
ctx.set_baselines(first_baseline, last_baseline);
}
// If there's only a first baseline alignment group, use it for both our baselines.
(Some(ascent), None) => {
ctx.set_baselines(ascent, ascent);
}
// If there's only a last baseline alignment group, use it for both our baselines.
(None, Some(descent)) => {
let baseline = size.get_coord(cross) - descent;
ctx.set_baselines(baseline, baseline);
}
// If there are no baseline alignment groups then derive it from specific children.
(None, None) => {
let any_child_widgets = self.children.iter().any(|child| child.is_widget());
if any_child_widgets {
// We use the startmost/endmost children. This is easier to implement
// and provides more stable baselines, however it does mean that
// the baselines won't necessarily match visual first/last baselines.
let first_child = self
.children
.iter()
.find(|c| c.is_widget())
.unwrap()
.widget()
.unwrap();
let (first_baseline, _) = ctx.child_aligned_baselines(first_child);
let first_child_origin = ctx.child_origin(first_child);
let first_baseline = first_child_origin.y + first_baseline;
let last_child = self
.children
.iter()
.rfind(|c| c.is_widget())
.unwrap()
.widget()
.unwrap();
let (_, last_baseline) = ctx.child_aligned_baselines(last_child);
let last_child_origin = ctx.child_origin(last_child);
let last_baseline = last_child_origin.y + last_baseline;
ctx.set_baselines(first_baseline, last_baseline);
} else {
// No child widgets, so fall back to default baselines.
ctx.clear_baselines();
}
}
}
}
fn paint(
&mut self,
_ctx: &mut PaintCtx<'_>,
_props: &PropertiesRef<'_>,
_painter: &mut Painter<'_>,
) {
}
fn accessibility_role(&self) -> Role {
Role::GenericContainer
}
fn accessibility(
&mut self,
_ctx: &mut AccessCtx<'_>,
_props: &PropertiesRef<'_>,
_node: &mut Node,
) {
}
fn children_ids(&self) -> ChildrenIds {
self.children
.iter()
.filter_map(|child| child.widget())
.map(|widget_pod| widget_pod.id())
.collect()
}
fn make_trace_span(&self, id: WidgetId) -> Span {
trace_span!("Flex", id = id.trace())
}
}
// --- MARK: TESTS
#[cfg(test)]
mod tests {
use super::*;
use crate::core::WidgetTag;
use crate::kurbo::{Cap, Line, Rect, Stroke};
use crate::layout::AsUnit;
use crate::palette;
use crate::properties::{BorderColor, BorderWidth, Dimensions, Padding};
use crate::testing::{ModularWidget, TestHarness, assert_debug_panics, assert_render_snapshot};
use crate::theme::{ACCENT_COLOR, test_property_set};
use crate::widgets::{Label, SizedBox};
#[test]
fn test_main_axis_alignment_spacing() {
let apply_align = |align, extra, child_count| {
let (space_before, space_between) = get_spacing(align, extra, child_count);
let space_after =
extra - space_before - space_between * child_count.saturating_sub(1) as f64;
(space_before, space_between, space_after)
};
// Formatting note: in the comments below:
// `[-]` represents a child.
// a number represents a non-zero amount of space.
let align = MainAxisAlignment::Start;
let (before, _, after) = apply_align(align, 10., 1);
// Spacing: [-] 10
assert_eq!(before, 0.);
assert_eq!(after, 10.);
let (before, between, after) = apply_align(align, 10., 2);
// Spacing: [-][-] 10
assert_eq!(before, 0.);
assert_eq!(between, 0.);
assert_eq!(after, 10.);
let align = MainAxisAlignment::End;
let (before, _, after) = apply_align(align, 10., 1);
// Spacing: 10 [-]
assert_eq!(before, 10.);
assert_eq!(after, 0.);
let (before, between, after) = apply_align(align, 10., 2);
// Spacing: 10 [-][-]
assert_eq!(before, 10.);
assert_eq!(between, 0.);
assert_eq!(after, 0.);
let align = MainAxisAlignment::Center;
let (before, _, after) = apply_align(align, 10., 1);
// Spacing: 5 [-] 5
assert_eq!(before, 5.);
assert_eq!(after, 5.);
let (before, between, after) = apply_align(align, 10., 3);
// Spacing: 5 [-][-][-] 5
assert_eq!(before, 5.);
assert_eq!(between, 0.);
assert_eq!(after, 5.);
let (before, between, after) = apply_align(align, 5., 2);
// Spacing: 2.5 [-][-] 2.5
assert_eq!(before, 2.5);
assert_eq!(between, 0.);
assert_eq!(after, 2.5);
let align = MainAxisAlignment::SpaceBetween;
let (before, _, after) = apply_align(align, 10., 1);
// Spacing: [-] 10
assert_eq!(before, 0.);
assert_eq!(after, 10.);
let (before, between, after) = apply_align(align, 10., 2);
// Spacing: [-] 10 [-]
assert_eq!(before, 0.);
assert_eq!(between, 10.);
assert_eq!(after, 0.);
let (before, between, after) = apply_align(align, 30., 5);
// Spacing: [-] 7.5 [-] 7.5 [-] 7.5 [-] 7.5 [-]
assert_eq!(before, 0.);
assert_eq!(between, 7.5);
assert_eq!(after, 0.);
let align = MainAxisAlignment::SpaceEvenly;
let (before, _, after) = apply_align(align, 10., 1);
// Spacing: 5 [-] 5
assert_eq!(before, 5.);
assert_eq!(after, 5.);
let (before, between, after) = apply_align(align, 10., 3);
// Spacing: 2.5 [-] 2.5 [-] 2.5 [-] 2.5
assert_eq!(before, 2.5);
assert_eq!(between, 2.5);
assert_eq!(after, 2.5);
let align = MainAxisAlignment::SpaceAround;
let (before, _, after) = apply_align(align, 10., 1);
// Spacing: 5 [-] 5
assert_eq!(before, 5.);
assert_eq!(after, 5.);
let (before, between, after) = apply_align(align, 10., 2);
// Spacing: 2.5 [-] 5 [-] 2.5
assert_eq!(before, 2.5);
assert_eq!(between, 5.);
assert_eq!(after, 2.5);
let (before, between, after) = apply_align(align, 35., 5);
// Spacing: 3.5 [-] 7 [-] 7 [-] 7 [-] 7 [-] 3.5
assert_eq!(before, 3.5);
assert_eq!(between, 7.);
assert_eq!(after, 3.5);
}
#[test]
fn invalid_flex_params() {
assert_debug_panics!(
FlexParams::new(f64::NAN, None, None),
"flex factor must be finite. Received: NaN"
);
assert_debug_panics!(
FlexParams::new(f64::INFINITY, None, None),
"flex factor must be finite. Received: inf"
);
assert_debug_panics!(
FlexParams::new(-0.5, None, None),
"flex factor must be non-negative. Received: -0.5"
);
assert_debug_panics!(
FlexParams::new(-1.0, None, None),
"flex factor must be non-negative. Received: -1"
);
}
#[test]
fn flex_row_fixed_size_only() {
let widget = NewWidget::new(
Flex::row()
.with_fixed(Label::new("hello").prepare())
.with_fixed(Label::new("world").prepare())
.with_fixed(Label::new("foo").prepare())
.with_fixed(Label::new("bar").prepare()),
)
.with_props((BorderWidth::all(2.px()), BorderColor::new(ACCENT_COLOR)));
let mut harness = TestHarness::create_with_size(test_property_set(), widget, (200, 150));
harness.edit_root_widget(|mut flex| {
Flex::set_main_axis_alignment(&mut flex, MainAxisAlignment::Start);
});
assert_render_snapshot!(harness, "flex_row_fixed_children_start");
harness.edit_root_widget(|mut flex| {
Flex::set_main_axis_alignment(&mut flex, MainAxisAlignment::Center);
});
assert_render_snapshot!(harness, "flex_row_fixed_children_center");
harness.edit_root_widget(|mut flex| {
Flex::set_main_axis_alignment(&mut flex, MainAxisAlignment::End);
});
assert_render_snapshot!(harness, "flex_row_fixed_children_end");
harness.edit_root_widget(|mut flex| {
Flex::set_main_axis_alignment(&mut flex, MainAxisAlignment::SpaceBetween);
});
assert_render_snapshot!(harness, "flex_row_fixed_children_spaceBetween");
harness.edit_root_widget(|mut flex| {
Flex::set_main_axis_alignment(&mut flex, MainAxisAlignment::SpaceEvenly);
});
assert_render_snapshot!(harness, "flex_row_fixed_children_spaceEvenly");
harness.edit_root_widget(|mut flex| {
Flex::set_main_axis_alignment(&mut flex, MainAxisAlignment::SpaceAround);
});
assert_render_snapshot!(harness, "flex_row_fixed_children_spaceAround");
}
#[test]
fn equal_children_snap_shared_edges() {
let child_1 = WidgetTag::unique();
let child_2 = WidgetTag::unique();
let child_3 = WidgetTag::unique();
let widget = Flex::row()
.cross_axis_alignment(CrossAxisAlignment::Stretch)
.with(SizedBox::empty().prepare().with_tag(child_1), 1.0)
.with(SizedBox::empty().prepare().with_tag(child_2), 1.0)
.with(SizedBox::empty().prepare().with_tag(child_3), 1.0)
.prepare()
.with_props(Gap::new(0.px()));
let harness = TestHarness::create_with_size(test_property_set(), widget, (100, 10));
let rect = |tag: WidgetTag<SizedBox>| {
let widget = harness.get_widget(tag);
let ctx = widget.ctx();
ctx.window_transform().transform_rect_bbox(ctx.border_box())
};
let rect_1 = rect(child_1);
let rect_2 = rect(child_2);
let rect_3 = rect(child_3);
assert_eq!(rect_1, Rect::new(0., 0., 33., 10.));
assert_eq!(rect_2, Rect::new(33., 0., 67., 10.));
assert_eq!(rect_3, Rect::new(67., 0., 100., 10.));
assert_eq!(rect_1.x1, rect_2.x0);
assert_eq!(rect_2.x1, rect_3.x0);
}
#[test]
fn main_axis_spacing_snaps_shared_edges() {
let child_1 = WidgetTag::unique();
let child_2 = WidgetTag::unique();
let child_3 = WidgetTag::unique();
let child = |tag| {
SizedBox::empty()
.size(10.px(), 10.px())
.prepare()
.with_tag(tag)
};
let widget = Flex::row()
.main_axis_alignment(MainAxisAlignment::SpaceEvenly)
.with_fixed(child(child_1))
.with_fixed(child(child_2))
.with_fixed(child(child_3))
.prepare()
.with_props(Gap::new(0.px()));
let harness = TestHarness::create_with_size(test_property_set(), widget, (101, 10));
let rect = |tag: WidgetTag<SizedBox>| {
let widget = harness.get_widget(tag);
let ctx = widget.ctx();
ctx.window_transform().transform_rect_bbox(ctx.border_box())
};
assert_eq!(rect(child_1), Rect::new(18., 0., 28., 10.));
assert_eq!(rect(child_2), Rect::new(46., 0., 56., 10.));
assert_eq!(rect(child_3), Rect::new(73., 0., 83., 10.));
}
#[test]
fn center_cross_alignment_snap() {
let child_tag = WidgetTag::unique();
let widget = Flex::row()
.cross_axis_alignment(CrossAxisAlignment::Center)
.with_fixed(
SizedBox::empty()
.size(10.px(), 5.4.px())
.prepare()
.with_tag(child_tag),
)
.prepare();
let harness = TestHarness::create_with_size(test_property_set(), widget, (20, 10));
let child = harness.get_widget(child_tag);
let ctx = child.ctx();
let rect = ctx.window_transform().transform_rect_bbox(ctx.border_box());
assert_eq!(rect, Rect::new(0., 2., 10., 8.));
}
// TODO - Reduce copy-pasting?
#[test]
fn flex_row_cross_axis_snapshots() {
let widget = NewWidget::new(
Flex::row()
.with_fixed(Label::new("hello").prepare())
.with(Label::new("world").prepare(), 1.0)
.with_fixed(Label::new("foo").prepare())
.with(
Label::new("bar").prepare(),
FlexParams::new(2.0, None, CrossAxisAlignment::Start),
),
)
.with_props((BorderWidth::all(2.px()), BorderColor::new(ACCENT_COLOR)));
let mut harness = TestHarness::create_with_size(test_property_set(), widget, (200, 150));
harness.edit_root_widget(|mut flex| {
Flex::set_cross_axis_alignment(&mut flex, CrossAxisAlignment::Start);
});
assert_render_snapshot!(harness, "flex_row_cross_axis_start");
harness.edit_root_widget(|mut flex| {
Flex::set_cross_axis_alignment(&mut flex, CrossAxisAlignment::Center);
});
assert_render_snapshot!(harness, "flex_row_cross_axis_center");
harness.edit_root_widget(|mut flex| {
Flex::set_cross_axis_alignment(&mut flex, CrossAxisAlignment::End);
});
assert_render_snapshot!(harness, "flex_row_cross_axis_end");
harness.edit_root_widget(|mut flex| {
Flex::set_cross_axis_alignment(&mut flex, CrossAxisAlignment::FirstBaseline);
});
assert_render_snapshot!(harness, "flex_row_cross_axis_first_baseline");
harness.edit_root_widget(|mut flex| {
Flex::set_cross_axis_alignment(&mut flex, CrossAxisAlignment::LastBaseline);
});
assert_render_snapshot!(harness, "flex_row_cross_axis_last_baseline");
// TODO: Stretch with text doesn't make sense, it's not visible,
// unless we paint borders or background for the Label widget.
harness.edit_root_widget(|mut flex| {
Flex::set_cross_axis_alignment(&mut flex, CrossAxisAlignment::Stretch);
});
assert_render_snapshot!(harness, "flex_row_cross_axis_stretch");
}
#[test]
fn flex_row_main_axis_snapshots() {
// ALl children need to be fixed, otherwise a flexible child will use up all the space.
let widget = NewWidget::new(
Flex::row()
.with_fixed(Label::new("hello").prepare())
.with_fixed(Label::new("world").prepare())
.with_fixed(Label::new("foo").prepare())
.with(Label::new("bar").prepare(), CrossAxisAlignment::Start),
)
.with_props((BorderWidth::all(2.px()), BorderColor::new(ACCENT_COLOR)));
let mut harness = TestHarness::create_with_size(test_property_set(), widget, (200, 150));
// MAIN AXIS ALIGNMENT
harness.edit_root_widget(|mut flex| {
Flex::set_main_axis_alignment(&mut flex, MainAxisAlignment::Start);
});
assert_render_snapshot!(harness, "flex_row_main_axis_start");
harness.edit_root_widget(|mut flex| {
Flex::set_main_axis_alignment(&mut flex, MainAxisAlignment::Center);
});
assert_render_snapshot!(harness, "flex_row_main_axis_center");
harness.edit_root_widget(|mut flex| {
Flex::set_main_axis_alignment(&mut flex, MainAxisAlignment::End);
});
assert_render_snapshot!(harness, "flex_row_main_axis_end");
harness.edit_root_widget(|mut flex| {
Flex::set_main_axis_alignment(&mut flex, MainAxisAlignment::SpaceBetween);
});
assert_render_snapshot!(harness, "flex_row_main_axis_spaceBetween");
harness.edit_root_widget(|mut flex| {
Flex::set_main_axis_alignment(&mut flex, MainAxisAlignment::SpaceEvenly);
});
assert_render_snapshot!(harness, "flex_row_main_axis_spaceEvenly");
harness.edit_root_widget(|mut flex| {
Flex::set_main_axis_alignment(&mut flex, MainAxisAlignment::SpaceAround);
});
assert_render_snapshot!(harness, "flex_row_main_axis_spaceAround");
}
#[test]
fn flex_col_cross_axis_snapshots() {
let widget = NewWidget::new(
Flex::column()
.with_fixed(Label::new("hello").prepare())
.with(Label::new("world").prepare(), 1.0)
.with_fixed(Label::new("foo").prepare())
.with(
Label::new("bar").prepare(),
FlexParams::new(2.0, None, CrossAxisAlignment::Start),
),
)
.with_props((BorderWidth::all(2.px()), BorderColor::new(ACCENT_COLOR)));
let mut harness = TestHarness::create_with_size(test_property_set(), widget, (200, 150));
harness.edit_root_widget(|mut flex| {
Flex::set_cross_axis_alignment(&mut flex, CrossAxisAlignment::Start);
});
assert_render_snapshot!(harness, "flex_col_cross_axis_start");
harness.edit_root_widget(|mut flex| {
Flex::set_cross_axis_alignment(&mut flex, CrossAxisAlignment::Center);
});
assert_render_snapshot!(harness, "flex_col_cross_axis_center");
harness.edit_root_widget(|mut flex| {
Flex::set_cross_axis_alignment(&mut flex, CrossAxisAlignment::End);
});
assert_render_snapshot!(harness, "flex_col_cross_axis_end");
harness.edit_root_widget(|mut flex| {
Flex::set_cross_axis_alignment(&mut flex, CrossAxisAlignment::FirstBaseline);
});
assert_render_snapshot!(harness, "flex_col_cross_axis_first_baseline");
harness.edit_root_widget(|mut flex| {
Flex::set_cross_axis_alignment(&mut flex, CrossAxisAlignment::LastBaseline);
});
assert_render_snapshot!(harness, "flex_col_cross_axis_last_baseline");
// TODO: Stretch with text doesn't make sense, it's not visible,
// unless we paint borders or background for the Label widget.
harness.edit_root_widget(|mut flex| {
Flex::set_cross_axis_alignment(&mut flex, CrossAxisAlignment::Stretch);
});
assert_render_snapshot!(harness, "flex_col_cross_axis_stretch");
}
#[test]
fn flex_col_main_axis_snapshots() {
// ALl children need to be fixed, otherwise a flexible child will use up all the space.
let widget = NewWidget::new(
Flex::column()
.with_fixed(Label::new("hello").prepare())
.with_fixed(Label::new("world").prepare())
.with_fixed(Label::new("foo").prepare())
.with(Label::new("bar").prepare(), CrossAxisAlignment::Start),
)
.with_props((BorderWidth::all(2.px()), BorderColor::new(ACCENT_COLOR)));
let mut harness = TestHarness::create_with_size(test_property_set(), widget, (200, 150));
// MAIN AXIS ALIGNMENT
harness.edit_root_widget(|mut flex| {
Flex::set_main_axis_alignment(&mut flex, MainAxisAlignment::Start);
});
assert_render_snapshot!(harness, "flex_col_main_axis_start");
harness.edit_root_widget(|mut flex| {
Flex::set_main_axis_alignment(&mut flex, MainAxisAlignment::Center);
});
assert_render_snapshot!(harness, "flex_col_main_axis_center");
harness.edit_root_widget(|mut flex| {
Flex::set_main_axis_alignment(&mut flex, MainAxisAlignment::End);
});
assert_render_snapshot!(harness, "flex_col_main_axis_end");
harness.edit_root_widget(|mut flex| {
Flex::set_main_axis_alignment(&mut flex, MainAxisAlignment::SpaceBetween);
});
assert_render_snapshot!(harness, "flex_col_main_axis_spaceBetween");
harness.edit_root_widget(|mut flex| {
Flex::set_main_axis_alignment(&mut flex, MainAxisAlignment::SpaceEvenly);
});
assert_render_snapshot!(harness, "flex_col_main_axis_spaceEvenly");
harness.edit_root_widget(|mut flex| {
Flex::set_main_axis_alignment(&mut flex, MainAxisAlignment::SpaceAround);
});
assert_render_snapshot!(harness, "flex_col_main_axis_spaceAround");
}
#[test]
fn flex_row_baselines() {
let props = |top, bottom| {
(
Padding {
top,
bottom,
left: Length::ZERO,
right: Length::ZERO,
},
BorderWidth::all(1.px()),
BorderColor::new(palette::css::CYAN),
)
};
let flex_tag = WidgetTag::unique();
let flex = NewWidget::new(
Flex::row()
.cross_axis_alignment(CrossAxisAlignment::Center)
.with_fixed(
Label::new("Left")
.prepare()
.with_props(props(0.px(), 0.px())),
)
.with_fixed(
Label::new("A\nB")
.prepare()
.with_props(props(30.px(), 10.px())),
)
.with_fixed(
Label::new("C\nD\nE")
.prepare()
.with_props(props(20.px(), 115.px())),
)
.with_fixed(
Label::new("F\nG\nH\nI")
.prepare()
.with_props(props(20.px(), 20.px())),
)
.with_fixed(
Label::new("J\nK\nL\nM\nN")
.prepare()
.with_props(props(0.px(), 30.px())),
)
.with_fixed(
Label::new("Right\nToo")
.prepare()
.with_props(props(50.px(), 50.px())),
),
)
.with_tag(flex_tag)
.with_props((BorderWidth::all(2.px()), BorderColor::new(ACCENT_COLOR)));
let root = Flex::row()
.cross_axis_alignment(CrossAxisAlignment::FirstBaseline)
.with_fixed(
Label::new("Out")
.prepare()
.with_props(props(10.px(), 10.px())),
)
.with(flex, 1.0)
.prepare()
.with_props((Gap::new(0.px()), Padding::all(20.px())));
let mut harness = TestHarness::create_with_size(test_property_set(), root, (240, 240));
assert_render_snapshot!(harness, "flex_row_baselines_four_center_and_first");
harness.edit_root_widget(|mut root| {
Flex::set_cross_axis_alignment(&mut root, CrossAxisAlignment::LastBaseline);
});
assert_render_snapshot!(harness, "flex_row_baselines_four_center_and_last");
harness.edit_widget(flex_tag, |mut flex| {
Flex::set_params(&mut flex, 1, CrossAxisAlignment::FirstBaseline);
Flex::set_params(&mut flex, 2, CrossAxisAlignment::FirstBaseline);
Flex::set_params(&mut flex, 3, CrossAxisAlignment::FirstBaseline);
Flex::set_params(&mut flex, 4, CrossAxisAlignment::FirstBaseline);
});
assert_render_snapshot!(harness, "flex_row_baselines_four_first_and_last");
harness.edit_root_widget(|mut root| {
Flex::set_cross_axis_alignment(&mut root, CrossAxisAlignment::FirstBaseline);
});
assert_render_snapshot!(harness, "flex_row_baselines_four_first_and_first");
harness.edit_widget(flex_tag, |mut flex| {
Flex::set_params(&mut flex, 4, CrossAxisAlignment::LastBaseline);
});
assert_render_snapshot!(harness, "flex_row_baselines_three_first_one_last_and_first");
harness.edit_root_widget(|mut root| {
Flex::set_cross_axis_alignment(&mut root, CrossAxisAlignment::LastBaseline);
});
assert_render_snapshot!(harness, "flex_row_baselines_three_first_one_last_and_last");
harness.edit_widget(flex_tag, |mut flex| {
Flex::set_params(&mut flex, 3, CrossAxisAlignment::LastBaseline);
});
assert_render_snapshot!(harness, "flex_row_baselines_two_first_two_last_and_last");
harness.edit_root_widget(|mut root| {
Flex::set_cross_axis_alignment(&mut root, CrossAxisAlignment::FirstBaseline);
});
assert_render_snapshot!(harness, "flex_row_baselines_two_first_two_last_and_first");
harness.edit_widget(flex_tag, |mut flex| {
Flex::set_params(&mut flex, 2, CrossAxisAlignment::LastBaseline);
});
assert_render_snapshot!(harness, "flex_row_baselines_one_first_three_last_and_first");
harness.edit_root_widget(|mut root| {
Flex::set_cross_axis_alignment(&mut root, CrossAxisAlignment::LastBaseline);
});
assert_render_snapshot!(harness, "flex_row_baselines_one_first_three_last_and_last");
harness.edit_widget(flex_tag, |mut flex| {
Flex::set_params(&mut flex, 1, CrossAxisAlignment::LastBaseline);
});
assert_render_snapshot!(harness, "flex_row_baselines_four_last_and_last");
harness.edit_root_widget(|mut root| {
Flex::set_cross_axis_alignment(&mut root, CrossAxisAlignment::FirstBaseline);
});
assert_render_snapshot!(harness, "flex_row_baselines_four_last_and_first");
}
// The green baseline should be a 1px straight line in both first and last baseline cases.
// Currently that is not the case and so pixel snapping in relation to baselines needs work.
#[test]
fn flex_row_baseline_pixel_snapping() {
struct Def {
ascent: f64,
descent: f64,
}
let child = |ascent: f64, descent: f64| {
let def = Def { ascent, descent };
ModularWidget::new(def)
.measure_fn(|s, _, _, axis, _, _| match axis {
Axis::Horizontal => 10.px(),
Axis::Vertical => (s.ascent + s.descent).px(),
})
.layout_fn(|s, ctx, _, _| {
ctx.set_baselines(s.ascent, s.ascent);
})
.paint_fn(|s, ctx, _, scene| {
let style = Stroke::new(1.).with_caps(Cap::Butt);
let line_color = palette::css::LIME_GREEN;
let bg_color = palette::css::BLACK;
let border_box = ctx.border_box();
let line = Line::new(
(border_box.x0, s.ascent + 0.5),
(border_box.x1, s.ascent + 0.5),
);
scene.fill(border_box, bg_color).draw();
scene.stroke(line, &style, line_color).draw();
})
.prepare()
};
let mut first = Flex::row().main_axis_alignment(MainAxisAlignment::Center);
for i in 0..21 {
first = first.with(
child(1. + i as f64 * 0.1, 1.),
CrossAxisAlignment::FirstBaseline,
);
}
for i in 0..21 {
first = first.with(
child(2., 1. + i as f64 * 0.1),
CrossAxisAlignment::FirstBaseline,
);
}
let mut last = Flex::row().main_axis_alignment(MainAxisAlignment::Center);
for i in 0..21 {
last = last.with(
child(1. + i as f64 * 0.1, 1.),
CrossAxisAlignment::LastBaseline,
);
}
for i in 0..21 {
last = last.with(
child(2., 1. + i as f64 * 0.1),
CrossAxisAlignment::LastBaseline,
);
}
let props = (
Gap::new(0.px()),
BorderWidth::all(1.px()),
BorderColor::new(palette::css::DARK_GRAY),
Dimensions::height(14.px()),
);
let root = Flex::column()
.main_axis_alignment(MainAxisAlignment::SpaceBetween)
.with_fixed(first.prepare().with_props(props))
.with_fixed(last.prepare().with_props(props))
.prepare()
.with_props((Gap::new(2.px()), Padding::all(10.px())));
let mut harness = TestHarness::create_with_size(test_property_set(), root, (450, 50));
assert_render_snapshot!(harness, "flex_row_baseline_pixel_snapping");
}
#[test]
fn edit_flex_container() {
let window_size = (50, 300);
let image_1 = {
let widget = Flex::column()
.with_fixed(Label::new("q").prepare())
.with_fixed(Label::new("b").prepare())
.with_fixed(Label::new("w").prepare())
.with_fixed(Label::new("d").prepare())
.prepare();
// -> qbwd
let mut harness =
TestHarness::create_with_size(test_property_set(), widget, window_size);
harness.edit_root_widget(|mut flex| {
Flex::set_fixed(&mut flex, 0, Label::new("a").prepare());
// -> abwd
Flex::set(&mut flex, 2, Label::new("c").prepare(), 0.);
// -> abcd
Flex::remove(&mut flex, 1);
// -> acd
Flex::add_fixed(&mut flex, Label::new("x").prepare());
// -> acdx
Flex::add(&mut flex, Label::new("y").prepare(), 2.0);
// -> acdxy
Flex::add_fixed_spacer(&mut flex, 5.px());
// -> acdxy_
Flex::add_spacer(&mut flex, 1.0);
// -> acdxy__
Flex::insert_fixed(&mut flex, 2, Label::new("i").prepare());
// -> acidxy__
Flex::insert(&mut flex, 2, Label::new("j").prepare(), 2.0);
// -> acjidxy__
Flex::insert_fixed_spacer(&mut flex, 2, 5.px());
// -> ac_jidxy__
Flex::insert_spacer(&mut flex, 2, 1.0);
// -> ac__jidxy__
});
harness.render()
};
let image_2 = {
let widget = Flex::column()
.with_fixed(Label::new("a").prepare())
.with_fixed(Label::new("c").prepare())
.with_spacer(1.0)
.with_fixed_spacer(5.px())
.with(Label::new("j").prepare(), 2.0)
.with_fixed(Label::new("i").prepare())
.with_fixed(Label::new("d").prepare())
.with_fixed(Label::new("x").prepare())
.with(Label::new("y").prepare(), 2.0)
.with_fixed_spacer(5.px())
.with_spacer(1.0)
.prepare();
let mut harness =
TestHarness::create_with_size(test_property_set(), widget, window_size);
harness.render()
};
// We don't use assert_eq because we don't want rich assert
assert!(image_1 == image_2);
}
#[test]
fn get_flex_child() {
let widget = Flex::column()
.with_fixed(Label::new("hello").prepare())
.with_fixed(Label::new("world").prepare())
.with_fixed_spacer(1.px())
.prepare();
let mut harness = TestHarness::create_with_size(test_property_set(), widget, (200, 150));
harness.edit_root_widget(|mut flex| {
let mut child = Flex::get_mut(&mut flex, 1);
assert_eq!(
child
.try_downcast::<Label>()
.unwrap()
.widget
.text()
.to_string(),
"world"
);
drop(child);
});
// TODO - test out-of-bounds access?
}
#[test]
fn divide_by_zero() {
let widget = Flex::column().with_spacer(0.0).prepare();
// Running layout should not panic when the flex sum is zero.
let mut harness = TestHarness::create_with_size(test_property_set(), widget, (200, 150));
harness.render();
}
}