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
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
//! [`TabBar`]: a **controlled** tab bar plus the selected panel.
//!
//! It is composite: its children are `[bar, panel]`, in a column. Only the selected tab's
//! content is realised, the application rebuilding the view every frame.
//!
//! The bar is a **tab bar**, not a row of buttons: labels on the surface, a sliding
//! indicator under the selected one, and a hairline across the whole bar separating it from
//! the panel. The two variants are the reference's — a *primary* bar's indicator is as wide
//! as its **label** and rounded at the top, a *secondary* bar's spans the whole **tab** and
//! is square — and every measurement and colour in either is overridable, by the caller or
//! by [`crate::TabBarTheme`].
use std::rc::Rc;
use frus_core::{BorderRadius, Color, Point, Rect, Scene, TextStyle};
use frus_layout::{Dimension, FlexDirection, Style};
use crate::disabled::disabled_content;
use crate::icons::IconData;
use crate::interaction::Status;
use crate::pageview::PageView;
use crate::theme::Theme;
use crate::transparent::Shared;
use crate::widget::Widget;
/// The height of the tabs themselves, indicator excluded.
pub const TAB_HEIGHT: f32 = 46.0;
/// The height of the tabs when **any** of them stacks an icon over a label. The
/// reference's second figure, and it applies to the whole row: tabs of two heights in
/// one bar would put their labels on two different lines.
pub const TAB_ICON_HEIGHT: f32 = 72.0;
/// The side of a tab's icon.
pub const TAB_ICON_SIZE: f32 = 24.0;
/// The room between a tab's icon and the label under it.
pub const TAB_ICON_GAP: f32 = 2.0;
/// The room on either side of a label.
pub const TAB_LABEL_PADDING: f32 = 16.0;
/// The inset [`TabAlignment::StartOffset`] leaves before the first tab.
pub const TAB_START_OFFSET: f32 = 52.0;
/// The thickness of a **primary** bar's indicator, which is also its corner radius.
pub const TAB_INDICATOR_PRIMARY: f32 = 3.0;
/// The thickness of a **secondary** bar's indicator.
pub const TAB_INDICATOR_SECONDARY: f32 = 2.0;
/// The hairline between the bar and the panel.
pub const TAB_DIVIDER_HEIGHT: f32 = 1.0;
/// Which of the two tab bars this is.
///
/// They differ in more than looks: a *primary* bar marks the selected tab with an indicator
/// as wide as its label, and a *secondary* bar with one as wide as the whole tab. A primary
/// bar is for the top level of a screen, a secondary one for a division inside it.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
pub enum TabBarVariant {
/// Label-wide indicator, rounded at the top; the selected label takes the accent.
#[default]
Primary,
/// Tab-wide indicator, square.
Secondary,
}
/// Where the tabs sit in a bar with room to spare.
///
/// The question only arises when the tabs do not already fill the bar — which is either
/// because they were told not to share it, or because there are two of them in a window
/// meant for six.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
pub enum TabAlignment {
/// Whatever the bar's mode implies: [`Fill`](Self::Fill) when it shares its width,
/// [`Start`](Self::Start) when it scrolls. The default, and the reference's.
#[default]
Auto,
/// Each tab as wide as it needs, packed against the leading edge.
Start,
/// The same, after an inset of [`TAB_START_OFFSET`].
StartOffset,
/// The tabs share the bar's width in equal parts.
///
/// Meaningless on a bar that **scrolls**, since sharing a width is the opposite of
/// exceeding it, and it reads as [`Start`](Self::Start) there. The reference throws
/// instead; a layout that throws is a crash on somebody's phone for a combination
/// that has an obvious reading.
Fill,
/// Each tab as wide as it needs, the row centred in the bar.
///
/// For a bar that does **not** scroll. Centring needs something definite to centre
/// in, and the content of a scroll region has no definite width across the axis it
/// scrolls along — the strip is measured by its own tabs, so a percentage of its
/// parent resolves against nothing and it comes out exactly as wide as the tabs it
/// holds, with no room left over to share. So it reads as [`Start`](Self::Start)
/// there.
///
/// The two are not really alternatives anyway: a bar whose tabs might overflow wants
/// `Start` and a scroll, and a bar whose tabs certainly fit wants `Center` and no
/// scroll at all.
Center,
}
impl TabAlignment {
/// What this means for a bar that does or does not scroll.
///
/// The reference forbids [`Start`](Self::Start) and [`StartOffset`](Self::StartOffset)
/// on a bar that shares its width, for reasons that are its own history rather than
/// anything about the layout — packing natural-width tabs against the leading edge of
/// a bar that does not scroll is a perfectly ordinary thing to want, and it is what
/// they do here.
fn resolved(self, scrolls: bool) -> Self {
match (self, scrolls) {
(Self::Auto, true) | (Self::Fill, true) | (Self::Center, true) => Self::Start,
(Self::Auto, false) => Self::Fill,
(other, _) => other,
}
}
/// The inset before the first tab.
fn lead(self) -> f32 {
match self {
Self::StartOffset => TAB_START_OFFSET,
_ => 0.0,
}
}
}
/// One tab's content: what it says, what it shows, and which of the two is drawn.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct TabSpec {
/// The tab's text — drawn when `show_label`, and what a screen reader is told
/// either way.
pub label: String,
/// The icon above the label, if any.
pub icon: Option<IconData>,
/// Whether the label is **drawn**. False for an icon-only tab, whose label is still
/// its name as far as anything that cannot see is concerned. The reference leaves an
/// icon-only tab nameless and expects the caller to wrap it; asking for the word up
/// front costs nothing and cannot be forgotten.
pub show_label: bool,
/// Whether the caller draws this tab themselves, in which case the label and the icon
/// above are only what it is **called** and nothing is painted from them.
pub drawn: bool,
/// How wide this tab asks to be when the bar scrolls. `None` — the ordinary answer —
/// leaves it to the label and the icon.
pub width: Option<f32>,
}
impl TabSpec {
/// A tab that shows its text.
fn text(label: impl Into<String>) -> Self {
Self {
label: label.into(),
icon: None,
show_label: true,
drawn: false,
width: None,
}
}
/// Does this tab stack an icon **over** a label? The question the row's height turns
/// on: an icon on its own sits in an ordinary tab.
fn stacked(&self) -> bool {
self.icon.is_some() && self.show_label && !self.label.is_empty()
}
}
/// Everything about a tab bar's appearance, each part `None` until someone says otherwise.
///
/// Held by the bar and by each tab, so that both measure the indicator the same way — the
/// bar draws it, the tabs are what it is measured against, and the two disagreeing would be
/// an indicator that does not line up with the label it points at.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct TabStyle {
pub variant: Option<TabBarVariant>,
pub indicator_color: Option<Color>,
pub indicator_weight: Option<f32>,
pub label_color: Option<Color>,
pub unselected_label_color: Option<Color>,
pub label_style: Option<TextStyle>,
pub divider_color: Option<Color>,
pub divider_height: Option<f32>,
pub label_padding: Option<f32>,
pub tab_height: Option<f32>,
/// Where the tabs sit when they do not fill the bar; see [`TabBar::alignment`].
pub alignment: Option<TabAlignment>,
/// Does any tab in this bar stack an icon over a label? Not an override but a fact
/// about the row, recorded here because the bar and every tab must measure the same
/// height and this is the one thing both already hold.
pub tall: bool,
}
impl TabStyle {
fn variant(&self, theme: &Theme) -> TabBarVariant {
self.variant
.or(theme.widgets.tab_bar.variant)
.unwrap_or_default()
}
fn indicator_weight(&self, theme: &Theme) -> f32 {
self.indicator_weight
.or(theme.widgets.tab_bar.indicator_weight)
.unwrap_or(match self.variant(theme) {
TabBarVariant::Primary => TAB_INDICATOR_PRIMARY,
TabBarVariant::Secondary => TAB_INDICATOR_SECONDARY,
})
}
fn indicator_color(&self, theme: &Theme) -> Color {
self.indicator_color
.or(theme.widgets.tab_bar.indicator_color)
.unwrap_or(theme.scheme.primary)
}
fn label_color(&self, theme: &Theme) -> Color {
self.label_color
.or(theme.widgets.tab_bar.label_color)
.unwrap_or(match self.variant(theme) {
// A primary bar's selected label takes the accent; a secondary bar's stays
// on the surface, the indicator alone marking it.
TabBarVariant::Primary => theme.scheme.primary,
TabBarVariant::Secondary => theme.scheme.on_surface,
})
}
fn unselected_label_color(&self, theme: &Theme) -> Color {
self.unselected_label_color
.or(theme.widgets.tab_bar.unselected_label_color)
.unwrap_or(theme.scheme.on_surface_variant)
}
fn label_style(&self, theme: &Theme) -> TextStyle {
self.label_style
.or(theme.widgets.tab_bar.label_style)
.unwrap_or(theme.text.title_small)
}
fn divider_color(&self, theme: &Theme) -> Color {
self.divider_color
.or(theme.widgets.tab_bar.divider_color)
.unwrap_or(theme.scheme.outline_variant)
}
fn divider_height(&self, theme: &Theme) -> f32 {
self.divider_height
.or(theme.widgets.tab_bar.divider_height)
.unwrap_or(TAB_DIVIDER_HEIGHT)
}
fn label_padding(&self, theme: &Theme) -> f32 {
self.label_padding
.or(theme.widgets.tab_bar.label_padding)
.unwrap_or(TAB_LABEL_PADDING)
}
/// Where the tabs sit, resolved against what the bar does.
fn alignment(&self, theme: &Theme, scrolls: bool) -> TabAlignment {
self.alignment
.or(theme.widgets.tab_bar.alignment)
.unwrap_or_default()
.resolved(scrolls)
}
fn tab_height(&self, theme: &Theme) -> f32 {
self.tab_height
.or(theme.widgets.tab_bar.tab_height)
.unwrap_or(match self.tall {
true => TAB_ICON_HEIGHT,
false => TAB_HEIGHT,
})
}
/// The **whole bar**'s height: the tabs, plus the indicator sitting under them.
fn bar_height(&self, theme: &Theme) -> f32 {
self.tab_height(theme) + self.indicator_weight(theme)
}
/// The width the indicator takes under the tab holding `label`, within a tab `tab_width`
/// wide. A primary bar measures the label; a secondary one takes the tab.
/// How wide one tab is when the bar **scrolls**: its label, plus the label's own
/// room either side.
///
/// The tab lays itself out to this number and the indicator is placed by it, which
/// is the point of there being one function. A tab that measured itself one way and
/// an indicator that measured it another would agree on every label until they did
/// not, and the failure would be an underline creeping away from its tab as the bar
/// filled up.
fn scrolled_tab_width(&self, theme: &Theme, spec: &TabSpec) -> f32 {
self.content_width(theme, spec) + 2.0 * self.label_padding(theme)
}
/// How wide a tab's **content** is: its text, its icon, or whichever of the two is
/// wider when it has both, since they are stacked rather than side by side.
///
/// One function, and both the tab's width and the indicator's come from it. A tab
/// measured one way and an indicator measured another would agree on every label
/// until they did not.
fn content_width(&self, theme: &Theme, spec: &TabSpec) -> f32 {
// A tab the caller drew cannot be asked how wide it would like to be
// ([#52](https://github.com/KalybosPro/frus/issues/52)), so it says. Unsaid, its
// name is the proxy — right for a label with a dot beside it, short for a label
// with a count in a pill, and never consulted at all on a bar that does not
// scroll, where the tabs share the width in equal parts.
if let Some(width) = spec.width {
return width;
}
let text = match spec.show_label && !spec.label.is_empty() {
true => {
let style = self.label_style(theme);
frus_text::measure_style(&spec.label, style).width
}
false => 0.0,
};
let icon = match spec.icon {
Some(_) => TAB_ICON_SIZE,
None => 0.0,
};
text.max(icon)
}
/// Where each tab starts and how wide it is, in the bar's own coordinates.
///
/// Not scrollable, the tabs share the width in equal parts — the reference's rule,
/// and the one that keeps a tab still when another is renamed. Scrollable, each takes
/// the room its label needs.
fn tab_spans(
&self,
theme: &Theme,
tabs: &[TabSpec],
width: f32,
alignment: TabAlignment,
) -> Vec<(f32, f32)> {
if alignment == TabAlignment::Fill {
let each = width / tabs.len().max(1) as f32;
return (0..tabs.len()).map(|i| (i as f32 * each, each)).collect();
}
let widths: Vec<f32> = tabs
.iter()
.map(|spec| self.scrolled_tab_width(theme, spec))
.collect();
// Centred, the row's own leading inset is half of whatever is left over — and
// nothing when there is nothing left over, which is the case that matters: a
// scrolling bar's strip is as wide as its tabs, so the two agree at zero rather
// than the indicator drifting off by half an overflow.
let lead = match alignment {
TabAlignment::Center => (width - widths.iter().sum::<f32>()) / 2.0,
other => other.lead(),
}
.max(0.0);
let mut spans = Vec::with_capacity(tabs.len());
let mut x = lead;
for w in widths {
spans.push((x, w));
x += w;
}
spans
}
fn indicator_width(&self, theme: &Theme, spec: &TabSpec, tab_width: f32) -> f32 {
match self.variant(theme) {
TabBarVariant::Secondary => tab_width,
TabBarVariant::Primary => {
// Never past the content's own room: an indicator running into the next
// tab's would point at two labels at once.
let room = (tab_width - 2.0 * self.label_padding(theme)).max(0.0);
self.content_width(theme, spec).min(room)
}
}
}
}
/// One tab: a label, a tap, and the ink a tap leaves.
struct Tab<Msg> {
spec: TabSpec,
/// `[the caller's widget]` for a tab they drew, empty otherwise.
children: Vec<Box<dyn Widget<Msg>>>,
selected: bool,
style: TabStyle,
/// The bar's availability, handed down to every tab.
enabled: bool,
/// Whether the bar scrolls. Half of the question "does this tab share the bar's
/// width"; the other half is the [`TabAlignment`], which only the theme can settle.
scrolls: bool,
message: Msg,
}
impl<Msg: Clone> Widget<Msg> for Tab<Msg> {
fn style(&self) -> Style {
self.style_themed(&Theme::default())
}
fn style_themed(&self, theme: &Theme) -> Style {
// A zero basis with equal growth: the tabs share the bar's width in equal parts,
// which is what the reference does with a bar that is not scrollable. Sharing it in
// proportion to the labels instead would move every tab whenever one was renamed.
// The padding is the label's own room, and the smallest a tab will agree to be.
let pad = self.style.label_padding(theme);
// Asked of the **theme**, here rather than once at build time: an application
// that sets the alignment on its theme sets it for tabs that were built before
// the theme was ever consulted.
// A tab the caller drew holds their widget as a child, centred in whatever room
// the tab ends up with — a row of one, rather than a slot the tab paints into.
let drawn = match self.spec.drawn {
true => Style {
flex_direction: FlexDirection::Row,
align: frus_layout::Align::Center,
justify: frus_layout::Justify::Center,
..Default::default()
},
false => Style::default(),
};
if self.style.alignment(theme, self.scrolls) == TabAlignment::Fill {
return Style {
width: Dimension::Length(0.0),
flex_grow: 1.0,
padding: frus_core::Insets::new(0.0, pad, 0.0, pad),
..drawn
};
}
// Otherwise the tab takes the room its content needs and no more, which is the
// whole difference — eight tabs on a phone stop being eight crushed columns and
// become eight readable ones the bar scrolls through.
//
// The width is **stated**, not left to the content, because a tab paints its own
// label rather than holding a `Text` child: there is nothing here for the layout
// engine to measure. Stating it also makes the tab and the indicator agree by
// construction, since both ask the same function.
Style {
width: Dimension::Length(self.style.scrolled_tab_width(theme, &self.spec)),
flex_grow: 0.0,
flex_shrink: 0.0,
padding: frus_core::Insets::new(0.0, pad, 0.0, pad),
..drawn
}
}
fn children(&self) -> &[Box<dyn Widget<Msg>>] {
&self.children
}
fn paint(&self, bounds: Rect, status: Status, theme: &Theme, scene: &mut Scene) {
// A tab the caller drew paints **nothing** of its own. Its name is still its name
// — the semantics below say it — but a bar that painted a label under a caller's
// badge would be drawing the same thing twice.
if self.spec.drawn {
return;
}
let o = status.opacity;
let label_style = self.style.label_style(theme);
// A label is content whichever tab it is on, so both the selected and the
// unselected one flatten to the same grey. Fading the accent instead would read as
// *quietly selected* rather than as unavailable.
let color = if !self.enabled {
disabled_content(theme)
} else if self.selected {
self.style.label_color(theme)
} else {
self.style.unselected_label_color(theme)
};
let shows_label = self.spec.show_label && !self.spec.label.is_empty();
let measured = match shows_label {
true => frus_text::measure_style(&self.spec.label, label_style),
false => frus_core::Size::new(0.0, 0.0),
};
// Centred across the tab, and centred in the **tabs' own** height rather than the
// bar's: the indicator's weight belongs to the bar, not to the row of labels, so
// counting it here would push every label a pixel and a half down.
let height = self.style.tab_height(theme);
// Icon over label, as one block, centred as one block. Measuring the two
// separately and centring each would leave the pair looking untidy in a row
// where one tab has an icon and its neighbour does not.
let icon_block = match self.spec.icon {
Some(_) if shows_label => TAB_ICON_SIZE + TAB_ICON_GAP,
Some(_) => TAB_ICON_SIZE,
None => 0.0,
};
let block = icon_block + measured.height * f32::from(u8::from(shows_label));
let top = bounds.y + (height - block) / 2.0;
if let Some(icon) = self.spec.icon {
// The 24x24 grid, unscaled, centred across the tab.
let path = icon.placed(
TAB_ICON_SIZE,
bounds.x + (bounds.width - TAB_ICON_SIZE) / 2.0,
top,
theme.direction,
);
scene.fill_path(&path, color.fade(o));
}
if shows_label {
scene.text(
Point::new(
bounds.x + (bounds.width - measured.width) / 2.0,
top + icon_block,
),
self.spec.label.clone(),
&label_style.resolved(),
color.fade(o),
);
}
}
fn on_click(&self) -> Option<Msg> {
if !self.enabled {
return None;
}
Some(self.message.clone())
}
fn ink(&self, theme: &Theme) -> Option<crate::InkStyle> {
// A disabled tab does not answer a tap, so it does not splash either.
if !self.enabled {
return None;
}
// The splash follows the label: the accent under a selected tab, the surface's own
// ink under the others — the reference's overlay, which changes with the state
// rather than being one colour for the bar.
let splash = if self.selected {
self.style.indicator_color(theme).fade(0.10)
} else {
theme.scheme.on_surface.fade(0.08)
};
Some(crate::InkStyle::of(theme).color(splash).radius(0.0))
}
fn focusable(&self) -> bool {
self.enabled
}
fn semantics(&self) -> Option<frus_core::SemanticsProperties> {
// Which tab is showing survives: a reader who cannot switch is still owed where
// they are.
let semantics = frus_core::SemanticsProperties::new(frus_core::Role::Tab)
.label(self.spec.label.clone())
.toggled(self.selected);
Some(if self.enabled {
semantics.clickable()
} else {
semantics.disabled(true)
})
}
}
/// The bar itself: the tabs in a row, the hairline under them, and the indicator that
/// slides from one to the next.
struct TabStrip<Msg> {
selected: usize,
tabs: Vec<TabSpec>,
style: TabStyle,
/// Whether the bar scrolls: it decides both the strip's width and where the
/// indicator goes.
scrolls: bool,
/// The bar's availability. The **indicator** is the part that would otherwise keep the
/// accent on a disabled bar: milestone 324's golden showed exactly that, flattened
/// labels above a bar still painted in the accent colour.
enabled: bool,
children: Vec<Box<dyn Widget<Msg>>>,
}
impl<Msg: Clone> Widget<Msg> for TabStrip<Msg> {
fn style(&self) -> Style {
self.style_themed(&Theme::default())
}
fn style_themed(&self, theme: &Theme) -> Style {
// Centring needs something to centre **in**: the strip takes the bar's whole
// width, and the row is placed inside it. Only reachable on a bar that does not
// scroll, for exactly that reason — see [`TabAlignment::Center`].
let alignment = self.style.alignment(theme, self.scrolls);
let centred = alignment == TabAlignment::Center;
Style {
// Scrollable, the strip is as wide as its tabs, which is what gives the
// scroll something to scroll through.
width: match self.scrolls && !centred {
true => Dimension::Auto,
false => Dimension::Percent(1.0),
},
height: Dimension::Length(self.style.bar_height(theme)),
flex_direction: FlexDirection::Row,
justify: match centred {
true => frus_layout::Justify::Center,
false => frus_layout::Justify::Start,
},
padding: frus_core::Insets::new(0.0, 0.0, 0.0, alignment.lead()),
..Default::default()
}
}
fn children(&self) -> &[Box<dyn Widget<Msg>>] {
&self.children
}
/// The selected index, handed to the runtime so that it arrives here as a **fractional**
/// index while the selection moves: that is what the indicator slides along.
fn anim_target(&self) -> Option<f32> {
Some(self.selected as f32)
}
fn paint(&self, bounds: Rect, status: Status, theme: &Theme, scene: &mut Scene) {
let count = self.tabs.len();
if count == 0 || bounds.width <= 0.0 {
return;
}
let o = status.opacity;
let weight = self.style.indicator_weight(theme);
// The hairline is **not** here. It divides the bar from the panel and belongs to
// neither tab -- and once the strip can scroll, drawing it here would send it
// sliding away with the labels and leave a scrollable bar with two tabs ruling a
// stub instead of a line. `TabBar` draws it, across its own width, which is the
// width it always meant.
if weight <= 0.0 {
return;
}
// Where the indicator is, which is generally **between** two tabs: the runtime
// tweens the selected index, so this is a fractional position and the indicator
// slides rather than jumps. Its width travels with it, so an indicator moving
// between a short label and a long one grows on the way.
let spans = self.style.tab_spans(
theme,
&self.tabs,
bounds.width,
self.style.alignment(theme, self.scrolls),
);
let last = (count - 1) as f32;
let value = status.value.clamp(0.0, last);
let (low, high) = (value.floor(), value.ceil());
let t = value - low;
let span = |index: f32| {
let i = index as usize;
let (start, tab_width) = spans[i];
let centre = bounds.x + start + tab_width / 2.0;
let width = self.style.indicator_width(theme, &self.tabs[i], tab_width);
(centre, width)
};
let (centre_low, width_low) = span(low);
let (centre_high, width_high) = span(high);
let centre = centre_low + (centre_high - centre_low) * t;
let width = width_low + (width_high - width_low) * t;
// It sits **on** the hairline, at the bar's bottom edge, rounded at the top for a
// primary bar only — square where it spans the whole tab, since a rounded end
// touching the next tab's would read as a gap that is not there.
let radius = match self.style.variant(theme) {
TabBarVariant::Primary => BorderRadius {
top_left: weight,
top_right: weight,
..BorderRadius::ZERO
},
TabBarVariant::Secondary => BorderRadius::ZERO,
};
scene.draw_rect(
Rect::new(
centre - width / 2.0,
bounds.y + bounds.height - weight,
width,
weight,
),
if self.enabled {
self.style.indicator_color(theme)
} else {
disabled_content(theme)
}
.fade(o),
radius,
0.0,
Color::TRANSPARENT,
);
}
fn on_click(&self) -> Option<Msg> {
None
}
/// The selected tab, so a bar wider than its window slides to it.
///
/// Only when the bar **scrolls**. A bar that shares its width has every tab on
/// screen already, and the region it would ask does not exist.
///
/// Centred rather than merely brought in, which is the reference's behaviour and the
/// readable one: a selected tab flush against the edge reads as the end of the row
/// when it is only the edge of the window. The clamp keeps the first and last tabs
/// where they belong.
fn keep_visible(&self, size: frus_core::Size, theme: &Theme) -> Option<crate::ui::KeepVisible> {
if !self.scrolls {
return None;
}
let spans = self.style.tab_spans(
theme,
&self.tabs,
size.width,
self.style.alignment(theme, self.scrolls),
);
let &(x, width) = spans.get(self.selected)?;
Some(crate::ui::KeepVisible {
key: self.selected as u64,
rect: Rect::new(x, 0.0, width, size.height),
centre: true,
})
}
}
/// **One tab of a [`TabBar`]**: what is drawn on it, and what it is called.
///
/// The four shorthands on the bar — [`tab`](TabBar::tab), [`icon_tab`](TabBar::icon_tab),
/// [`icon_only_tab`](TabBar::icon_only_tab) and [`tab_widget`](TabBar::tab_widget) — each
/// build one of these and are what most call sites should write. This is the door to the
/// one thing they cannot carry: how wide a tab asks to be on a bar that **scrolls**.
///
/// **The label is never optional**, even on a tab that draws neither the word nor
/// anything resembling one. It is what a screen reader says, and a tab nobody can name is
/// a tab nobody can use. The reference leaves such a tab nameless and expects the caller
/// to wrap it in something that names it; asking for the word here costs nothing and
/// cannot be forgotten.
///
/// ```
/// use frus_widgets::{Align, Badge, Container, Flex, TabBar, TabItem, text};
///
/// # #[derive(Clone)] enum Msg { Select(usize) }
/// let unread: Flex<Msg> = Flex::row()
/// .align(Align::Center)
/// .gap(6.0)
/// .child(text("Inbox").size(14.0))
/// .child(Badge::new("12"));
/// let bar = TabBar::new(0, Msg::Select)
/// .scrollable(true)
/// .item(
/// TabItem::widget(unread, "Inbox").width(110.0),
/// Container::<Msg>::new(),
/// )
/// .tab("Archive", Container::<Msg>::new());
/// ```
pub struct TabItem<Msg = crate::callback::Callback> {
spec: TabSpec,
child: Option<Rc<dyn Widget<Msg>>>,
}
impl<Msg> TabItem<Msg> {
/// A tab that is a word — what [`TabBar::tab`] builds.
pub fn new(label: impl Into<String>) -> Self {
Self {
spec: TabSpec::text(label),
child: None,
}
}
/// A tab with an **icon over its label**.
pub fn icon(icon: IconData, label: impl Into<String>) -> Self {
Self {
spec: TabSpec {
icon: Some(icon),
..TabSpec::text(label)
},
child: None,
}
}
/// A tab showing **only** an icon, in a row of the ordinary height. The label is what
/// it is called, not what is drawn.
pub fn icon_only(icon: IconData, label: impl Into<String>) -> Self {
Self {
spec: TabSpec {
icon: Some(icon),
show_label: false,
..TabSpec::text(label)
},
child: None,
}
}
/// A tab **the caller draws**: a label with an unread count beside it, a coloured dot,
/// two lines, rich text.
///
/// `label` is what it is called. The bar paints nothing of its own on such a tab —
/// drawing a label under the caller's own would be drawing the same thing twice — but
/// the ink of a press, the indicator and the announcement are all still the bar's.
pub fn widget(child: impl Widget<Msg> + 'static, label: impl Into<String>) -> Self {
Self {
spec: TabSpec {
drawn: true,
..TabSpec::text(label)
},
child: Some(Rc::new(child)),
}
}
/// How wide this tab asks to be **when the bar scrolls**, in logical pixels.
///
/// A bar that does not scroll shares its width between its tabs in equal parts and
/// never asks, so this is meaningless there. When it does scroll, an ordinary tab is
/// measured from its label and a tab the caller drew cannot be measured at all — a
/// widget cannot be asked how wide it would like to be
/// ([#52](https://github.com/KalybosPro/frus/issues/52)) — so it falls back to its
/// name, which is right for a label with a dot beside it and short for a label with a
/// count in a pill. This is how the caller says.
#[must_use]
pub fn width(mut self, width: f32) -> Self {
self.spec.width = Some(width);
self
}
}
/// A tabbed view: the bar, and the selected tab's panel under it.
pub struct TabBar<Msg = crate::callback::Callback> {
selected: usize,
on_select: Rc<dyn Fn(usize) -> Msg>,
tabs: Vec<TabSpec>,
/// The widget on each tab the caller drew, by tab index.
drawn: Vec<Option<Rc<dyn Widget<Msg>>>>,
enabled: bool,
style: TabStyle,
/// Whether the bar scrolls rather than sharing its width; see [`TabBar::scrollable`].
scrollable: bool,
/// Whether a drag across the panel changes tab; see [`TabBar::swipeable`].
swipeable: bool,
/// Every tab's panel, kept only while [`swipeable`](TabBar::swipeable) — the page view
/// needs to be able to build any of them, not just the one showing.
panels: Vec<Rc<dyn Widget<Msg>>>,
/// Either `[bar]` or `[bar, panel]`.
children: Vec<Box<dyn Widget<Msg>>>,
}
impl<Msg: Clone + 'static> TabBar<Msg> {
/// Creates tabs: `selected` is the active index, `on_select(i)` the message on click.
pub fn new(selected: usize, on_select: impl Fn(usize) -> Msg + 'static) -> Self {
let mut tabs = Self {
selected,
on_select: Rc::new(on_select),
tabs: Vec::new(),
drawn: Vec::new(),
enabled: true,
style: TabStyle::default(),
scrollable: false,
swipeable: false,
panels: Vec::new(),
children: Vec::new(),
};
tabs.rebuild_bar();
tabs
}
/// Adds a tab, a label plus content. The content is realised only when it belongs
/// to the selected tab.
pub fn tab(self, label: impl Into<String>, content: impl Widget<Msg> + 'static) -> Self {
self.item(TabItem::new(label), content)
}
/// Adds a tab **the caller draws** — a label with an unread count beside it, a
/// coloured dot, two lines, rich text — plus the word it is called by and its content.
///
/// See [`TabItem::widget`], and [`TabItem::width`] for a bar that scrolls.
pub fn tab_widget(
self,
child: impl Widget<Msg> + 'static,
label: impl Into<String>,
content: impl Widget<Msg> + 'static,
) -> Self {
self.item(TabItem::widget(child, label), content)
}
/// Adds a tab however it was built, plus its content — the door to
/// [`TabItem::width`], which no shorthand carries.
pub fn item(mut self, tab: TabItem<Msg>, content: impl Widget<Msg> + 'static) -> Self {
self.push(tab, content);
self
}
/// Adds a tab with an **icon over its label**.
///
/// The whole row grows to [`TAB_ICON_HEIGHT`] as soon as one tab does this, because
/// tabs of two heights in one bar would put their labels on two different lines.
pub fn icon_tab(
self,
icon: IconData,
label: impl Into<String>,
content: impl Widget<Msg> + 'static,
) -> Self {
self.item(TabItem::icon(icon, label), content)
}
/// Adds a tab showing **only** an icon, in a row of the ordinary height.
///
/// The label is not drawn, and it is not optional: it is what a screen reader says,
/// and a tab nobody can name is a tab nobody can use. The reference leaves an
/// icon-only tab nameless and expects the caller to wrap it in something that names
/// it; asking for the word here costs nothing and cannot be forgotten.
pub fn icon_only_tab(
self,
icon: IconData,
label: impl Into<String>,
content: impl Widget<Msg> + 'static,
) -> Self {
self.item(TabItem::icon_only(icon, label), content)
}
/// Adds a tab to the row, keeping `content` only when it is the selected tab's —
/// unless the panel can be swiped, in which case every one of them is kept, because
/// the page view has to be able to build the tab you are dragging **towards**.
fn push(&mut self, tab: TabItem<Msg>, content: impl Widget<Msg> + 'static) {
let index = self.tabs.len();
self.tabs.push(tab.spec);
self.drawn.push(tab.child);
self.panels.push(Rc::new(content));
self.rebuild_bar();
self.rebuild_panel(index);
}
/// Puts the panel in place: the selected tab's content, or the page view when the
/// panel can be swiped.
fn rebuild_panel(&mut self, added: usize) {
let panel: Option<Box<dyn Widget<Msg>>> = if self.swipeable {
let panels = self.panels.clone();
let on_select = self.on_select.clone();
Some(Box::new(
PageView::new(panels.len(), move |i| Shared::new(panels[i].clone()))
.page(self.selected)
// The page view reports where the finger left it; the bar's own
// selection is still the application's, so this is the same message a
// press on the tab sends. One rule, reached two ways.
.on_page_changed(move |i| on_select(i))
.flex(1.0),
))
} else if added == self.selected {
Some(Box::new(Shared::new(self.panels[added].clone())))
} else {
None
};
let Some(panel) = panel else { return };
if self.children.len() > 1 {
self.children[1] = panel;
} else {
self.children.push(panel);
}
}
/// **Whether a drag across the panel changes tab.**
///
/// Off by default, and deliberately opt-in: it is a behaviour change for every bar
/// already written, and a panel that scrolls sideways of its own accord would fight
/// the gesture rather than answer it.
///
/// On, the panel becomes a [`PageView`] over every tab's content — the milestone-277
/// physics, so the drag, the fling and the spring to rest are the ones a page view
/// already has — and the bar's indicator slides to the tab the finger settled on.
///
/// Two things follow, and both are the point rather than side effects:
///
/// - **Every tab's content is kept**, not only the showing one, because the page view
/// has to be able to build the tab you are dragging *towards*. The panels were
/// already built by the caller either way; what changes is that they are held.
/// - **The set takes the height it is offered**, as it already takes the width. A
/// paged panel cannot be sized by whichever page happens to be longest, or the
/// control would change height as you swiped through it.
pub fn swipeable(mut self, swipeable: bool) -> Self {
self.swipeable = swipeable;
self.children.truncate(1);
for index in 0..self.panels.len() {
self.rebuild_panel(index);
}
self
}
/// Lets the bar **scroll** rather than sharing its width between the tabs.
///
/// Off by default, which is the reference's default and the right one for the two or
/// three tabs most bars have: equal columns, and a tab that stays where it is when
/// another is renamed.
///
/// On, each tab takes the room its label needs and the bar scrolls through them. That
/// is what eight tabs on a phone want — the alternative is eight columns of forty-odd
/// pixels, which is not a tab bar with more tabs, it is a tab bar with none you can
/// read.
///
/// The indicator follows the tabs at their real widths, and the hairline still runs
/// the whole foot of the bar even when the tabs do not fill it.
pub fn scrollable(mut self, scrollable: bool) -> Self {
self.scrollable = scrollable;
self.rebuild_bar();
self
}
/// Where the tabs sit when they do not fill the bar.
///
/// [`Auto`](TabAlignment::Auto) — the default — is what the bar's mode implies:
/// shared width when it does not scroll, packed at the leading edge when it does.
pub fn alignment(mut self, alignment: TabAlignment) -> Self {
self.style.alignment = Some(alignment);
self.rebuild_bar();
self
}
/// Whether the bar can be switched. Disabled every tab is **inert** - no press, no
/// ink, out of the tab order - and the **panel stays**, because which tab is showing
/// is still the answer even when it cannot be changed.
///
/// See [`crate::disabled`] for the whole contract.
pub fn enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self.rebuild_bar();
self
}
/// Chooses between the two bars. See [`TabBarVariant`].
pub fn variant(mut self, variant: TabBarVariant) -> Self {
self.style.variant = Some(variant);
self.rebuild_bar();
self
}
/// The indicator's colour. Defaults to the theme's accent.
pub fn indicator_color(mut self, color: Color) -> Self {
self.style.indicator_color = Some(color);
self.rebuild_bar();
self
}
/// The indicator's thickness — and, on a primary bar, the radius of its top corners.
/// `0.0` removes it.
pub fn indicator_weight(mut self, weight: f32) -> Self {
self.style.indicator_weight = Some(weight);
self.rebuild_bar();
self
}
/// The **selected** label's colour.
pub fn label_color(mut self, color: Color) -> Self {
self.style.label_color = Some(color);
self.rebuild_bar();
self
}
/// The colour of every label but the selected one.
pub fn unselected_label_color(mut self, color: Color) -> Self {
self.style.unselected_label_color = Some(color);
self.rebuild_bar();
self
}
/// The labels' type. Defaults to the theme's `title_small` step.
pub fn label_style(mut self, style: TextStyle) -> Self {
self.style.label_style = Some(style);
self.rebuild_bar();
self
}
/// The hairline's colour.
pub fn divider_color(mut self, color: Color) -> Self {
self.style.divider_color = Some(color);
self.rebuild_bar();
self
}
/// The hairline's thickness. `0.0` removes it — a bar sitting directly on a coloured
/// surface usually wants that.
pub fn divider_height(mut self, height: f32) -> Self {
self.style.divider_height = Some(height);
self.rebuild_bar();
self
}
/// The room on either side of a label.
pub fn label_padding(mut self, padding: f32) -> Self {
self.style.label_padding = Some(padding);
self.rebuild_bar();
self
}
/// The tabs' height, the indicator excluded.
pub fn tab_height(mut self, height: f32) -> Self {
self.style.tab_height = Some(height);
self.rebuild_bar();
self
}
/// (Re)builds the bar at index 0.
///
/// Every builder calls this, because the bar carries the style and a builder run after
/// `tab(…)` would otherwise be written into a bar that had already been built — the
/// order of a builder chain is not something a caller should have to think about.
fn rebuild_bar(&mut self) {
// One tall tab makes the whole row tall. Recorded on the style, which the bar and
// every tab already share, so the height cannot be answered two ways.
self.style.tall = self.tabs.iter().any(TabSpec::stacked);
let tabs: Vec<Box<dyn Widget<Msg>>> = self
.tabs
.iter()
.enumerate()
.map(|(i, spec)| {
Box::new(Tab {
spec: spec.clone(),
children: self.drawn[i]
.clone()
.map(|inner| Box::new(Shared::new(inner)) as Box<dyn Widget<Msg>>)
.into_iter()
.collect(),
selected: i == self.selected,
style: self.style,
enabled: self.enabled,
scrolls: self.scrollable,
message: (self.on_select)(i),
}) as Box<dyn Widget<Msg>>
})
.collect();
let strip = TabStrip {
selected: self.selected,
tabs: self.tabs.clone(),
style: self.style,
enabled: self.enabled,
scrolls: self.scrollable,
children: tabs,
};
// Scrollable, the strip goes inside a horizontal scroll -- and inside nothing
// else, because the scroll is the only difference. Everything that makes the bar
// a bar (the indicator, the hairline, the ink, the tap) stays in the strip and
// does not know it is being scrolled.
let bar: Box<dyn Widget<Msg>> = match self.scrollable {
true => Box::new(
crate::SingleChildScrollView::new()
.axis(crate::scroll::Axis::Horizontal)
.child(strip),
),
false => Box::new(strip),
};
if self.children.is_empty() {
self.children.push(bar);
} else {
self.children[0] = bar;
}
}
}
impl<Msg: Clone> Widget<Msg> for TabBar<Msg> {
fn style(&self) -> Style {
Style {
width: Dimension::Auto,
flex_direction: FlexDirection::Column,
// No gap: the hairline at the bar's foot is what separates it from the panel,
// and a gap on top of it would leave the line floating.
..Default::default()
}
}
fn children(&self) -> &[Box<dyn Widget<Msg>>] {
&self.children
}
/// A tab set takes the **width it is offered**, as the reference's does. Sized by its
/// content instead, the widest thing on the busiest tab decides how wide the whole
/// control is — so the bar jumps from tab to tab, and a panel that does not fit hangs
/// out of whatever is centring it rather than being told to fit.
fn fill_axes(&self, _theme: &Theme) -> crate::widget::FillAxes {
// And the **height** too once the panel can be swiped: a page view's pages fill
// its viewport, so a viewport sized by whichever page happens to be longest would
// make the control change height as the finger moved through it.
match self.swipeable {
true => crate::widget::FillAxes::BOTH,
false => crate::widget::FillAxes::WIDTH,
}
}
/// The hairline at the foot of the bar.
///
/// Drawn here rather than by the strip because it belongs to the bar: it runs the
/// bar's whole width whatever the tabs do, and a scrollable strip would carry it off
/// the side. The measurement is the same one the strip uses for its own height, so
/// the line lands exactly where it always did.
fn paint(&self, bounds: Rect, status: Status, theme: &Theme, scene: &mut Scene) {
let divider = self.style.divider_height(theme);
if divider <= 0.0 || bounds.width <= 0.0 {
return;
}
scene.fill_rect(
Rect::new(
bounds.x,
bounds.y + self.style.bar_height(theme) - divider,
bounds.width,
divider,
),
self.style.divider_color(theme).fade(status.opacity),
);
}
fn on_click(&self) -> Option<Msg> {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::icons::Icons;
use crate::runtime::Runtime;
use crate::ui::build_ui;
use crate::Text;
use frus_core::{Primitive, Size};
#[derive(Clone, Debug, PartialEq)]
enum Msg {
Select(usize),
}
/// **A tab can be a widget the caller drew.** An unread count beside a label, a
/// coloured dot, two lines, rich text — none of which a `&str` can say, and the first
/// of which is on half the tab bars ever shipped.
///
/// The bar paints **nothing** of its own on such a tab: a label under the caller's own
/// label would be drawing the same thing twice. What stays the bar's is the press, the
/// ink, the indicator — and the name, which is what a reader hears.
#[test]
fn a_tab_can_be_a_widget_the_caller_drew() {
let mark = Color::rgb(0.9, 0.1, 0.1);
let bar = TabBar::new(0, Msg::Select)
.tab_widget(
crate::Container::<Msg>::new()
.width(40.0)
.height(18.0)
.color(mark),
"Inbox",
crate::Container::<Msg>::new(),
)
.tab("Archive", crate::Container::<Msg>::new());
let root = crate::flex::Flex::column()
.width(300.0)
.height(120.0)
.child(bar);
let ui = build_ui(
&root,
Size::new(300.0, 120.0),
&Runtime::default(),
&Theme::default(),
);
assert!(
rects(ui.scene()).iter().any(|(_, color)| *color == mark),
"the caller's own widget is drawn"
);
let drawn = texts(ui.scene());
assert!(
!drawn.iter().any(|t| t == "Inbox"),
"and the bar draws no label of its own under it: {drawn:?}"
);
assert!(
drawn.iter().any(|t| t == "Archive"),
"while an ordinary tab still does"
);
}
/// **A drawn tab is still named**, because a tab nobody can name is a tab nobody can
/// use — the same demand `icon_only_tab` has always made, for the same reason.
#[test]
fn a_drawn_tab_is_still_named_for_a_reader() {
let bar = TabBar::new(0, Msg::Select).tab_widget(
crate::Container::<Msg>::new().width(20.0).height(20.0),
"Inbox",
crate::Container::<Msg>::new(),
);
let strip = &Widget::<Msg>::children(&bar)[0];
let tab = &strip.children()[0];
let announced = tab.semantics().expect("announced");
assert_eq!(announced.label.as_deref(), Some("Inbox"));
assert!(tab.focusable(), "and it is still a tab");
assert_eq!(tab.on_click(), Some(Msg::Select(0)));
}
/// **A drawn tab says how wide it is when the bar scrolls**, because it cannot be
/// asked ([#52](https://github.com/KalybosPro/frus/issues/52)). Unsaid, its name is
/// the proxy — right for a label with a dot beside it, short for a label with a count
/// in a pill.
///
/// Never consulted at all on a bar that does not scroll, where the tabs share the
/// width in equal parts: the second half of this is that the same two bars come out
/// identical when they do not scroll.
#[test]
fn a_drawn_tab_says_how_wide_it_is_when_the_bar_scrolls() {
let bar = |width: Option<f32>, scrollable: bool| {
let mut item = TabItem::widget(
crate::Container::<Msg>::new().width(20.0).height(20.0),
"Hi",
);
if let Some(width) = width {
item = item.width(width);
}
TabBar::new(0, Msg::Select)
.scrollable(scrollable)
.item(item, crate::Container::<Msg>::new())
.tab("Archive", crate::Container::<Msg>::new())
};
// The stated width reaches the tab's box: a press a hundred across lands on the
// first tab when it said a hundred and fifty, and on the second when it said
// nothing, since "Hi" measures nowhere near that.
let press = |bar: TabBar<Msg>| {
let root = crate::flex::Flex::column()
.width(400.0)
.height(120.0)
.child(bar);
let ui = build_ui(
&root,
Size::new(400.0, 120.0),
&Runtime::default(),
&Theme::default(),
);
ui.hit(crate::Point::new(100.0, 20.0))
.and_then(|id| ui.msg_for(id))
};
assert_eq!(press(bar(Some(150.0), true)), Some(Msg::Select(0)));
assert_eq!(press(bar(None, true)), Some(Msg::Select(1)));
// And on a bar that does not scroll the two come out identical, because the tabs
// share the width in equal parts and nobody is asked.
assert_eq!(press(bar(Some(150.0), false)), press(bar(None, false)));
}
/// **A drag across the panel lands on the next tab**, once the bar has been told the
/// panel can be swiped.
///
/// Driven the way the shell drives it: the offset is moved one page across, and the
/// runtime is asked which paged regions have turned. The message that comes back is
/// the **same one a press on the tab sends** — one rule, reached two ways, rather than
/// a second path into the selection that can drift from the first.
#[test]
fn a_drag_across_the_panel_lands_on_the_next_tab() {
let bar = || {
TabBar::new(0, Msg::Select)
.swipeable(true)
.tab("One", crate::Container::<Msg>::new())
.tab("Two", crate::Container::<Msg>::new())
.tab("Three", crate::Container::<Msg>::new())
};
let root = |bar| {
crate::flex::Flex::column()
.width(300.0)
.height(400.0)
.child(bar)
};
let mut runtime = Runtime::default();
let ui = build_ui(
&root(bar()),
Size::new(300.0, 400.0),
&runtime,
&Theme::default(),
);
let region = ui
.scroll_regions()
.iter()
.find(|area| area.page.is_some())
.expect("the panel is paged");
let id = region.id;
let snap = region.page.expect("a paged region");
assert_eq!(snap.count, 3, "one page per tab");
// The first frame settles the runtime on the page it opened at, so the second is
// where a change can be seen at all.
runtime.page_changes(ui.scroll_regions());
runtime.scroll.insert(id, (snap.extent, 0.0));
let ui = build_ui(
&root(bar()),
Size::new(300.0, 400.0),
&runtime,
&Theme::default(),
);
let turned = runtime.page_changes(ui.scroll_regions());
assert_eq!(turned, vec![(id, 1)], "one page across");
let bar = bar();
let panel = &Widget::<Msg>::children(&bar)[1];
assert_eq!(
panel.on_page_changed(1),
Some(Msg::Select(1)),
"and it reports the tab a press would have"
);
}
/// **A bar that cannot be swiped keeps only the tab that is showing**, which is what
/// it has always done; one that can keeps them all, because the page view has to be
/// able to build the tab you are dragging towards.
#[test]
fn only_a_swipeable_bar_keeps_every_panel() {
let bar = |swipeable: bool| {
TabBar::new(0, Msg::Select)
.swipeable(swipeable)
.tab("One", crate::Container::<Msg>::new().width(11.0))
.tab("Two", crate::Container::<Msg>::new().width(22.0))
};
let plain = bar(false);
assert_eq!(
Widget::<Msg>::children(&plain).len(),
2,
"a bar and a panel"
);
let root = crate::flex::Flex::column()
.width(300.0)
.height(400.0)
.child(bar(true));
let ui = build_ui(
&root,
Size::new(300.0, 400.0),
&Runtime::default(),
&Theme::default(),
);
assert!(
ui.scroll_regions().iter().any(|area| area.page.is_some()),
"and the swipeable one has a paged panel instead"
);
}
/// Every filled rectangle in the frame, innermost layers included.
fn rects(scene: &frus_core::Scene) -> Vec<(Rect, Color)> {
fn walk(primitives: &[frus_core::Primitive], out: &mut Vec<(Rect, Color)>) {
for p in primitives {
match p {
frus_core::Primitive::Rect { rect, color, .. } => out.push((*rect, *color)),
frus_core::Primitive::Layer { primitives, .. } => walk(primitives, out),
_ => {}
}
}
}
let mut out = Vec::new();
walk(scene.primitives(), &mut out);
out
}
/// Every run of text in the frame.
fn texts(scene: &frus_core::Scene) -> Vec<String> {
fn walk(primitives: &[frus_core::Primitive], out: &mut Vec<String>) {
for p in primitives {
match p {
frus_core::Primitive::Text { text, .. } => out.push(text.clone()),
frus_core::Primitive::Layer { primitives, .. } => walk(primitives, out),
_ => {}
}
}
}
let mut out = Vec::new();
walk(scene.primitives(), &mut out);
out
}
/// Ten tabs in a 300 px window: far more than fits, which is what `scrollable` is
/// for and where the selected tab can go missing.
fn wide(selected: usize) -> TabBar<Msg> {
let mut tabs = TabBar::new(selected, Msg::Select).scrollable(true);
for i in 0..10 {
tabs = tabs.tab(format!("Section {i}"), Text::new("panel"));
}
tabs
}
fn frame(tabs: TabBar<Msg>, runtime: &Runtime) -> crate::Ui<Msg> {
build_ui(&tabs, Size::new(300.0, 400.0), runtime, &Theme::default())
}
/// Where a label was drawn, or `None` if it was not.
fn label_x(ui: &crate::Ui<Msg>, label: &str) -> Option<f32> {
ui.scene().primitives().iter().find_map(|p| match p {
Primitive::Text { position, text, .. } if text == label => Some(position.x),
_ => None,
})
}
/// **A scrollable bar's panel starts under its hairline**, not two hundred pixels
/// below it (#65).
///
/// A scrollable bar wraps its strip in a horizontal viewport, and a viewport's default
/// height — two hundred pixels, the height of a window onto something taller — belongs
/// to the axis that scrolls. A horizontal one took it too, so a bar forty-eight pixels
/// tall claimed two hundred and everything under it began in empty space.
///
/// The picture is the whole bug, which is why one was added with it; this pins the
/// arithmetic. Nothing in the suite caught it because nothing rendered a scrollable bar
/// **with something under it** — every test read the strip's own geometry, which was
/// right whatever box the scroll claimed.
#[test]
fn a_scrolling_bar_does_not_push_its_panel_down_the_page() {
let panel = crate::Container::new()
.height(30.0)
.color(Color::rgb(1.0, 0.0, 0.0));
let tabs = TabBar::new(0, Msg::Select)
.scrollable(true)
.tab("One", panel)
.tab("Two", crate::Container::new().height(30.0));
let ui = build_ui(
&tabs,
Size::new(400.0, 400.0),
&Runtime::default(),
&Theme::default(),
);
let red = ui
.scene()
.primitives()
.iter()
.find_map(|p| match p {
Primitive::Rect { rect, color, .. } if color.r > 0.9 && color.g < 0.1 => {
Some(*rect)
}
_ => None,
})
.expect("the panel is drawn");
// The bar is `tab_height + the hairline` tall, and the panel starts there. The
// measurement in the issue found it at y > 150 against a hairline at 48.
let bar = TAB_HEIGHT;
assert!(
(red.y - bar).abs() <= 4.0,
"the panel starts under the bar ({bar}), not at {}",
red.y
);
}
/// A bar wider than its window **opens** on the selected tab. Before this, an
/// application restored on its ninth tab showed the first three and nothing said
/// where the selection had gone.
#[test]
fn a_scrolling_bar_opens_on_its_selected_tab() {
let runtime = Runtime::default();
let ui = frame(wide(8), &runtime);
let area = ui.scroll_regions()[0];
let keep = area
.keep_visible
.expect("the bar keeps its selected tab in view");
assert_eq!(keep.key, 8);
assert!(keep.centre, "centred, as the reference's bar is");
// And it is really on screen: the ninth label is drawn inside the window.
let x = label_x(&ui, "Section 8").expect("the selected tab is drawn");
assert!(x > 0.0 && x < 300.0, "Section 8 drawn at {x}");
// The first one is off the leading edge, which is the point.
assert!(label_x(&ui, "Section 0").is_none_or(|x| x < 0.0));
}
/// A bar that shares its width has every tab on screen already, and asks for
/// nothing: there is no region to ask.
#[test]
fn a_bar_that_shares_its_width_asks_for_nothing() {
let runtime = Runtime::default();
let mut tabs = TabBar::new(8, Msg::Select);
for i in 0..10 {
tabs = tabs.tab(format!("Section {i}"), Text::new("panel"));
}
assert!(frame(tabs, &runtime).scroll_regions().is_empty());
}
/// Changing the selection **glides**: a target, not a jump, so the bar reads as one
/// movement rather than a cut.
#[test]
fn changing_the_tab_slides_the_bar() {
let mut runtime = Runtime::default();
let regions = frame(wide(0), &runtime).scroll_regions().to_vec();
let id = regions[0].id;
// The first sighting is where the bar opens, and it opens on tab 0, at the start.
runtime.sync_visible(®ions);
assert_eq!(runtime.scroll[&id], (0.0, 0.0));
assert!(!runtime.scroll_target.contains_key(&id));
let regions = frame(wide(8), &runtime).scroll_regions().to_vec();
runtime.sync_visible(®ions);
let target = runtime.scroll_target[&id];
assert!(
target.0 > 100.0,
"glides across to the ninth tab: {target:?}"
);
assert_eq!(runtime.scroll[&id], (0.0, 0.0), "a target, not a jump");
}
/// The same selection twice does not pull the bar back: the reader is allowed to
/// look at the other tabs. A region chasing the box every frame would pin the strip
/// in place and no finger could move it.
#[test]
fn the_same_tab_twice_does_not_fight_the_finger() {
let mut runtime = Runtime::default();
let regions = frame(wide(3), &runtime).scroll_regions().to_vec();
let id = regions[0].id;
runtime.sync_visible(®ions);
runtime.scroll_target.remove(&id);
// The reader drags the bar somewhere else.
runtime.scroll.insert(id, (500.0, 0.0));
let regions = frame(wide(3), &runtime).scroll_regions().to_vec();
runtime.sync_visible(®ions);
assert!(
!runtime.scroll_target.contains_key(&id),
"nothing pulls it back"
);
assert_eq!(runtime.scroll[&id], (500.0, 0.0));
}
/// The bar's own height, as the hairline it draws across its foot reveals it.
fn drawn_bar_height(tabs: TabBar<Msg>) -> f32 {
let root = crate::flex::Flex::column()
.width(400.0)
.height(300.0)
.child(tabs);
let mut runtime = Runtime::default();
runtime.advance_values::<Msg>(&root, 0.0);
build_ui(&root, Size::new(400.0, 300.0), &runtime, &Theme::default())
.scene()
.primitives()
.iter()
.filter_map(|p| match p {
// The hairline: the bar's full width, one pixel tall.
Primitive::Rect { rect, .. } if rect.width > 399.0 && rect.height < 2.0 => {
Some(rect.y + rect.height)
}
_ => None,
})
.next()
.expect("the hairline is drawn")
}
/// What the frame drew for a bar: the paths (icons) and the texts (labels).
fn drawn(tabs: TabBar<Msg>) -> (usize, Vec<String>) {
let root = crate::flex::Flex::column()
.width(400.0)
.height(300.0)
.child(tabs);
let mut runtime = Runtime::default();
runtime.advance_values::<Msg>(&root, 0.0);
let ui = build_ui(&root, Size::new(400.0, 300.0), &runtime, &Theme::default());
let mut paths = 0;
let mut texts = Vec::new();
for p in ui.scene().primitives() {
match p {
Primitive::Path { .. } => paths += 1,
Primitive::Text { text, .. } => texts.push(text.clone()),
_ => {}
}
}
(paths, texts)
}
/// An icon over a label draws both, and the row grows to the taller measurement.
#[test]
fn an_icon_tab_draws_its_icon_and_its_label() {
let tabs = TabBar::new(0, Msg::Select)
.icon_tab(Icons::STAR, "Home", Text::new("panel"))
.icon_tab(Icons::FAVORITE, "Search", Text::new("panel"));
let (paths, texts) = drawn(tabs);
assert_eq!(paths, 2, "one icon per tab");
assert!(texts.contains(&"Home".to_string()));
assert!(texts.contains(&"Search".to_string()));
}
/// One tall tab makes the **whole row** tall. Two heights in one bar would put the
/// labels on two different lines.
#[test]
fn one_icon_tab_raises_the_whole_row() {
let plain = TabBar::new(0, Msg::Select)
.tab("One", Text::new("panel"))
.tab("Two", Text::new("panel"));
let mixed = TabBar::new(0, Msg::Select)
.tab("One", Text::new("panel"))
.icon_tab(Icons::FAVORITE, "Two", Text::new("panel"));
let short = drawn_bar_height(plain);
let tall = drawn_bar_height(mixed);
assert!(
(short - (TAB_HEIGHT + TAB_INDICATOR_PRIMARY)).abs() < 0.5,
"{short}"
);
assert!(
(tall - (TAB_ICON_HEIGHT + TAB_INDICATOR_PRIMARY)).abs() < 0.5,
"{tall}"
);
}
/// An icon **on its own** stays in an ordinary row, and its label is not drawn —
/// but it is still what a reader is told.
#[test]
fn an_icon_only_tab_is_short_and_still_named() {
let tabs = TabBar::new(0, Msg::Select)
.icon_only_tab(Icons::STAR, "Home", Text::new("panel"))
.icon_only_tab(Icons::FAVORITE, "Search", Text::new("panel"));
let (paths, texts) = drawn(tabs);
assert_eq!(paths, 2, "the icons");
assert!(!texts.contains(&"Home".to_string()), "no label is drawn");
let short = drawn_bar_height(TabBar::new(0, Msg::Select).icon_only_tab(
Icons::STAR,
"Home",
Text::new("panel"),
));
assert!(
(short - (TAB_HEIGHT + TAB_INDICATOR_PRIMARY)).abs() < 0.5,
"{short}"
);
// The word survives where it matters.
let root = crate::flex::Flex::column()
.width(400.0)
.height(300.0)
.child(TabBar::new(0, Msg::Select).icon_only_tab(
Icons::STAR,
"Home",
Text::new("panel"),
));
let ui = build_ui(
&root,
Size::new(400.0, 300.0),
&Runtime::default(),
&Theme::default(),
);
assert!(
ui.semantics()
.iter()
.any(|(_, _, s)| s.label.as_deref() == Some("Home")),
"the icon-only tab still has a name"
);
}
/// A scrolling bar measures an icon tab by whichever of its two parts is wider,
/// since they are stacked rather than side by side.
#[test]
fn a_stacked_tab_is_as_wide_as_its_widest_part() {
let style = TabStyle::default();
let theme = Theme::default();
let narrow = TabSpec {
icon: Some(Icons::STAR),
..TabSpec::text("Hi")
};
// "Hi" is narrower than a 24 px icon, so the icon decides.
assert_eq!(
style.scrolled_tab_width(&theme, &narrow),
TAB_ICON_SIZE + 2.0 * TAB_LABEL_PADDING
);
// A long label decides instead.
let wide = TabSpec {
icon: Some(Icons::STAR),
..TabSpec::text("Notifications")
};
assert!(
style.scrolled_tab_width(&theme, &wide) > style.scrolled_tab_width(&theme, &narrow)
);
}
/// Where each tab's label was actually drawn, left to right.
fn label_xs(tabs: TabBar<Msg>, width: f32) -> Vec<f32> {
let root = crate::flex::Flex::column()
.width(width)
.height(300.0)
.child(tabs);
let mut runtime = Runtime::default();
runtime.advance_values::<Msg>(&root, 0.0);
let ui = build_ui(&root, Size::new(width, 300.0), &runtime, &Theme::default());
// The tabs' own labels, and not the panel's text, which is empty and sits at
// the origin: a stray zero at the head of the list would make every comparison
// below quietly about the wrong thing.
let mut xs: Vec<f32> = ui
.scene()
.primitives()
.iter()
.filter_map(|p| match p {
Primitive::Text { position, text, .. } if text == "One" || text == "Two" => {
Some(position.x)
}
_ => None,
})
.collect();
xs.sort_by(f32::total_cmp);
xs
}
fn two(alignment: TabAlignment, scrolls: bool) -> TabBar<Msg> {
TabBar::new(0, Msg::Select)
.scrollable(scrolls)
.alignment(alignment)
.tab("One", crate::text(""))
.tab("Two", crate::text(""))
}
/// The default is the bar's mode, said out loud: shared width when it does not
/// scroll, packed at the leading edge when it does.
#[test]
fn auto_is_whatever_the_bar_already_did() {
assert_eq!(TabAlignment::Auto.resolved(false), TabAlignment::Fill);
assert_eq!(TabAlignment::Auto.resolved(true), TabAlignment::Start);
// And filling a bar that scrolls is a contradiction, so it reads as `Start`
// rather than throwing the way the reference does.
assert_eq!(TabAlignment::Fill.resolved(true), TabAlignment::Start);
// The rest mean what they say either way.
assert_eq!(TabAlignment::Center.resolved(false), TabAlignment::Center);
assert_eq!(TabAlignment::Center.resolved(true), TabAlignment::Start);
assert_eq!(TabAlignment::Start.resolved(false), TabAlignment::Start);
}
/// Two tabs in a wide bar: filled they sit in the middle of their halves, started
/// they hug the leading edge, centred they sit together in the middle.
#[test]
fn the_tabs_go_where_they_were_told() {
let filled = label_xs(two(TabAlignment::Fill, false), 600.0);
let started = label_xs(two(TabAlignment::Start, false), 600.0);
let centred = label_xs(two(TabAlignment::Center, false), 600.0);
// Filled, each tab is 300 wide, so the labels are nowhere near each other.
assert!(filled[1] - filled[0] > 250.0, "{filled:?}");
// Started, they are as wide as their words and sit at the leading edge.
assert!((started[0] - TAB_LABEL_PADDING).abs() < 1.0, "{started:?}");
assert!(started[1] - started[0] < 120.0, "{started:?}");
// Centred, the pair keeps its spacing and moves right as a block.
let gap = |xs: &[f32]| xs[1] - xs[0];
assert!((gap(¢red) - gap(&started)).abs() < 1.0, "{centred:?}");
assert!(centred[0] > started[0] + 100.0, "{centred:?}");
// And the block really is centred: as much room after it as before it.
let width: f32 = (0..2)
.map(|i| {
TabStyle::default().scrolled_tab_width(
&Theme::default(),
&TabSpec::text(if i == 0 { "One" } else { "Two" }),
)
})
.sum();
assert!(
(centred[0] - TAB_LABEL_PADDING - (600.0 - width) / 2.0).abs() < 1.0,
"{centred:?}"
);
}
/// The offset is an inset before the first tab and nothing else: the second tab
/// moves by exactly the same amount.
#[test]
fn the_start_offset_moves_the_whole_row() {
let started = label_xs(two(TabAlignment::Start, false), 600.0);
let offset = label_xs(two(TabAlignment::StartOffset, false), 600.0);
for (a, b) in started.iter().zip(&offset) {
assert!(
(b - a - TAB_START_OFFSET).abs() < 1.0,
"{started:?} {offset:?}"
);
}
}
/// A **scrolling** bar cannot centre, and says so by reading as `Start` rather than
/// by pretending.
///
/// Centring wants something definite to centre in, and the content of a scroll has
/// no definite width across the axis it scrolls along: the strip is measured by its
/// own tabs, so a percentage of its parent resolves against nothing and it comes out
/// exactly as wide as the tabs, with nothing left over to share. Measured here
/// rather than assumed — this is the trap of milestones 368 and 377, and the third
/// time it has been paid for.
#[test]
fn a_scrolling_bar_cannot_centre_and_does_not_pretend() {
let started = label_xs(two(TabAlignment::Start, true), 600.0);
let centred = label_xs(two(TabAlignment::Center, true), 600.0);
assert_eq!(started, centred);
assert!((started[0] - TAB_LABEL_PADDING).abs() < 1.0, "{started:?}");
// Without the scroll, the same bar centres.
let still = label_xs(two(TabAlignment::Center, false), 600.0);
assert!(still[0] > started[0] + 100.0, "{still:?}");
}
/// The indicator follows, because it reads the same spans the tabs are laid out to.
/// This is the part that would drift.
#[test]
fn the_indicator_follows_the_alignment() {
let indicator = |alignment: TabAlignment| {
let root = crate::flex::Flex::column()
.width(600.0)
.height(300.0)
.child(two(alignment, false));
let mut runtime = Runtime::default();
runtime.advance_values::<Msg>(&root, 0.0);
build_ui(&root, Size::new(600.0, 300.0), &runtime, &Theme::default())
.scene()
.primitives()
.iter()
.filter_map(|p| match p {
// The indicator: as thick as a primary bar's, not the hairline.
Primitive::Rect { rect, .. }
if (rect.height - TAB_INDICATOR_PRIMARY).abs() < 0.5 =>
{
Some(rect.x + rect.width / 2.0)
}
_ => None,
})
.next()
.expect("an indicator")
};
let started = indicator(TabAlignment::Start);
let centred = indicator(TabAlignment::Center);
let labels_started = label_xs(two(TabAlignment::Start, false), 600.0);
let labels_centred = label_xs(two(TabAlignment::Center, false), 600.0);
// The indicator moved by exactly as much as the label it marks.
assert!(
((centred - started) - (labels_centred[0] - labels_started[0])).abs() < 1.0,
"{started} {centred}"
);
}
fn three(selected: usize) -> TabBar<Msg> {
TabBar::new(selected, Msg::Select)
.tab("One", Text::new("panel one"))
.tab("Two", Text::new("panel two"))
.tab("Three", Text::new("panel three"))
}
/// A tab set takes the width it is offered rather than the width of whatever is on
/// the busiest tab. Sized by its content, a centring row lets it hang out either side
/// instead of telling it to fit — which is how a settings screen came to draw 5 px
/// off a phone (milestone 335).
#[test]
fn a_tab_set_takes_the_width_it_is_offered() {
let root = crate::flex::Flex::row()
.width(300.0)
.height(200.0)
.justify(frus_layout::Justify::Center)
.child(three(0));
let mut runtime = Runtime::default();
runtime.advance_values::<Msg>(&root, 0.0);
let ui = build_ui(&root, Size::new(300.0, 200.0), &runtime, &Theme::default());
// The bar is `width: 100%` of the tab set, so the hairline under it is the tab
// set's width made visible.
let widest = ui
.scene()
.primitives()
.iter()
.filter_map(|p| match p {
Primitive::Rect { rect, .. } => Some(rect.width),
_ => None,
})
.fold(0.0_f32, f32::max);
assert!(
(widest - 300.0).abs() < 0.5,
"the whole row, not the widest label: {widest}"
);
}
/// The frame's crisp boxes: the hairline, then the indicator.
fn boxes(tabs: TabBar<Msg>) -> Vec<(Rect, Color)> {
let root = crate::flex::Flex::column()
.width(300.0)
.height(200.0)
.child(tabs);
// The shell settles the animated values before it builds; a bare runtime would
// catch the indicator on its way to the selected tab rather than under it.
let mut runtime = Runtime::default();
runtime.advance_values::<Msg>(&root, 0.0);
build_ui(&root, Size::new(300.0, 200.0), &runtime, &Theme::default())
.scene()
.primitives()
.iter()
.filter_map(|p| match p {
Primitive::Rect {
rect, color, blur, ..
} if *blur == 0.0 => Some((*rect, *color)),
_ => None,
})
.collect()
}
#[test]
fn shows_bar_and_selected_panel() {
let tabs = three(1);
// [bar, panel] — the panel is the selected tab's content, tab 1.
let children = Widget::<Msg>::children(&tabs);
assert_eq!(children.len(), 2);
assert_eq!(children[0].children().len(), 3, "three tabs in the bar");
}
#[test]
fn no_panel_when_selection_out_of_range() {
let tabs = TabBar::new(9, Msg::Select).tab("One", Text::new("x"));
assert_eq!(Widget::<Msg>::children(&tabs).len(), 1); // the bar alone
}
#[test]
fn the_indicator_sits_under_the_selected_tab() {
// The point of the whole widget: which tab is selected has to be visible without
// reading the labels' colours.
let theme = Theme::default();
let painted = boxes(three(1));
let indicator = painted
.iter()
.find(|(_, color)| *color == theme.scheme.primary)
.expect("an indicator in the accent colour");
// Three tabs across 300: the middle one runs from 100 to 200.
let centre = indicator.0.x + indicator.0.width / 2.0;
assert!(
(centre - 150.0).abs() < 1.0,
"centred on the second tab, not at {centre}"
);
assert_eq!(indicator.0.height, TAB_INDICATOR_PRIMARY);
}
#[test]
fn a_primary_indicator_is_as_wide_as_its_label_and_a_secondary_one_as_wide_as_its_tab() {
// The difference between the two bars is not decoration: it is what the indicator
// measures itself against.
let theme = Theme::default();
let width = |tabs: TabBar<Msg>| {
boxes(tabs)
.iter()
.find(|(_, color)| *color == theme.scheme.primary)
.expect("an indicator")
.0
.width
};
let primary = width(three(1));
let secondary = width(three(1).variant(TabBarVariant::Secondary));
assert_eq!(secondary, 100.0, "a third of 300 — the whole tab");
assert!(
primary < secondary,
"a label is narrower than its tab: {primary} against {secondary}"
);
assert!(primary > 0.0, "and it is not nothing");
}
#[test]
fn the_hairline_runs_the_whole_bar() {
let theme = Theme::default();
let painted = boxes(three(0));
let line = painted
.iter()
.find(|(_, color)| *color == theme.scheme.outline_variant)
.expect("a divider");
assert_eq!(line.0.width, 300.0, "across the bar, not across a tab");
assert_eq!(line.0.height, TAB_DIVIDER_HEIGHT);
// The indicator sits on it: both end at the bar's foot.
let indicator = painted
.iter()
.find(|(_, color)| *color == theme.scheme.primary)
.expect("an indicator");
assert_eq!(
line.0.y + line.0.height,
indicator.0.y + indicator.0.height,
"the indicator sits on the hairline"
);
}
#[test]
fn the_bar_is_the_tabs_plus_the_indicator() {
let theme = Theme::default();
let tabs = three(0);
let bar = &Widget::<Msg>::children(&tabs)[0];
assert_eq!(
bar.style_themed(&theme).height,
Dimension::Length(TAB_HEIGHT + TAB_INDICATOR_PRIMARY)
);
}
#[test]
fn every_measurement_is_the_callers_and_then_the_themes() {
// `caller ?? theme ?? framework`, on the one measurement that reaches layout.
let mut theme = Theme::default();
theme.widgets.tab_bar.tab_height = Some(60.0);
let height = |tabs: TabBar<Msg>, theme: &Theme| {
Widget::<Msg>::style_themed(&Widget::<Msg>::children(&tabs)[0], theme).height
};
assert_eq!(
height(three(0), &Theme::default()),
Dimension::Length(TAB_HEIGHT + TAB_INDICATOR_PRIMARY),
"the framework's"
);
assert_eq!(
height(three(0), &theme),
Dimension::Length(60.0 + TAB_INDICATOR_PRIMARY),
"the theme's"
);
assert_eq!(
height(three(0).tab_height(20.0), &theme),
Dimension::Length(20.0 + TAB_INDICATOR_PRIMARY),
"the caller's, over the theme's"
);
}
#[test]
fn a_builder_after_the_tabs_still_reaches_them() {
// The trap in a builder that assembles its children as it goes: `.tab(…)` builds
// the bar, so anything said after it has to rebuild the bar or be dropped.
let painted = boxes(three(1).indicator_weight(9.0));
assert!(
painted.iter().any(|(rect, _)| rect.height == 9.0),
"the indicator took the weight set after the tabs"
);
}
#[test]
fn tabs_are_tabs_to_a_screen_reader() {
let tabs = three(0);
let bar = &Widget::<Msg>::children(&tabs)[0];
let first = &bar.children()[0];
let semantics = first.semantics().expect("a tab announces itself");
assert_eq!(semantics.role, frus_core::Role::Tab);
assert_eq!(semantics.label.as_deref(), Some("One"));
assert!(semantics.clickable);
}
#[test]
fn a_tab_emits_its_index() {
let tabs = three(0);
let bar = &Widget::<Msg>::children(&tabs)[0];
assert_eq!(bar.children()[2].on_click(), Some(Msg::Select(2)));
}
#[test]
fn a_disabled_bar_is_inert_but_keeps_its_panel() {
let dead = TabBar::new(1, Msg::Select)
.tab("One", Text::new("first"))
.tab("Two", Text::new("second"))
.enabled(false);
// The panel survives: which tab is showing is still the answer.
assert_eq!(
Widget::<Msg>::children(&dead).len(),
2,
"the bar and its panel"
);
let bar = &Widget::<Msg>::children(&dead)[0];
for (i, tab) in bar.children().iter().enumerate() {
assert_eq!(tab.on_click(), None, "tab {i} still answers");
assert!(!tab.focusable(), "tab {i} is still in the tab order");
assert!(
tab.ink(&Theme::default()).is_none(),
"tab {i} still splashes"
);
let semantics = tab.semantics().expect("still announced");
assert!(semantics.disabled, "tab {i} does not say it is disabled");
}
// And the selected one still says so.
assert_eq!(
bar.children()[1].semantics().unwrap().toggled,
frus_core::Toggled::True
);
}
#[test]
fn a_disabled_bar_flattens_rather_than_fading_the_accent() {
// Selected and unselected labels go to the same grey; the accent never appears.
let theme = Theme::default();
let dead = TabBar::new(0, Msg::Select)
.tab("One", Text::new("first"))
.tab("Two", Text::new("second"))
.enabled(false);
let bar = &Widget::<Msg>::children(&dead)[0];
for tab in bar.children() {
let mut scene = frus_core::Scene::new();
tab.paint(
Rect::new(0.0, 0.0, 80.0, 48.0),
Status {
opacity: 1.0,
..Default::default()
},
&theme,
&mut scene,
);
let color = scene
.primitives()
.iter()
.find_map(|p| match p {
Primitive::Text { color, .. } => Some(*color),
_ => None,
})
.expect("a label");
assert_eq!(color, disabled_content(&theme));
}
}
/// The indicator is the part a flattened bar would otherwise keep the accent on -
/// found by reading milestone 324's golden, not by a test.
#[test]
fn a_disabled_bars_indicator_loses_the_accent_too() {
let theme = Theme::default();
let indicator = |enabled: bool| {
let tabs = TabBar::new(0, Msg::Select)
.tab("One", Text::new("first"))
.tab("Two", Text::new("second"))
.enabled(enabled);
let bar = &Widget::<Msg>::children(&tabs)[0];
let mut scene = frus_core::Scene::new();
bar.paint(
Rect::new(0.0, 0.0, 200.0, 48.0),
Status {
opacity: 1.0,
..Default::default()
},
&theme,
&mut scene,
);
// The indicator is the last box the bar paints, over the hairline.
scene
.primitives()
.iter()
.rev()
.find_map(|p| match p {
Primitive::Rect { color, .. } => Some(*color),
_ => None,
})
.expect("an indicator")
};
assert_eq!(indicator(false), disabled_content(&theme));
assert_ne!(indicator(true), disabled_content(&theme));
assert_ne!(
indicator(false),
indicator(true),
"the instrument must be able to tell the two apart"
);
}
}
/// A bar with more tabs than fit.
#[cfg(test)]
mod scrollable_tests {
use super::*;
use crate::{build_ui, Runtime, Size};
use frus_core::Primitive;
#[derive(Clone, Debug, PartialEq)]
enum Msg {
Pick(usize),
}
/// Eight tabs of deliberately unequal label lengths.
const LABELS: [&str; 8] = [
"All", "Unread", "Starred", "Drafts", "Sent", "Archived", "Spam", "Bin",
];
fn bar(scrollable: bool) -> TabBar<Msg> {
let mut tabs = TabBar::new(0, Msg::Pick);
for label in LABELS {
tabs = tabs.tab(label, crate::text(""));
}
tabs.scrollable(scrollable)
}
/// The rects the bar painted, largest first -- the indicator is the small one.
fn painted(tabs: TabBar<Msg>, width: f32) -> Vec<frus_core::Rect> {
build_ui(
&tabs,
Size::new(width, 200.0),
&Runtime::default(),
&Theme::default(),
)
.scene()
.primitives()
.iter()
.filter_map(|p| match p {
Primitive::Rect { rect, .. } => Some(*rect),
_ => None,
})
.collect()
}
/// Off by default: nothing about an ordinary bar changes.
#[test]
fn a_bar_says_nothing_and_shares_its_width() {
let tabs = bar(false);
let ui = build_ui(
&tabs,
Size::new(360.0, 200.0),
&Runtime::default(),
&Theme::default(),
);
assert!(
ui.scrollable_maxes().is_empty(),
"an ordinary bar registers no scrollable"
);
}
/// Scrollable, the strip is wider than the bar and there is somewhere to scroll to.
///
/// Eight labels at their own widths do not fit in 360 px -- which is the whole reason
/// this exists, and the assertion says so rather than assuming it.
#[test]
fn eight_tabs_on_a_phone_scroll() {
let ui = build_ui(
&bar(true),
Size::new(360.0, 200.0),
&Runtime::default(),
&Theme::default(),
);
let maxes = ui.scrollable_maxes();
assert_eq!(maxes.len(), 1, "the strip is inside a scroll");
assert!(maxes[0].1 > 0.0, "and it has room to move: {:?}", maxes[0]);
assert_eq!(maxes[0].2, 0.0, "across, not down");
}
/// Each tab takes its label's room, so a long label gets a wide tab and a short one
/// does not. Shared equally, every tab is the same width and this cannot be true.
#[test]
fn a_long_label_gets_a_wide_tab() {
let theme = Theme::default();
let style = TabStyle::default();
let narrow = style.scrolled_tab_width(&theme, &TabSpec::text("Bin"));
let wide = style.scrolled_tab_width(&theme, &TabSpec::text("Archived"));
assert!(wide > narrow, "{wide} should exceed {narrow}");
}
/// The indicator follows the **real** tab widths.
///
/// This is the part that would drift: the tab lays itself out to one number and the
/// indicator is placed by another. They ask the same function, and this checks the
/// answer against a hand-computed prefix sum rather than against that function --
/// otherwise the test would agree with a mistake.
#[test]
fn the_indicator_sits_over_the_tab_it_marks() {
let theme = Theme::default();
let style = TabStyle::default();
let labels: Vec<TabSpec> = LABELS.iter().map(|s| TabSpec::text(*s)).collect();
let spans = style.tab_spans(&theme, &labels, 360.0, TabAlignment::Start);
let mut expected = 0.0;
for (i, label) in labels.iter().enumerate() {
assert!(
(spans[i].0 - expected).abs() < 0.01,
"tab {i} starts at {} rather than {expected}",
spans[i].0
);
expected += style.scrolled_tab_width(&theme, label);
}
// And the last tab ends where the strip does.
let (start, width) = spans[labels.len() - 1];
assert!((start + width - expected).abs() < 0.01);
}
/// Not scrollable, the spans are still equal parts -- the old rule, untouched.
#[test]
fn an_ordinary_bar_still_divides_its_width_evenly() {
let labels: Vec<TabSpec> = LABELS.iter().map(|s| TabSpec::text(*s)).collect();
let spans =
TabStyle::default().tab_spans(&Theme::default(), &labels, 800.0, TabAlignment::Fill);
assert_eq!(spans[0], (0.0, 100.0));
assert_eq!(spans[7], (700.0, 100.0));
}
/// Two tabs in a scrollable bar still get a hairline across the whole foot, rather
/// than a stub under the labels. The strip is never narrower than the bar.
#[test]
fn a_short_scrollable_bar_still_rules_a_full_line() {
let mut tabs = TabBar::new(0, Msg::Pick);
tabs = tabs.tab("A", crate::text("")).tab("B", crate::text(""));
let rects = painted(tabs.scrollable(true), 400.0);
assert!(
rects.iter().any(|r| r.width >= 399.0),
"something runs the full width: {rects:?}"
);
}
}