frus-widgets 0.5.0

frus — declarative widget tree
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
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
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
//! [`AppBar`]: an **adaptive application bar**, Material style.
//!
//! The developer declares an optional title, an optional `leading` and a list of
//! **actions**, each any widget — typically icon buttons. Beside them, a bar may have
//! **foldable actions**: text buttons the bar shows inline while they fit and **folds
//! into an overflow menu** when the **available width** runs out, never asking whether
//! this is mobile or desktop. A wide screen → everything inline; a narrow phone →
//! overflow.
//!
//! **Everything is customisable** (themed defaults, never imposed): the title is any
//! widget (`title`) with a themed type (`title_style`), every action is any widget, and
//! the spacing, the action size, the background and the height can all be overridden.
//!
//! ```ignore
//! AppBar::new()
//!     .title(Text::new("My Tasks"))           // any widget; a bar may have none
//!     .leading(IconButton::new(Icons::MENU).on_press(Msg::ToggleMenu))
//!     .action(IconButton::new(Icons::SEARCH).on_press(Msg::Search))  // any widget
//!     .action(Badge::new("3"))
//!     .overflow(app.menu_open, Msg::ToggleMenu)
//!     .foldable_action("Pause", Msg::ToggleTimer) // folds when the bar is narrow
//!     .foldable_action("Settings", Msg::OpenSettings)
//!     .build()
//! ```

#[cfg(test)]
use frus_core::FontWeight;
use frus_core::{BorderRadius, Color, Rect, ShapeBorder, TextStyle};
use frus_layout::{Align, Dimension};

use crate::button::Variant;
use crate::constraints::ConstrainedBox;
use crate::container::Container;
use crate::dsl::button;
use crate::flex::Flex;
use crate::media::MediaQuery;
use crate::menu::PopupMenuButton;
#[cfg(test)]
use crate::text::Text;
use crate::theme::Theme;
use crate::widget::Widget;
use crate::widgettheme::{DefaultTextStyle, IconTheme};

/// Does a bar following `platform`'s conventions centre its title by default?
///
/// Where the system centres its own — iOS and macOS — so does a bar that has not been
/// told otherwise, and **only while there is room to read it that way**: past one action
/// the title goes back to being flush after the leading, because a centred title
/// squeezed between a leading and three buttons is neither centred nor readable. Every
/// other platform starts the title after the leading and leaves it there.
///
/// The reference's rule (`app_bar.dart:805`), read from the **theme's** platform, so a
/// theme set to iOS centres the title on an Android phone (milestone 615).
/// [`AppBar::center_title`] overrides it either way.
pub const fn platform_centers_title(platform: frus_core::TargetPlatform, actions: usize) -> bool {
    use frus_core::TargetPlatform as P;
    match platform {
        P::Ios | P::MacOs => actions < 2,
        P::Android | P::Fuchsia | P::Linux | P::Windows => false,
    }
}

/// The bar's height, the reference's Material 3 `toolbarHeight`.
///
/// A **fixed** height, not the content's: chrome that changes height with what happens
/// to be in it makes every screen a slightly different shape, and the page below it move
/// when an action appears. [`AppBar::height`] overrides it.
pub const APP_BAR_HEIGHT: f32 = 64.0;
/// The title's type: what the caller said, else what the theme's `app_bar` says, else the
/// step of the type scale the reference names — `titleLarge`.
///
/// It used to be a private `TextStyle::new(22.0).weight(Medium)`, which had the size right
/// and **the weight wrong**: `titleLarge` is regular. A number written beside the scale is a
/// number that can drift from it without anybody seeing, which is milestone 413's lesson and
/// this is the same constant one file over.
fn title_style_of(over: Option<TextStyle>, theme: &Theme) -> TextStyle {
    over.or(theme.widgets.app_bar.title_style)
        .unwrap_or(theme.text.title_large)
}
/// How far the reader's font setting may enlarge the **title**, and no further.
///
/// A bar is chrome: it keeps [`APP_BAR_HEIGHT`] whatever the reader asked for, because a
/// toolbar that grew with the type would push every screen down. So the reference caps the
/// title's scaler rather than the bar's height — the same 1.34 — "to keep the visual
/// hierarchy the same even with larger font sizes". A caller who wants the whole scale
/// gives the title its own [`AppBar::title_style`] and their own height.
pub const APP_BAR_MAX_TITLE_SCALE: f32 = 1.34;
/// The actions' size: what the caller said, else the step the reference gives them.
///
/// A bar's actions **are text buttons**, so they take `labelLarge` — the same step
/// [`crate::Button`] already reads — rather than the `bodyMedium` the reference gives the
/// toolbar's other text.
fn action_size_of(over: Option<f32>, theme: &Theme) -> f32 {
    over.or(theme.text.label_large.size)
        .unwrap_or(frus_core::DEFAULT_TEXT_SIZE)
}
/// Whether an untold bar sits at the top of the screen. The reference's default, and the
/// one that makes a bar used **outside** a shell behave: it consumes the status bar itself
/// rather than waiting for something to inset it.
const PRIMARY: bool = true;

/// The space between the bar's elements (the default, overridden by [`AppBar::gap`]): none,
/// as the reference's toolbar puts its actions side by side, each an icon button whose own
/// 48 px box is the room around its glyph (milestone 611). It was 8 px.
const GAP: f32 = 0.0;
/// The space between the leading and the title, and between the start edge and a title
/// with no leading: the reference's `NavigationToolbar.kMiddleSpacing`.
const TITLE_SPACING: f32 = 16.0;
/// The width reserved for the `leading` slot (a leading icon, Material style).
const LEADING_SLOT: f32 = 56.0;
/// The bar's horizontal margin: none. The leading's 56 px slot starts at the edge and the
/// actions end there, as the reference's do; the glyphs' distance from the edge is their
/// buttons' own (milestone 611). It was 8 px on each side. Counted in the folding budget.
const H_PAD: f32 = 0.0;
/// The width the title is never squeezed below, in px. A title cut to nothing tells a
/// reader less than a title cut to two characters and an ellipsis.
const TITLE_MIN: f32 = 64.0;
/// An action: any widget (always inline — an arbitrary widget cannot become a text menu
/// row), or labelled and foldable into the overflow.
enum Action<Msg> {
    Labeled { label: String, message: Msg },
    Custom(Box<dyn Widget<Msg>>),
}

/// An adaptive application bar. A fluent builder finished by [`AppBar::build`].
pub struct AppBar<Msg = crate::callback::Callback> {
    title: Option<Box<dyn Widget<Msg>>>,
    title_style: Option<TextStyle>,
    /// Was the title's style left at the framework's default? Only then may the theme
    /// have its say — a caller who set one outranks it.
    width: f32,
    leading: Option<Box<dyn Widget<Msg>>>,
    /// Whether a bar with no `leading` of its own may take one from the shell it stands in.
    automatically_imply_leading: bool,
    /// The same for the trailing end.
    automatically_imply_actions: bool,
    overflow: Option<(bool, Msg)>,
    actions: Vec<Action<Msg>>,
    action_size: Option<f32>,
    primary: bool,
    /// What the surface's side intrusions take, left and right, read with the width: a
    /// primary bar keeps its row clear of them (milestone 728).
    side_insets: f32,
    gap: f32,
    background: Option<Color>,
    height: Option<f32>,
    /// `None` = the platform's convention (see [`platform_centers_title`]).
    center_title: Option<bool>,
    bottom: Option<Box<dyn Widget<Msg>>>,
    leading_width: Option<f32>,
    title_spacing: f32,
    foreground: Option<Color>,
    elevation: f32,
    shape: Option<ShapeBorder>,
    shadow_color: Option<Color>,
    surface_tint: Option<Color>,
    force_material_transparency: bool,
    toolbar_opacity: f32,
    bottom_opacity: f32,
    actions_padding: Option<f32>,
    flexible_space: Option<Box<dyn Widget<Msg>>>,
    icon_theme: Option<IconTheme>,
    actions_icon_theme: Option<IconTheme>,
    toolbar_text_style: Option<TextStyle>,
    exclude_header_semantics: bool,
}

impl<Msg: Clone + 'static> Default for AppBar<Msg> {
    /// The same as [`AppBar::new`]: a bar with no title, as wide as the surface.
    fn default() -> Self {
        Self::new()
    }
}

impl<Msg: Clone + 'static> AppBar<Msg> {
    /// Creates a bar with **no title**, as wide as **the surface it is being built
    /// for** — which is what decides how many actions fit on the line and how many
    /// fold into the overflow menu.
    ///
    /// The title is [`AppBar::title`], and it is any widget. A bar that has none keeps its
    /// leading and its actions where they would be and puts nothing between them.
    ///
    /// The width is read from [`MediaQuery::of`], so no caller passes it. Outside any
    /// surface description — a unit test that builds a bar on its own — there is no
    /// width to fold against and nothing folds, which is what this did before the
    /// surface was ambient. A bar that is **not** the full width of the screen (one
    /// beside a rail, say) still says so with [`AppBar::width`].
    ///
    /// **Breaking**: this took the title as a string until milestone 522.
    /// `AppBar::new().title(Text::new("Inbox"))` is `AppBar::new().title(Text::new("Inbox"))`.
    pub fn new() -> Self {
        let surface = MediaQuery::of();
        Self {
            // **A widget, never a string — and not always one.** The reference's `title`
            // is a `Widget?` and nothing else (`app_bar.dart:1067`). A string constructor
            // that took a second path through the bar is what made a bar's accessibility
            // depend on which constructor the caller had reached for (milestone 397), and
            // a constructor that demanded a string is what made "no title" an empty text,
            // laid out and painted where the title would have been (milestone 522).
            title: None,
            title_style: None,
            width: if surface.is_described() {
                surface.size.width
            } else {
                f32::MAX
            },
            leading: None,
            automatically_imply_leading: true,
            automatically_imply_actions: true,
            overflow: None,
            actions: Vec::new(),
            action_size: None,
            primary: PRIMARY,
            side_insets: if surface.is_described() {
                surface.padding.left + surface.padding.right
            } else {
                0.0
            },
            gap: GAP,
            background: None,
            height: None,
            center_title: None,
            bottom: None,
            leading_width: None,
            title_spacing: TITLE_SPACING,
            foreground: None,
            elevation: 0.0,
            shape: None,
            shadow_color: None,
            surface_tint: None,
            force_material_transparency: false,
            toolbar_opacity: 1.0,
            bottom_opacity: 1.0,
            actions_padding: None,
            flexible_space: None,
            icon_theme: None,
            actions_icon_theme: None,
            toolbar_text_style: None,
            exclude_header_semantics: false,
        }
    }

    /// The **available width** for the bar, in logical pixels: what drives the
    /// folding. It is a *size*, not a platform indicator.
    ///
    /// An override. [`AppBar::new`] already takes the surface's width from
    /// [`MediaQuery::of`]; this is for a bar that does not get the whole of it.
    pub fn width(mut self, width: f32) -> Self {
        self.width = width;
        self
    }

    /// The text title's style (size/weight/italic/color). Default: the reference's
    /// `title_large` at medium weight, in the theme's colour.
    pub fn title_style(mut self, style: TextStyle) -> Self {
        self.title_style = Some(style);
        self
    }

    /// The title, as **any widget** — a text, a logo, a composed row.
    ///
    /// This is the title in the reference, where `title` is a `Widget?` and there is no
    /// string form at all. Unset, the bar has none: nothing is laid out, painted or
    /// announced between the leading and the actions.
    ///
    /// No style is put on it. It takes the resolved title type from the
    /// `DefaultTextStyle` the bar hands down, which is what the reference does at
    /// `app_bar.dart:1084`, so a `Text` that chose nothing wears the bar's type and one
    /// that chose its own size keeps it. And it is announced as the screen's heading
    /// unless [`AppBar::exclude_header_semantics`] says otherwise.
    ///
    /// It was called `title_widget` while the bar had two kinds of title, and
    /// [`AppBar::new`] took a string until milestone 522. There is one kind, and it is
    /// optional.
    pub fn title(mut self, widget: impl Widget<Msg> + 'static) -> Self {
        self.title = Some(Box::new(widget));
        self
    }

    /// The leading element (a menu or back button…), optional.
    pub fn leading(mut self, widget: impl Widget<Msg> + 'static) -> Self {
        self.leading = Some(Box::new(widget));
        self
    }

    /// Whether a bar with **no `leading` of its own** may take one from the shell it
    /// stands in. `true` unless said otherwise, as in the reference.
    ///
    /// A bar on a screen that has a drawer then grows the button that opens it, and a bar
    /// on a screen that has none stays as it was — the shell is what knows, and until
    /// milestone 422 it had no way to say so to a slot handed to it already built.
    ///
    /// The reference's other branch has no counterpart here. There a bar also implies a
    /// **back button** when the route it is in can be popped; frus's
    /// [`Navigator`](crate::Navigator) is controlled — the application holds the stack — so
    /// the framework does not know a depth to imply anything from. A screen that can be
    /// left says so with [`AppBar::leading`].
    ///
    /// `false` is for a bar that wants its leading slot empty on a screen that has a
    /// drawer: a logo where the button would be, and some other way in.
    pub fn automatically_imply_leading(mut self, imply: bool) -> Self {
        self.automatically_imply_leading = imply;
        self
    }

    /// Whether a bar with **no actions of its own** may take one from the shell it stands
    /// in. `true` unless said otherwise, as in the reference (`app_bar.dart:1113`).
    ///
    /// A bar with nothing at its trailing end, on a screen that has an end drawer, grows
    /// the button that opens it. One action of its own and it does not: the reference's
    /// test is the same — the implied button is what fills an **empty** end, never
    /// something added beside what the caller put there.
    pub fn automatically_imply_actions(mut self, imply: bool) -> Self {
        self.automatically_imply_actions = imply;
        self
    }

    /// Enables the overflow menu: its open state (controlled by the app) and the
    /// toggle message (emitted by the `⋯` button and on an outside click).
    pub fn overflow(mut self, open: bool, toggle: Msg) -> Self {
        self.overflow = Some((open, toggle));
        self
    }

    /// Adds an action: **any widget**, at the bar's trailing end, after those already
    /// added. Typically an [`IconButton`](crate::IconButton), or a
    /// [`PopupMenuButton`] for a menu of its own.
    ///
    /// The reference's `actions` is a list of widgets, and this is one more of them. The
    /// actions sit side by side, centred across the bar, inset by
    /// [`AppBar::actions_padding`], their glyphs in [`AppBar::actions_icon_theme`]. A widget
    /// is never folded into the overflow menu: an arbitrary widget cannot become a menu
    /// row. An action that may fold is a [`AppBar::foldable_action`].
    ///
    /// **Breaking**: until milestone 613 this took a label and a message and made the
    /// foldable button; that is now `foldable_action`, and this is what `action_widget` was.
    pub fn action(mut self, widget: impl Widget<Msg> + 'static) -> Self {
        self.actions.push(Action::Custom(Box::new(widget)));
        self
    }

    /// Adds every action of an iterator, **already boxed**, for actions built in a loop:
    /// the reference's `actions: [...]` in one call. The same as [`AppBar::action`] for
    /// each, in order.
    pub fn actions(mut self, actions: impl IntoIterator<Item = Box<dyn Widget<Msg>>>) -> Self {
        self.actions.extend(actions.into_iter().map(Action::Custom));
        self
    }

    /// Adds an action that **folds**: a text button with `label`, shown inline while it
    /// fits and moved into the overflow menu ([`AppBar::overflow`]) when the bar is too
    /// narrow for it. The last ones fold first.
    ///
    /// This is frus's own, beside the reference's list of widgets: a bar that adapts to
    /// its width without the application measuring anything. It was `action` until
    /// milestone 613.
    pub fn foldable_action(mut self, label: impl Into<String>, message: Msg) -> Self {
        self.actions.push(Action::Labeled {
            label: label.into(),
            message,
        });
        self
    }

    /// Adds a widget action: [`AppBar::action`], under its former name.
    #[deprecated(
        since = "0.3.0",
        note = "an action is any widget: use `AppBar::action`"
    )]
    pub fn action_widget(self, widget: impl Widget<Msg> + 'static) -> Self {
        self.action(widget)
    }

    /// The foldable actions' font size (the theme's `label_large` by default).
    pub fn action_size(mut self, size: f32) -> Self {
        self.action_size = Some(size);
        self
    }

    /// Whether this bar sits at the **top of the screen**, and so has to keep its content
    /// out of the status bar. `true` unless said otherwise, as in the reference.
    ///
    /// The bar pads **itself**: its surface still runs behind the status bar — that is what
    /// a Material bar looks like — and only its toolbar and its `bottom` are held clear.
    /// The two things this separates are the shell's job and the bar's: a
    /// [`Scaffold`](crate::Scaffold) makes the slot tall enough, and the bar decides
    /// whether to use the room. Until milestone 417 the shell insetted the bar from
    /// outside, which is one switch where the reference has two — and why a bar used
    /// *without* a shell drew under the status bar.
    ///
    /// Turn it off for a bar that is not at the top: one nested in a page, or a second bar
    /// under the first.
    #[must_use]
    pub fn primary(mut self, primary: bool) -> Self {
        self.primary = primary;
        self
    }

    /// The space between the bar's elements (8 px by default).
    pub fn gap(mut self, gap: f32) -> Self {
        self.gap = gap;
        self
    }

    /// The bar's background color (transparent by default: the parent decides).
    pub fn background(mut self, color: Color) -> Self {
        self.background = Some(color);
        self
    }

    /// An imposed bar height (by default, the content's natural height).
    pub fn height(mut self, height: f32) -> Self {
        self.height = Some(height);
        self
    }

    /// Centres the title in the space left between the leading and the actions,
    /// rather than starting it flush after the leading.
    ///
    /// **Overrides the platform's convention**, which is what a bar that has not been
    /// told anything follows: centred where the system centres its own titles, flush
    /// after the leading everywhere else. See [`platform_centers_title`].
    ///
    /// Centred, the title still yields to the actions first: it is centred in what is
    /// left, not in the window.
    pub fn center_title(mut self, centered: bool) -> Self {
        self.center_title = Some(centered);
        self
    }

    /// A widget **under** the bar, spanning its width — a row of tabs, a search field,
    /// a progress bar. It belongs to the bar, so it sits inside the background.
    pub fn bottom(mut self, widget: impl Widget<Msg> + 'static) -> Self {
        self.bottom = Some(Box::new(widget));
        self
    }

    /// The width reserved for the leading slot. Unset, it is the Material slot width;
    /// a leading wider than that would otherwise push the title without the folding
    /// budget knowing, and the actions would run off the edge.
    pub fn leading_width(mut self, width: f32) -> Self {
        self.leading_width = Some(width);
        self
    }

    /// The gap between the leading and the title.
    pub fn title_spacing(mut self, spacing: f32) -> Self {
        self.title_spacing = spacing;
        self
    }

    /// The colour of the bar's own text — the title, and the labelled actions. Unset,
    /// each follows the theme.
    pub fn foreground(mut self, color: Color) -> Self {
        self.foreground = Some(color);
        self
    }

    /// How far off the page the bar sits. `0` — the default — is flat, which is what a bar
    /// sitting on a surface of the same colour wants.
    ///
    /// A height casts a shadow only where a [`shadow_color`](Self::shadow_color) is named,
    /// and tints only where a [`surface_tint`](Self::surface_tint) is: the reference's
    /// Material 3 bar makes both transparent (its app bar defaults, lines 2542 and 2545).
    pub fn elevation(mut self, elevation: f32) -> Self {
        self.elevation = elevation.max(0.0);
        self
    }

    /// **What shape the bar is** — the reference's `shape` (`app_bar.dart:209`), and a
    /// whole [`ShapeBorder`] since milestone 455. Square by default, as the reference's is.
    ///
    /// The bar clips to it, so a coloured surface and anything drawn on it stop at the
    /// curve rather than squaring off the corner the shadow already rounded.
    ///
    /// A bar is a **rectangle**, so what a shape contributes here is the corners it
    /// resolves to in the bar's own box — a stadium rounds to half the bar's height,
    /// which is what a stadium means on a wide, short box. A shape with no rounded form
    /// at all leaves the bar square rather than clipping it to something it is not.
    ///
    /// **Breaking**: this took a `BorderRadius` under the same name until milestone 455.
    /// A caller passing a number says [`radius`](Self::radius) instead.
    pub fn shape(mut self, shape: ShapeBorder) -> Self {
        self.shape = Some(shape);
        self
    }

    /// The corner radii — the shorthand for a rounded rectangle, writing into the same
    /// one field [`shape`](Self::shape) does. The last of the two called is the one that
    /// counts.
    pub fn radius(mut self, radius: impl Into<BorderRadius>) -> Self {
        self.shape = Some(ShapeBorder::rounded(radius));
        self
    }

    /// The colour of the shadow the bar casts. Only visible with an
    /// [`elevation`](Self::elevation).
    ///
    /// The reference's `shadowColor`, **alpha included**. Left unset it is transparent, as
    /// the reference's Material 3 bar is (its app bar defaults, line 2542), and an
    /// elevated bar casts nothing.
    pub fn shadow_color(mut self, color: Color) -> Self {
        self.shadow_color = Some(color);
        self
    }

    /// The colour laid over the bar's surface **in proportion to its elevation** — the
    /// reference's `surfaceTintColor`, and Material 3's way of showing height.
    ///
    /// A shadow says a thing is above the page; the tint says how far, and it is what
    /// still reads on a dark background where a shadow shows nothing. The strength comes
    /// from the specification's table (see
    /// [`surface_tint_opacity`](frus_core::surface_tint_opacity)), so an elevation of 3
    /// tints at 8% whoever asks.
    ///
    /// Nothing is tinted at elevation zero, which is the default: a flat bar is the
    /// surface it was given.
    pub fn surface_tint(mut self, color: Color) -> Self {
        self.surface_tint = Some(color);
        self
    }

    /// Draws the bar with **no surface at all**: no background, no tint, no shadow —
    /// only what it holds.
    ///
    /// The reference's `forceMaterialTransparency`, and it exists for the same case: a
    /// bar over an image or a video, where the chrome should be the controls and nothing
    /// else. It overrides the background, the tint and the elevation rather than
    /// arguing with them, because a caller asking for transparency has already decided.
    pub fn force_material_transparency(mut self, force: bool) -> Self {
        self.force_material_transparency = force;
        self
    }

    /// The opacity of the toolbar row — the leading, the title and the actions — without
    /// touching the bar's surface. `1.0` by default.
    ///
    /// The reference's `toolbarOpacity`. It is what fades a collapsing header's contents
    /// out while its background stays, and it is a **group** opacity: overlapping
    /// children do not darken where they overlap.
    pub fn toolbar_opacity(mut self, opacity: f32) -> Self {
        self.toolbar_opacity = opacity.clamp(0.0, 1.0);
        self
    }

    /// The opacity of the [`bottom`](Self::bottom) slot, independently of the toolbar.
    /// `1.0` by default. The reference's `bottomOpacity`.
    pub fn bottom_opacity(mut self, opacity: f32) -> Self {
        self.bottom_opacity = opacity.clamp(0.0, 1.0);
        self
    }

    /// Padding **across** the **actions** as a group, at its two ends, on top of the gap
    /// between them.
    ///
    /// The reference's `actionsPadding`, added in its 3.27 line for the same reason: an
    /// icon button's own hit area already reaches the bar's edge, so a design that wants
    /// the *glyphs* inset has nowhere else to say so.
    pub fn actions_padding(mut self, padding: f32) -> Self {
        self.actions_padding = Some(padding);
        self
    }
    /// Stops the title being announced as a **heading**. `false` by default, as the
    /// reference's `excludeHeaderSemantics` is.
    ///
    /// A screen reader's user moves through a screen by its headings, and the bar's title
    /// is the one every screen has. Excluding it is for a bar whose title is decorative,
    /// or one of two bars on a page where only the outer one names it — announcing both
    /// as headings gives the user two landmarks where there is one screen.
    pub fn exclude_header_semantics(mut self, exclude: bool) -> Self {
        self.exclude_header_semantics = exclude;
        self
    }

    /// A widget stacked **behind** the toolbar and the [`bottom`](Self::bottom), filling
    /// the bar's whole box.
    ///
    /// The reference's `flexibleSpace`, and it is what makes a collapsing header possible
    /// at all: an image, a gradient, a photograph that the title sits on. The bar's height
    /// is unchanged — this is a layer, not a slot — so the space is exactly as tall as
    /// the bar however tall the widget would rather be.
    ///
    /// The bar's own background is drawn first and this over it, so a translucent surface
    /// still tints what is behind, and a caller who wants only the image says
    /// [`force_material_transparency`](Self::force_material_transparency).
    pub fn flexible_space(mut self, widget: impl Widget<Msg> + 'static) -> Self {
        self.flexible_space = Some(Box::new(widget));
        self
    }

    /// The colour and the size of the **glyphs in the bar** — the reference's `iconTheme`.
    ///
    /// It reaches every icon in the leading slot and, unless
    /// [`actions_icon_theme`](Self::actions_icon_theme) says otherwise, in the actions
    /// too. It is delivered as a theme for that subtree rather than as an argument to
    /// each widget, so it reaches an icon nested inside a button the bar never sees —
    /// which is what the reference's inherited `IconTheme` does and why it is one.
    ///
    /// An icon that names its own colour still wins: `caller ?? this ?? the scheme`.
    pub fn icon_theme(mut self, icons: IconTheme) -> Self {
        self.icon_theme = Some(icons);
        self
    }

    /// The same, for the **actions** alone — the reference's `actionsIconTheme`.
    ///
    /// Unset, the actions follow [`icon_theme`](Self::icon_theme). Set, they part company
    /// with the leading slot, which is the case it exists for: a back arrow in the
    /// foreground colour beside actions in a muted one.
    pub fn actions_icon_theme(mut self, icons: IconTheme) -> Self {
        self.actions_icon_theme = Some(icons);
        self
    }

    /// The type worn by the **words in the bar that are not the title** — a label beside
    /// the back arrow, a "Save" in the actions, anything a caller handed over already
    /// assembled.
    ///
    /// Not the title: the title has [`title_style`](Self::title_style), and the reference
    /// keeps the same two apart for the same reason. A bar's title is one line the bar
    /// itself lays out and can measure; the rest is other people's widgets, and the only
    /// way to reach a `Text` nested three levels inside one of them is to hand the style
    /// *down* rather than pass it *in*.
    ///
    /// It is handed down **field by field**: setting a size leaves the colours alone, and
    /// a `Text` that chose its own size keeps it. See
    /// [`DefaultTextStyle`](crate::DefaultTextStyle) for the rule in full.
    pub fn toolbar_text_style(mut self, style: TextStyle) -> Self {
        self.toolbar_text_style = Some(style);
        self
    }

    /// The button a labelled action is drawn as — made in this one place, so that the
    /// width the fold is decided on is the width of what is then drawn. The bar used to
    /// estimate it with a padding and no minimum of its own, and the two drifted apart.
    ///
    /// A **text button**, as an action with words is in the reference: no outline, the bar
    /// is its surface (milestone 611). It was an outlined pill.
    fn action_button(label: String, message: Msg, size: f32) -> impl Widget<Msg> + 'static {
        button(label, message).variant(Variant::Text).size(size)
    }

    /// The button that opens the overflow menu: the reference's three dots, upright, in an
    /// icon button (milestone 611). It was a `⋯` in an outlined pill.
    fn overflow_button(message: Msg) -> impl Widget<Msg> + 'static {
        crate::IconButton::new(crate::Icons::MORE_VERT)
            .label("More")
            .on_press(message)
    }

    /// A widget's declared width (0 if it depends on layout).
    fn widget_width(widget: &dyn Widget<Msg>, theme: &Theme) -> f32 {
        match widget.style_themed(theme).width {
            Dimension::Length(v) => v,
            _ => 0.0,
        }
    }

    /// Assembles the bar into a widget ready to display (the row `leading . title .
    /// spring . inline actions . overflow`, over an optional `bottom`).
    ///
    /// The order in which space is handed out is worth stating, because it is a
    /// decision and not an accident: **the actions are served first and the title
    /// yields.** A title cut short is still a title; an action pushed off the edge is
    /// gone. So the folding budget is computed against the title's *floor*, and
    /// whatever is left afterwards is what the title gets - with an ellipsis if it
    /// does not fit.
    /// Finishes the bar.
    ///
    /// The composition is **deferred until the theme is known** ([`ThemeBuilder`]):
    /// `center_title` decides which children exist and in what order, so it cannot be
    /// resolved by a hook that runs after the row has been assembled. Everything the
    /// theme has a say in — the title's centring, its type, the bar's colours — is
    /// resolved inside, `caller ?? theme ?? framework`.
    ///
    /// [`ThemeBuilder`]: crate::ThemeBuilder
    pub fn build(self) -> Box<dyn Widget<Msg>> {
        Box::new(crate::themebuilder::ThemeBuilder::boxed(move |theme| {
            self.build_with(theme)
        }))
    }

    /// The composition proper, against a known theme.
    fn build_with(self, theme: &Theme) -> Box<dyn Widget<Msg>> {
        let t = theme.widgets.app_bar;
        let AppBar {
            title,
            title_style,
            width,
            leading,
            automatically_imply_leading,
            automatically_imply_actions,
            overflow,
            actions,
            action_size,
            gap,
            background,
            height,
            center_title,
            bottom,
            leading_width,
            title_spacing,
            foreground,
            elevation,
            shape,
            shadow_color,
            surface_tint,
            force_material_transparency,
            toolbar_opacity,
            bottom_opacity,
            actions_padding,
            primary,
            side_insets,
            flexible_space,
            icon_theme,
            actions_icon_theme,
            toolbar_text_style,
            exclude_header_semantics,
        } = self;

        // **Is that width a measurement or a sentinel?** `AppBar::new` takes the surface's
        // width from the ambient description, and falls back to `f32::MAX` when nothing
        // described it — a bar built outside a frame, which is every bar a test builds by
        // hand. `f32::MAX` is finite, so every arithmetic below happily produced a number:
        // a row `f32::MAX` wide, a title ceiling just under it, and a leading spring that
        // pushed a centred title to `x = 1.7e38`, off any screen there will ever be. The
        // sentinel is asked about once, here, and the two places that need a real width
        // fill the space they are offered instead.
        let known_width = width.is_finite() && width < f32::MAX;

        // **What the shell knows and the bar does not** (milestone 422). This bar was
        // handed to its `Scaffold` already built, so it cannot see the screen it stands on;
        // the shell tells it, through the ambient the walk installs on the way down, and
        // this composition runs under that ambient because it is deferred.
        //
        // A bar with no `leading` of its own, on a screen with a drawer, grows the button
        // that opens it — the reference's first branch at `app_bar.dart:1010`. The second,
        // a back button for a route that can be popped, has no counterpart: frus's
        // `Navigator` is controlled, so there is no stack depth for the framework to read.
        let shell = crate::ScaffoldInfo::of();
        let leading = leading.or_else(|| {
            if !automatically_imply_leading {
                return None;
            }
            let toggle = shell.drawer_toggle::<Msg>()?;
            Some(
                Box::new(crate::IconButton::new(crate::Icons::MENU).on_press(toggle))
                    as Box<dyn Widget<Msg>>,
            )
        });
        // And the trailing end, on the same terms: **an empty end**, never a button added
        // beside what the caller put there (`app_bar.dart:1113`). An overflow toggle counts
        // as something at that end, since it is what the bar puts there itself.
        let mut actions = actions;
        if actions.is_empty() && overflow.is_none() && automatically_imply_actions {
            if let Some(toggle) = shell.end_drawer_toggle::<Msg>() {
                actions.push(Action::Custom(Box::new(
                    crate::IconButton::new(crate::Icons::MENU).on_press(toggle),
                )));
            }
        }

        // `caller ?? theme ?? platform`. The platform is the last word rather than the
        // framework's own taste, because where a title sits is a system convention before
        // it is a design one — see `platform_centers_title`.
        let center_title = center_title
            .or(t.center_title)
            .unwrap_or_else(|| platform_centers_title(theme.platform, actions.len()));

        // The title's type, likewise: the caller's style, else the theme's, else the
        // reference's `titleLarge`.
        let mut title_style = title_style_of(title_style, theme);
        let action_size = action_size_of(action_size, theme);
        let foreground = foreground
            .or(t.foreground)
            .unwrap_or(theme.scheme.on_surface);
        title_style.color = Some(foreground);
        // The bar keeps its height, so the title is capped rather than let out. See
        // [`APP_BAR_MAX_TITLE_SCALE`]: this is the reference's answer for chrome, and the
        // opposite of the one its components give (there the height is a floor and the
        // content wins).
        let title_style = title_style.clamp_scale(APP_BAR_MAX_TITLE_SCALE);
        // The title's type as something a subtree can **hand down**, plus the two settings
        // the reference pairs with it: one line, cut with an ellipsis. A `Text` that never
        // chose a size, a wrap or an overflow takes all three; one that did keeps its own.
        let title_words = DefaultTextStyle {
            soft_wrap: Some(false),
            overflow: Some(frus_core::TextOverflow::Ellipsis),
            ..DefaultTextStyle::from_text_style(title_style)
        };
        // The same thing as a whole theme, for asking a title how wide it naturally is.
        let dressed_title_theme = {
            let mut dressed = theme.clone();
            dressed.widgets.text = dressed.widgets.text.merge(title_words);
            dressed
        };
        let background = background.or(t.background);
        let elevation = if elevation > 0.0 {
            elevation
        } else {
            t.elevation.unwrap_or(0.0)
        };
        let height = height.or(t.height);
        let leading_w = match (&leading, leading_width) {
            (None, _) => 0.0,
            (Some(_), Some(w)) => w,
            (Some(widget), None) => Self::widget_width(widget.as_ref(), theme).max(LEADING_SLOT),
        };
        // The title's natural width, asked of the widget **under the type it will
        // actually wear**. Asking it bare would measure a string title at the framework's
        // 16 px and reserve room for a bar that draws it at 22.
        // Nought for a bar with no title: it reserves nothing, and holds no floor.
        let natural_title = title.as_ref().map_or(0.0, |title| {
            Self::widget_width(title.as_ref(), &dressed_title_theme)
        });

        // The room the actions may claim: everything except the margins, the leading,
        // the spacing, and what the title is **reserved**.
        //
        // The order matters and it is a decision. A bar that folds actions into an
        // overflow already has a way of making room, and that is the one to use first:
        // the title keeps its natural width — up to half the bar, so a long one cannot
        // starve the actions — and the actions fold to fit what is left. Truncating
        // the title is the *last* resort, for when even one action and the overflow
        // button will not fit beside it.
        //
        // The row's own children before the actions are counted as the row below will
        // have them: the leading, the spacer that widens its gap to `title_spacing`, a
        // spring before a centred title, the title if there is one, and the spring after
        // it — each joined to the next by a gap. The gap joining the last of them to the
        // actions is each action's own, below, so a bar with no actions still owes it here.
        // With a leading, the spacing sits between it and the title; without one, between
        // the start edge and the title, as the reference's toolbar puts it. A centred title
        // has no start to keep it from.
        let spacer_w =
            if title.is_some() && (leading.is_some() || !center_title) && title_spacing > gap {
                title_spacing - gap
            } else {
                0.0
            };
        let before_actions = usize::from(leading.is_some())
            + usize::from(spacer_w > 0.0)
            + usize::from(center_title)
            + usize::from(title.is_some())
            + 1;
        let joins = before_actions - 1 + usize::from(actions.is_empty());
        // A primary bar keeps its row clear of the side intrusions (the `SafeArea` below):
        // a phone on its side has its cutout and corners there. What it takes is not room
        // for actions, or they are counted into a row that is narrower than the bar, and the
        // last ones run off its end (milestone 728).
        let sides = if primary { side_insets } else { 0.0 };
        let fixed = H_PAD * 2.0
            + sides
            + leading_w
            + spacer_w
            + gap * joins as f32
            + actions_padding.map_or(0.0, |pad| pad * 2.0);
        let room = (width - fixed).max(0.0);
        let title_reserve = natural_title
            .min(room * 0.5)
            .max(TITLE_MIN.min(natural_title));
        let budget = room - title_reserve;
        // The `⋯` is made as the actions are, and measured as they are.
        let overflow_btn_w = match &overflow {
            Some((_, toggle)) => {
                let glyph = Self::overflow_button(toggle.clone());
                Self::widget_width(&glyph, theme) + gap
            }
            None => 0.0,
        };

        // Each action's width; free widgets are **always** inline.
        let widths: Vec<f32> = actions
            .iter()
            .map(|action| match action {
                Action::Labeled { label, message } => {
                    let drawn = Self::action_button(label.clone(), message.clone(), action_size);
                    Self::widget_width(&drawn, theme) + gap
                }
                Action::Custom(widget) => Self::widget_width(widget.as_ref(), theme) + gap,
            })
            .collect();
        let total: f32 = widths.iter().sum();
        let custom_total: f32 = actions
            .iter()
            .zip(&widths)
            .filter(|(action, _)| matches!(action, Action::Custom(_)))
            .map(|(_, w)| *w)
            .sum();

        // How many **labelled** actions fit inline? If everything fits, no overflow;
        // otherwise reserve the overflow button and the free widgets and keep as many
        // labelled ones as possible, in order - so it is the last actions that fold,
        // which is where a reader has learnt to go looking for them.
        let (kept_labeled, actions_w) = if total <= budget {
            (usize::MAX, total)
        } else {
            let mut used = overflow_btn_w + custom_total;
            let mut kept = 0;
            for (action, w) in actions.iter().zip(&widths) {
                if matches!(action, Action::Custom(_)) {
                    continue;
                }
                if used + w <= budget {
                    used += w;
                    kept += 1;
                } else {
                    break;
                }
            }
            (kept, used)
        };

        // What is left for the title, once the actions have taken theirs. Unknown when
        // the width is: a ceiling computed from the sentinel is `f32::MAX` less a few
        // pixels, which is not a ceiling.
        let title_room = if known_width {
            (width - fixed - actions_w).max(TITLE_MIN.min(natural_title))
        } else {
            f32::INFINITY
        };

        // An icon theme is delivered as a **theme for the subtree**, not as an argument
        // to each widget: that is the only way it reaches a glyph nested inside a button
        // the bar never sees. The reference's `IconTheme` is an inherited widget for the
        // same reason.
        //
        // A toolbar text style travels the same road, and for the same reason: the words
        // it is meant for are inside widgets the bar was handed, not ones it built.
        let dress = |widget: Box<dyn Widget<Msg>>, icons: Option<IconTheme>| {
            if icons.is_none() && toolbar_text_style.is_none() {
                return widget;
            }
            let words = toolbar_text_style.map(DefaultTextStyle::from_text_style);
            Box::new(crate::Themed::tweak(
                move |t| {
                    if let Some(icons) = icons {
                        if let Some(color) = icons.color {
                            t.widgets.icon.color = Some(color);
                            t.widgets.icon_button.icon_color = Some(color);
                        }
                        if let Some(size) = icons.size {
                            t.widgets.icon.size = Some(size);
                            t.widgets.icon_button.icon_size = Some(size);
                        }
                    }
                    // **Merged onto** whatever an enclosing subtree already handed down,
                    // rather than replacing it: two nested subtrees each setting one field
                    // must leave a text wearing both.
                    if let Some(words) = words {
                        t.widgets.text = t.widgets.text.merge(words);
                    }
                },
                widget,
            )) as Box<dyn Widget<Msg>>
        };

        let mut row = Flex::row().align(Align::Center).gap(gap);
        // The leading **in its slot**, centred: the reference gives it a box of exactly the
        // leading width, so an icon button's glyph sits 16 px from the edge and the title
        // starts at 72. The slot used to be counted in the budget and not given, and the
        // glyph touched the edge (milestone 611).
        if let Some(leading) = leading {
            row = row.child(
                Container::new()
                    .width(leading_w)
                    .alignment(crate::Alignment::CENTER)
                    .child(dress(leading, icon_theme)),
            );
        }
        if spacer_w > 0.0 {
            row = row.child(Container::new().width(spacer_w));
        }
        // Centred: a spring on either side of the title. Otherwise one spring after it,
        // which is what pushes the actions to the right.
        if center_title {
            row = row.child(Container::new().flex(1.0));
        }
        // The bar's title is the **heading** of the screen it names — the landmark a
        // screen reader's user jumps to — and now that is true of *every* title rather
        // than only of one written as a string. The reference wraps the same way
        // (`app_bar.dart:1071`), and milestone 401's `Semantics` wrapper is what lets a
        // container state a role for a child it was handed already assembled.
        let title = title.map(|title| -> Box<dyn Widget<Msg>> {
            if exclude_header_semantics {
                title
            } else {
                Box::new(crate::Semantics::heading(title))
            }
        });
        // **The type, handed down rather than applied.** The words are cut by the box they
        // are given instead of by arithmetic here: `soft_wrap: false` and an ellipsis, on a
        // `Text` that never chose either, exactly as the reference sets them
        // (`app_bar.dart:1084`). Cutting the string by hand needed a width computed before
        // the layout ran, which is the class of mistake milestone 392 was.
        // And a **ceiling**, the reference's `_AppBarTitleBox` (`app_bar.dart:1069`). The
        // ellipsis alone would very nearly do it — a text handed an overflow mode grants
        // the squeeze, so flexbox may shrink it — but "very nearly" is how an over-long
        // task name evicted its own delete button in milestone 333. What is left after the
        // actions have taken theirs is a number the bar knows; saying it outright is one
        // line, and it is the line that makes the guarantee testable.
        // A bar with no title puts nothing here: the reference's toolbar is handed a `null`
        // middle and builds none.
        if let Some(title) = title {
            row = row.child(
                ConstrainedBox::new(crate::Themed::tweak(
                    move |t| t.widgets.text = t.widgets.text.merge(title_words),
                    title,
                ))
                .max_width(title_room),
            );
        }
        row = row.child(Container::new().flex(1.0));

        let mut labeled_seen = 0;
        let mut folded: Vec<(String, Msg)> = Vec::new();
        // The actions as a **group**, so that `actions_padding` insets the glyphs rather
        // than each button's own hit area. Without a padding the group is the row itself
        // and nothing is nested that was not nested before.
        let mut group = Flex::row().align(Align::Center).gap(gap);
        for action in actions {
            match action {
                Action::Custom(widget) => group = group.child_boxed(widget),
                Action::Labeled { label, message } => {
                    if labeled_seen < kept_labeled {
                        group = group.child(Self::action_button(label, message, action_size));
                    } else {
                        folded.push((label, message));
                    }
                    labeled_seen += 1;
                }
            }
        }

        if !folded.is_empty() {
            match overflow {
                // A controlled overflow menu: the glyph opens it, the items emit the
                // actions.
                Some((open, toggle)) => {
                    let mut menu =
                        PopupMenuButton::new(Self::overflow_button(toggle.clone()), open, toggle);
                    for (label, message) in folded {
                        menu = menu.item(label, message);
                    }
                    group = group.child(menu);
                }
                // No overflow configured: show everything inline (it may overflow).
                None => {
                    for (label, message) in folded {
                        group = group.child(Self::action_button(label, message, action_size));
                    }
                }
            }
        }
        // Unset, the actions follow the bar's icon theme; set, they part company with
        // the leading slot — a back arrow in the foreground colour beside actions in a
        // muted one, which is the case the reference's `actionsIconTheme` exists for.
        // Untold, the actions' glyphs are the scheme's `on_surface_variant`, a step quieter
        // than the leading's `on_surface`: the reference's default `actionsIconTheme`
        // (milestone 611).
        let actions_icons = actions_icon_theme.or(icon_theme).or(Some(IconTheme {
            color: Some(theme.scheme.on_surface_variant),
            size: None,
        }));
        let group = dress(Box::new(group), actions_icons);
        row = match actions_padding {
            // Across, at both ends of the group: what insets the glyphs from the bar's edge.
            // Not above and below, where a bar of a fixed height has no room to give — an
            // icon button is already 48 of its 64 (milestone 611).
            Some(pad) => row.child(
                Container::new()
                    .padding_each(0.0, pad, 0.0, pad)
                    .child(group),
            ),
            None => row.child_boxed(group),
        };

        // The toolbar proper: the row, with its horizontal margin and any imposed
        // height. The `bottom` sits under it inside the same background - it belongs to
        // the bar, rather than being something the application places beneath one.
        // The row is given the bar's width less its margins, so that the springs
        // inside it have something to share: a row that hugged its content would leave
        // a centred title with no space to be centred in.
        let row = if known_width {
            row.width((width - H_PAD * 2.0).max(0.0))
        } else {
            // Nobody described the surface, so `width` is the sentinel rather than a
            // number. Fill what the parent offers instead of laying the row out across
            // `f32::MAX`: a spring in a row that wide puts a centred title at infinity,
            // which is where every Apple-platform title went until milestone 474.
            row.width_fraction(1.0)
        };
        // The bar is a **fixed** height, the caller's or the reference's. It used to hug
        // its content, which made the chrome a different shape on every screen and moved
        // the page below it the moment an action appeared or a title wrapped.
        let mut toolbar = Container::new().padding_each(0.0, H_PAD, 0.0, H_PAD);
        toolbar = toolbar.height(height.unwrap_or(APP_BAR_HEIGHT));
        let toolbar = toolbar.child(row);

        // The two opacities are **group** opacities and independent of one another: a
        // collapsing header fades its contents out while its surface stays, and the
        // `bottom` — a tab strip, usually — fades on its own schedule.
        let toolbar: Box<dyn Widget<Msg>> = if toolbar_opacity < 1.0 {
            Box::new(Container::new().opacity(toolbar_opacity).child(toolbar))
        } else {
            Box::new(toolbar)
        };
        let bottom = bottom.map(|widget| -> Box<dyn Widget<Msg>> {
            if bottom_opacity < 1.0 {
                Box::new(Container::new().opacity(bottom_opacity).child(widget))
            } else {
                widget
            }
        });
        let content: Box<dyn Widget<Msg>> = match bottom {
            Some(bottom) => Box::new(Flex::column().child_boxed(toolbar).child_boxed(bottom)),
            None => toolbar,
        };
        // **The padding applies to the toolbar and the bottom, not to the surface** — the
        // reference says so in as many words (`app_bar.dart:1189`), and it is what makes a
        // Material bar look the way it does: the colour runs behind the status bar while
        // the title sits below it. The bottom edge is left alone; a bar has something under
        // it by definition.
        let content: Box<dyn Widget<Msg>> = if primary {
            Box::new(crate::SafeArea::new(content).edges(crate::Edges::ALL.without_bottom()))
        } else {
            content
        };

        // The bar **occupies** the width it was told about rather than hugging its
        // content. Hugging made two things quietly wrong: a background painted only
        // behind the text instead of across the bar, and a centred title with no free
        // space to be centred in.
        let mut chrome = Container::new();
        if known_width {
            chrome = chrome.width(width);
        } else {
            chrome = chrome.width_fraction(1.0);
        }
        // **Transparency wins outright.** A caller asking for a bar over an image has
        // already decided; arguing with the background and the elevation it inherited
        // from a theme would only make that decision conditional on the theme.
        if !force_material_transparency {
            // Material 3 shows height by **tinting** the surface, not only by casting a
            // shadow: at elevation 3 the tint is 8%, and it is what still reads on a dark
            // background where a shadow shows nothing at all.
            let surface = match (background, surface_tint) {
                (Some(base), Some(tint)) => Some(base.surface_tint(tint, elevation)),
                (base, _) => base,
            };
            if let Some(color) = surface {
                chrome = chrome.color(color);
            }
            // A shadow only where a colour is named: the reference's is transparent.
            if let Some(shadow) = shadow_color
                .or(t.shadow_color)
                .filter(|shadow| elevation > 0.0 && shadow.a > 0.0)
            {
                chrome = chrome.shadow(0.0, elevation * 0.25, elevation, shadow);
            }
        }
        // The shape clips as well as rounds: a surface that stopped short of its own
        // corner would square off the one the shadow had already curved.
        //
        // The corners a shape *resolves to* in the bar's own box, not the shape itself:
        // the chrome is a rectangle, and a shape that is not one has no corners to give.
        if let Some(shape) = shape.or(t.shape) {
            let box_ = Rect::new(0.0, 0.0, width, height.unwrap_or(APP_BAR_HEIGHT));
            if let Some((_, radius)) = shape.as_rounded(box_) {
                chrome = chrome.radius(radius).clip();
            }
        }
        // **Behind the toolbar, filling the bar's box.** A layer, not a slot: the bar is
        // exactly as tall as it was, however tall the widget would rather be. The bar's
        // own surface is painted by `chrome` underneath, so a translucent flexible space
        // still tints what the surface put there.
        let content: Box<dyn Widget<Msg>> = match flexible_space {
            Some(space) => Box::new(crate::Stack::new().layer(space).layer(content)),
            None => content,
        };
        Box::new(chrome.child(content))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{build_ui, Runtime, Size, Theme};

    #[derive(Clone, Debug, PartialEq)]
    enum Msg {
        PopupMenuButton,
        A,
        B,
        C,
    }

    /// **A bar folds against the surface it was built for, with no caller saying how
    /// wide that is.**
    ///
    /// Milestone 393. The width used to be an argument, and an application that got it
    /// wrong got a bar that folded too early or ran off the edge. `AppBar::new` reads
    /// [`MediaQuery::of`] instead: the same three actions fit on a wide surface and
    /// fold into the overflow menu on a narrow one, and neither build says a number.
    #[test]
    fn a_bar_folds_against_the_surface_it_was_built_for() {
        let built = |width: f32| {
            let size = Size::new(width, 80.0);
            let bar = MediaQuery::new(size).scope(|| {
                AppBar::new()
                    .title(Text::new("Title"))
                    .overflow(false, Msg::PopupMenuButton)
                    .foldable_action("Action One", Msg::A)
                    .foldable_action("Action Two", Msg::B)
                    .foldable_action("Action Three", Msg::C)
                    .build()
            });
            // The actions still on the bar, by their words: a folded one leaves, and the
            // overflow button that takes its place says no words of its own.
            texts_of(bar.as_ref(), width)
                .into_iter()
                .filter(|t| t.starts_with("Action"))
                .count()
        };
        assert_eq!(built(1000.0), 3, "a wide surface shows them all");
        assert!(
            built(1000.0) > built(300.0),
            "a narrow surface folds what a wide one shows"
        );
    }

    /// **A bar beside a cutout folds against the room it is left** (milestone 728): a
    /// phone on its side keeps its cutout and corners at the sides, the bar's row is kept
    /// clear of them, and the actions are counted into that row — not into the whole width,
    /// where the last ones ran off its end.
    #[test]
    fn a_bar_beside_a_cutout_folds_against_what_is_left() {
        let built = |width: f32, sides: f32| {
            let surface = MediaQuery::new(Size::new(width, 80.0)).with_insets(
                frus_core::WindowInsets::bars(frus_core::Insets::new(0.0, sides, 0.0, sides)),
            );
            let bar = surface.scope(|| {
                AppBar::new()
                    .title(Text::new("Title"))
                    .overflow(false, Msg::PopupMenuButton)
                    .foldable_action("Action One", Msg::A)
                    .foldable_action("Action Two", Msg::B)
                    .foldable_action("Action Three", Msg::C)
                    .build()
            });
            texts_of(bar.as_ref(), width)
                .into_iter()
                .filter(|t| t.starts_with("Action"))
                .count()
        };
        // The narrowest surface on which all three fit with nothing at the sides…
        let snug = (300..1000)
            .step_by(4)
            .map(|w| w as f32)
            .find(|&w| built(w, 0.0) == 3)
            .expect("a width on which all three fit");
        // …folds one once 59 a side is taken.
        assert!(
            built(snug, 59.0) < 3,
            "at {snug}, the cutouts leave no room for all three"
        );
        assert_eq!(
            built(snug + 2.0 * 59.0, 59.0),
            3,
            "given the room back, they fit"
        );
    }

    /// The bar's surface as it is actually painted: the first filled rectangle as wide
    /// as the bar.
    fn surface(bar: &dyn Widget<Msg>, width: f32) -> Option<(Color, f32)> {
        let ui = build_ui(
            bar,
            Size::new(width, 200.0),
            &Runtime::default(),
            &Theme::default(),
        );
        // **Into the layers, not only across the top.** A clipped subtree is drained
        // into a composited `Layer`, so a bar with a shape paints nothing at the scene's
        // top level at all — which is what the first version of this helper concluded.
        fn find(primitives: &[crate::Primitive], width: f32) -> Option<(Color, f32)> {
            for p in primitives {
                match p {
                    // `blur > 0` is a **shadow**: drawn as wide as the thing casting it,
                    // and otherwise mistaken for the surface. This helper was, and
                    // reported a black at 22% alpha.
                    crate::Primitive::Rect {
                        rect,
                        color,
                        radius,
                        blur,
                        ..
                    } if rect.width >= width - 0.5 && *blur == 0.0 => {
                        return Some((*color, radius.top_left))
                    }
                    crate::Primitive::Layer { primitives, .. } => {
                        if let Some(found) = find(primitives, width) {
                            return Some(found);
                        }
                    }
                    _ => {}
                }
            }
            None
        }
        find(ui.scene().primitives(), width)
    }

    /// **Material 3 shows height by tinting, not only by shadowing.**
    ///
    /// A shadow says a thing is above the page; the tint says how far, and on a dark
    /// background a shadow says nothing at all. The strength is the specification's
    /// table — 8% at elevation 3 — so the check is that the painted surface is the
    /// background moved **exactly** that far towards the tint, not merely that it moved.
    #[test]
    fn an_elevated_bar_is_tinted_by_its_elevation() {
        const W: f32 = 400.0;
        let base = Color::rgb(0.10, 0.10, 0.12);
        let tint = Color::rgb(0.60, 0.40, 1.00);
        let flat = AppBar::<Msg>::new()
            .title(Text::new("Title"))
            .width(W)
            .background(base)
            .build();
        let raised = AppBar::<Msg>::new()
            .title(Text::new("Title"))
            .width(W)
            .background(base)
            .elevation(3.0)
            .surface_tint(tint)
            .build();
        let (flat_color, _) = surface(flat.as_ref(), W).expect("a flat surface");
        let (raised_color, _) = surface(raised.as_ref(), W).expect("a raised surface");
        assert_eq!(flat_color, base, "nothing is tinted without a tint");
        let expected = base.lerp(tint, 0.08);
        assert!(
            (raised_color.r - expected.r).abs() < 1e-4
                && (raised_color.g - expected.g).abs() < 1e-4
                && (raised_color.b - expected.b).abs() < 1e-4,
            "elevation 3 should tint at 8%: {raised_color:?} against {expected:?}"
        );
    }

    /// **An elevated bar casts nothing until it is given a shadow colour**
    /// (the reference's app bar defaults, line 2542). Its Material 3 bar keeps its height for the
    /// tint and makes the shadow transparent; this one drew a near-black of its own at 22 %
    /// under any bar with a height.
    #[test]
    fn an_elevated_bar_casts_a_shadow_only_in_a_colour_it_was_given() {
        const W: f32 = 400.0;
        // A shadow is a blurred rectangle — or, from a bar with no height, an unblurred one in
        // the shadow's colour, a hard box that a blur test alone never sees.
        fn shadows(primitives: &[crate::Primitive], named: Color, out: &mut Vec<Color>) {
            for p in primitives {
                match p {
                    crate::Primitive::Rect { color, blur, .. }
                        if *blur > 0.0 || *color == named =>
                    {
                        out.push(*color)
                    }
                    crate::Primitive::Layer { primitives, .. } => shadows(primitives, named, out),
                    _ => {}
                }
            }
        }
        let named = Color::rgba(0.0, 0.0, 0.0, 0.3);
        let cast = |bar: AppBar<Msg>, theme: &Theme| {
            let bar = bar.build();
            let ui = build_ui(
                bar.as_ref(),
                Size::new(W, 200.0),
                &Runtime::default(),
                theme,
            );
            let mut out = Vec::new();
            shadows(ui.scene().primitives(), named, &mut out);
            out
        };
        let bar = || AppBar::<Msg>::new().title(Text::new("Title")).width(W);
        let plain = Theme::default();
        assert!(
            cast(bar().elevation(3.0), &plain).is_empty(),
            "a height alone is no shadow"
        );

        assert_eq!(
            cast(bar().elevation(3.0).shadow_color(named), &plain),
            vec![named]
        );
        let mut themed = Theme::default();
        themed.widgets.app_bar.shadow_color = Some(named);
        assert_eq!(
            cast(bar().elevation(3.0), &themed),
            vec![named],
            "or a colour the theme names"
        );
        assert!(
            cast(bar().shadow_color(named), &plain).is_empty(),
            "and a flat bar has no height to cast it from"
        );
    }

    /// **A bar told to be transparent has no surface at all** — no background, no tint,
    /// no shadow — whatever a theme handed it.
    ///
    /// The reference's `forceMaterialTransparency`, for a bar over an image where the
    /// chrome should be the controls and nothing else. It overrides rather than argues,
    /// because a caller asking for transparency has already decided.
    #[test]
    fn a_transparent_bar_paints_no_surface() {
        const W: f32 = 400.0;
        let bar = AppBar::<Msg>::new()
            .title(Text::new("Title"))
            .width(W)
            .background(Color::rgb(0.9, 0.1, 0.1))
            .elevation(6.0)
            .surface_tint(Color::rgb(0.0, 1.0, 0.0))
            .force_material_transparency(true)
            .build();
        assert!(
            surface(bar.as_ref(), W).is_none(),
            "the bar painted a surface it was told not to"
        );
    }

    /// **A bar takes a whole shape, not only a corner** (`app_bar.dart:209`).
    ///
    /// A bar is a rectangle, so what a shape contributes is the corners it resolves to in
    /// the bar's **own** box — and a stadium's box is a wide, short one, so it rounds to
    /// half the bar's height. That is the number the old `BorderRadius`-only property
    /// could never have been given, because it would have had to be written out at the
    /// call site and would then have been wrong for a bar of any other height.
    #[test]
    fn a_bar_takes_a_whole_shape_and_not_only_a_corner() {
        // A background, because `surface` looks for the widest opaque rectangle and a
        // bar the theme gives no colour paints none.
        let corner = |bar: AppBar<Msg>| {
            let built = bar
                .width(400.0)
                .background(Color::rgb(0.2, 0.2, 0.2))
                .build();
            surface(built.as_ref(), 400.0).map(|(_, radius)| radius)
        };

        // A stadium: half the short side of a 400x64 bar (`APP_BAR_HEIGHT`), so 32.
        assert_eq!(
            corner(
                AppBar::new()
                    .title(Text::new("Title"))
                    .shape(ShapeBorder::stadium())
            ),
            Some(APP_BAR_HEIGHT / 2.0)
        );

        // And half of a taller one, without the caller doing the arithmetic.
        assert_eq!(
            corner(
                AppBar::new()
                    .title(Text::new("Title"))
                    .height(80.0)
                    .shape(ShapeBorder::stadium())
            ),
            Some(40.0)
        );

        // The shorthand still says what it always said.
        assert_eq!(
            corner(AppBar::new().title(Text::new("Title")).radius(18.0)),
            Some(18.0)
        );

        // A shape with no rounded form leaves the bar square rather than clipping it to
        // something a bar is not.
        assert_eq!(
            corner(
                AppBar::new()
                    .title(Text::new("Title"))
                    .shape(ShapeBorder::beveled(6.0))
            ),
            Some(0.0)
        );
    }

    /// **And a theme can name one**, which it could not: `AppBarTheme::shape` was the last
    /// theme field left carrying the reference's word with a corner radius behind it.
    #[test]
    fn a_theme_names_the_bar_s_shape() {
        let mut theme = Theme::dark();
        theme.widgets.app_bar.shape = Some(ShapeBorder::stadium());
        theme.widgets.app_bar.background = Some(Color::rgb(0.2, 0.2, 0.2));
        let built = AppBar::<Msg>::new()
            .title(Text::new("Title"))
            .width(400.0)
            .build();
        let ui = build_ui(
            built.as_ref(),
            Size::new(400.0, 200.0),
            &Runtime::default(),
            &theme,
        );
        fn find(primitives: &[crate::Primitive]) -> Option<f32> {
            for p in primitives {
                match p {
                    crate::Primitive::Rect {
                        rect, radius, blur, ..
                    } if rect.width >= 399.5 && *blur == 0.0 => return Some(radius.top_left),
                    crate::Primitive::Layer { primitives, .. } => {
                        if let Some(found) = find(primitives) {
                            return Some(found);
                        }
                    }
                    _ => {}
                }
            }
            None
        }
        assert_eq!(find(ui.scene().primitives()), Some(APP_BAR_HEIGHT / 2.0));
    }

    /// **The shape rounds the bar's corners**, and the caller's outranks the theme's.
    #[test]
    fn the_bar_takes_the_shape_it_was_given() {
        const W: f32 = 400.0;
        let square = AppBar::<Msg>::new()
            .title(Text::new("Title"))
            .width(W)
            .background(Color::rgb(0.2, 0.2, 0.2))
            .build();
        let rounded = AppBar::<Msg>::new()
            .title(Text::new("Title"))
            .width(W)
            .background(Color::rgb(0.2, 0.2, 0.2))
            .radius(18.0)
            .build();
        assert_eq!(surface(square.as_ref(), W).expect("square").1, 0.0);
        assert_eq!(surface(rounded.as_ref(), W).expect("rounded").1, 18.0);
    }

    /// **The bar's title is the screen's heading, and it was announced as a label.**
    ///
    /// A screen reader's user moves through a screen by its headings. The one every
    /// screen has is the bar's title, and ours carried `Role::Label` — one more piece of
    /// text among the rest, with nothing to jump to. The roadmap had this marked *done*
    /// since before milestone 397 and nothing in the framework emitted `Role::Heading` at
    /// all.
    #[test]
    fn the_bars_title_is_the_screens_heading() {
        const W: f32 = 400.0;
        let role_of_title = |exclude: bool| {
            let bar = AppBar::<Msg>::new()
                .title(Text::new("Inbox"))
                .width(W)
                .exclude_header_semantics(exclude)
                .build();
            let ui = build_ui(
                bar.as_ref(),
                Size::new(W, 200.0),
                &Runtime::default(),
                &Theme::default(),
            );
            ui.semantics()
                .iter()
                .find(|(_, _, s)| s.label.as_deref() == Some("Inbox"))
                .map(|(_, _, s)| s.role)
                .expect("the title is described")
        };
        assert_eq!(role_of_title(false), frus_core::Role::Heading);
        // And a bar that says its title is not the screen's name gets a plain label back.
        assert_eq!(role_of_title(true), frus_core::Role::Label);
    }

    /// **A widget title is the screen's heading too**, which it was not until now.
    ///
    /// Milestone 397 could mark a *text* title as a landmark and not a widget one, because
    /// by then a widget title is a `Box<dyn Widget>` and the bar had no way in. So the
    /// accessibility of a bar depended on which constructor the caller had reached for —
    /// not a distinction anybody using assistive technology should be able to feel, and not
    /// one the reference has: its `title` is a `Widget?` and nothing else, wrapped once in
    /// `Semantics(header: true)` (`app_bar.dart:1071`).
    ///
    /// The two constructors are now the same path, and this asserts they answer the same.
    #[test]
    fn a_widget_title_is_a_heading_exactly_as_a_string_one_is() {
        const W: f32 = 400.0;
        let role_of = |bar: Box<dyn Widget<Msg>>| {
            let ui = build_ui(
                bar.as_ref(),
                Size::new(W, 200.0),
                &Runtime::default(),
                &Theme::default(),
            );
            ui.semantics()
                .iter()
                .find(|(_, _, s)| s.label.as_deref() == Some("Inbox"))
                .map(|(_, _, s)| s.role)
                .expect("the title is described")
        };
        let from_string = role_of(
            AppBar::<Msg>::new()
                .title(Text::new("Inbox"))
                .width(W)
                .build(),
        );
        let from_widget = role_of(
            AppBar::<Msg>::new()
                .title(crate::Text::new("Inbox"))
                .width(W)
                .build(),
        );
        assert_eq!(from_string, frus_core::Role::Heading);
        assert_eq!(
            from_widget, from_string,
            "the same bar, described differently by which constructor was used"
        );
    }

    /// **A widget title wears the bar's type**, without the bar reaching into it.
    ///
    /// The reference hands the title style down rather than applying it
    /// (`app_bar.dart:1084`), which is the only thing that works when the title is a
    /// caller's widget with a `Text` somewhere inside it. A text that chose its own size
    /// keeps it — that is milestone 400's rule, and it is what makes the handover safe to
    /// apply to a widget the bar never looked into.
    #[test]
    fn the_bar_hands_its_type_to_a_title_it_did_not_build() {
        const W: f32 = 500.0;
        let size_of = |bar: Box<dyn Widget<Msg>>| {
            let ui = build_ui(
                bar.as_ref(),
                Size::new(W, 200.0),
                &Runtime::default(),
                &Theme::default(),
            );
            let mut found = None;
            fn walk(prims: &[crate::Primitive], out: &mut Option<f32>) {
                for p in prims {
                    match p {
                        crate::Primitive::Text { text, size, .. } if text == "Inbox" => {
                            *out = Some(*size)
                        }
                        crate::Primitive::Layer { primitives, .. } => walk(primitives, out),
                        _ => {}
                    }
                }
            }
            walk(ui.scene().primitives(), &mut found);
            found.expect("the title is drawn")
        };
        let inherited = size_of(
            AppBar::<Msg>::new()
                .title(crate::Text::new("Inbox"))
                .width(W)
                .build(),
        );
        assert_eq!(
            inherited,
            Theme::default().text.title_large.size.unwrap(),
            "a title that chose nothing wears the bar's type"
        );
        // And one that chose keeps its own, which is what makes the handover safe.
        let chosen = size_of(
            AppBar::<Msg>::new()
                .title(crate::Text::new("Inbox").size(11.0))
                .width(W)
                .build(),
        );
        assert_eq!(chosen, 11.0);
    }

    /// **A bar with no title has none**, rather than an empty one.
    ///
    /// Milestone 522. `AppBar::new` took the title as a string, so a bar with nothing
    /// between its leading and its actions — a back button and a Save — was written
    /// `new("")`, and an empty text was laid out and painted where a title would have
    /// been. The reference's title is a `Widget?`: absent, nothing is built there.
    #[test]
    fn a_bar_with_no_title_builds_none() {
        const W: f32 = 400.0;
        let bar = AppBar::<Msg>::new()
            .width(W)
            .leading(button("Back", Msg::A))
            .foldable_action("Save", Msg::B)
            .build();
        assert_eq!(
            texts_of(bar.as_ref(), W),
            ["Back", "Save"],
            "nothing is drawn between the leading and the action"
        );
        let ui = build_ui(
            bar.as_ref(),
            Size::new(W, 200.0),
            &Runtime::default(),
            &Theme::default(),
        );
        assert!(
            ui.semantics()
                .iter()
                .all(|(_, _, s)| s.role != frus_core::Role::Heading),
            "and nothing is announced as the screen's heading"
        );
        let save_x = ui
            .scene()
            .primitives()
            .iter()
            .find_map(|p| match p {
                frus_core::Primitive::Text { text, position, .. } if text == "Save" => {
                    Some(position.x)
                }
                _ => None,
            })
            .expect("the action is drawn");
        assert!(save_x > W / 2.0, "the action keeps the end: x = {save_x}");
        assert_eq!(bar_height(bar.as_ref()), Some(APP_BAR_HEIGHT));
    }

    /// **A bar with no title owes the fold no room for one**, nor a spacing before it.
    ///
    /// The budget counts the row's children before the actions, and the title was always
    /// one of them. At exactly the width one action takes, an untitled bar shows the action;
    /// charged a spacing or a join for a title it has not got, it would fold it away.
    ///
    /// Told where its title goes rather than left to the platform: Apple's platforms centre
    /// a bar with one action, and a centred title has a spring of its own. Neither costs room
    /// now that the reference's toolbar has no gaps (milestone 611).
    #[test]
    fn an_untitled_bar_gives_its_actions_the_room() {
        let theme = Theme::default();
        let size = action_size_of(None, &theme);
        let save = AppBar::<Msg>::widget_width(
            &AppBar::<Msg>::action_button("Save".into(), Msg::B, size),
            &theme,
        );
        let shows = |centered: bool, width: f32| {
            let bar = AppBar::<Msg>::new()
                .width(width)
                .center_title(centered)
                .overflow(false, Msg::PopupMenuButton)
                .foldable_action("Save", Msg::B)
                .build();
            texts_of(bar.as_ref(), width).iter().any(|t| t == "Save")
        };
        let width = H_PAD * 2.0 + save + 0.25;
        assert!(
            shows(false, width),
            "flush, the action fits a bar {width} px wide"
        );
        assert!(shows(true, width), "centred, too");
        assert!(!shows(false, width - 1.0), "and a pixel less folds it");
    }

    /// Every path the bar paints, layers included.
    fn glyph_colors(bar: &dyn Widget<Msg>, width: f32) -> Vec<Color> {
        fn walk(primitives: &[crate::Primitive], out: &mut Vec<Color>) {
            for p in primitives {
                match p {
                    crate::Primitive::Path {
                        fill: Some(color), ..
                    } => out.push(*color),
                    crate::Primitive::Layer { primitives, .. } => walk(primitives, out),
                    _ => {}
                }
            }
        }
        let ui = build_ui(
            bar,
            Size::new(width, 200.0),
            &Runtime::default(),
            &Theme::default(),
        );
        let mut out = Vec::new();
        walk(ui.scene().primitives(), &mut out);
        out
    }

    /// **The bar's icon theme reaches a glyph it never sees.**
    ///
    /// The reference's `IconTheme` is an *inherited* widget, and that is the whole point:
    /// an app bar cannot restyle an icon nested inside a button it was handed. Delivering
    /// the colour as a theme for the subtree is what reaches it. The check is a leading
    /// slot holding a plain `Icon`, recoloured without the bar touching the widget.
    #[test]
    fn the_bars_icon_theme_reaches_a_glyph_it_never_sees() {
        const W: f32 = 400.0;
        let wanted = Color::rgb(0.9, 0.2, 0.4);
        let plain = AppBar::<Msg>::new()
            .title(Text::new("Title"))
            .width(W)
            .leading(crate::Icon::new(crate::Icons::STAR))
            .build();
        let themed = AppBar::<Msg>::new()
            .title(Text::new("Title"))
            .width(W)
            .leading(crate::Icon::new(crate::Icons::STAR))
            .icon_theme(crate::widgettheme::IconTheme {
                color: Some(wanted),
                size: None,
            })
            .build();
        assert!(
            !glyph_colors(plain.as_ref(), W).contains(&wanted),
            "the plain bar should not already be that colour"
        );
        assert!(
            glyph_colors(themed.as_ref(), W).contains(&wanted),
            "the icon theme never reached the glyph"
        );
    }

    /// Every text in the built bar, as `(the words, their size)`. Composited layers are
    /// walked into: a clipped subtree is drained into one, and a bar with a shape clips.
    fn toolbar_texts(bar: &dyn Widget<Msg>, width: f32) -> Vec<(String, f32)> {
        fn walk(prims: &[crate::Primitive], out: &mut Vec<(String, f32)>) {
            for p in prims {
                match p {
                    crate::Primitive::Text { text, size, .. } => out.push((text.clone(), *size)),
                    crate::Primitive::Layer { primitives, .. } => walk(primitives, out),
                    _ => {}
                }
            }
        }
        let ui = build_ui(
            bar,
            Size::new(width, 200.0),
            &Runtime::default(),
            &Theme::default(),
        );
        let mut out = Vec::new();
        walk(ui.scene().primitives(), &mut out);
        out
    }

    /// **The bar's toolbar style reaches a text it never sees, and not its title.**
    ///
    /// Same reasoning as the icon theme, and the same delivery: an app bar cannot restyle
    /// a run of words nested inside a widget it was handed, so the style goes down as a
    /// theme for the subtree rather than in as an argument.
    ///
    /// The second half is the one worth a test of its own. The reference keeps
    /// `toolbarTextStyle` and `titleTextStyle` apart, and a bar that let the first reach
    /// the title would quietly resize it — the one line in the bar that already had an
    /// answer, and the one whose width decides how many actions still fit.
    #[test]
    fn the_toolbar_style_reaches_the_words_around_the_title() {
        const W: f32 = 600.0;
        let size_of = |texts: &[(String, f32)], words: &str| {
            texts
                .iter()
                .find(|(t, _)| t == words)
                .map(|(_, s)| *s)
                .unwrap_or_else(|| panic!("no {words:?} in {texts:?}"))
        };
        let bar = |style: Option<TextStyle>| {
            let mut bar = AppBar::<Msg>::new()
                .title(Text::new("Title"))
                .width(W)
                .leading(crate::Text::new("Back"));
            if let Some(style) = style {
                bar = bar.toolbar_text_style(style);
            }
            toolbar_texts(bar.build().as_ref(), W)
        };
        let plain = bar(None);
        let dressed = bar(Some(TextStyle::new(11.0)));
        assert!(
            size_of(&plain, "Back") > 11.0,
            "the plain bar should not already be at 11 px"
        );
        assert_eq!(size_of(&dressed, "Back"), 11.0, "the style never arrived");
        assert_eq!(
            size_of(&dressed, "Title"),
            size_of(&plain, "Title"),
            "and it must not have touched the title"
        );
    }

    /// **The actions may part company with the leading slot** — the reference's
    /// `actionsIconTheme`, for a back arrow in the foreground colour beside actions in a
    /// muted one. Unset, they follow the bar's own.
    #[test]
    fn the_actions_may_wear_their_own_icon_theme() {
        const W: f32 = 600.0;
        let lead = Color::rgb(0.1, 0.8, 0.2);
        let acts = Color::rgb(0.2, 0.1, 0.9);
        let bar = AppBar::<Msg>::new()
            .title(Text::new("Title"))
            .width(W)
            .leading(crate::Icon::new(crate::Icons::STAR))
            .action(crate::Icon::new(crate::Icons::FAVORITE))
            .icon_theme(crate::widgettheme::IconTheme {
                color: Some(lead),
                size: None,
            })
            .actions_icon_theme(crate::widgettheme::IconTheme {
                color: Some(acts),
                size: None,
            })
            .build();
        let colors = glyph_colors(bar.as_ref(), W);
        assert!(colors.contains(&lead), "the leading glyph kept its colour");
        assert!(colors.contains(&acts), "the action glyph took its own");
    }

    /// **An action is any widget**, as the reference's `actions` is a list of widgets
    /// (milestone 613): added one at a time or as a list, they keep the order they were
    /// given in, and none of them folds, however narrow the bar.
    #[test]
    fn actions_are_widgets_kept_in_order() {
        let bar = |width: f32| {
            AppBar::<Msg>::new()
                .title(Text::new("Title"))
                .width(width)
                .overflow(false, Msg::A)
                .action(Text::new("First"))
                .actions([
                    Box::new(Text::new("Second")) as Box<dyn Widget<Msg>>,
                    Box::new(Text::new("Third")),
                ])
                .action(crate::IconButton::new(crate::Icons::SEARCH).on_press(Msg::B))
                .action(Text::new("Fourth"))
                .build()
        };
        for width in [1000.0, 200.0] {
            let texts: Vec<String> = texts_of(bar(width).as_ref(), width)
                .into_iter()
                .filter(|t| t != "Title")
                .collect();
            assert_eq!(
                texts,
                ["First", "Second", "Third", "Fourth"],
                "at {width} px"
            );
        }
    }

    /// **A widget action is a press away**: the bar hands it its message untouched.
    #[test]
    fn a_widget_action_emits_its_own_message() {
        const W: f32 = 600.0;
        let bar = AppBar::<Msg>::new()
            .title(Text::new("Title"))
            .width(W)
            .action(button("Go", Msg::C))
            .build();
        crate::build_deferred(bar.as_ref(), &Theme::default(), &Runtime::default());
        fn walk(widget: &dyn Widget<Msg>, out: &mut Vec<Msg>) {
            if let Some(message) = widget.on_click() {
                out.push(message);
            }
            for child in widget.children() {
                walk(child.as_ref(), out);
            }
        }
        let mut messages = Vec::new();
        walk(bar.as_ref(), &mut messages);
        assert_eq!(messages, vec![Msg::C]);
    }

    /// **The flexible space is a layer, not a slot**: it fills the bar's box and leaves
    /// its height alone, however tall the widget would rather be.
    #[test]
    fn the_flexible_space_does_not_make_the_bar_taller() {
        const W: f32 = 400.0;
        let height = |with_space: bool| {
            let mut bar = AppBar::<Msg>::new().title(Text::new("Title")).width(W);
            if with_space {
                bar = bar.flexible_space(Container::new().height(400.0));
            }
            let built = bar.build();
            let ui = build_ui(
                built.as_ref(),
                Size::new(W, 800.0),
                &Runtime::default(),
                &Theme::default(),
            );
            ui.scene()
                .primitives()
                .iter()
                .filter_map(|p| match p {
                    crate::Primitive::Text { position, .. } => Some(position.y),
                    _ => None,
                })
                .fold(0.0_f32, f32::max)
        };
        // The title sits where it sat: a 400 px flexible space did not push it down.
        assert!(
            (height(true) - height(false)).abs() < 0.5,
            "the flexible space moved the title by {}",
            height(true) - height(false)
        );
    }

    /// Counts the buttons (rectangles with a shadow), excluding floating menu items.
    /// **The actions a bar keeps inline fit in the bar**, at every width and whatever
    /// its labels are.
    ///
    /// The fold was decided on an estimate of each button that the buttons did not
    /// share — 20 px either side of the label where a button takes 24, and no minimum
    /// where a button is never narrower than 64 — and on a row with a gap fewer than it
    /// had. Each slip was a few pixels, and they add up: the demo's own bar ran 13 px
    /// past its edge on a desktop the day one action was taken out of it.
    #[test]
    fn the_actions_a_bar_keeps_fit_in_it_at_every_width() {
        const LABELS: [&str; 11] = [
            "Light",
            "Seed: default",
            "RTL",
            "Français",
            "A+",
            "A−",
            "Log →",
            "Settings →",
            "Quick actions",
            "Save",
            "Clear completed",
        ];
        let mut worst: Vec<String> = Vec::new();
        // The leading is an icon button, as in the demo, or a labelled button, whose width is
        // declared exactly: an icon button is charged the whole leading slot and drawn
        // narrower, and that slack alone would hide a gap the budget forgot.
        //
        // Each from the narrowest bar it can be, and not a pixel wider: below that, with every
        // action folded, the leading, the spacing, the title's floor and the overflow button
        // are wider than the bar on their own, and there is nothing left to fold. The
        // reference's toolbar has no margin and no gaps (milestone 611), so it is their sum:
        // an icon leading's 56 px slot + 16 + 64 + the 48 px overflow button is 184; a
        // labelled "Menu" leading is 87 px, so 215; with no leading the 16 px spacing still
        // opens the title, so 128; a centred title costs nothing more, and a 12 px padding
        // two sides of the actions does.
        //
        // And without a title: no floor and no spacing, the leading and the overflow alone.
        let configurations = [
            ("icon", false, None, true, 184),
            ("button", false, None, true, 215),
            ("none", false, None, true, 128),
            ("button", true, None, true, 215),
            ("button", false, Some(12.0), true, 239),
            ("button", false, None, false, 135),
            ("button", true, None, false, 135),
        ];
        for (leading, centered, padding, titled, narrowest) in configurations {
            for width in (narrowest..=1600).step_by(7) {
                let size = Size::new(width as f32, 80.0);
                let bar = MediaQuery::new(size).scope(|| {
                    let mut bar = AppBar::new()
                        .center_title(centered)
                        .overflow(false, Msg::PopupMenuButton);
                    if titled {
                        bar = bar.title(Text::new("My Tasks"));
                    }
                    match leading {
                        "icon" => {
                            bar = bar.leading(
                                crate::IconButton::new(crate::Icons::MENU).on_press(Msg::A),
                            )
                        }
                        "button" => bar = bar.leading(button::<Msg>("Menu", Msg::A)),
                        _ => {}
                    }
                    if let Some(padding) = padding {
                        bar = bar.actions_padding(padding);
                    }
                    for label in LABELS {
                        bar = bar.foldable_action(label, Msg::B);
                    }
                    bar.build()
                });
                let ui = build_ui(bar.as_ref(), size, &Runtime::default(), &Theme::default());
                for o in ui.overflows() {
                    worst.push(format!(
                        "{width} px, leading {leading}, centred {centered}, padding {padding:?}, \
                         titled {titled}: \
                         {:?} by {:.1} px",
                        o.side, o.amount
                    ));
                }
            }
        }
        assert!(worst.is_empty(), "{worst:#?}");
    }

    /// **A title with nothing beside it stops short of the edge too.**
    ///
    /// The join between the title's spring and the actions is charged to each action. A
    /// bar with none still has that join — the actions' row is there, empty — so leaving it
    /// out caps a long title one gap too wide.
    #[test]
    fn a_title_with_no_actions_stops_short_of_the_edge() {
        let mut worst: Vec<String> = Vec::new();
        for width in (240..=900).step_by(11) {
            let size = Size::new(width as f32, 80.0);
            let bar = MediaQuery::new(size).scope(|| {
                AppBar::new()
                    .title(Text::new(
                        "A title long enough to be cut short at every width this sweeps, and more",
                    ))
                    // A leading of an exact width, so no slack in its slot hides the gap.
                    .leading(button::<Msg>("Menu", Msg::A))
                    .build()
            });
            let ui = build_ui(bar.as_ref(), size, &Runtime::default(), &Theme::default());
            for o in ui.overflows() {
                worst.push(format!("{width} px: {:?} by {:.1} px", o.side, o.amount));
            }
        }
        assert!(worst.is_empty(), "{worst:#?}");
    }

    fn inline_buttons(width: f32, open: bool) -> usize {
        let bar = AppBar::new()
            .title(Text::new("Title"))
            .width(width)
            .overflow(open, Msg::PopupMenuButton)
            .foldable_action("Action One", Msg::A)
            .foldable_action("Action Two", Msg::B)
            .foldable_action("Action Three", Msg::C)
            .build();
        let ui = build_ui(
            bar.as_ref(),
            Size::new(width, 80.0),
            &Runtime::default(),
            &Theme::default(),
        );
        // Count the buttons by what they *are* rather than by what they paint: they used
        // to be counted by their shadows, and milestone 313 took the shadow off every
        // button but the elevated one — a proxy that stopped standing for anything.
        ui.semantics()
            .iter()
            .filter(|(_, _, s)| s.role == frus_core::Role::Button)
            .count()
    }

    /// The middle term milestone 318 could not add. `center_title` decides which children
    /// exist and in what order, so it cannot be resolved by any hook that runs after the
    /// row has been assembled — the composition is deferred to the theme instead.
    #[test]
    fn center_title_resolves_caller_then_theme_then_platform() {
        // A centred title is a spring, the title, another spring; a flush one is the
        // title straight after the leading. Counting the springs reads the decision.
        fn springs(widget: &dyn Widget<Msg>, theme: &crate::theme::Theme) -> usize {
            widget.build_themed(theme);
            let mine = usize::from(matches!(
                widget.style().flex_grow,
                g if g > 0.0
            ));
            mine + widget
                .children()
                .iter()
                .map(|c| springs(c.as_ref(), theme))
                .sum::<usize>()
        }
        let bar = || AppBar::<Msg>::new().title(Text::new("Title")).width(400.0);
        let plain = crate::theme::Theme::default();
        let mut centred = crate::theme::Theme::default();
        centred.widgets.app_bar.center_title = Some(true);
        let mut flush = crate::theme::Theme::default();
        flush.widgets.app_bar.center_title = Some(false);

        let untold = springs(bar().build().as_ref(), &plain);
        // Guard the instrument before trusting it: if centring did not change the
        // composition, every assertion below would pass while proving nothing.
        assert_ne!(
            springs(bar().center_title(true).build().as_ref(), &plain),
            springs(bar().center_title(false).build().as_ref(), &plain),
            "centring changes the row, or this test cannot see anything"
        );
        assert_eq!(
            springs(bar().build().as_ref(), &centred),
            springs(bar().center_title(true).build().as_ref(), &plain),
            "the theme centres it, as the caller would have"
        );
        assert_eq!(
            springs(bar().build().as_ref(), &flush),
            springs(bar().center_title(false).build().as_ref(), &plain),
            "and un-centres it"
        );
        // The caller outranks the theme, whichever way the theme leant.
        assert_eq!(
            springs(bar().center_title(false).build().as_ref(), &centred),
            springs(bar().center_title(false).build().as_ref(), &plain)
        );
        // And with neither, the platform still has the last word.
        assert_eq!(
            untold,
            springs(
                bar()
                    .center_title(platform_centers_title(plain.platform, 0))
                    .build()
                    .as_ref(),
                &plain
            )
        );
    }

    /// Chrome is a **fixed** height, not its content's. A bar that hugged what happened
    /// to be in it made every screen a slightly different shape, and moved the page below
    /// it the moment an action appeared or a title grew.
    #[test]
    fn the_bar_is_the_references_height() {
        let plain = AppBar::<Msg>::new()
            .title(Text::new("Title"))
            .width(400.0)
            .build();
        let busy = AppBar::<Msg>::new()
            .title(Text::new("Title"))
            .width(400.0)
            .leading(button("=", Msg::A))
            .foldable_action("One", Msg::A)
            .foldable_action("Two", Msg::B)
            .build();
        assert_eq!(bar_height(plain.as_ref()), Some(APP_BAR_HEIGHT));
        assert_eq!(
            bar_height(busy.as_ref()),
            Some(APP_BAR_HEIGHT),
            "content does not change the chrome's height"
        );
        let tall = AppBar::<Msg>::new()
            .title(Text::new("Title"))
            .width(400.0)
            .height(96.0)
            .build();
        assert_eq!(
            bar_height(tall.as_ref()),
            Some(96.0),
            "and the caller still decides"
        );
    }

    /// The toolbar's imposed height, wherever it sits in the composition.
    ///
    /// The bar defers its composition to the theme, so the walk down has to build it —
    /// exactly as the layout pass does — before the children are there to look at.
    fn bar_height(widget: &dyn Widget<Msg>) -> Option<f32> {
        widget.build_themed(&crate::theme::Theme::default());
        if let frus_layout::Dimension::Length(h) = widget.style().height {
            if (h - APP_BAR_HEIGHT).abs() < 0.01 || h > APP_BAR_HEIGHT {
                return Some(h);
            }
        }
        widget
            .children()
            .iter()
            .find_map(|c| bar_height(c.as_ref()))
    }

    #[test]
    fn wide_bar_shows_all_actions_inline() {
        // Wide enough: the 3 actions fit, and there is no overflow button.
        assert_eq!(inline_buttons(1200.0, false), 3);
    }

    #[test]
    fn narrow_bar_collapses_into_overflow() {
        // Narrow: at most one or two inline actions + the `⋯` button.
        let n = inline_buttons(300.0, false);
        assert!(
            n < 3,
            "expected a fold into overflow, got {n} inline buttons"
        );
        assert!(n >= 1, "the overflow button must be present");
    }

    /// The bar keeps a horizontal margin: the content (the leading on the left, the
    /// last action on the right) does not touch the viewport's edges.
    #[test]
    fn content_keeps_a_horizontal_margin() {
        const W: f32 = 400.0;
        let bar = AppBar::new()
            .title(Text::new("Title"))
            .width(W)
            .leading(button("M", Msg::PopupMenuButton).size(16.0))
            .overflow(false, Msg::PopupMenuButton)
            .foldable_action("One", Msg::A)
            .build();
        let ui = build_ui(
            bar.as_ref(),
            Size::new(W, 80.0),
            &Runtime::default(),
            &Theme::default(),
        );
        // The horizontal bounds of the **texts** (title + labels): having no shadow,
        // they reflect the content's real position (a shadow's blur, by contrast,
        // legitimately overflows).
        let mut min_x = f32::MAX;
        let mut max_x = f32::MIN;
        for p in ui.scene().primitives() {
            if let frus_core::Primitive::Text {
                position,
                size,
                text,
                ..
            } = p
            {
                min_x = min_x.min(position.x);
                // An approximate text width (an upper bound is enough here).
                max_x = max_x.max(position.x + text.chars().count() as f32 * size * 0.7);
            }
        }
        assert!(
            min_x >= H_PAD - 0.5,
            "content flush against the left edge ({min_x})"
        );
        assert!(
            max_x <= W - H_PAD + 0.5,
            "content overflowing on the right ({max_x} > {})",
            W - H_PAD
        );
    }

    /// **A bar outside a shell keeps its own content out of the status bar.**
    ///
    /// It did not, and that was the recorded cost of the shell owning the switch: the
    /// scaffold insetted the bar from outside, so a bar used on its own had nothing to
    /// inset it and would not inset itself. Milestone 417 gives it the reference's
    /// arrangement — the shell says what there is to consume, the bar consumes it.
    ///
    /// The **surface** still runs behind the status bar; only the toolbar is held clear.
    /// That is what a Material bar looks like, and what `app_bar.dart:1189` says in words.
    #[test]
    fn a_bar_on_its_own_clears_the_status_bar() {
        const TOP: f32 = 40.0;
        let title_y = |primary: bool| {
            let size = frus_core::Size::new(400.0, 200.0);
            let surface = crate::MediaQuery::new(size).with_insets(frus_core::WindowInsets::bars(
                frus_core::Insets::new(TOP, 0.0, 0.0, 0.0),
            ));
            // Built **and laid out** under the surface, the way a frame does it: the
            // shell holds one description across the build, the layout and the paint
            // (milestone 408), and a bar reads it when the walk reaches it.
            surface.scope(|| {
                let bar = AppBar::<Msg>::new()
                    .title(Text::new("Inbox"))
                    .primary(primary)
                    .build();
                crate::build_ui(
                    bar.as_ref(),
                    size,
                    &crate::Runtime::default(),
                    &Theme::default(),
                )
                .scene()
                .primitives()
                .iter()
                .find_map(|p| match p {
                    frus_core::Primitive::Text { position, .. } => Some(position.y),
                    _ => None,
                })
                .expect("the title is drawn")
            })
        };
        assert!(
            (title_y(true) - title_y(false) - TOP).abs() < 0.5,
            "a primary bar holds its title off by exactly the intrusion: {} vs {}",
            title_y(true),
            title_y(false)
        );
        assert!(
            title_y(true) >= TOP,
            "and it is below the status bar, not under it: {}",
            title_y(true)
        );
    }

    #[test]
    fn title_style_is_customizable() {
        // An overridden title style: bold 24, instead of the default medium 20.
        let bar = AppBar::<Msg>::new()
            .title(Text::new("Title"))
            .title_style(TextStyle::new(24.0).weight(FontWeight::Bold))
            .build();
        let ui = build_ui(
            bar.as_ref(),
            Size::new(800.0, 80.0),
            &Runtime::default(),
            &Theme::default(),
        );
        let styled = ui.scene().primitives().iter().any(|p| {
            matches!(
                p,
                frus_core::Primitive::Text { text, size, weight, .. }
                    if text == "Title" && *size == 24.0 && *weight == FontWeight::Bold
            )
        });
        assert!(styled, "the title must carry the overridden style");
    }

    #[test]
    fn title_can_be_an_arbitrary_widget() {
        let bar = AppBar::<Msg>::new()
            .title(Text::new("ignored"))
            .title(Text::new("Logo").size(18.0))
            .build();
        let ui = build_ui(
            bar.as_ref(),
            Size::new(800.0, 80.0),
            &Runtime::default(),
            &Theme::default(),
        );
        let texts: Vec<_> = ui
            .scene()
            .primitives()
            .iter()
            .filter_map(|p| match p {
                frus_core::Primitive::Text { text, .. } => Some(text.clone()),
                _ => None,
            })
            .collect();
        assert!(
            texts.contains(&"Logo".to_string()),
            "the title widget is rendered"
        );
        assert!(
            !texts.contains(&"ignored".to_string()),
            "the text title is replaced"
        );
    }

    /// The texts a bar paints, in paint order.
    fn texts_of(bar: &dyn Widget<Msg>, width: f32) -> Vec<String> {
        let ui = build_ui(
            bar,
            Size::new(width, 120.0),
            &Runtime::default(),
            &Theme::default(),
        );
        ui.scene()
            .primitives()
            .iter()
            .filter_map(|p| match p {
                frus_core::Primitive::Text { text, .. } => Some(text.clone()),
                _ => None,
            })
            .collect()
    }

    #[test]
    fn a_title_too_long_for_the_bar_is_cut_not_pushed_off() {
        const W: f32 = 320.0;
        let bar = AppBar::new()
            .title(Text::new(
                "A title far too long to fit in a narrow application bar",
            ))
            .width(W)
            .overflow(false, Msg::PopupMenuButton)
            .foldable_action("One", Msg::A)
            .build();
        let texts = texts_of(bar.as_ref(), W);
        let title = texts.first().expect("a title");
        assert!(title.ends_with('\u{2026}'), "cut with an ellipsis: {title}");
        assert!(
            title.len() < "A title far too long to fit in a narrow application bar".len(),
            "actually shortened: {title}"
        );
        // And the action survived: it is the actions that are served first.
        assert!(texts.iter().any(|t| t == "One"), "{texts:?}");
    }

    #[test]
    fn a_title_that_fits_is_left_exactly_as_it_was() {
        let bar = AppBar::<Msg>::new()
            .title(Text::new("Short"))
            .width(900.0)
            .build();
        assert_eq!(
            texts_of(bar.as_ref(), 900.0).first().map(String::as_str),
            Some("Short")
        );
    }

    /// **The reference's table** (`app_bar.dart:805`): iOS and macOS centre a title with
    /// fewer than two actions; the other four never do.
    #[test]
    fn the_title_follows_the_platform_until_it_is_told_otherwise() {
        use frus_core::TargetPlatform as P;
        for platform in P::ALL {
            let apple = matches!(platform, P::Ios | P::MacOs);
            assert_eq!(
                platform_centers_title(platform, 0),
                apple,
                "{platform}, bare"
            );
            assert_eq!(
                platform_centers_title(platform, 1),
                apple,
                "{platform}, one"
            );
            assert!(!platform_centers_title(platform, 2), "{platform}, crowded");
        }
    }

    /// **The theme's platform, not the build's** (milestone 615): a theme set to iOS
    /// centres the title on whatever this test runs on, and one set to Android does not;
    /// and two actions put an iOS bar's title flush.
    #[test]
    fn the_title_follows_the_theme_s_platform() {
        fn springs(widget: &dyn Widget<Msg>, theme: &crate::theme::Theme) -> usize {
            widget.build_themed(theme);
            let mine = usize::from(widget.style().flex_grow > 0.0);
            mine + widget
                .children()
                .iter()
                .map(|c| springs(c.as_ref(), theme))
                .sum::<usize>()
        }
        let bar = || AppBar::<Msg>::new().title(Text::new("Title")).width(400.0);
        let ios = crate::theme::Theme::default().with_platform(frus_core::TargetPlatform::Ios);
        let android =
            crate::theme::Theme::default().with_platform(frus_core::TargetPlatform::Android);
        let centred = springs(bar().center_title(true).build().as_ref(), &android);
        let flush = springs(bar().center_title(false).build().as_ref(), &android);
        assert_ne!(centred, flush, "the instrument tells the two apart");
        assert_eq!(springs(bar().build().as_ref(), &ios), centred);
        assert_eq!(springs(bar().build().as_ref(), &android), flush);
        // Two actions of its own, and an iOS bar puts its title flush.
        let crowded = || bar().action(Text::new("A")).action(Text::new("B"));
        assert_eq!(
            springs(crowded().build().as_ref(), &ios),
            springs(crowded().center_title(false).build().as_ref(), &ios)
        );
    }

    /// **A width nobody gave is not a width of `f32::MAX`.** `AppBar::new` reads the
    /// surface from the ambient description and falls back to that sentinel when nothing
    /// described one — a bar built outside a frame, which is every bar built by hand.
    /// The sentinel is finite, so the bar laid a row out `f32::MAX` wide, and the spring
    /// before a centred title pushed it to `x = 1.7e38` with an ellipsis where the words
    /// had been. Nothing caught it for as long as the platforms CI ran on all put their
    /// titles flush: only Apple's centre one by default, and the leading spring is the
    /// half of the arrangement that only a centred title has.
    #[test]
    fn a_centred_title_with_no_described_surface_stays_on_the_screen() {
        const W: f32 = 800.0;
        let bar = AppBar::<Msg>::new()
            .title(Text::new("Title"))
            .center_title(true)
            .build();
        let ui = build_ui(
            bar.as_ref(),
            Size::new(W, 80.0),
            &Runtime::default(),
            &Theme::default(),
        );
        let title = ui
            .scene()
            .primitives()
            .iter()
            .find_map(|p| match p {
                frus_core::Primitive::Text { text, position, .. } if text.starts_with("Title") => {
                    Some((text.clone(), position.x))
                }
                _ => None,
            })
            .expect("the bar paints its title");
        assert_eq!(title.0, "Title", "and paints all of it, un-ellipsised");
        assert!(
            title.1.is_finite() && (0.0..W).contains(&title.1),
            "on the surface rather than at infinity: x = {}",
            title.1
        );
    }

    #[test]
    fn a_centred_title_sits_between_the_two_ends() {
        const W: f32 = 800.0;
        let centred = AppBar::new()
            .title(Text::new("Task"))
            .width(W)
            .center_title(true)
            .leading(button("M", Msg::PopupMenuButton).size(16.0))
            .build();
        // Explicitly flush: the default now follows the platform, and this test is
        // about the two arrangements, not about which one this build prefers.
        let flush = AppBar::new()
            .title(Text::new("Task"))
            .width(W)
            .center_title(false)
            .leading(button("M", Msg::PopupMenuButton).size(16.0))
            .build();
        let x_of = |bar: &dyn Widget<Msg>| {
            let ui = build_ui(
                bar,
                Size::new(W, 80.0),
                &Runtime::default(),
                &Theme::default(),
            );
            ui.scene()
                .primitives()
                .iter()
                .find_map(|p| match p {
                    frus_core::Primitive::Text { text, position, .. } if text == "Task" => {
                        Some(position.x)
                    }
                    _ => None,
                })
                .expect("the title")
        };
        let centred_x = x_of(centred.as_ref());
        let flush_x = x_of(flush.as_ref());
        assert!(
            centred_x > flush_x + 100.0,
            "centred ({centred_x}) should sit well right of flush ({flush_x})"
        );
        assert!(centred_x < W * 0.6, "and not off to the right: {centred_x}");
    }

    #[test]
    fn a_bottom_slot_is_part_of_the_bar() {
        let bar = AppBar::<Msg>::new()
            .title(Text::new("Title"))
            .width(600.0)
            .bottom(Text::new("Tabs").size(14.0))
            .build();
        let texts = texts_of(bar.as_ref(), 600.0);
        assert!(texts.iter().any(|t| t == "Tabs"), "{texts:?}");
        // Under the title, not beside it.
        let ui = build_ui(
            bar.as_ref(),
            Size::new(600.0, 120.0),
            &Runtime::default(),
            &Theme::default(),
        );
        let y = |wanted: &str| {
            ui.scene()
                .primitives()
                .iter()
                .find_map(|p| match p {
                    frus_core::Primitive::Text { text, position, .. } if text == wanted => {
                        Some(position.y)
                    }
                    _ => None,
                })
                .expect("the text")
        };
        assert!(
            y("Tabs") > y("Title"),
            "the bottom slot sits under the toolbar"
        );
    }

    #[test]
    fn a_wide_leading_is_counted_in_the_budget() {
        // A leading far wider than the Material slot: declared, it must eat into what
        // the actions may claim, so more of them fold.
        let narrow = AppBar::new()
            .title(Text::new("Title"))
            .width(520.0)
            .overflow(false, Msg::PopupMenuButton)
            .foldable_action("Action One", Msg::A)
            .foldable_action("Action Two", Msg::B)
            .build();
        let wide = AppBar::new()
            .title(Text::new("Title"))
            .width(520.0)
            .leading_width(300.0)
            .leading(button("M", Msg::PopupMenuButton).size(16.0))
            .overflow(false, Msg::PopupMenuButton)
            .foldable_action("Action One", Msg::A)
            .foldable_action("Action Two", Msg::B)
            .build();
        let inline = |bar: &dyn Widget<Msg>| {
            texts_of(bar, 520.0)
                .iter()
                .filter(|t| t.starts_with("Action"))
                .count()
        };
        assert!(
            inline(wide.as_ref()) < inline(narrow.as_ref()),
            "a wide leading must push actions into the overflow"
        );
    }

    #[test]
    fn custom_widget_action_never_folds() {
        // A very narrow bar: the labelled actions fold, but the free widget (which
        // cannot be represented as a menu row) stays inline.
        let bar = AppBar::new()
            .title(Text::new("Title"))
            .width(260.0)
            .overflow(false, Msg::PopupMenuButton)
            .foldable_action("A long labelled action", Msg::A)
            .action(Text::new("★badge★").size(14.0))
            .foldable_action("Another long action", Msg::B)
            .build();
        let ui = build_ui(
            bar.as_ref(),
            Size::new(260.0, 80.0),
            &Runtime::default(),
            &Theme::default(),
        );
        let has_badge = ui
            .scene()
            .primitives()
            .iter()
            .any(|p| matches!(p, frus_core::Primitive::Text { text, .. } if text == "★badge★"));
        assert!(
            has_badge,
            "the widget action stays inline even when cramped"
        );
    }
}