waft-material 0.8.0

Material Design widgets for Waft
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
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
//! Flutter counterpart: material_ui's `navigation_rail.dart` (and its part
//! `generated/navigation_rail_defaults_m3.g.dart`).

use std::fmt::{self, Debug};
use std::rc::Rc;

use waft_animation::{
    Animation, AnimationBehavior, AnimationController, AnimationRef, AnyAnimation, CurveTween,
    CurvedAnimation, Curves, Drive, Interval, ReverseAnimation,
};
use waft_embedder::SemanticsRole;
use waft_embedder::{Color, Offset, Radius, Rect, lerp_double};
use waft_foundation::{App, Handle, K_IS_WEB, Listener, OptionRetained, Ref, ValueChanged};
use waft_painting::{
    Alignment, AlignmentGeometry, BorderRadius, BoxShape, EdgeInsetsGeometry, ShapeBorderRef,
    TextDirection, TextStyle,
};
use waft_rendering::{BoxConstraints, MainAxisAlignment, MainAxisSize};
use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
use waft_widgets::{
    Align, BuildContext, Center, ClipRect, Column, ConstrainedBox, DefaultTextStyle,
    Directionality, FadeTransition, Flexible, IconTheme, IconThemeData, InheritedWidget,
    IntoWidget, KeyRef, MergeSemantics, Padding, Row, SafeArea, Semantics, SingleChildScrollView,
    SizedBox, Stack, State, StateData, StatefulWidget, StatelessWidget, TickerProviderStateMixin,
    TickerProviderStateMixinData, Visibility, WidgetRef,
};

use crate::generated::navigation_rail_defaults_m3::NavigationRailDefaultsM3;
use crate::ink_well::InkResponse;
use crate::material::{Material, MaterialType, RectCallback};
use crate::material_localizations::MaterialLocalizations;
use crate::navigation_bar::NavigationIndicator;
use crate::navigation_rail_theme::{
    NavigationRailTheme, NavigationRailThemeData, NavigationRailThemeDataGetters,
};
use crate::theme::{K_THEME_ANIMATION_DURATION, Theme};
use crate::theme_data_getters::DefaultsContext;

const K_CIRCULAR_INDICATOR_DIAMETER: f64 = 56.0;
const K_INDICATOR_HEIGHT: f64 = 32.0;

/// A Material Design widget that is meant to be displayed at the left or right of an
/// app to navigate between a small number of views, typically between three and
/// five.
///
/// Learn more about [`NavigationRail`] on the [Flutter YouTube channel](https://www.youtube.com/watch?v=y9xchtVTtqQ).
///
/// The navigation rail is meant for layouts with wide viewports, such as a
/// desktop web or tablet landscape layout. For smaller layouts, like mobile
/// portrait, a `BottomNavigationBar` should be used instead.
///
/// A navigation rail is usually used as the first or last element of a `Row`
/// which defines the app's `Scaffold` body.
///
/// The appearance of all of the [`NavigationRail`]s within an app can be
/// specified with [`NavigationRailTheme`]. The default values for null theme
/// properties are based on the `Theme`'s `ThemeData::text_theme`,
/// `ThemeData::icon_theme`, and `ThemeData::color_scheme`.
///
/// Adaptive layouts can build different instances of the `Scaffold` in order to
/// have a navigation rail for more horizontal layouts and a bottom navigation
/// bar for more vertical layouts. See
/// [the adaptive_scaffold.dart sample](https://github.com/flutter/demos/blob/main/web_dashboard/lib/src/widgets/third_party/adaptive_scaffold.dart)
/// for an example.
///
/// See also:
///
///  * `Scaffold`, which can display the navigation rail within a `Row` of the
///    `Scaffold::body` slot.
///  * [`NavigationRailDestination`], which is used as a model to create tappable
///    destinations in the navigation rail.
///  * `BottomNavigationBar`, which is a similar navigation widget that's laid
///    out horizontally.
///  * <https://material.io/components/navigation-rail/>
///  * <https://m3.material.io/components/navigation-rail>
pub struct NavigationRail {
    pub key: Option<KeyRef>,

    /// Sets the color of the Container that holds all of the [`NavigationRail`]'s
    /// contents.
    ///
    /// The default value is `NavigationRailThemeData::background_color`. If
    /// `NavigationRailThemeData::background_color` is null, then the default value
    /// is based on `ColorScheme::surface` of `ThemeData::color_scheme`.
    pub background_color: Option<Color>,

    /// Indicates that the [`NavigationRail`] should be in the extended state.
    ///
    /// The extended state has a wider rail container, and the labels are
    /// positioned next to the icons. [`min_extended_width`](Self::min_extended_width) can be
    /// used to set the minimum width of the rail when it is in this state.
    ///
    /// The rail will implicitly animate between the extended and normal state.
    ///
    /// If the rail is going to be in the extended state, then the
    /// [`label_type`](Self::label_type) must be set to [`NavigationRailLabelType::None`].
    ///
    /// The default value is false.
    pub extended: bool,

    /// The leading widget in the rail that is placed above the destinations.
    ///
    /// It is placed at the top of the rail, above the [`destinations`](Self::destinations).
    /// Its location is not affected by [`group_alignment`](Self::group_alignment).
    ///
    /// This is commonly a `FloatingActionButton`, but may also be a non-button,
    /// such as a logo.
    ///
    /// The default value is null.
    pub leading: Option<WidgetRef>,

    /// The trailing widget in the rail that is placed below the destinations.
    ///
    /// The trailing widget is placed below the last [`NavigationRailDestination`].
    /// It's location is affected by [`group_alignment`](Self::group_alignment).
    ///
    /// This is commonly a list of additional options or destinations that is
    /// usually only rendered when [`extended`](Self::extended) is true.
    ///
    /// The default value is null.
    pub trailing: Option<WidgetRef>,

    /// Defines the appearance of the button items that are arrayed within the
    /// navigation rail.
    ///
    /// The value must be a list of zero or more [`NavigationRailDestination`]
    /// values.
    pub destinations: Vec<NavigationRailDestination>,

    /// The index into [`destinations`](Self::destinations) for the current selected
    /// [`NavigationRailDestination`] or null if no destination is selected.
    pub selected_index: Option<usize>,

    /// Called when one of the [`destinations`](Self::destinations) is selected.
    ///
    /// The stateful widget that creates the navigation rail needs to keep
    /// track of the index of the selected [`NavigationRailDestination`] and call
    /// `set_state` to rebuild the navigation rail with the new
    /// [`selected_index`](Self::selected_index).
    pub on_destination_selected: Option<ValueChanged<usize>>,

    /// The rail's elevation or z-coordinate.
    ///
    /// If `Directionality` is `TextDirection::Ltr`, the inner side is the
    /// right side, and if `Directionality` is `TextDirection::Rtl`, it is
    /// the left side.
    ///
    /// The default value is 0.
    pub elevation: Option<f64>,

    /// The vertical alignment for the group of [`destinations`](Self::destinations) within
    /// the rail.
    ///
    /// The [`NavigationRailDestination`]s are by default grouped together with the
    /// [`trailing`](Self::trailing) widget, due to
    /// [`trailing_at_bottom`](Self::trailing_at_bottom) being `false`. The
    /// [`leading`](Self::leading) widget, can also be in the aligned group by setting
    /// [`leading_at_top`](Self::leading_at_top) to `false`. If these widgets are not
    /// included in the group, they are placed at the top and bottom, respectively, of the
    /// rail and only the space between them is considered for the alignment.
    ///
    /// The value must be between -1.0 and 1.0.
    ///
    /// If [`group_alignment`](Self::group_alignment) is -1.0, then the items are aligned to
    /// the top. If [`group_alignment`](Self::group_alignment) is 0.0, then the items are
    /// aligned to the center. If [`group_alignment`](Self::group_alignment) is 1.0, then the
    /// items are aligned to the bottom.
    ///
    /// The default is -1.0.
    ///
    /// See also:
    ///   * `Alignment::y`
    ///
    pub group_alignment: Option<f64>,

    /// Defines the layout and behavior of the labels for the default, unextended
    /// [`NavigationRail`].
    ///
    /// When a navigation rail is [`extended`](Self::extended), the labels are always shown.
    ///
    /// The default value is `NavigationRailThemeData::label_type`. If
    /// `NavigationRailThemeData::label_type` is null, then the default value is
    /// [`NavigationRailLabelType::None`].
    ///
    /// See also:
    ///
    ///   * [`NavigationRailLabelType`] for information on the meaning of different
    ///     types.
    pub label_type: Option<NavigationRailLabelType>,

    /// The `TextStyle` of a destination's label when it is unselected.
    ///
    /// When one of the [`destinations`](Self::destinations) is selected the
    /// [`selected_label_text_style`](Self::selected_label_text_style) will be used instead.
    ///
    /// The default value is based on the `Theme`'s `TextTheme::body_large`. The
    /// default color is based on the `Theme`'s `ColorScheme::on_surface`.
    ///
    /// Properties from this text style, or
    /// `NavigationRailThemeData::unselected_label_text_style` if this is null, are
    /// merged into the defaults.
    pub unselected_label_text_style: Option<TextStyle>,

    /// The `TextStyle` of a destination's label when it is selected.
    ///
    /// When a [`NavigationRailDestination`] is not selected,
    /// [`unselected_label_text_style`](Self::unselected_label_text_style) will be used.
    ///
    /// The default value is based on the `TextTheme::body_large` of
    /// `ThemeData::text_theme`. The default color is based on the `Theme`'s
    /// `ColorScheme::primary`.
    ///
    /// Properties from this text style,
    /// or `NavigationRailThemeData::selected_label_text_style` if this is null, are
    /// merged into the defaults.
    pub selected_label_text_style: Option<TextStyle>,

    /// The visual properties of the icon in the unselected destination.
    ///
    /// If this field is not provided, or provided with any null properties, then
    /// a copy of the `IconThemeData::fallback` with a custom [`NavigationRail`]
    /// specific color will be used.
    ///
    /// The default value is the `Theme`'s `ThemeData::icon_theme` with a color
    /// of the `Theme`'s `ColorScheme::on_surface` with an opacity of 0.64.
    /// Properties from this icon theme, or
    /// `NavigationRailThemeData::unselected_icon_theme` if this is null, are
    /// merged into the defaults.
    pub unselected_icon_theme: Option<IconThemeData>,

    /// The visual properties of the icon in the selected destination.
    ///
    /// When a [`NavigationRailDestination`] is not selected,
    /// [`unselected_icon_theme`](Self::unselected_icon_theme) will be used.
    ///
    /// The default value is the `Theme`'s `ThemeData::icon_theme` with a color
    /// of the `Theme`'s `ColorScheme::primary`. Properties from this icon theme,
    /// or `NavigationRailThemeData::selected_icon_theme` if this is null, are
    /// merged into the defaults.
    pub selected_icon_theme: Option<IconThemeData>,

    /// The smallest possible width for the rail regardless of the destination's
    /// icon or label size.
    ///
    /// The default is 72.
    ///
    /// This value also defines the min width and min height of the destinations.
    ///
    /// To make a compact rail, set this to 56 and use
    /// [`NavigationRailLabelType::None`].
    pub min_width: Option<f64>,

    /// The final width when the animation is complete for setting
    /// [`extended`](Self::extended) to true.
    ///
    /// This is only used when [`extended`](Self::extended) is set to true.
    ///
    /// The default value is 256.
    pub min_extended_width: Option<f64>,

    /// If `true`, adds a rounded [`NavigationIndicator`] behind the selected
    /// destination's icon.
    ///
    /// The indicator's shape will be circular if [`label_type`](Self::label_type) is
    /// [`NavigationRailLabelType::None`], or a `StadiumBorder` if
    /// [`label_type`](Self::label_type) is [`NavigationRailLabelType::All`] or
    /// [`NavigationRailLabelType::Selected`].
    ///
    /// If `null`, defaults to `NavigationRailThemeData::use_indicator`. If that is
    /// `null`, defaults to `ThemeData::use_material3`.
    pub use_indicator: Option<bool>,

    /// Overrides the default value of [`NavigationRail`]'s selection indicator color,
    /// when [`use_indicator`](Self::use_indicator) is true.
    ///
    /// If this is null, `NavigationRailThemeData::indicator_color` is used. If
    /// that is null, defaults to `ColorScheme::secondary_container`.
    pub indicator_color: Option<Color>,

    /// Overrides the default value of [`NavigationRail`]'s selection indicator shape,
    /// when [`use_indicator`](Self::use_indicator) is true.
    ///
    /// If this is null, `NavigationRailThemeData::indicator_shape` is used. If
    /// that is null, defaults to `StadiumBorder`.
    pub indicator_shape: Option<ShapeBorderRef>,

    /// Pin the [`leading`](Self::leading) widget to the top.
    ///
    /// If `true`, the [`leading`](Self::leading) widget is pinned to the top of the
    /// [`NavigationRail`]. Otherwise it precedes directly the main group of
    /// [`destinations`](Self::destinations).
    ///
    /// See also [`scrollable`](Self::scrollable) for a description of the interplay of
    /// these parameters.
    pub leading_at_top: bool,

    /// Pin the [`trailing`](Self::trailing) widget to the bottom.
    ///
    /// If `true`, the [`trailing`](Self::trailing) widget is pinned to the bottom of the
    /// [`NavigationRail`]. Otherwise it follows directly the main group of
    /// [`destinations`](Self::destinations).
    ///
    /// See also [`scrollable`](Self::scrollable) for a description of the interplay of
    /// these parameters.
    pub trailing_at_bottom: bool,

    /// Whether the main group of items should be scrollable when vertical space
    /// is insufficient to show all of [`destinations`](Self::destinations),
    /// [`leading`](Self::leading) and [`trailing`](Self::trailing).
    ///
    /// If [`leading_at_top`](Self::leading_at_top) or
    /// [`trailing_at_bottom`](Self::trailing_at_bottom) are false,
    /// [`leading`](Self::leading) or [`trailing`](Self::trailing) widgets, respectively,
    /// are part of the main group in addition to [`destinations`](Self::destinations).
    /// Otherwise these are statical at the top or bottom, respectively.
    pub scrollable: bool,

    /// How the [`destinations`](Self::destinations) should be placed along the vertical
    /// axis.
    ///
    /// When there is extra vertical space in the [`NavigationRail`], this
    /// property controls the alignment and spacing of the items. For example,
    /// setting this to `MainAxisAlignment::SpaceEvenly` will distribute the
    /// destinations equally along the available vertical space.
    ///
    /// When this property is not null, [`group_alignment`](Self::group_alignment) is
    /// ignored.
    ///
    /// If null, the layout behaves as if `MainAxisAlignment::Start` was
    /// specified.
    ///
    /// See also:
    ///
    ///  * `Column::main_axis_alignment`, which describes the different values and
    ///    their effects on the layout.
    pub main_axis_alignment: Option<MainAxisAlignment>,
}

impl NavigationRail {
    /// Creates a Material Design navigation rail.
    ///
    /// The value of [`destinations`](Self::destinations) must be a list of zero or more
    /// [`NavigationRailDestination`] values.
    ///
    /// If [`elevation`](Self::elevation) is specified, it must be non-negative.
    ///
    /// If [`min_width`](Self::min_width) is specified, it must be non-negative, and if
    /// [`min_extended_width`](Self::min_extended_width) is specified, it must be
    /// non-negative and greater than [`min_width`](Self::min_width).
    ///
    /// The [`extended`](Self::extended) argument can only be set to true when the
    /// [`label_type`](Self::label_type) is null or [`NavigationRailLabelType::None`].
    ///
    /// If [`background_color`](Self::background_color), [`elevation`](Self::elevation),
    /// [`group_alignment`](Self::group_alignment), [`label_type`](Self::label_type),
    /// [`unselected_label_text_style`](Self::unselected_label_text_style),
    /// [`selected_label_text_style`](Self::selected_label_text_style),
    /// [`unselected_icon_theme`](Self::unselected_icon_theme), or
    /// [`selected_icon_theme`](Self::selected_icon_theme) are null, then their
    /// [`NavigationRailThemeData`] values will be used. If the corresponding
    /// [`NavigationRailThemeData`] property is null, then the navigation rail
    /// defaults are used. See the individual properties for more information.
    ///
    /// Typically used within a `Row` that defines the `Scaffold::body` property.
    pub fn new(
        destinations: Vec<NavigationRailDestination>,
        selected_index: Option<usize>,
    ) -> NavigationRail {
        debug_assert!(selected_index.is_none_or(|index| index < destinations.len()));
        NavigationRail {
            key: None,
            background_color: None,
            extended: false,
            leading: None,
            trailing: None,
            destinations,
            selected_index,
            on_destination_selected: None,
            elevation: None,
            group_alignment: None,
            label_type: None,
            unselected_label_text_style: None,
            selected_label_text_style: None,
            unselected_icon_theme: None,
            selected_icon_theme: None,
            min_width: None,
            min_extended_width: None,
            use_indicator: None,
            indicator_color: None,
            indicator_shape: None,
            leading_at_top: true,
            trailing_at_bottom: false,
            scrollable: false,
            main_axis_alignment: None,
        }
    }

    /// Dart `NavigationRail(key:)`.
    pub fn key(mut self, key: KeyRef) -> NavigationRail {
        self.key = Some(key);
        self
    }

    /// Dart `NavigationRail(backgroundColor:)`.
    pub fn background_color(mut self, background_color: Color) -> NavigationRail {
        self.background_color = Some(background_color);
        self
    }

    /// Dart `NavigationRail(extended:)`.
    pub fn extended(mut self, extended: bool) -> NavigationRail {
        self.extended = extended;
        self
    }

    /// Dart `NavigationRail(leading:)`.
    pub fn leading<K>(mut self, leading: impl IntoWidget<K>) -> NavigationRail {
        self.leading = Some(leading.into_widget());
        self
    }

    /// Dart `NavigationRail(trailing:)`.
    pub fn trailing<K>(mut self, trailing: impl IntoWidget<K>) -> NavigationRail {
        self.trailing = Some(trailing.into_widget());
        self
    }

    /// Dart `NavigationRail(onDestinationSelected:)`.
    pub fn on_destination_selected(
        mut self,
        on_destination_selected: impl Fn(&mut App, usize) + 'static,
    ) -> NavigationRail {
        self.on_destination_selected = Some(Rc::new(on_destination_selected));
        self
    }

    /// Dart `NavigationRail(elevation:)`.
    pub fn elevation(mut self, elevation: f64) -> NavigationRail {
        debug_assert!(elevation > 0.0);
        self.elevation = Some(elevation);
        self
    }

    /// Dart `NavigationRail(groupAlignment:)`.
    pub fn group_alignment(mut self, group_alignment: f64) -> NavigationRail {
        self.group_alignment = Some(group_alignment);
        self
    }

    /// Dart `NavigationRail(labelType:)`.
    pub fn label_type(mut self, label_type: NavigationRailLabelType) -> NavigationRail {
        self.label_type = Some(label_type);
        self
    }

    /// Dart `NavigationRail(unselectedLabelTextStyle:)`.
    pub fn unselected_label_text_style(
        mut self,
        unselected_label_text_style: TextStyle,
    ) -> NavigationRail {
        self.unselected_label_text_style = Some(unselected_label_text_style);
        self
    }

    /// Dart `NavigationRail(selectedLabelTextStyle:)`.
    pub fn selected_label_text_style(
        mut self,
        selected_label_text_style: TextStyle,
    ) -> NavigationRail {
        self.selected_label_text_style = Some(selected_label_text_style);
        self
    }

    /// Dart `NavigationRail(unselectedIconTheme:)`.
    pub fn unselected_icon_theme(mut self, unselected_icon_theme: IconThemeData) -> NavigationRail {
        self.unselected_icon_theme = Some(unselected_icon_theme);
        self
    }

    /// Dart `NavigationRail(selectedIconTheme:)`.
    pub fn selected_icon_theme(mut self, selected_icon_theme: IconThemeData) -> NavigationRail {
        self.selected_icon_theme = Some(selected_icon_theme);
        self
    }

    /// Dart `NavigationRail(minWidth:)`.
    pub fn min_width(mut self, min_width: f64) -> NavigationRail {
        debug_assert!(min_width > 0.0);
        self.min_width = Some(min_width);
        self
    }

    /// Dart `NavigationRail(minExtendedWidth:)`.
    pub fn min_extended_width(mut self, min_extended_width: f64) -> NavigationRail {
        debug_assert!(min_extended_width > 0.0);
        self.min_extended_width = Some(min_extended_width);
        self
    }

    /// Dart `NavigationRail(useIndicator:)`.
    pub fn use_indicator(mut self, use_indicator: bool) -> NavigationRail {
        self.use_indicator = Some(use_indicator);
        self
    }

    /// Dart `NavigationRail(indicatorColor:)`.
    pub fn indicator_color(mut self, indicator_color: Color) -> NavigationRail {
        self.indicator_color = Some(indicator_color);
        self
    }

    /// Dart `NavigationRail(indicatorShape:)`.
    pub fn indicator_shape(mut self, indicator_shape: impl Into<ShapeBorderRef>) -> NavigationRail {
        self.indicator_shape = Some(indicator_shape.into());
        self
    }

    /// Dart `NavigationRail(leadingAtTop:)`.
    pub fn leading_at_top(mut self, leading_at_top: bool) -> NavigationRail {
        self.leading_at_top = leading_at_top;
        self
    }

    /// Dart `NavigationRail(trailingAtBottom:)`.
    pub fn trailing_at_bottom(mut self, trailing_at_bottom: bool) -> NavigationRail {
        self.trailing_at_bottom = trailing_at_bottom;
        self
    }

    /// Dart `NavigationRail(scrollable:)`.
    pub fn scrollable(mut self, scrollable: bool) -> NavigationRail {
        self.scrollable = scrollable;
        self
    }

    /// Dart `NavigationRail(mainAxisAlignment:)`.
    pub fn main_axis_alignment(mut self, main_axis_alignment: MainAxisAlignment) -> NavigationRail {
        self.main_axis_alignment = Some(main_axis_alignment);
        self
    }

    /// Returns the animation that controls the [`NavigationRail::extended`] state.
    ///
    /// This can be used to synchronize animations in the [`leading`](Self::leading) or
    /// [`trailing`](Self::trailing) widget, such as an animated menu or a
    /// `FloatingActionButton` animation.
    pub fn extended_animation(app: &mut App, context: BuildContext) -> AnyAnimation<f64> {
        context
            .depend_on_inherited_widget_of_exact_type::<ExtendedNavigationRailAnimation>(app)
            .expect("a NavigationRail above the context")
            .animation
            .handle()
    }
}

impl Debug for NavigationRail {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("NavigationRail")
            .field("extended", &self.extended)
            .field("destinations", &self.destinations.len())
            .field("selected_index", &self.selected_index)
            .field("label_type", &self.label_type)
            .finish_non_exhaustive()
    }
}

impl StatefulWidget for NavigationRail {
    type State = NavigationRailState;

    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn debug_check_constructor(&self) {
        debug_assert!(
            self.min_width.is_none()
                || self.min_extended_width.is_none()
                || self.min_extended_width >= self.min_width
        );
        debug_assert!(
            !self.extended
                || self.label_type.is_none()
                || self.label_type == Some(NavigationRailLabelType::None)
        );
    }

    fn create_state(&self) -> NavigationRailState {
        NavigationRailState {
            state: StateData::new(),
            ticker_provider: TickerProviderStateMixinData::new(),
            destination_controllers: Vec::new(),
            destination_animations: Vec::new(),
            extended_controller: None,
            extended_animation: None,
        }
    }
}

/// Dart's `_NavigationRailState`.
pub struct NavigationRailState {
    state: StateData<NavigationRail>,
    ticker_provider: TickerProviderStateMixinData,
    destination_controllers: Vec<Ref<AnimationController>>,
    destination_animations: Vec<AnimationRef<f64>>,
    extended_controller: Option<Ref<AnimationController>>,
    extended_animation: Option<Ref<CurvedAnimation>>,
}

impl TickerProviderStateMixin for NavigationRailState {
    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
        &app.get(self).ticker_provider
    }

    fn ticker_provider_data_mut(
        self: Handle<Self>,
        app: &mut App,
    ) -> &mut TickerProviderStateMixinData {
        &mut app.get_mut(self).ticker_provider
    }
}

impl TickerProviderObject for NavigationRailState {
    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
        TickerProviderStateMixin::create_ticker(self, app, on_tick)
    }
}

impl State for NavigationRailState {
    type Widget = NavigationRail;
    waft_widgets::state_accessors!();

    fn init_state(self: Handle<Self>, app: &mut App) {
        self.init_controllers(app);
    }

    fn activate(self: Handle<Self>, app: &mut App) {
        TickerProviderStateMixin::activate(self, app);
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        self.dispose_controllers(app);
        TickerProviderStateMixin::dispose(self, app);
    }

    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &NavigationRail) {
        let widget = self.widget(app);
        let extended = widget.extended;
        let destinations_len = widget.destinations.len();
        let selected_index = widget.selected_index;
        if extended != old_widget.extended {
            let extended_controller = self.extended_controller(app);
            if extended {
                extended_controller.forward(app, None);
            } else {
                extended_controller.reverse(app, None);
            }
        }

        // No animated segue if the length of the items list changes.
        if destinations_len != old_widget.destinations.len() {
            self.reset_state(app);
            return;
        }

        if selected_index != old_widget.selected_index {
            if let Some(old_selected_index) = old_widget.selected_index {
                app.get(self).destination_controllers[old_selected_index].reverse(app, None);
            }
            if let Some(selected_index) = selected_index {
                app.get(self).destination_controllers[selected_index].forward(app, None);
            }
        }
    }

    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
        let navigation_rail_theme = NavigationRailTheme::of(app, context);
        let defaults: Box<dyn NavigationRailThemeDataGetters> =
            if Theme::of(app, context).use_material3 {
                Box::new(NavigationRailDefaultsM3::new(context))
            } else {
                Box::new(NavigationRailDefaultsM2::new(app, context))
            };
        let localizations = <dyn MaterialLocalizations>::of(app, context);

        let widget_ref = context.widget(app).clone();
        let widget = waft_widgets::downcast_widget::<NavigationRail>(&*widget_ref)
            .expect("a NavigationRailState builds its NavigationRail");
        let background_color = widget
            .background_color
            .or(navigation_rail_theme.background_color)
            .or_else(|| defaults.background_color(app))
            .expect("the defaults give a background color");
        let elevation = widget
            .elevation
            .or(navigation_rail_theme.elevation)
            .or_else(|| defaults.elevation(app))
            .expect("the defaults give an elevation");
        let min_width = widget
            .min_width
            .or(navigation_rail_theme.min_width)
            .or_else(|| defaults.min_width(app))
            .expect("the defaults give a min width");
        let min_extended_width = widget
            .min_extended_width
            .or(navigation_rail_theme.min_extended_width)
            .or_else(|| defaults.min_extended_width(app))
            .expect("the defaults give a min extended width");
        let unselected_label_text_style = widget
            .unselected_label_text_style
            .clone()
            .or(navigation_rail_theme.unselected_label_text_style.clone())
            .or_else(|| defaults.unselected_label_text_style(app))
            .expect("the defaults give an unselected label text style");
        let selected_label_text_style = widget
            .selected_label_text_style
            .clone()
            .or(navigation_rail_theme.selected_label_text_style.clone())
            .or_else(|| defaults.selected_label_text_style(app))
            .expect("the defaults give a selected label text style");
        let unselected_icon_theme = widget
            .unselected_icon_theme
            .clone()
            .or(navigation_rail_theme.unselected_icon_theme.clone())
            .or_else(|| defaults.unselected_icon_theme(app))
            .expect("the defaults give an unselected icon theme");
        let selected_icon_theme = widget
            .selected_icon_theme
            .clone()
            .or(navigation_rail_theme.selected_icon_theme.clone())
            .or_else(|| defaults.selected_icon_theme(app))
            .expect("the defaults give a selected icon theme");
        let group_alignment = widget
            .group_alignment
            .or(navigation_rail_theme.group_alignment)
            .or_else(|| defaults.group_alignment(app))
            .expect("the defaults give a group alignment");
        let label_type = widget
            .label_type
            .or(navigation_rail_theme.label_type)
            .or_else(|| defaults.label_type(app))
            .expect("the defaults give a label type");
        let use_indicator = widget
            .use_indicator
            .or(navigation_rail_theme.use_indicator)
            .or_else(|| defaults.use_indicator(app))
            .expect("the defaults give use_indicator");
        let indicator_color = widget
            .indicator_color
            .or(navigation_rail_theme.indicator_color)
            .or_else(|| defaults.indicator_color(app));
        let indicator_shape = widget
            .indicator_shape
            .clone()
            .or(navigation_rail_theme.indicator_shape.clone())
            .or_else(|| defaults.indicator_shape(app));

        // For backwards compatibility, in M2 the opacity of the unselected icons needs
        // to be set to the default if it isn't in the given theme. This can be removed
        // when Material 3 is the default.
        let effective_unselected_icon_theme = if Theme::of(app, context).use_material3 {
            unselected_icon_theme
        } else {
            let opacity = unselected_icon_theme.opacity.or_else(|| {
                defaults
                    .unselected_icon_theme(app)
                    .expect("the M2 defaults give an unselected icon theme")
                    .opacity
            });
            match opacity {
                Some(opacity) => unselected_icon_theme.copy_with().opacity(opacity),
                None => unselected_icon_theme.copy_with(),
            }
        };

        let is_rtl_direction = Directionality::of(app, context) == TextDirection::Rtl;

        let state = app.get(self);
        let extended_animation: AnimationRef<f64> = state
            .extended_animation
            .as_ref()
            .expect("created in init_state")
            .erase();
        let destination_animations = state.destination_animations.clone();
        let widget = self.widget(app);
        let destinations_len = widget.destinations.len();

        let mut main_group_children = Vec::new();
        if !widget.leading_at_top
            && let Some(leading) = &widget.leading
        {
            main_group_children.push(leading.clone());
            main_group_children.push(vertical_spacer());
        }
        let rail_destinations: Vec<WidgetRef> = widget
            .destinations
            .iter()
            .enumerate()
            .map(|(i, destination)| {
                let selected = widget.selected_index == Some(i);
                let on_destination_selected = widget.on_destination_selected.clone();
                RailDestination {
                    min_width,
                    min_extended_width,
                    extended_transition_animation: extended_animation.clone(),
                    selected,
                    icon: if selected {
                        destination.selected_icon.clone()
                    } else {
                        destination.icon.clone()
                    },
                    label: destination.label.clone(),
                    destination_animation: destination_animations[i].clone(),
                    label_type,
                    icon_theme: if selected {
                        selected_icon_theme.clone()
                    } else {
                        effective_unselected_icon_theme.clone()
                    },
                    label_text_style: if selected {
                        selected_label_text_style.clone()
                    } else {
                        unselected_label_text_style.clone()
                    },
                    padding: destination.padding,
                    use_indicator,
                    indicator_color: if use_indicator { indicator_color } else { None },
                    indicator_shape: if use_indicator {
                        indicator_shape.clone()
                    } else {
                        None
                    },
                    on_tap: Listener::new(move |app| {
                        if let Some(on_destination_selected) = &on_destination_selected {
                            on_destination_selected(app, i);
                        }
                    }),
                    index_label: localizations.tab_label(i as i32 + 1, destinations_len as i32),
                    disabled: destination.disabled,
                }
                .into_widget()
            })
            .collect();
        main_group_children.push(
            Semantics::new()
                .role(SemanticsRole::TabBar)
                .explicit_child_nodes(true)
                .container(true)
                .child(
                    Column::new()
                        .main_axis_size(MainAxisSize::Min)
                        .children(rail_destinations),
                )
                .into_widget(),
        );
        if !widget.trailing_at_bottom
            && let Some(trailing) = &widget.trailing
        {
            main_group_children.push(trailing.clone());
        }
        let mut main_group = Column::new()
            .main_axis_size(if widget.main_axis_alignment.is_some() {
                MainAxisSize::Max
            } else {
                MainAxisSize::Min
            })
            .main_axis_alignment(
                widget
                    .main_axis_alignment
                    .unwrap_or(MainAxisAlignment::Start),
            )
            .children(main_group_children)
            .into_widget();

        if widget.scrollable {
            main_group = SingleChildScrollView::new().child(main_group).into_widget();
        }

        let mut column_children = vec![vertical_spacer()];
        if widget.leading_at_top
            && let Some(leading) = &widget.leading
        {
            column_children.push(leading.clone());
            column_children.push(vertical_spacer());
        }
        column_children.push(
            Flexible::new(
                Align::new()
                    .alignment(AlignmentGeometry::Alignment(Alignment::new(
                        0.0,
                        group_alignment,
                    )))
                    .child(main_group),
            )
            .into_widget(),
        );
        if widget.trailing_at_bottom
            && let Some(trailing) = &widget.trailing
        {
            column_children.push(trailing.clone());
        }

        Semantics::new()
            .container(true)
            .child(ExtendedNavigationRailAnimation {
                animation: extended_animation.clone(),
                child: Semantics::new()
                    .explicit_child_nodes(true)
                    .child(
                        Material::new()
                            .elevation(elevation)
                            .color(background_color)
                            .child(
                                SafeArea::new(Column::new().children(column_children))
                                    .right(is_rtl_direction)
                                    .left(!is_rtl_direction),
                            ),
                    )
                    .into_widget(),
            })
            .into_widget()
    }
}

impl NavigationRailState {
    fn extended_controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
        app.get(self)
            .extended_controller
            .handle()
            .expect("created in init_state")
    }

    fn dispose_controllers(self: Handle<Self>, app: &mut App) {
        let state = app.get(self);
        let destination_controllers = state.destination_controllers.clone();
        let extended_controller = state
            .extended_controller
            .handle()
            .expect("created in init_state");
        let extended_animation = state
            .extended_animation
            .handle()
            .expect("created in init_state");
        for controller in destination_controllers {
            controller.dispose(app);
        }
        extended_controller.dispose(app);
        extended_animation.dispose(app);
    }

    fn init_controllers(self: Handle<Self>, app: &mut App) {
        let destinations_len = self.widget(app).destinations.len();
        let destination_controllers: Vec<Ref<AnimationController>> = (0..destinations_len)
            .map(|_| {
                let controller = AnimationController::new(
                    app,
                    None,
                    Some(K_THEME_ANIMATION_DURATION),
                    None,
                    0.0,
                    1.0,
                    AnimationBehavior::Normal,
                    self,
                );
                Animation::add_listener(
                    controller.handle(),
                    app,
                    Listener::handle_method(self, Self::rebuild),
                );
                controller
            })
            .collect();
        let destination_animations = destination_controllers
            .iter()
            .map(|controller| controller.erase())
            .collect();
        if let Some(selected_index) = self.widget(app).selected_index {
            destination_controllers[selected_index].set_value(app, 1.0);
        }
        let extended = self.widget(app).extended;
        let extended_controller = AnimationController::new(
            app,
            Some(if extended { 1.0 } else { 0.0 }),
            Some(K_THEME_ANIMATION_DURATION),
            None,
            0.0,
            1.0,
            AnimationBehavior::Normal,
            self,
        );
        let extended_animation = CurvedAnimation::new(
            app,
            extended_controller.erase(),
            Curves::ease_in_out(),
            None,
        );
        Animation::add_listener(
            extended_controller.handle(),
            app,
            Listener::handle_method(self, Self::rebuild),
        );
        let state = app.get_mut(self);
        state.destination_controllers = destination_controllers;
        state.destination_animations = destination_animations;
        state.extended_controller = Some(extended_controller);
        state.extended_animation = Some(extended_animation);
    }

    fn reset_state(self: Handle<Self>, app: &mut App) {
        self.dispose_controllers(app);
        self.init_controllers(app);
    }

    fn rebuild(self: Handle<Self>, app: &mut App) {
        self.set_state(app, |_| {
            // Rebuilding when any of the controllers tick, i.e. when the items are
            // animating.
        });
    }
}

/// Dart's `_RailDestination`.
struct RailDestination {
    min_width: f64,
    min_extended_width: f64,
    icon: WidgetRef,
    label: WidgetRef,
    destination_animation: AnimationRef<f64>,
    label_type: NavigationRailLabelType,
    selected: bool,
    extended_transition_animation: AnimationRef<f64>,
    icon_theme: IconThemeData,
    label_text_style: TextStyle,
    on_tap: Listener,
    index_label: String,
    padding: Option<EdgeInsetsGeometry>,
    use_indicator: bool,
    indicator_color: Option<Color>,
    indicator_shape: Option<ShapeBorderRef>,
    disabled: bool,
}

impl Debug for RailDestination {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("_RailDestination")
            .field("label_type", &self.label_type)
            .field("selected", &self.selected)
            .field("disabled", &self.disabled)
            .finish_non_exhaustive()
    }
}

impl StatefulWidget for RailDestination {
    type State = RailDestinationState;

    fn create_state(&self) -> RailDestinationState {
        RailDestinationState {
            state: StateData::new(),
            position_animation: None,
        }
    }
}

/// Dart's `_RailDestinationState`.
struct RailDestinationState {
    state: StateData<RailDestination>,
    /// Dart's `_positionAnimation`, a `CurvedAnimation` over a `ReverseAnimation`.
    position_animation: Option<Ref<CurvedAnimation>>,
}

impl RailDestinationState {
    fn set_position_animation(self: Handle<Self>, app: &mut App) {
        let destination_animation = self.widget(app).destination_animation.clone();
        let reversed = ReverseAnimation::new(app, destination_animation);
        let curved = CurvedAnimation::new(
            app,
            reversed.erase(),
            Curves::ease_in_out(),
            Some(Rc::new(Curves::ease_in_out().flipped())),
        );
        app.get_mut(self).position_animation = Some(curved);
    }

    fn dispose_position_animation(self: Handle<Self>, app: &mut App) {
        let position_animation = app
            .get_mut(self)
            .position_animation
            .take()
            .expect("set in init_state");
        position_animation.dispose(app);
    }

    fn position_animation_value(self: Handle<Self>, app: &App) -> f64 {
        app.get(self)
            .position_animation
            .as_ref()
            .expect("set in init_state")
            .value(app)
    }

    /// Dart's `parent.drive(CurveTween(curve: Interval(begin, end)))`.
    fn label_fade_animation(
        app: &mut App,
        parent: AnimationRef<f64>,
        begin: f64,
        end: f64,
    ) -> AnimationRef<f64> {
        let curve_tween =
            CurveTween::new(app, Rc::new(Interval::new(begin, end, Curves::linear())));
        parent.drive(app, curve_tween)
    }
}

impl State for RailDestinationState {
    type Widget = RailDestination;
    waft_widgets::state_accessors!();

    fn init_state(self: Handle<Self>, app: &mut App) {
        self.set_position_animation(app);
    }

    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &RailDestination) {
        if self.widget(app).destination_animation != old_widget.destination_animation {
            self.dispose_position_animation(app);
            self.set_position_animation(app);
        }
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        self.dispose_position_animation(app);
    }

    #[expect(deprecated, reason = "Dart calls the deprecated `Color.withOpacity`")]
    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
        {
            let widget = self.widget(app);
            debug_assert!(
                widget.use_indicator || widget.indicator_color.is_none(),
                "[NavigationRail.indicatorColor] does not have an effect when \
                 [NavigationRail.useIndicator] is false"
            );
        }

        let theme = Theme::of(app, context);
        let text_direction = Directionality::of(app, context);
        let material3 = theme.use_material3;
        let m2_min_width = NavigationRailDefaultsM2::new(app, context)
            .min_width(app)
            .expect("the M2 defaults give a min width");
        let position_animation_value = self.position_animation_value(app);
        let extended_transition_value = self.widget(app).extended_transition_animation.value(app);

        let widget = self.widget(app);
        let destination_padding = widget
            .padding
            .unwrap_or(EdgeInsetsGeometry::ZERO)
            .resolve(Some(text_direction));
        let indicator_offset: Offset;
        let mut apply_x_offset = false;

        let themed_icon = IconTheme::new(
            if widget.disabled {
                widget
                    .icon_theme
                    .copy_with()
                    .color(theme.color_scheme.on_surface().with_opacity(0.38))
            } else {
                widget.icon_theme.clone()
            },
            widget.icon.clone(),
        )
        .into_widget();
        let styled_label = DefaultTextStyle::new(
            if widget.disabled {
                widget
                    .label_text_style
                    .copy_with()
                    .color(theme.color_scheme.on_surface().with_opacity(0.38))
            } else {
                widget.label_text_style.clone()
            },
            widget.label.clone(),
        )
        .into_widget();

        let content: WidgetRef;

        // The indicator height is fixed and equal to _kIndicatorHeight.
        // When the icon height is larger than the indicator height the indicator
        // vertical offset is used to vertically center the indicator.
        let is_large_icon_size = widget
            .icon_theme
            .size
            .is_some_and(|size| size > K_INDICATOR_HEIGHT);
        let indicator_vertical_offset = if is_large_icon_size {
            (widget.icon_theme.size.expect("checked above") - K_INDICATOR_HEIGHT) / 2.0
        } else {
            0.0
        };

        let add_indicator = |is_circular: bool, child: WidgetRef| AddIndicator {
            add_indicator: widget.use_indicator,
            indicator_color: widget.indicator_color,
            indicator_shape: widget.indicator_shape.clone(),
            is_circular,
            indicator_animation: widget.destination_animation.clone(),
            child,
        };

        match widget.label_type {
            NavigationRailLabelType::None => {
                // Split the destination spacing across the top and bottom to keep the icon
                // centered.
                let spacing = material3.then(|| {
                    SizedBox::new()
                        .height(VERTICAL_DESTINATION_SPACING_M3 / 2.0)
                        .into_widget()
                });
                indicator_offset = Offset::new(
                    widget.min_width / 2.0 + destination_padding.left,
                    VERTICAL_DESTINATION_SPACING_M3 / 2.0
                        + destination_padding.top
                        + indicator_vertical_offset,
                );
                let mut icon_box = SizedBox::new().width(widget.min_width);
                if !material3 {
                    icon_box = icon_box.height(widget.min_width);
                }
                let icon_part = Column::new()
                    .children(
                        spacing
                            .clone()
                            .into_iter()
                            .chain([icon_box
                                .child(Center::new().child(add_indicator(!material3, themed_icon)))
                                .into_widget()])
                            .chain(spacing),
                    )
                    .into_widget();
                if extended_transition_value == 0.0 {
                    content = Padding::new(widget.padding.unwrap_or(EdgeInsetsGeometry::ZERO))
                        .child(
                            Stack::new().children([
                                icon_part,
                                // For semantics when label is not showing,
                                SizedBox::shrink()
                                    .child(
                                        Visibility::maintain(widget.label.clone()).visible(false),
                                    )
                                    .into_widget(),
                            ]),
                        )
                        .into_widget();
                } else {
                    let extended_transition_animation =
                        widget.extended_transition_animation.clone();
                    let min_width = widget.min_width;
                    let min_extended_width = widget.min_extended_width;
                    let padding = widget.padding.unwrap_or(EdgeInsetsGeometry::ZERO);
                    let label_fade_animation = RailDestinationState::label_fade_animation(
                        app,
                        extended_transition_animation,
                        0.0,
                        0.25,
                    );
                    apply_x_offset = true;
                    content = Padding::new(padding)
                        .child(
                            ConstrainedBox::new(
                                BoxConstraints::new().min_width(
                                    lerp_double(
                                        Some(min_width),
                                        Some(min_extended_width),
                                        extended_transition_value,
                                    )
                                    .expect("both ends given"),
                                ),
                            )
                            .child(
                                ClipRect::new().child(
                                    Row::new().main_axis_size(MainAxisSize::Min).children([
                                        icon_part,
                                        Flexible::new(
                                            Align::new()
                                                .height_factor(1.0)
                                                .width_factor(extended_transition_value)
                                                .alignment(AlignmentGeometry::CENTER_START)
                                                .child(
                                                    FadeTransition::new(label_fade_animation)
                                                        .child(styled_label),
                                                ),
                                        )
                                        .into_widget(),
                                        SizedBox::new()
                                            .width(
                                                HORIZONTAL_DESTINATION_PADDING
                                                    * extended_transition_value,
                                            )
                                            .into_widget(),
                                    ]),
                                ),
                            ),
                        )
                        .into_widget();
                }
            }
            NavigationRailLabelType::Selected => {
                let appearing_animation_value = 1.0 - position_animation_value;
                let vertical_padding = lerp_double(
                    Some(VERTICAL_DESTINATION_PADDING_NO_LABEL),
                    Some(VERTICAL_DESTINATION_PADDING_WITH_LABEL),
                    appearing_animation_value,
                )
                .expect("both ends given");
                let (interval_begin, interval_end) = if widget.selected {
                    (0.25, 0.75)
                } else {
                    (0.75, 1.0)
                };
                let min_height = if material3 { 0.0 } else { widget.min_width };
                let top_spacing = SizedBox::new()
                    .height(if material3 { 0.0 } else { vertical_padding })
                    .into_widget();
                let label_spacing = SizedBox::new()
                    .height(if material3 {
                        lerp_double(
                            Some(0.0),
                            Some(VERTICAL_ICON_LABEL_SPACING_M3),
                            appearing_animation_value,
                        )
                        .expect("both ends given")
                    } else {
                        0.0
                    })
                    .into_widget();
                let bottom_spacing = SizedBox::new()
                    .height(if material3 {
                        VERTICAL_DESTINATION_SPACING_M3
                    } else {
                        vertical_padding
                    })
                    .into_widget();
                let indicator_horizontal_padding =
                    (destination_padding.left / 2.0) - (destination_padding.right / 2.0);
                let indicator_vertical_padding = destination_padding.top;
                let mut offset = Offset::new(
                    widget.min_width / 2.0 + indicator_horizontal_padding,
                    indicator_vertical_padding + indicator_vertical_offset,
                );
                if widget.min_width < m2_min_width {
                    offset = Offset::new(
                        widget.min_width / 2.0 + HORIZONTAL_DESTINATION_SPACING_M3,
                        indicator_vertical_padding + indicator_vertical_offset,
                    );
                }
                indicator_offset = offset;
                let indicator = add_indicator(false, themed_icon).into_widget();
                let min_width = widget.min_width;
                let padding = widget.padding.unwrap_or(EdgeInsetsGeometry::symmetric(
                    0.0,
                    HORIZONTAL_DESTINATION_PADDING,
                ));
                let destination_animation = widget.destination_animation.clone();
                let label_fade_animation = RailDestinationState::label_fade_animation(
                    app,
                    destination_animation,
                    interval_begin,
                    interval_end,
                );
                content = ConstrainedBox::new(
                    BoxConstraints::new()
                        .min_width(min_width)
                        .min_height(min_height),
                )
                .child(
                    Padding::new(padding).child(
                        ClipRect::new().child(
                            Column::new()
                                .main_axis_size(MainAxisSize::Min)
                                .main_axis_alignment(MainAxisAlignment::Center)
                                .children([
                                    top_spacing,
                                    indicator,
                                    label_spacing,
                                    Align::new()
                                        .alignment(AlignmentGeometry::TOP_CENTER)
                                        .height_factor(appearing_animation_value)
                                        .width_factor(1.0)
                                        .child(
                                            FadeTransition::new(label_fade_animation)
                                                .child(styled_label),
                                        )
                                        .into_widget(),
                                    bottom_spacing,
                                ]),
                        ),
                    ),
                )
                .into_widget();
            }
            NavigationRailLabelType::All => {
                let min_height = if material3 { 0.0 } else { widget.min_width };
                let top_spacing = SizedBox::new()
                    .height(if material3 {
                        0.0
                    } else {
                        VERTICAL_DESTINATION_PADDING_WITH_LABEL
                    })
                    .into_widget();
                let label_spacing = SizedBox::new()
                    .height(if material3 {
                        VERTICAL_ICON_LABEL_SPACING_M3
                    } else {
                        0.0
                    })
                    .into_widget();
                let bottom_spacing = SizedBox::new()
                    .height(if material3 {
                        VERTICAL_DESTINATION_SPACING_M3
                    } else {
                        VERTICAL_DESTINATION_PADDING_WITH_LABEL
                    })
                    .into_widget();
                let indicator_horizontal_padding =
                    (destination_padding.left / 2.0) - (destination_padding.right / 2.0);
                let indicator_vertical_padding = destination_padding.top;
                let mut offset = Offset::new(
                    widget.min_width / 2.0 + indicator_horizontal_padding,
                    indicator_vertical_padding + indicator_vertical_offset,
                );
                if widget.min_width < m2_min_width {
                    offset = Offset::new(
                        widget.min_width / 2.0 + HORIZONTAL_DESTINATION_SPACING_M3,
                        indicator_vertical_padding + indicator_vertical_offset,
                    );
                }
                indicator_offset = offset;
                content = ConstrainedBox::new(
                    BoxConstraints::new()
                        .min_width(widget.min_width)
                        .min_height(min_height),
                )
                .child(
                    Padding::new(widget.padding.unwrap_or(EdgeInsetsGeometry::symmetric(
                        0.0,
                        HORIZONTAL_DESTINATION_PADDING,
                    )))
                    .child(Column::new().children([
                        top_spacing,
                        add_indicator(false, themed_icon).into_widget(),
                        label_spacing,
                        styled_label,
                        bottom_spacing,
                    ])),
                )
                .into_widget();
            }
        }

        let colors = &Theme::of(app, context).color_scheme;
        let primary_color_alpha_modified = (colors.primary().alpha() as f64) < 255.0;
        let effective_splash_color = if primary_color_alpha_modified {
            colors.primary()
        } else {
            colors.primary().with_opacity(0.12)
        };
        let effective_hover_color = if primary_color_alpha_modified {
            colors.primary()
        } else {
            colors.primary().with_opacity(0.04)
        };
        let widget = self.widget(app);
        let mut stack_children = vec![
            Material::new()
                .r#type(MaterialType::Transparency)
                .child(indicator_ink_well(IndicatorInkWell {
                    child: content,
                    on_tap: (!widget.disabled).then(|| widget.on_tap.clone()),
                    border_radius: BorderRadius::all(Radius::circular(widget.min_width / 2.0)),
                    custom_border: widget.indicator_shape.clone(),
                    splash_color: effective_splash_color,
                    hover_color: effective_hover_color,
                    use_material3: material3,
                    indicator_offset,
                    apply_x_offset,
                    text_direction,
                }))
                .into_widget(),
        ];
        if !K_IS_WEB {
            stack_children.push(
                Semantics::new()
                    .label(widget.index_label.clone())
                    .into_widget(),
            );
        }
        let mut semantics = Semantics::new()
            .role(SemanticsRole::Tab)
            .selected(widget.selected);
        if widget.disabled {
            semantics = semantics.enabled(false);
        }
        MergeSemantics::new()
            .child(semantics.child(Stack::new().children(stack_children)))
            .into_widget()
    }
}

/// The arguments of Dart's `_IndicatorInkWell`, an `InkResponse` subclass.
struct IndicatorInkWell {
    child: WidgetRef,
    on_tap: Option<Listener>,
    custom_border: Option<ShapeBorderRef>,
    border_radius: BorderRadius,
    splash_color: Color,
    hover_color: Color,
    use_material3: bool,
    // The offset used to position Ink highlight.
    indicator_offset: Offset,
    // Whether the horizontal offset from indicatorOffset should be used to position Ink
    // highlight. If true, Ink highlight uses the indicator horizontal offset. If false, Ink
    // highlight is centered horizontally.
    apply_x_offset: bool,
    // The text direction used to adjust the indicator horizontal offset.
    text_direction: TextDirection,
}

/// Dart's `_IndicatorInkWell`: the `InkResponse` its constructor makes, with its
/// `getRectCallback` override.
fn indicator_ink_well(ink_well: IndicatorInkWell) -> InkResponse {
    let IndicatorInkWell {
        child,
        on_tap,
        custom_border,
        border_radius,
        splash_color,
        hover_color,
        use_material3,
        indicator_offset,
        apply_x_offset,
        text_direction,
    } = ink_well;
    let mut response = InkResponse::new()
        .child(child)
        .splash_color(splash_color)
        .hover_color(hover_color)
        .contained_ink_well(true)
        .highlight_shape(BoxShape::Rectangle)
        .override_get_rect_callback(move |app, reference_box| -> Option<RectCallback> {
            if use_material3 {
                let box_width = reference_box.size(app).width();
                let mut indicator_horizontal_center = if apply_x_offset {
                    indicator_offset.dx()
                } else {
                    box_width / 2.0
                };
                if text_direction == TextDirection::Rtl {
                    indicator_horizontal_center = box_width - indicator_horizontal_center;
                }
                return Some(Rc::new(move |_app| {
                    Rect::from_ltwh(
                        indicator_horizontal_center - (K_CIRCULAR_INDICATOR_DIAMETER / 2.0),
                        indicator_offset.dy(),
                        K_CIRCULAR_INDICATOR_DIAMETER,
                        K_INDICATOR_HEIGHT,
                    )
                }));
            }
            None
        });
    if let Some(on_tap) = on_tap {
        response = response.on_tap(on_tap);
    }
    if !use_material3 {
        response = response.border_radius(border_radius);
    }
    if use_material3 && let Some(custom_border) = custom_border {
        response = response.custom_border(custom_border);
    }
    response
}

/// When `add_indicator` is `true`, puts `child` center aligned in a `Stack` with
/// a [`NavigationIndicator`] behind it, otherwise returns `child`.
///
/// When `is_circular` is true, the indicator will be a circle, otherwise the
/// indicator will be a stadium shape.
struct AddIndicator {
    add_indicator: bool,
    is_circular: bool,
    indicator_color: Option<Color>,
    indicator_shape: Option<ShapeBorderRef>,
    indicator_animation: AnimationRef<f64>,
    child: WidgetRef,
}

impl Debug for AddIndicator {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("_AddIndicator")
            .field("add_indicator", &self.add_indicator)
            .field("is_circular", &self.is_circular)
            .field("indicator_color", &self.indicator_color)
            .field("indicator_shape", &self.indicator_shape)
            .field("child", &self.child)
            .finish_non_exhaustive()
    }
}

impl StatelessWidget for AddIndicator {
    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
        if !self.add_indicator {
            return self.child.clone();
        }
        let indicator = if self.is_circular {
            let mut indicator = NavigationIndicator::new(self.indicator_animation.clone())
                .height(K_CIRCULAR_INDICATOR_DIAMETER)
                .width(K_CIRCULAR_INDICATOR_DIAMETER)
                .border_radius(BorderRadius::all(Radius::circular(
                    K_CIRCULAR_INDICATOR_DIAMETER / 2.0,
                )));
            if let Some(color) = self.indicator_color {
                indicator = indicator.color(color);
            }
            indicator
        } else {
            let mut indicator = NavigationIndicator::new(self.indicator_animation.clone())
                .width(K_CIRCULAR_INDICATOR_DIAMETER);
            if let Some(shape) = self.indicator_shape.clone() {
                indicator = indicator.shape(shape);
            }
            if let Some(color) = self.indicator_color {
                indicator = indicator.color(color);
            }
            indicator
        };

        Stack::new()
            .alignment(AlignmentGeometry::CENTER)
            .children([indicator.into_widget(), self.child.clone()])
            .into_widget()
    }
}

/// Defines the behavior of the labels of a [`NavigationRail`].
///
/// See also:
///
///   * [`NavigationRail`]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NavigationRailLabelType {
    /// Only the [`NavigationRailDestination`]s are shown.
    None,

    /// Only the selected [`NavigationRailDestination`] will show its label.
    ///
    /// The label will animate in and out as new [`NavigationRailDestination`]s are
    /// selected.
    Selected,

    /// All [`NavigationRailDestination`]s will show their label.
    All,
}

/// Defines a [`NavigationRail`] button that represents one "destination" view.
///
/// See also:
///
///  * [`NavigationRail`]
#[derive(Clone, Debug)]
pub struct NavigationRailDestination {
    /// The icon of the destination.
    ///
    /// Typically the icon is an `Icon` or an `ImageIcon` widget. If another type
    /// of widget is provided then it should configure itself to match the current
    /// `IconTheme` size and color.
    ///
    /// If [`selected_icon`](Self::selected_icon) is provided, this will only be displayed
    /// when the destination is not selected.
    ///
    /// To make the [`NavigationRail`] more accessible, consider choosing an
    /// icon with a stroked and filled version, such as `Icons::cloud` and
    /// `Icons::cloud_queue`. The [`icon`](Self::icon) should be set to the stroked version
    /// and [`selected_icon`](Self::selected_icon) to the filled version.
    pub icon: WidgetRef,

    /// An alternative icon displayed when this destination is selected.
    ///
    /// If this icon is not provided, the [`NavigationRail`] will display
    /// [`icon`](Self::icon) in either state. The size, color, and opacity of the
    /// [`NavigationRail::selected_icon_theme`] will still apply.
    ///
    /// See also:
    ///
    ///  * [`NavigationRailDestination::icon`], for a description of how to pair
    ///    icons.
    pub selected_icon: WidgetRef,

    /// The color of the [`indicator_shape`](Self::indicator_shape) when this destination is
    /// selected.
    pub indicator_color: Option<Color>,

    /// The shape of the selection indicator.
    pub indicator_shape: Option<ShapeBorderRef>,

    /// The label for the destination.
    ///
    /// The label must be provided when used with the [`NavigationRail`]. When the
    /// [`NavigationRail::label_type`] is [`NavigationRailLabelType::None`], the label is
    /// still used for semantics, and may still be used if
    /// [`NavigationRail::extended`] is true.
    pub label: WidgetRef,

    /// The amount of space to inset the destination item.
    pub padding: Option<EdgeInsetsGeometry>,

    /// Indicates that this destination is inaccessible.
    pub disabled: bool,
}

impl NavigationRailDestination {
    /// Creates a destination that is used with [`NavigationRail::destinations`].
    ///
    /// When the [`NavigationRail::label_type`] is [`NavigationRailLabelType::None`], the
    /// label is still used for semantics, and may still be used if
    /// [`NavigationRail::extended`] is true.
    pub fn new<I, L>(
        icon: impl IntoWidget<I>,
        label: impl IntoWidget<L>,
    ) -> NavigationRailDestination {
        let icon = icon.into_widget();
        NavigationRailDestination {
            selected_icon: icon.clone(),
            icon,
            indicator_color: None,
            indicator_shape: None,
            label: label.into_widget(),
            padding: None,
            disabled: false,
        }
    }

    /// Dart `NavigationRailDestination(selectedIcon:)`.
    pub fn selected_icon<K>(
        mut self,
        selected_icon: impl IntoWidget<K>,
    ) -> NavigationRailDestination {
        self.selected_icon = selected_icon.into_widget();
        self
    }

    /// Dart `NavigationRailDestination(indicatorColor:)`.
    pub fn indicator_color(mut self, indicator_color: Color) -> NavigationRailDestination {
        self.indicator_color = Some(indicator_color);
        self
    }

    /// Dart `NavigationRailDestination(indicatorShape:)`.
    pub fn indicator_shape(
        mut self,
        indicator_shape: impl Into<ShapeBorderRef>,
    ) -> NavigationRailDestination {
        self.indicator_shape = Some(indicator_shape.into());
        self
    }

    /// Dart `NavigationRailDestination(padding:)`.
    pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> NavigationRailDestination {
        self.padding = Some(padding.into());
        self
    }

    /// Dart `NavigationRailDestination(disabled:)`.
    pub fn disabled(mut self, disabled: bool) -> NavigationRailDestination {
        self.disabled = disabled;
        self
    }
}

/// Dart's `_ExtendedNavigationRailAnimation`.
#[derive(Debug)]
struct ExtendedNavigationRailAnimation {
    animation: AnimationRef<f64>,
    child: WidgetRef,
}

impl InheritedWidget for ExtendedNavigationRailAnimation {
    fn child(&self) -> &WidgetRef {
        &self.child
    }

    fn update_should_notify(&self, old: &ExtendedNavigationRailAnimation) -> bool {
        self.animation != old.animation
    }
}

// There don't appear to be tokens for these values, but they are
// shown in the spec.
const HORIZONTAL_DESTINATION_PADDING: f64 = 8.0;
const VERTICAL_DESTINATION_PADDING_NO_LABEL: f64 = 24.0;
const VERTICAL_DESTINATION_PADDING_WITH_LABEL: f64 = 16.0;
/// Dart's `const Widget _verticalSpacer = SizedBox(height: 8.0)`.
fn vertical_spacer() -> WidgetRef {
    SizedBox::new().height(8.0).into_widget()
}
const VERTICAL_ICON_LABEL_SPACING_M3: f64 = 4.0;
const VERTICAL_DESTINATION_SPACING_M3: f64 = 12.0;
const HORIZONTAL_DESTINATION_SPACING_M3: f64 = 12.0;

/// Dart's `_NavigationRailDefaultsM2`.
struct NavigationRailDefaultsM2 {
    /// Dart's `super(..)` arguments.
    navigation_rail_theme_data: NavigationRailThemeData,
    context: DefaultsContext,
}

impl NavigationRailDefaultsM2 {
    fn new(app: &mut App, context: BuildContext) -> NavigationRailDefaultsM2 {
        NavigationRailDefaultsM2 {
            navigation_rail_theme_data: NavigationRailThemeData::new()
                .elevation(0.0)
                .group_alignment(-1.0)
                .label_type(NavigationRailLabelType::None)
                .use_indicator(false)
                .min_width(72.0)
                .min_extended_width(256.0),
            context: DefaultsContext::with_theme(app, context),
        }
    }
}

#[expect(deprecated, reason = "Dart calls the deprecated `Color.withOpacity`")]
impl NavigationRailThemeDataGetters for NavigationRailDefaultsM2 {
    fn navigation_rail_theme_data(&self) -> &NavigationRailThemeData {
        &self.navigation_rail_theme_data
    }

    fn background_color(&self, app: &mut App) -> Option<Color> {
        let theme = self.context.theme(app);
        let colors = &theme.color_scheme;
        Some(colors.surface())
    }

    fn unselected_label_text_style(&self, app: &mut App) -> Option<TextStyle> {
        let theme = self.context.theme(app);
        let colors = &theme.color_scheme;
        Some(
            theme
                .text_theme
                .body_large
                .as_ref()
                .expect("the text theme has bodyLarge")
                .copy_with()
                .color(colors.on_surface().with_opacity(0.64)),
        )
    }

    fn selected_label_text_style(&self, app: &mut App) -> Option<TextStyle> {
        let theme = self.context.theme(app);
        let colors = &theme.color_scheme;
        Some(
            theme
                .text_theme
                .body_large
                .as_ref()
                .expect("the text theme has bodyLarge")
                .copy_with()
                .color(colors.primary()),
        )
    }

    fn unselected_icon_theme(&self, app: &mut App) -> Option<IconThemeData> {
        let theme = self.context.theme(app);
        let colors = &theme.color_scheme;
        Some(
            IconThemeData::new()
                .size(24.0)
                .color(colors.on_surface())
                .opacity(0.64),
        )
    }

    fn selected_icon_theme(&self, app: &mut App) -> Option<IconThemeData> {
        let theme = self.context.theme(app);
        let colors = &theme.color_scheme;
        Some(
            IconThemeData::new()
                .size(24.0)
                .color(colors.primary())
                .opacity(1.0),
        )
    }
}

#[cfg(test)]
mod tests {
    //! Ported from `test/navigation_rail_test.dart` and laid out in FlutterTest, whose glyphs
    //! are squares of the font size (`install_platform_fonts`).

    use std::time::Duration;
    use waft_painting::ShapeBorder;

    use waft_embedder::{FontWeight, Size};
    use waft_rendering::{AnyRenderBox, RenderParagraph};
    use waft_widgets::{
        AnyElement, Builder, Expanded, GlobalKey, Icon, IconData, MediaQuery, RichText, Text,
    };

    use waft_painting::EdgeInsets;

    use waft_widgets::testing::{
        TestPointer, WidgetTester, expect, find, finds_nothing, finds_one_widget, finds_widgets,
        test_widgets,
    };

    use super::*;
    use crate::colors::Colors;
    use crate::floating_action_button::FloatingActionButton;
    use crate::icons::Icons;
    use crate::scaffold::Scaffold;
    use crate::test_support::material_app;
    use crate::theme_data::ThemeData;

    fn destination(
        icon: IconData,
        selected_icon: IconData,
        label: &str,
    ) -> NavigationRailDestination {
        NavigationRailDestination::new(Icon::new(Some(icon)), Text::new(label))
            .selected_icon(Icon::new(Some(selected_icon)))
    }

    /// Dart's `_destinations()`.
    fn destinations() -> Vec<NavigationRailDestination> {
        vec![
            destination(Icons::favorite_border(), Icons::favorite(), "Abc"),
            destination(Icons::bookmark_border(), Icons::bookmark(), "Def"),
            destination(Icons::star_border(), Icons::star(), "Ghi"),
            destination(Icons::hotel(), Icons::home(), "Jkl"),
        ]
    }

    /// The arguments of Dart's `_pumpNavigationRail` besides the rail.
    struct Pump {
        text_scale_factor: f64,
        use_material3: bool,
        navigation_rail_theme: Option<NavigationRailThemeData>,
    }

    impl Default for Pump {
        fn default() -> Pump {
            Pump {
                text_scale_factor: 1.0,
                use_material3: true,
                navigation_rail_theme: None,
            }
        }
    }

    fn theme(app: &App, use_material3: bool) -> ThemeData {
        ThemeData::builder().use_material3(use_material3).build(app)
    }

    /// Dart's `_pumpNavigationRail`.
    fn pump_navigation_rail_with(
        tester: &mut WidgetTester,
        navigation_rail: NavigationRail,
        pump: Pump,
    ) {
        let root = {
            let app = tester.cell.borrow();
            let mut builder = ThemeData::builder().use_material3(pump.use_material3);
            if let Some(navigation_rail_theme) = pump.navigation_rail_theme {
                builder = builder.navigation_rail_theme(navigation_rail_theme);
            }
            let theme = builder.build(&app);
            let rail = navigation_rail.into_widget();
            let text_scale_factor = pump.text_scale_factor;
            material_app(
                theme,
                Builder::new(move |_app, _context| {
                    MediaQuery::with_clamped_text_scaling(
                        None,
                        text_scale_factor,
                        text_scale_factor,
                        Scaffold::new().body(Row::new().children([
                            rail.clone(),
                            Expanded::new(Text::new("body")).into_widget(),
                        ])),
                    )
                })
                .into_widget(),
            )
        };
        tester.pump_widget(root);
    }

    fn pump_navigation_rail(tester: &mut WidgetTester, navigation_rail: NavigationRail) {
        pump_navigation_rail_with(tester, navigation_rail, Pump::default());
    }

    /// Dart's `_buildWidget`.
    fn build_widget(app: &App, child: WidgetRef, use_material3: bool, is_rtl: bool) -> WidgetRef {
        material_app(
            theme(app, use_material3),
            Directionality::new(
                if is_rtl {
                    TextDirection::Rtl
                } else {
                    TextDirection::Ltr
                },
                Scaffold::new().body(
                    Row::new().children([child, Expanded::new(Text::new("body")).into_widget()]),
                ),
            )
            .into_widget(),
        )
    }

    fn pump_built_widget<K>(
        tester: &mut WidgetTester,
        child: impl IntoWidget<K>,
        use_material3: bool,
        is_rtl: bool,
    ) {
        let child = child.into_widget();
        let root = build_widget(&tester.cell.borrow(), child, use_material3, is_rtl);
        tester.pump_widget(root);
    }

    fn rail_box(tester: &WidgetTester) -> AnyRenderBox {
        tester.render_box_of(find::by_type::<NavigationRail>().evaluate(tester)[0])
    }

    fn global_top_left(tester: &WidgetTester, render: AnyRenderBox) -> Offset {
        render.local_to_global(&tester.cell.borrow(), Offset::ZERO, None)
    }

    /// The `RichText` below `element`.
    fn rich_text_below(tester: &WidgetTester, element: AnyElement) -> AnyElement {
        tester.descendants_of_type::<RichText>(element)[0]
    }

    /// Dart's `_iconRenderBox`.
    fn icon_render_box(tester: &WidgetTester, icon: IconData) -> AnyRenderBox {
        let icon = tester.element(find::by_icon(&icon).first());
        tester.render_box_of(rich_text_below(tester, icon))
    }

    /// Dart's `_labelRenderBox`.
    fn label_render_box(tester: &WidgetTester, text: &str) -> AnyRenderBox {
        let text = find::text(text).evaluate(tester)[0];
        tester.render_box_of(rich_text_below(tester, text))
    }

    /// Dart's `_iconStyle`.
    fn icon_style(tester: &WidgetTester, icon: IconData) -> TextStyle {
        tester.glyph_style(tester.element(find::by_icon(&icon).first()))
    }

    /// Dart's `tester.renderObject<RenderParagraph>(find.text(text)).text.style!`.
    fn paragraph_style(tester: &WidgetTester, text: &str) -> TextStyle {
        let render = label_render_box(tester, text);
        let app = tester.cell.borrow();
        render
            .as_object()
            .downcast::<RenderParagraph>(&app)
            .expect("a Text renders a paragraph")
            .text(&app)
            .style()
            .cloned()
            .expect("the paragraph's text has a style")
    }

    /// Dart's `_labelOpacity`. Only valid when labelType != all.
    fn label_opacity(tester: &WidgetTester, text: &str) -> f64 {
        let text = find::text(text).evaluate(tester)[0];
        let ancestors = tester.ancestors(text);
        let app = tester.cell.borrow();
        // We search for both Visibility and FadeTransition since in some
        // cases opacity is animated, in other it's not.
        if let Some(visibility) = ancestors.iter().find_map(|element| {
            waft_widgets::downcast_widget::<Visibility>(&**element.widget(&app))
        }) {
            return if visibility.visible { 1.0 } else { 0.0 };
        }
        // first because there's also a FadeTransition from the MaterialPageRoute, which is
        // up the tree
        let fade = ancestors
            .iter()
            .find_map(|element| {
                waft_widgets::downcast_widget::<FadeTransition>(&**element.widget(&app))
                    .map(|fade| fade.opacity.clone())
            })
            .expect("a FadeTransition above the label");
        fade.value(&app)
    }

    /// Dart's `_opacityAboveLabel(text)` found anything.
    fn has_opacity_above_label(tester: &WidgetTester, text: &str) -> bool {
        let text = find::text(text).evaluate(tester)[0];
        let ancestors = tester.ancestors(text);
        let app = tester.cell.borrow();
        ancestors.iter().any(|element| {
            waft_widgets::downcast_widget::<waft_widgets::Opacity>(&**element.widget(&app))
                .is_some()
        })
    }

    /// Dart's `_railMaterial`: the first material is for the rail, and the rest are for the
    /// destinations.
    fn rail_material<R>(tester: &WidgetTester, read: impl FnOnce(&Material) -> R) -> R {
        let rail = find::by_type::<NavigationRail>().evaluate(tester)[0];
        let material = tester.descendants_of_type::<Material>(rail)[0];
        tester.widget(material, read)
    }

    /// Dart's `expect(offset, equals(expected))` for a position Waft works out through
    /// valo's `f32` matrices: equal within `f32` precision.
    fn assert_offset(actual: Offset, expected: Offset) {
        let near = |a: f64, b: f64| (a - b).abs() <= 1e-4 * b.abs().max(1.0);
        assert!(
            near(actual.dx(), expected.dx()) && near(actual.dy(), expected.dy()),
            "{actual:?} (dx {}, dy {}) is not {expected:?} (dx {}, dy {})",
            actual.dx(),
            actual.dy(),
            expected.dx(),
            expected.dy()
        );
    }

    /// Asserts that the icon `render` is centred in a destination `destination_width` wide
    /// whose 32 high indicator starts at `next_destination_y`.
    fn expect_icon_at(
        tester: &WidgetTester,
        render: AnyRenderBox,
        destination_width: f64,
        destination_height: f64,
        next_destination_y: f64,
    ) {
        let size = tester.get_size(render);
        assert_offset(
            global_top_left(tester, render),
            Offset::new(
                (destination_width - size.width()) / 2.0,
                next_destination_y + (destination_height - size.height()) / 2.0,
            ),
        );
    }

    #[test]
    fn custom_selected_and_unselected_text_styles_are_honored() {
        test_widgets(|tester| {
            let selected_text_style = TextStyle::new()
                .font_weight(FontWeight::W300)
                .font_size(17.0);
            let unselected_text_style = TextStyle::new()
                .font_weight(FontWeight::W800)
                .font_size(11.0);
            pump_navigation_rail(
                tester,
                NavigationRail::new(destinations(), Some(0))
                    .label_type(NavigationRailLabelType::All)
                    .selected_label_text_style(selected_text_style.clone())
                    .unselected_label_text_style(unselected_text_style.clone()),
            );

            let actual_selected_text_style = paragraph_style(tester, "Abc");
            let actual_unselected_text_style = paragraph_style(tester, "Def");
            assert_eq!(
                actual_selected_text_style.font_size,
                selected_text_style.font_size
            );
            assert_eq!(
                actual_selected_text_style.font_weight,
                selected_text_style.font_weight
            );
            assert_eq!(
                actual_unselected_text_style.font_size,
                actual_unselected_text_style.font_size
            );
            assert_eq!(
                actual_unselected_text_style.font_weight,
                actual_unselected_text_style.font_weight
            );
        });
    }

    #[test]
    fn custom_selected_and_unselected_icon_themes_are_honored() {
        test_widgets(|tester| {
            let selected_icon_theme = IconThemeData::new()
                .size(36.0)
                .color(Color::new(0x00000001));
            let unselected_icon_theme = IconThemeData::new()
                .size(18.0)
                .color(Color::new(0x00000002));
            pump_navigation_rail(
                tester,
                NavigationRail::new(destinations(), Some(0))
                    .label_type(NavigationRailLabelType::All)
                    .selected_icon_theme(selected_icon_theme.clone())
                    .unselected_icon_theme(unselected_icon_theme.clone()),
            );

            let actual_selected_icon_theme = icon_style(tester, Icons::favorite());
            let actual_unselected_icon_theme = icon_style(tester, Icons::bookmark_border());
            assert_eq!(actual_selected_icon_theme.color, selected_icon_theme.color);
            assert_eq!(
                actual_selected_icon_theme.font_size,
                selected_icon_theme.size
            );
            assert_eq!(
                actual_unselected_icon_theme.color,
                unselected_icon_theme.color
            );
            assert_eq!(
                actual_unselected_icon_theme.font_size,
                unselected_icon_theme.size
            );
        });
    }

    #[test]
    fn no_selected_destination_when_selected_index_is_null() {
        test_widgets(|tester| {
            pump_navigation_rail(tester, NavigationRail::new(destinations(), None));

            let selected = find::by_type::<Semantics>()
                .evaluate(tester)
                .into_iter()
                .filter(|element| {
                    tester.widget(*element, |semantics: &Semantics| {
                        semantics.properties.selected.unwrap_or(false)
                    })
                })
                .count();
            assert_eq!(selected, 0);
        });
    }

    #[test]
    fn background_color_can_be_changed() {
        test_widgets(|tester| {
            pump_navigation_rail(
                tester,
                NavigationRail::new(destinations(), Some(0))
                    .label_type(NavigationRailLabelType::All),
            );

            // default surface color in M3 colorScheme
            assert_eq!(
                rail_material(tester, |material| material.color),
                Some(Color::new(0xfffef7ff))
            );

            pump_navigation_rail(
                tester,
                NavigationRail::new(destinations(), Some(0))
                    .label_type(NavigationRailLabelType::All)
                    .background_color(Colors::GREEN.primary()),
            );

            assert_eq!(
                rail_material(tester, |material| material.color),
                Some(Colors::GREEN.primary())
            );
        });
    }

    #[test]
    fn elevation_can_be_changed() {
        test_widgets(|tester| {
            pump_navigation_rail(
                tester,
                NavigationRail::new(destinations(), Some(0))
                    .label_type(NavigationRailLabelType::All),
            );

            assert_eq!(rail_material(tester, |material| material.elevation), 0.0);

            pump_navigation_rail(
                tester,
                NavigationRail::new(destinations(), Some(0))
                    .label_type(NavigationRailLabelType::All)
                    .elevation(7.0),
            );

            assert_eq!(rail_material(tester, |material| material.elevation), 7.0);
        });
    }

    #[test]
    fn renders_at_the_correct_default_width_label_type_none_default() {
        test_widgets(|tester| {
            pump_navigation_rail(tester, NavigationRail::new(destinations(), Some(0)));

            assert_eq!(tester.get_size(rail_box(tester)).width(), 80.0);
        });
    }

    #[test]
    fn renders_at_the_correct_default_width_label_type_selected() {
        test_widgets(|tester| {
            pump_navigation_rail(
                tester,
                NavigationRail::new(destinations(), Some(0))
                    .label_type(NavigationRailLabelType::Selected),
            );

            assert_eq!(tester.get_size(rail_box(tester)).width(), 80.0);
        });
    }

    #[test]
    fn renders_at_the_correct_default_width_label_type_all() {
        test_widgets(|tester| {
            pump_navigation_rail(
                tester,
                NavigationRail::new(destinations(), Some(0))
                    .label_type(NavigationRailLabelType::All),
            );

            assert_eq!(tester.get_size(rail_box(tester)).width(), 80.0);
        });
    }

    /// The `MaterialApp(home: Scaffold(body: Row([NavigationRail(..), Expanded(Text('body'))])))`
    /// that Dart's `StatefulBuilder` cases rebuild.
    fn pump_rail_in_app(tester: &mut WidgetTester, rail: NavigationRail) {
        pump_rail_in_app_with(tester, rail, true);
    }

    /// [`pump_rail_in_app`] under `ThemeData(useMaterial3: use_material3)`.
    fn pump_rail_in_app_with(tester: &mut WidgetTester, rail: NavigationRail, use_material3: bool) {
        let root = {
            let app = tester.cell.borrow();
            material_app(
                theme(&app, use_material3),
                Scaffold::new()
                    .body(Row::new().children([
                        rail.into_widget(),
                        Expanded::new(Text::new("body")).into_widget(),
                    ]))
                    .into_widget(),
            )
        };
        tester.pump_widget(root);
    }

    fn render_box_of_key(tester: &WidgetTester, key: &GlobalKey) -> AnyRenderBox {
        tester.render_object(key).as_box().expect("a render box")
    }

    #[test]
    fn leading_and_trailing_spacing_is_correct_with_0_2_destinations() {
        test_widgets(|tester| {
            // Padding at the top of the rail.
            let top_padding = 8.0;
            // Padding at after the leading widget.
            let spacer_padding = 8.0;
            // Width of a destination.
            let destination_width = 80.0;
            // Height of a destination indicator with icon.
            let destination_height = 32.0;
            // Space between destinations.
            let destination_spacing = 12.0;
            // Height of the leading and trailing widgets.
            let fab_height = 56.0;

            let leading_widget_key = GlobalKey::new();
            let trailing_widget_key = GlobalKey::new();
            let fab = |key: &GlobalKey| {
                FloatingActionButton::new(Some(Listener::new(|_| {})))
                    .key(KeyRef::from(key.clone()))
                    .into_widget()
            };
            let one = || {
                vec![destination(
                    Icons::favorite_border(),
                    Icons::favorite(),
                    "Abc",
                )]
            };
            let two = || {
                vec![
                    destination(Icons::favorite_border(), Icons::favorite(), "Abc"),
                    destination(Icons::bookmark_border(), Icons::bookmark(), "Longer Label"),
                ]
            };
            let match_expect = |tester: &WidgetTester, render: AnyRenderBox, y: f64| {
                expect_icon_at(tester, render, destination_width, destination_height, y)
            };
            let leading_at = |tester: &WidgetTester, key: &GlobalKey| {
                let render = render_box_of_key(tester, key);
                (global_top_left(tester, render), tester.get_size(render))
            };

            pump_rail_in_app(tester, NavigationRail::new(Vec::new(), None));

            // empty destinations and leading widget
            pump_rail_in_app(
                tester,
                NavigationRail::new(Vec::new(), None).leading(fab(&leading_widget_key)),
            );
            tester.pump_and_settle();
            assert_eq!(
                leading_at(tester, &leading_widget_key).0,
                Offset::new(0.0, top_padding)
            );

            // one destination and leading widget
            pump_rail_in_app(
                tester,
                NavigationRail::new(one(), None).leading(fab(&leading_widget_key)),
            );
            tester.pump_and_settle();
            let mut next_destination_y = top_padding;
            let (position, size) = leading_at(tester, &leading_widget_key);
            assert_eq!(
                position,
                Offset::new((destination_width - size.width()) / 2.0, next_destination_y)
            );

            next_destination_y += fab_height + spacer_padding + destination_spacing / 2.0;
            match_expect(
                tester,
                icon_render_box(tester, Icons::favorite_border()),
                next_destination_y,
            );

            // two destinations and leading widget
            pump_rail_in_app(
                tester,
                NavigationRail::new(two(), None).leading(fab(&leading_widget_key)),
            );
            tester.pump_and_settle();
            next_destination_y = top_padding;
            let (position, size) = leading_at(tester, &leading_widget_key);
            assert_eq!(
                position,
                Offset::new((destination_width - size.width()) / 2.0, next_destination_y)
            );

            next_destination_y += fab_height + spacer_padding + destination_spacing / 2.0;
            match_expect(
                tester,
                icon_render_box(tester, Icons::favorite_border()),
                next_destination_y,
            );

            next_destination_y += destination_height + destination_spacing;
            match_expect(
                tester,
                icon_render_box(tester, Icons::bookmark_border()),
                next_destination_y,
            );

            // empty destinations and trailing widget
            pump_rail_in_app(
                tester,
                NavigationRail::new(Vec::new(), None).trailing(fab(&trailing_widget_key)),
            );
            tester.pump_and_settle();
            assert_eq!(
                leading_at(tester, &trailing_widget_key).0,
                Offset::new(0.0, top_padding)
            );

            // one destination and trailing widget
            pump_rail_in_app(
                tester,
                NavigationRail::new(one(), None).trailing(fab(&trailing_widget_key)),
            );
            tester.pump_and_settle();
            next_destination_y = top_padding + destination_spacing / 2.0;
            match_expect(
                tester,
                icon_render_box(tester, Icons::favorite_border()),
                next_destination_y,
            );

            next_destination_y += destination_height + destination_spacing / 2.0;
            let (position, size) = leading_at(tester, &trailing_widget_key);
            assert_eq!(
                position,
                Offset::new((destination_width - size.width()) / 2.0, next_destination_y)
            );

            // two destinations and trailing widget
            pump_rail_in_app(
                tester,
                NavigationRail::new(two(), None).trailing(fab(&trailing_widget_key)),
            );
            tester.pump_and_settle();
            next_destination_y = top_padding + destination_spacing / 2.0;
            match_expect(
                tester,
                icon_render_box(tester, Icons::favorite_border()),
                next_destination_y,
            );

            next_destination_y += destination_height + destination_spacing;
            match_expect(
                tester,
                icon_render_box(tester, Icons::bookmark_border()),
                next_destination_y,
            );

            next_destination_y += destination_height + destination_spacing / 2.0;
            let (position, size) = leading_at(tester, &trailing_widget_key);
            assert_eq!(
                position,
                Offset::new((destination_width - size.width()) / 2.0, next_destination_y)
            );
        });
    }

    fn rail_widget<R>(tester: &WidgetTester, read: impl FnOnce(&NavigationRail) -> R) -> R {
        tester.widget(find::by_type::<NavigationRail>().evaluate(tester)[0], read)
    }

    #[test]
    fn change_destinations_and_selected_index() {
        test_widgets(|tester| {
            pump_rail_in_app(tester, NavigationRail::new(Vec::new(), None));

            assert_eq!(rail_widget(tester, |rail| rail.destinations.len()), 0);
            assert_eq!(rail_widget(tester, |rail| rail.selected_index), None);

            let two = || {
                vec![
                    destination(Icons::favorite_border(), Icons::favorite(), "Abc"),
                    destination(Icons::bookmark_border(), Icons::bookmark(), "Longer Label"),
                ]
            };
            pump_rail_in_app(tester, NavigationRail::new(two(), None));
            tester.pump_and_settle();

            assert_eq!(rail_widget(tester, |rail| rail.destinations.len()), 2);
            assert_eq!(rail_widget(tester, |rail| rail.selected_index), None);

            pump_rail_in_app(tester, NavigationRail::new(two(), Some(0)));
            tester.pump_and_settle();

            assert_eq!(rail_widget(tester, |rail| rail.destinations.len()), 2);
            assert_eq!(rail_widget(tester, |rail| rail.selected_index), Some(0));

            pump_rail_in_app(
                tester,
                NavigationRail::new(
                    vec![destination(
                        Icons::favorite_border(),
                        Icons::favorite(),
                        "Abc",
                    )],
                    Some(0),
                ),
            );
            tester.pump_and_settle();

            assert_eq!(rail_widget(tester, |rail| rail.destinations.len()), 1);
            assert_eq!(rail_widget(tester, |rail| rail.selected_index), Some(0));
        });
    }

    #[test]
    fn renders_wider_for_a_destination_with_a_long_label_label_type_all() {
        test_widgets(|tester| {
            pump_navigation_rail(
                tester,
                NavigationRail::new(
                    vec![
                        destination(Icons::favorite_border(), Icons::favorite(), "Abc"),
                        destination(Icons::bookmark_border(), Icons::bookmark(), "Longer Label"),
                    ],
                    Some(0),
                )
                .label_type(NavigationRailLabelType::All),
            );

            // Total padding is 16 (8 on each side).
            assert_eq!(
                tester.get_size(rail_box(tester)).width(),
                tester
                    .get_size(label_render_box(tester, "Longer Label"))
                    .width()
                    + 16.0
            );
        });
    }

    fn finds_one_icon(tester: &WidgetTester, icon: IconData) -> bool {
        find::by_type::<Icon>()
            .evaluate(tester)
            .into_iter()
            .filter(|element| {
                tester.widget(*element, |widget: &Icon| {
                    widget.icon.as_ref() == Some(&icon)
                })
            })
            .count()
            == 1
    }

    #[test]
    fn renders_only_icons_label_type_none_default() {
        test_widgets(|tester| {
            pump_navigation_rail(tester, NavigationRail::new(destinations(), Some(0)));

            assert!(finds_one_icon(tester, Icons::favorite()));
            assert!(finds_one_icon(tester, Icons::bookmark_border()));
            assert!(finds_one_icon(tester, Icons::star_border()));
            assert!(finds_one_icon(tester, Icons::hotel()));

            // When there are no labels, a 0 opacity label is still shown for semantics.
            assert_eq!(label_opacity(tester, "Abc"), 0.0);
            assert_eq!(label_opacity(tester, "Def"), 0.0);
            assert_eq!(label_opacity(tester, "Ghi"), 0.0);
            assert_eq!(label_opacity(tester, "Jkl"), 0.0);
        });
    }

    #[test]
    fn renders_icons_and_labels_label_type_all() {
        test_widgets(|tester| {
            pump_navigation_rail(
                tester,
                NavigationRail::new(destinations(), Some(0))
                    .label_type(NavigationRailLabelType::All),
            );

            assert!(finds_one_icon(tester, Icons::favorite()));
            assert!(finds_one_icon(tester, Icons::bookmark_border()));
            assert!(finds_one_icon(tester, Icons::star_border()));
            assert!(finds_one_icon(tester, Icons::hotel()));

            for label in ["Abc", "Def", "Ghi", "Jkl"] {
                expect(tester, &find::text(label), finds_one_widget());
                // When displaying all labels, there is no opacity.
                assert!(!has_opacity_above_label(tester, label));
            }
        });
    }

    #[test]
    fn renders_icons_and_selected_label_label_type_selected() {
        test_widgets(|tester| {
            pump_navigation_rail(
                tester,
                NavigationRail::new(destinations(), Some(0))
                    .label_type(NavigationRailLabelType::Selected),
            );

            assert!(finds_one_icon(tester, Icons::favorite()));
            assert!(finds_one_icon(tester, Icons::bookmark_border()));
            assert!(finds_one_icon(tester, Icons::star_border()));
            assert!(finds_one_icon(tester, Icons::hotel()));

            // Only the selected label is visible.
            assert_eq!(label_opacity(tester, "Abc"), 1.0);
            assert_eq!(label_opacity(tester, "Def"), 0.0);
            assert_eq!(label_opacity(tester, "Ghi"), 0.0);
            assert_eq!(label_opacity(tester, "Jkl"), 0.0);
        });
    }

    /// The icons of [`destinations`] in order: the first selected.
    fn icons_in_order() -> [IconData; 4] {
        [
            Icons::favorite(),
            Icons::bookmark_border(),
            Icons::star_border(),
            Icons::hotel(),
        ]
    }

    #[test]
    fn destination_spacing_is_correct_label_type_none_default_text_scale_factor_1_0_default() {
        test_widgets(|tester| {
            // Padding at the top of the rail.
            let top_padding = 8.0;
            // Width of a destination.
            let destination_width = 80.0;
            // Height of a destination indicator with icon.
            let destination_height = 32.0;
            // Space between destinations.
            let destination_padding = 12.0;

            pump_navigation_rail(tester, NavigationRail::new(destinations(), Some(0)));

            assert_eq!(tester.get_size(rail_box(tester)).width(), destination_width);

            // The first destination below the rail top by some padding.
            let mut next_destination_y = top_padding + destination_padding / 2.0;
            for icon in icons_in_order() {
                expect_icon_at(
                    tester,
                    icon_render_box(tester, icon),
                    destination_width,
                    destination_height,
                    next_destination_y,
                );
                // The next destination is one height below this destination.
                next_destination_y += destination_height + destination_padding;
            }
        });
    }

    /// Asserts each icon of [`icons_in_order`] centred `destination_width` wide in its 32 high
    /// indicator, the first at `first_y` and each next one `steps[i]` below the one before.
    fn expect_icon_column(
        tester: &WidgetTester,
        destination_width: f64,
        first_y: f64,
        steps: [f64; 3],
    ) {
        expect_icon_column_in(tester, destination_width, 32.0, first_y, steps);
    }

    /// [`expect_icon_column`] in destinations `destination_height` high.
    fn expect_icon_column_in(
        tester: &WidgetTester,
        destination_width: f64,
        destination_height: f64,
        first_y: f64,
        steps: [f64; 3],
    ) {
        let mut next_destination_y = first_y;
        for (i, icon) in icons_in_order().into_iter().enumerate() {
            expect_icon_at(
                tester,
                icon_render_box(tester, icon),
                destination_width,
                destination_height,
                next_destination_y,
            );
            if i < 3 {
                next_destination_y += steps[i];
            }
        }
    }

    /// Asserts the label `text` centred `destination_width` wide with its top at `y`.
    fn expect_label_at(tester: &WidgetTester, text: &str, destination_width: f64, y: f64) {
        let render = label_render_box(tester, text);
        let size = tester.get_size(render);
        assert_offset(
            global_top_left(tester, render),
            Offset::new((destination_width - size.width()) / 2.0, y),
        );
    }

    /// The icon-only destination spacing cases at `text_scale_factor`, `min_width` wide.
    fn icon_only_spacing(text_scale_factor: f64, min_width: Option<f64>) {
        test_widgets(|tester| {
            // Since the rail is icon only, its destinations should not be affected by
            // textScaleFactor.

            // Padding at the top of the rail.
            let top_padding = 8.0;
            // Width of a destination.
            let destination_width = min_width.unwrap_or(80.0);
            // Height of a destination indicator with icon.
            let destination_height = 32.0;
            // Space between destinations.
            let destination_padding = 12.0;

            let mut rail = NavigationRail::new(destinations(), Some(0));
            if let Some(min_width) = min_width {
                rail = rail.min_width(min_width);
            }
            pump_navigation_rail_with(
                tester,
                rail,
                Pump {
                    text_scale_factor,
                    ..Pump::default()
                },
            );

            assert_eq!(tester.get_size(rail_box(tester)).width(), destination_width);

            // The first destination below the rail top by some padding; each next one is
            // one height below the one before.
            let step = destination_height + destination_padding;
            expect_icon_column(
                tester,
                destination_width,
                top_padding + destination_padding / 2.0,
                [step; 3],
            );
        });
    }

    #[test]
    fn destination_spacing_is_correct_label_type_none_default_text_scale_factor_3_0() {
        icon_only_spacing(3.0, None);
    }

    #[test]
    fn destination_spacing_is_correct_label_type_none_default_text_scale_factor_0_75() {
        icon_only_spacing(0.75, None);
    }

    #[test]
    fn destination_spacing_is_correct_for_a_compact_rail_preferred_width_56_text_scale_factor_1_0_default()
     {
        icon_only_spacing(1.0, Some(56.0));
    }

    #[test]
    fn destination_spacing_is_correct_for_a_compact_rail_preferred_width_56_text_scale_factor_3_0()
    {
        icon_only_spacing(3.0, Some(56.0));
    }

    #[test]
    fn destination_spacing_is_correct_for_a_compact_rail_preferred_width_56_text_scale_factor_0_75()
    {
        icon_only_spacing(0.75, Some(56.0));
    }

    /// The labelled destination spacing cases: `label_type` at `text_scale_factor`, whose
    /// destinations are `destination_width` wide.
    fn labelled_spacing(
        label_type: NavigationRailLabelType,
        text_scale_factor: f64,
        destination_width: f64,
    ) {
        test_widgets(|tester| {
            // Padding at the top of the rail.
            let top_padding = 8.0;
            // Height of a destination indicator with icon.
            let destination_height = 32.0;
            // Space between the indicator and label.
            let destination_label_spacing = 4.0;
            // Height of the label.
            let label_height = 16.0 * text_scale_factor;
            // Height of a destination with both icon and label.
            let destination_height_with_label =
                destination_height + destination_label_spacing + label_height;
            // Space between destinations.
            let destination_spacing = 12.0;

            pump_navigation_rail_with(
                tester,
                NavigationRail::new(destinations(), Some(0)).label_type(label_type),
                Pump {
                    text_scale_factor,
                    ..Pump::default()
                },
            );

            assert_eq!(tester.get_size(rail_box(tester)).width(), destination_width);

            // The first destination topPadding below the rail top.
            let next_destination_y = top_padding;
            expect_label_at(
                tester,
                "Abc",
                destination_width,
                next_destination_y + destination_height + destination_label_spacing,
            );

            // Each destination is below the one before with some spacing; with
            // [labelType]=selected, only the first shows its label.
            let labelled = destination_height_with_label + destination_spacing;
            let unlabelled = match label_type {
                NavigationRailLabelType::Selected => destination_height + destination_spacing,
                _ => labelled,
            };
            expect_icon_column(
                tester,
                destination_width,
                next_destination_y,
                [labelled, unlabelled, unlabelled],
            );
        });
    }

    #[test]
    fn destination_spacing_is_correct_label_type_selected_text_scale_factor_1_0_default() {
        labelled_spacing(NavigationRailLabelType::Selected, 1.0, 80.0);
    }

    #[test]
    fn destination_spacing_is_correct_label_type_selected_text_scale_factor_3_0() {
        labelled_spacing(NavigationRailLabelType::Selected, 3.0, 125.5);
    }

    #[test]
    fn destination_spacing_is_correct_label_type_selected_text_scale_factor_0_75() {
        labelled_spacing(NavigationRailLabelType::Selected, 0.75, 80.0);
    }

    #[test]
    fn destination_spacing_is_correct_label_type_all_text_scale_factor_1_0_default() {
        labelled_spacing(NavigationRailLabelType::All, 1.0, 80.0);
    }

    #[test]
    fn destination_spacing_is_correct_label_type_all_text_scale_factor_3_0() {
        labelled_spacing(NavigationRailLabelType::All, 3.0, 125.5);
    }

    #[test]
    fn destination_spacing_is_correct_label_type_all_text_scale_factor_0_75() {
        labelled_spacing(NavigationRailLabelType::All, 0.75, 80.0);
    }

    /// The group alignment cases: the destinations `offset` below where they start at the top.
    fn group_alignment(group_alignment: Option<f64>, offset: f64) {
        test_widgets(|tester| {
            // Padding at the top of the rail.
            let top_padding = 8.0;
            // Width of a destination.
            let destination_width = 80.0;
            // Height of a destination indicator with icon.
            let destination_height = 32.0;
            // Space between destinations.
            let destination_padding = 12.0;

            let mut rail = NavigationRail::new(destinations(), Some(0));
            if let Some(group_alignment) = group_alignment {
                rail = rail.group_alignment(group_alignment);
            }
            pump_navigation_rail(tester, rail);

            assert_eq!(tester.get_size(rail_box(tester)).width(), destination_width);

            // The first destination below the rail top by some padding with an offset for the
            // alignment.
            let step = destination_height + destination_padding;
            expect_icon_column(
                tester,
                destination_width,
                top_padding + destination_padding / 2.0 + offset,
                [step; 3],
            );
        });
    }

    #[test]
    fn group_alignment_works_group_alignment_minus_1_0_default() {
        group_alignment(None, 0.0);
    }

    #[test]
    fn group_alignment_works_group_alignment_0_0() {
        group_alignment(Some(0.0), 208.0);
    }

    #[test]
    fn group_alignment_works_group_alignment_1_0() {
        group_alignment(Some(1.0), 416.0);
    }

    fn fab() -> WidgetRef {
        FloatingActionButton::new(Some(Listener::new(|_| {}))).into_widget()
    }

    #[test]
    fn leading_and_trailing_appear_in_the_correct_places() {
        test_widgets(|tester| {
            pump_navigation_rail(
                tester,
                NavigationRail::new(destinations(), Some(0))
                    .leading(fab())
                    .trailing(fab()),
            );

            let fabs = find::by_type::<FloatingActionButton>().evaluate(tester);
            let leading = tester.render_box_of(fabs[0]);
            let trailing = tester.render_box_of(fabs[1]);
            assert_eq!(
                global_top_left(tester, leading),
                Offset::new((80.0 - tester.get_size(leading).width()) / 2.0, 8.0)
            );
            assert_eq!(
                global_top_left(tester, trailing),
                Offset::new((80.0 - tester.get_size(trailing).width()) / 2.0, 248.0)
            );
        });
    }

    /// What Dart's `stateSetter` cases pump: `rail` in the app, then the frame
    /// `tester.pump()` runs.
    fn set_rail(tester: &mut WidgetTester, rail: NavigationRail) {
        pump_rail_in_app(tester, rail);
    }

    #[test]
    fn extended_rail_animates_the_width_and_labels_appear_text_direction_ltr() {
        test_widgets(|tester| {
            // Padding at the top of the rail.
            let top_padding = 8.0;
            // Width of a destination.
            let destination_width = 80.0;
            // Height of a destination indicator with icon.
            let destination_height = 32.0;
            // Space between destinations.
            let destination_padding = 12.0;

            pump_rail_in_app(tester, NavigationRail::new(destinations(), Some(0)));

            let rail = rail_box(tester);
            assert_eq!(tester.get_size(rail).width(), destination_width);

            set_rail(
                tester,
                NavigationRail::new(destinations(), Some(0)).extended(true),
            );
            tester.pump_by(Duration::from_millis(100));
            assert_eq!(tester.get_size(rail).width(), 168.0);

            tester.pump_and_settle();
            assert_eq!(tester.get_size(rail).width(), 256.0);

            // The first destination below the rail top by some padding.
            let mut next_destination_y = top_padding + destination_padding / 2.0;
            for (icon, label) in icons_in_order()
                .into_iter()
                .zip(["Abc", "Def", "Ghi", "Jkl"])
            {
                expect_icon_at(
                    tester,
                    icon_render_box(tester, icon),
                    destination_width,
                    destination_height,
                    next_destination_y,
                );
                let label = label_render_box(tester, label);
                assert_offset(
                    global_top_left(tester, label),
                    Offset::new(
                        destination_width,
                        next_destination_y
                            + (destination_height - tester.get_size(label).height()) / 2.0,
                    ),
                );
                // The next destination is one height below this destination.
                next_destination_y += destination_height + destination_padding;
            }
        });
    }

    /// The `Directionality(rtl, Scaffold(body: Row(textDirection: rtl, [rail, body])))` of the
    /// RTL extended case.
    fn pump_rtl_rail(tester: &mut WidgetTester, rail: NavigationRail) {
        pump_rtl_rail_with(tester, rail, true);
    }

    /// [`pump_rtl_rail`] under `ThemeData(useMaterial3: use_material3)`.
    fn pump_rtl_rail_with(tester: &mut WidgetTester, rail: NavigationRail, use_material3: bool) {
        let root = {
            let app = tester.cell.borrow();
            material_app(
                theme(&app, use_material3),
                Directionality::new(
                    TextDirection::Rtl,
                    Scaffold::new().body(Row::new().text_direction(TextDirection::Rtl).children([
                        rail.into_widget(),
                        Expanded::new(Text::new("body")).into_widget(),
                    ])),
                )
                .into_widget(),
            )
        };
        tester.pump_widget(root);
    }

    #[test]
    fn extended_rail_animates_the_width_and_labels_appear_text_direction_rtl() {
        test_widgets(|tester| {
            // Padding at the top of the rail.
            let top_padding = 8.0;
            // Width of a destination.
            let destination_width = 80.0;
            // Height of a destination indicator with icon.
            let destination_height = 32.0;
            // Space between destinations.
            let destination_padding = 12.0;

            pump_rtl_rail(tester, NavigationRail::new(destinations(), Some(0)));

            let rail = rail_box(tester);
            assert_eq!(tester.get_size(rail).width(), destination_width);
            assert_eq!(global_top_left(tester, rail), Offset::new(720.0, 0.0));

            pump_rtl_rail(
                tester,
                NavigationRail::new(destinations(), Some(0)).extended(true),
            );
            tester.pump_by(Duration::from_millis(100));
            assert_eq!(tester.get_size(rail).width(), 168.0);
            assert_eq!(global_top_left(tester, rail), Offset::new(632.0, 0.0));

            tester.pump_and_settle();
            assert_eq!(tester.get_size(rail).width(), 256.0);
            assert_eq!(global_top_left(tester, rail), Offset::new(544.0, 0.0));

            // The first destination below the rail top by some padding.
            let mut next_destination_y = top_padding + destination_padding / 2.0;
            for (icon, label) in icons_in_order()
                .into_iter()
                .zip(["Abc", "Def", "Ghi", "Jkl"])
            {
                let icon = icon_render_box(tester, icon);
                let icon_size = tester.get_size(icon);
                assert_offset(
                    global_top_left(tester, icon),
                    Offset::new(
                        800.0 - (destination_width + icon_size.width()) / 2.0,
                        next_destination_y + (destination_height - icon_size.height()) / 2.0,
                    ),
                );
                let label = label_render_box(tester, label);
                let label_size = tester.get_size(label);
                assert_offset(
                    global_top_left(tester, label),
                    Offset::new(
                        800.0 - destination_width - label_size.width(),
                        next_destination_y + (destination_height - label_size.height()) / 2.0,
                    ),
                );
                // The next destination is one height below this destination.
                next_destination_y += destination_height + destination_padding;
            }
        });
    }

    fn abc_and_longer_label() -> Vec<NavigationRailDestination> {
        vec![
            destination(Icons::favorite_border(), Icons::favorite(), "Abc"),
            destination(Icons::bookmark_border(), Icons::bookmark(), "Longer Label"),
        ]
    }

    #[test]
    fn extended_rail_gets_wider_with_longer_labels_are_larger_text_scale() {
        test_widgets(|tester| {
            let pump = |tester: &mut WidgetTester, extended: bool| {
                let root = {
                    let app = tester.cell.borrow();
                    material_app(
                        ThemeData::new(&app),
                        Scaffold::new()
                            .body(
                                Row::new().children([
                                    MediaQuery::with_clamped_text_scaling(
                                        None,
                                        3.0,
                                        3.0,
                                        NavigationRail::new(abc_and_longer_label(), Some(0))
                                            .extended(extended),
                                    ),
                                    Expanded::new(Text::new("body")).into_widget(),
                                ]),
                            )
                            .into_widget(),
                    )
                };
                tester.pump_widget(root);
            };
            pump(tester, false);

            let rail = rail_box(tester);
            assert_eq!(tester.get_size(rail).width(), 80.0);

            pump(tester, true);
            tester.pump_by(Duration::from_millis(100));
            assert_eq!(tester.get_size(rail).width(), 303.0);

            tester.pump_and_settle();
            assert_eq!(tester.get_size(rail).width(), 526.0);
        });
    }

    #[test]
    fn extended_rail_final_width_can_be_changed() {
        test_widgets(|tester| {
            pump_rail_in_app(
                tester,
                NavigationRail::new(destinations(), Some(0)).min_extended_width(300.0),
            );

            let rail = rail_box(tester);
            assert_eq!(tester.get_size(rail).width(), 80.0);

            set_rail(
                tester,
                NavigationRail::new(destinations(), Some(0))
                    .min_extended_width(300.0)
                    .extended(true),
            );
            tester.pump_and_settle();
            assert_eq!(tester.get_size(rail).width(), 300.0);
        });
    }

    /// Regression test for https://github.com/flutter/flutter/issues/65657
    #[test]
    fn extended_rail_transition_does_not_jump_from_the_beginning() {
        test_widgets(|tester| {
            pump_rail_in_app(tester, NavigationRail::new(abc_and_longer_label(), Some(0)));

            // Before starting the animation, the rail has a width of 80.
            assert_eq!(tester.get_size(rail_box(tester)).width(), 80.0);

            set_rail(
                tester,
                NavigationRail::new(abc_and_longer_label(), Some(0)).extended(true),
            );
            // Create very close to 0, but non-zero, animation value.
            tester.pump_by(Duration::from_millis(1));
            let width = tester.get_size(rail_box(tester)).width();
            // Expect that it has started to extend.
            assert!(width > 80.0, "{width}");
            // Expect that it has only extended by a small amount, or that the first
            // frame does not jump. This helps verify that it is a smooth animation.
            assert!((width - 80.0).abs() <= 1.0, "{width}");
        });
    }

    #[test]
    fn extended_rail_animation_can_be_consumed() {
        test_widgets(|tester| {
            let animation: Rc<std::cell::Cell<Option<AnyAnimation<f64>>>> = Rc::default();
            let rail = |extended: bool| {
                let animation = Rc::clone(&animation);
                NavigationRail::new(destinations(), Some(0))
                    .leading(Builder::new(move |app, context| {
                        animation.set(Some(NavigationRail::extended_animation(app, context)));
                        fab()
                    }))
                    .extended(extended)
            };
            pump_rail_in_app(tester, rail(false));

            let read = |tester: &WidgetTester| {
                animation
                    .get()
                    .expect("the leading widget was built")
                    .status(&tester.cell.borrow())
            };
            assert!(read(tester).is_dismissed());

            set_rail(tester, rail(true));
            tester.pump_and_settle();

            assert!(read(tester).is_completed());
        });
    }

    fn center_of_element(tester: &WidgetTester, element: AnyElement) -> Offset {
        tester.get_rect(element).center()
    }

    fn center_of_text(tester: &WidgetTester, text: &str) -> Offset {
        center_of_element(tester, find::text(text).evaluate(tester)[0])
    }

    fn center_of_icon(tester: &WidgetTester, icon: IconData) -> Offset {
        center_of_element(tester, tester.element(find::by_icon(&icon).first()))
    }

    #[test]
    fn on_destination_selected_is_called() {
        test_widgets(|tester| {
            let selected_index = Rc::new(std::cell::Cell::new(None));
            let seen = Rc::clone(&selected_index);
            pump_navigation_rail(
                tester,
                NavigationRail::new(destinations(), Some(0))
                    .on_destination_selected(move |_app, index| seen.set(Some(index)))
                    .label_type(NavigationRailLabelType::All),
            );

            tester.tap_at(center_of_text(tester, "Def"), 1);
            assert_eq!(selected_index.get(), Some(1));

            tester.tap_at(center_of_text(tester, "Ghi"), 2);
            assert_eq!(selected_index.get(), Some(2));

            // Wait for any pending shader compilation.
            tester.pump_and_settle();
        });
    }

    #[test]
    fn on_destination_selected_is_not_called_if_null() {
        test_widgets(|tester| {
            let selected_index = 0;
            pump_navigation_rail(
                tester,
                NavigationRail::new(destinations(), Some(selected_index))
                    .label_type(NavigationRailLabelType::All),
            );

            tester.tap_at(center_of_text(tester, "Def"), 1);
            assert_eq!(selected_index, 0);

            // Wait for any pending shader compilation.
            tester.pump_and_settle();
        });
    }

    #[test]
    fn changing_destinations_animate_when_label_type_selected() {
        test_widgets(|tester| {
            let selected_index = Rc::new(std::cell::Cell::new(0_usize));
            let root = {
                let app = tester.cell.borrow();
                let selected_index = Rc::clone(&selected_index);
                material_app(
                    ThemeData::new(&app),
                    waft_widgets::StatefulBuilder::new(move |_app, _context, set_state| {
                        let selected = Rc::clone(&selected_index);
                        Scaffold::new()
                            .body(
                                Row::new().children([
                                    NavigationRail::new(destinations(), Some(selected_index.get()))
                                        .label_type(NavigationRailLabelType::Selected)
                                        .on_destination_selected(move |app, index| {
                                            let selected = Rc::clone(&selected);
                                            set_state(app, &mut |_app| selected.set(index));
                                        })
                                        .into_widget(),
                                    Expanded::new(Text::new("body")).into_widget(),
                                ]),
                            )
                            .into_widget()
                    })
                    .into_widget(),
                )
            };
            tester.pump_widget(root);

            // Tap the second destination.
            tester.tap_at(center_of_icon(tester, Icons::bookmark_border()), 1);
            assert_eq!(selected_index.get(), 1);

            // The second destination animates in.
            assert_eq!(label_opacity(tester, "Def"), 0.0);
            tester.pump();
            tester.pump_by(Duration::from_millis(100));
            assert_eq!(label_opacity(tester, "Def"), 0.5);
            tester.pump_and_settle();
            assert_eq!(label_opacity(tester, "Def"), 1.0);

            // Tap the third destination.
            tester.tap_at(center_of_icon(tester, Icons::star_border()), 2);
            assert_eq!(selected_index.get(), 2);

            // The second destination animates out quickly and the third destination
            // animates in.
            assert_eq!(label_opacity(tester, "Ghi"), 0.0);
            tester.pump();
            tester.pump_by(Duration::from_millis(25));
            assert_eq!(label_opacity(tester, "Def"), 0.5);
            assert_eq!(label_opacity(tester, "Ghi"), 0.0);
            tester.pump();
            tester.pump_by(Duration::from_millis(25));
            assert_eq!(label_opacity(tester, "Def"), 0.0);
            assert_eq!(label_opacity(tester, "Ghi"), 0.0);
            tester.pump();
            tester.pump_by(Duration::from_millis(50));
            assert_eq!(label_opacity(tester, "Ghi"), 0.5);
            tester.pump_and_settle();
            assert_eq!(label_opacity(tester, "Ghi"), 1.0);
        });
    }

    fn selected_rail(selected_index: Option<usize>) -> NavigationRail {
        NavigationRail::new(destinations(), selected_index)
            .label_type(NavigationRailLabelType::Selected)
    }

    #[test]
    fn changing_destinations_animate_for_selected_index_null() {
        test_widgets(|tester| {
            pump_rail_in_app(tester, selected_rail(Some(0)));

            // Unset the selected index.
            set_rail(tester, selected_rail(None));

            // The first destination animates out.
            assert_eq!(label_opacity(tester, "Abc"), 1.0);
            tester.pump_by(Duration::from_millis(25));
            assert_eq!(label_opacity(tester, "Abc"), 0.5);
            tester.pump_and_settle();
            assert_eq!(label_opacity(tester, "Abc"), 0.0);

            // Set the selected index to the first destination.
            set_rail(tester, selected_rail(Some(0)));

            // The first destination animates in.
            assert_eq!(label_opacity(tester, "Abc"), 0.0);
            tester.pump_by(Duration::from_millis(100));
            assert_eq!(label_opacity(tester, "Abc"), 0.5);
            tester.pump_and_settle();
            assert_eq!(label_opacity(tester, "Abc"), 1.0);
        });
    }

    /// Dart's `StatefulBuilder` over a rail of the `selected_index` it keeps, with the
    /// `stateSetter` the case calls without pumping a frame.
    struct StatefulRail {
        selected_index: Rc<std::cell::Cell<Option<usize>>>,
        set_state: Rc<std::cell::RefCell<Option<waft_widgets::StateSetter>>>,
    }

    impl StatefulRail {
        fn pump(
            tester: &mut WidgetTester,
            selected_index: Option<usize>,
            make: fn(Option<usize>) -> NavigationRail,
        ) -> StatefulRail {
            let rail = StatefulRail {
                selected_index: Rc::new(std::cell::Cell::new(selected_index)),
                set_state: Rc::default(),
            };
            let root = {
                let app = tester.cell.borrow();
                let selected_index = Rc::clone(&rail.selected_index);
                let state_setter = Rc::clone(&rail.set_state);
                material_app(
                    ThemeData::new(&app),
                    waft_widgets::StatefulBuilder::new(move |_app, _context, set_state| {
                        *state_setter.borrow_mut() = Some(set_state);
                        Scaffold::new()
                            .body(Row::new().children([
                                make(selected_index.get()).into_widget(),
                                Expanded::new(Text::new("body")).into_widget(),
                            ]))
                            .into_widget()
                    })
                    .into_widget(),
                )
            };
            tester.pump_widget(root);
            rail
        }

        /// Dart's `stateSetter(() { selectedIndex = selected_index; })`.
        fn set_selected_index(&self, tester: &WidgetTester, selected_index: Option<usize>) {
            let set_state = self
                .set_state
                .borrow()
                .clone()
                .expect("the builder was built");
            let selected = Rc::clone(&self.selected_index);
            set_state(&mut tester.cell.borrow_mut(), &mut |_app| {
                selected.set(selected_index)
            });
        }
    }

    #[test]
    fn changing_destinations_animate_when_selected_index_null_during_transition() {
        test_widgets(|tester| {
            let rail = StatefulRail::pump(tester, Some(0), selected_rail);

            rail.set_selected_index(tester, Some(1));

            tester.pump();
            tester.pump_by(Duration::from_millis(175));

            // Interrupt while animating from index 0 to 1.
            rail.set_selected_index(tester, None);

            assert_eq!(label_opacity(tester, "Abc"), 0.0);
            assert_eq!(label_opacity(tester, "Def"), 1.0);

            tester.pump();
            // Create very close to 0, but non-zero, animation value.
            tester.pump_by(Duration::from_millis(1));
            // Ensure the opacity is animated back towards 0.
            let def = label_opacity(tester, "Def");
            assert!(def < 0.5, "{def}");
            assert!((def - 0.5).abs() <= 0.03, "{def}");

            tester.pump_and_settle();
            assert_eq!(label_opacity(tester, "Abc"), 0.0);
            assert_eq!(label_opacity(tester, "Def"), 0.0);
        });
    }

    fn abc_def_ghi_with_padding() -> Vec<NavigationRailDestination> {
        vec![
            destination(Icons::favorite_border(), Icons::favorite(), "Abc"),
            destination(Icons::bookmark_border(), Icons::bookmark(), "Def")
                .padding(EdgeInsetsGeometry::symmetric(30.0, 0.0)),
            destination(Icons::star_border(), Icons::star(), "Ghi")
                .padding(EdgeInsetsGeometry::symmetric(0.0, 10.0)),
        ]
    }

    /// Dart's `tester.widget<Padding>(find.descendant(of: find.widgetWithText(
    /// _IndicatorInkWell, text), matching: find.widgetWithText(Padding, text))).padding`: the
    /// one `Padding` between the destination's ink well and its label.
    fn destination_padding(tester: &WidgetTester, text: &str) -> EdgeInsetsGeometry {
        let text = find::text(text).evaluate(tester)[0];
        let ancestors = tester.ancestors(text);
        let app = tester.cell.borrow();
        let below_ink_well: Vec<&AnyElement> = ancestors
            .iter()
            .take_while(|element| {
                waft_widgets::downcast_widget::<InkResponse>(&**element.widget(&app)).is_none()
            })
            .collect();
        assert!(
            below_ink_well.len() < ancestors.len(),
            "the label is inside an ink well"
        );
        let paddings: Vec<EdgeInsetsGeometry> = below_ink_well
            .into_iter()
            .filter_map(|element| {
                waft_widgets::downcast_widget::<Padding>(&**element.widget(&app))
                    .map(|padding| padding.padding)
            })
            .collect();
        assert_eq!(
            paddings.len(),
            1,
            "one Padding between the ink well and the label"
        );
        paddings[0]
    }

    fn padding_properly_applied(
        label_type: NavigationRailLabelType,
        default_padding: EdgeInsetsGeometry,
    ) {
        test_widgets(|tester| {
            let second_item_padding = EdgeInsetsGeometry::symmetric(30.0, 0.0);
            let third_item_padding = EdgeInsetsGeometry::symmetric(0.0, 10.0);

            pump_navigation_rail(
                tester,
                NavigationRail::new(abc_def_ghi_with_padding(), Some(0)).label_type(label_type),
            );

            assert_eq!(destination_padding(tester, "Abc"), default_padding);
            assert_eq!(destination_padding(tester, "Def"), second_item_padding);
            assert_eq!(destination_padding(tester, "Ghi"), third_item_padding);
        });
    }

    #[test]
    fn navigation_rail_destination_padding_properly_applied_navigation_rail_label_type_all() {
        padding_properly_applied(
            NavigationRailLabelType::All,
            EdgeInsetsGeometry::symmetric(0.0, 8.0),
        );
    }

    #[test]
    fn navigation_rail_destination_padding_properly_applied_navigation_rail_label_type_selected() {
        padding_properly_applied(
            NavigationRailLabelType::Selected,
            EdgeInsetsGeometry::symmetric(0.0, 8.0),
        );
    }

    #[test]
    fn navigation_rail_destination_padding_properly_applied_navigation_rail_label_type_none() {
        padding_properly_applied(NavigationRailLabelType::None, EdgeInsetsGeometry::ZERO);
    }

    fn abc_def_ghi() -> Vec<NavigationRailDestination> {
        vec![
            destination(Icons::favorite_border(), Icons::favorite(), "Abc"),
            destination(Icons::bookmark_border(), Icons::bookmark(), "Def"),
            destination(Icons::star_border(), Icons::star(), "Ghi"),
        ]
    }

    #[test]
    fn navigation_rail_destination_adds_indicator_by_default_when_theme_data_use_material3_is_true()
    {
        test_widgets(|tester| {
            pump_navigation_rail(
                tester,
                NavigationRail::new(abc_def_ghi(), Some(0))
                    .label_type(NavigationRailLabelType::Selected),
            );

            expect(
                tester,
                &find::by_type::<NavigationIndicator>(),
                finds_widgets(),
            );
        });
    }

    #[test]
    fn navigation_rail_destination_adds_indicator_when_use_indicator_is_true() {
        test_widgets(|tester| {
            pump_navigation_rail(
                tester,
                NavigationRail::new(abc_def_ghi(), Some(0))
                    .use_indicator(true)
                    .label_type(NavigationRailLabelType::Selected),
            );

            expect(
                tester,
                &find::by_type::<NavigationIndicator>(),
                finds_widgets(),
            );
        });
    }

    #[test]
    fn navigation_rail_destination_does_not_add_indicator_when_use_indicator_is_false() {
        test_widgets(|tester| {
            pump_navigation_rail(
                tester,
                NavigationRail::new(abc_def_ghi(), Some(0))
                    .use_indicator(false)
                    .label_type(NavigationRailLabelType::Selected),
            );

            expect(
                tester,
                &find::by_type::<NavigationIndicator>(),
                finds_nothing(),
            );
        });
    }

    fn adds_an_oval_indicator(label_type: NavigationRailLabelType) {
        test_widgets(|tester| {
            pump_navigation_rail(
                tester,
                NavigationRail::new(abc_def_ghi(), Some(0))
                    .use_indicator(true)
                    .label_type(label_type),
            );

            let indicator = find::by_type::<NavigationIndicator>().evaluate(tester)[0];
            let (width, height) = tester.widget(indicator, |indicator: &NavigationIndicator| {
                (indicator.width, indicator.height)
            });
            assert_eq!(width, 56.0);
            assert_eq!(height, 32.0);
        });
    }

    #[test]
    fn navigation_rail_destination_adds_an_oval_indicator_when_no_labels_are_present() {
        adds_an_oval_indicator(NavigationRailLabelType::None);
    }

    #[test]
    fn navigation_rail_destination_adds_an_oval_indicator_when_selected_labels_are_present() {
        adds_an_oval_indicator(NavigationRailLabelType::Selected);
    }

    #[test]
    fn navigation_rail_destination_adds_an_oval_indicator_when_all_labels_are_present() {
        adds_an_oval_indicator(NavigationRailLabelType::All);
    }

    /// The destinations of "has center aligned indicator": the first icon in a `Stack` with a
    /// small text over its corner.
    fn umbrella_destinations() -> Vec<NavigationRailDestination> {
        vec![
            NavigationRailDestination::new(
                Stack::new().children([
                    Icon::new(Some(Icons::umbrella())).into_widget(),
                    waft_widgets::Positioned::new(
                        Text::new("Text").style(
                            TextStyle::new()
                                .font_size(10.0)
                                .color(Colors::RED.primary()),
                        ),
                    )
                    .top(0.0)
                    .right(0.0)
                    .into_widget(),
                ]),
                Text::new("Abc"),
            ),
            NavigationRailDestination::new(Icon::new(Some(Icons::umbrella())), Text::new("Def")),
            NavigationRailDestination::new(
                Icon::new(Some(Icons::bookmark_border())),
                Text::new("Ghi"),
            ),
        ]
    }

    fn has_center_aligned_indicator(use_material3: bool, dx: f64) {
        test_widgets(|tester| {
            // This is a regression test for
            // https://github.com/flutter/flutter/issues/97753
            pump_navigation_rail_with(
                tester,
                NavigationRail::new(umbrella_destinations(), Some(0))
                    .label_type(NavigationRailLabelType::None),
                Pump {
                    use_material3,
                    ..Pump::default()
                },
            );
            let icons = find::by_type::<Icon>().evaluate(tester);
            // Indicator with Stack widget
            let first_indicator = tester.render_box_of(icons[0]);
            assert_eq!(global_top_left(tester, first_indicator).dx(), dx);
            // Indicator without Stack widget
            let last_indicator = tester.render_box_of(*icons.last().expect("icons"));
            assert_eq!(global_top_left(tester, last_indicator).dx(), dx);
        });
    }

    #[test]
    fn navigation_rail_destination_has_center_aligned_indicator_label_type_none() {
        has_center_aligned_indicator(true, 28.0);
    }

    fn two_destinations() -> Vec<NavigationRailDestination> {
        vec![
            destination(Icons::favorite_border(), Icons::favorite(), "Abc"),
            destination(Icons::bookmark_border(), Icons::bookmark(), "Def"),
        ]
    }

    fn respects_the_notch(use_material3: bool, default_rail_width: f64) {
        test_widgets(|tester| {
            let safe_area_padding = 40.0;
            let with_padding = |padding: EdgeInsets| {
                MediaQuery::new(
                    waft_widgets::MediaQueryData::new().padding(padding),
                    NavigationRail::new(two_destinations(), Some(0)),
                )
                .into_widget()
            };

            pump_built_widget(
                tester,
                NavigationRail::new(two_destinations(), Some(0)),
                use_material3,
                false,
            );
            let default_width = tester.get_size(rail_box(tester)).width();
            assert_eq!(default_width, default_rail_width);

            pump_built_widget(
                tester,
                with_padding(EdgeInsets::only(safe_area_padding, 0.0, 0.0, 0.0)),
                use_material3,
                false,
            );
            let updated_width = tester.get_size(rail_box(tester)).width();
            assert_eq!(updated_width, default_width + safe_area_padding);

            // test width when text direction is RTL.
            pump_built_widget(
                tester,
                with_padding(EdgeInsets::only(0.0, 0.0, safe_area_padding, 0.0)),
                use_material3,
                true,
            );
            let updated_width_rtl = tester.get_size(rail_box(tester)).width();
            assert_eq!(updated_width_rtl, default_width + safe_area_padding);
        });
    }

    #[test]
    fn navigation_rail_respects_the_notch_system_navigation_bar_in_landscape_mode() {
        respects_the_notch(true, 80.0);
    }

    /// What the ink features of the rail's materials draw, in tree order: Dart's `paints` on
    /// the first `_RenderInkFeatures`, the scaffold's, whose paint reaches theirs.
    fn rail_ink_ops(tester: &WidgetTester) -> Vec<waft_embedder::valo::Op> {
        let rail = rail_box(tester).as_object();
        let features = tester.all::<crate::material::RenderInkFeatures>();
        let mut ops = Vec::new();
        for render in features {
            let under_rail = {
                let app = tester.cell.borrow();
                std::iter::successors(
                    Some(waft_rendering::RenderBox::as_object(render)),
                    |object| object.parent(&app),
                )
                .any(|object| object == rail)
            };
            if under_rail {
                let mut canvas = waft_embedder::Canvas::new();
                render.paint_ink_features(&mut tester.cell.borrow_mut(), &mut canvas, Offset::ZERO);
                ops.extend(canvas.build().ops().iter().cloned());
            }
        }
        ops
    }

    /// Dart's `paints..clipPath(pathMatcher: isPathThat(includes: [the edge midpoints of
    /// indicator_rect], excludes: [those of indicator_rect.inflate(10)]))..rect(rect:
    /// indicator_rect, color: Color(0x0a6750a4))..rrect(rrect: rrect, color:
    /// Color(0xffe8def8))`: the hover highlight clipped to the indicator, then the selected
    /// destination's indicator.
    fn paints_indicator_highlight(
        ops: &[waft_embedder::valo::Op],
        indicator_rect: Rect,
        rrect: waft_embedder::RRect,
    ) -> bool {
        use waft_embedder::valo::{self, Op};
        let midpoints = |rect: Rect| {
            [
                rect.center_left(),
                rect.top_center(),
                rect.center_right(),
                rect.bottom_center(),
            ]
        };
        let contains = |path: &valo::Path, point: Offset| {
            path.contains(
                valo::Point::new(point.dx() as f32, point.dy() as f32),
                valo::FillRule::NonZero,
            )
        };
        let excluded_rect = indicator_rect.inflate(10.0);
        let Some(clip_at) = ops.iter().position(|op| match op {
            Op::ClipPath { path, .. } => {
                midpoints(indicator_rect)
                    .iter()
                    .all(|point| contains(path, *point))
                    && midpoints(excluded_rect)
                        .iter()
                        .all(|point| !contains(path, *point))
            }
            _ => false,
        }) else {
            return false;
        };
        let near = |a: f32, b: f64| (f64::from(a) - b).abs() < 1e-3;
        let highlight_color: valo::Color = Color::new(0x0a6750a4).into();
        let Some(rect_at) = ops[clip_at..].iter().position(|op| match op {
            Op::DrawRect { rect, paint, .. } => {
                paint.color == highlight_color
                    && near(rect.x, indicator_rect.left)
                    && near(rect.y, indicator_rect.top)
                    && near(rect.width, indicator_rect.width())
                    && near(rect.height, indicator_rect.height())
            }
            _ => false,
        }) else {
            return false;
        };
        let mut canvas = waft_embedder::Canvas::new();
        waft_painting::draw_rrect(&mut canvas, rrect, &waft_embedder::Paint::default());
        let expected = canvas.build();
        let Some(Op::DrawPath {
            path: expected_path,
            ..
        }) = expected.ops().first()
        else {
            panic!("draw_rrect records a path");
        };
        let indicator_color: valo::Color = Color::new(0xffe8def8).into();
        ops[clip_at + rect_at..].iter().any(|op| {
            matches!(
                op,
                Op::DrawPath { path, paint, .. }
                    if path == expected_path && paint.color == indicator_color
            )
        })
    }

    /// Dart's `createGesture(kind: mouse)`, `addPointer()`, `moveTo(center of icon)` and
    /// `pumpAndSettle()`.
    fn hover_icon(tester: &mut WidgetTester, icon: IconData) {
        let at = center_of_icon(tester, icon);
        let mut mouse = TestPointer::mouse(1, 0);
        tester.add_pointer(&mut mouse, Offset::ZERO);
        tester.move_to(&mut mouse, at, false);
        tester.pump_and_settle();
    }

    fn rrect(left: f64, top: f64, right: f64, bottom: f64) -> waft_embedder::RRect {
        waft_embedder::RRect::from_ltrbr(left, top, right, bottom, Radius::circular(16.0))
    }

    #[test]
    fn navigation_rail_indicator_renders_ripple() {
        test_widgets(|tester| {
            pump_navigation_rail(
                tester,
                NavigationRail::new(two_destinations(), Some(1))
                    .label_type(NavigationRailLabelType::All),
            );
            hover_icon(tester, Icons::favorite_border());

            let indicator_rect = Rect::from_ltrb(12.0, 0.0, 68.0, 32.0);
            assert!(paints_indicator_highlight(
                &rail_ink_ops(tester),
                indicator_rect,
                rrect(12.0, 0.0, 68.0, 32.0)
            ));
        });
    }

    #[test]
    fn navigation_rail_indicator_renders_ripple_extended() {
        test_widgets(|tester| {
            // This is a regression test for https://github.com/flutter/flutter/issues/117126
            pump_navigation_rail(
                tester,
                NavigationRail::new(two_destinations(), Some(1))
                    .extended(true)
                    .label_type(NavigationRailLabelType::None),
            );
            hover_icon(tester, Icons::favorite_border());

            let indicator_rect = Rect::from_ltrb(12.0, 6.0, 68.0, 38.0);
            assert!(paints_indicator_highlight(
                &rail_ink_ops(tester),
                indicator_rect,
                rrect(12.0, 6.0, 68.0, 38.0)
            ));
        });
    }

    fn padded_two_destinations() -> Vec<NavigationRailDestination> {
        vec![
            destination(Icons::favorite_border(), Icons::favorite(), "Abc")
                .padding(EdgeInsetsGeometry::all(10.0)),
            destination(Icons::bookmark_border(), Icons::bookmark(), "Def")
                .padding(EdgeInsetsGeometry::all(18.0)),
        ]
    }

    #[test]
    fn navigation_rail_indicator_renders_properly_when_padding_is_applied() {
        test_widgets(|tester| {
            // This is a regression test for https://github.com/flutter/flutter/issues/117126
            pump_navigation_rail(
                tester,
                NavigationRail::new(padded_two_destinations(), Some(1))
                    .extended(true)
                    .label_type(NavigationRailLabelType::None),
            );
            hover_icon(tester, Icons::favorite_border());

            let indicator_rect = Rect::from_ltrb(22.0, 16.0, 78.0, 48.0);
            assert!(paints_indicator_highlight(
                &rail_ink_ops(tester),
                indicator_rect,
                rrect(30.0, 24.0, 86.0, 56.0)
            ));
        });
    }

    #[test]
    fn indicator_renders_properly_when_navigation_rai_min_width_less_than_default_min_width() {
        test_widgets(|tester| {
            // This is a regression test for https://github.com/flutter/flutter/issues/117126
            pump_navigation_rail(
                tester,
                NavigationRail::new(two_destinations(), Some(1))
                    .min_width(50.0)
                    .extended(true)
                    .label_type(NavigationRailLabelType::None),
            );
            hover_icon(tester, Icons::favorite_border());

            let indicator_rect = Rect::from_ltrb(-3.0, 6.0, 53.0, 38.0);
            assert!(paints_indicator_highlight(
                &rail_ink_ops(tester),
                indicator_rect,
                rrect(0.0, 6.0, 50.0, 38.0)
            ));
        });
    }

    #[test]
    fn navigation_rail_indicator_renders_properly_with_custom_padding_and_min_width() {
        test_widgets(|tester| {
            // This is a regression test for https://github.com/flutter/flutter/issues/117126
            pump_navigation_rail(
                tester,
                NavigationRail::new(padded_two_destinations(), Some(1))
                    .min_width(300.0)
                    .extended(true)
                    .label_type(NavigationRailLabelType::None),
            );
            hover_icon(tester, Icons::favorite_border());

            let indicator_rect = Rect::from_ltrb(132.0, 16.0, 188.0, 48.0);
            assert!(paints_indicator_highlight(
                &rail_ink_ops(tester),
                indicator_rect,
                rrect(140.0, 24.0, 196.0, 56.0)
            ));
        });
    }

    #[test]
    fn navigation_rail_indicator_renders_properly_with_long_labels() {
        test_widgets(|tester| {
            // This is a regression test for https://github.com/flutter/flutter/issues/128005.
            pump_navigation_rail(
                tester,
                NavigationRail::new(
                    vec![
                        destination(
                            Icons::favorite_border(),
                            Icons::favorite(),
                            "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
                        ),
                        destination(Icons::bookmark_border(), Icons::bookmark(), "ABC"),
                    ],
                    Some(1),
                )
                .label_type(NavigationRailLabelType::All),
            );
            hover_icon(tester, Icons::favorite_border());

            // Default values from M3 specification.
            let rail_min_width = 80.0;
            let indicator_height = 32.0;
            let destination_width = 72.0;
            let destination_horizontal_padding = 8.0;
            let indicator_width = destination_width - 2.0 * destination_horizontal_padding; // 56.0

            // The navigation rail width is larger than default because of the first
            // destination long label.
            let rail_width = tester.get_size(rail_box(tester)).width();

            // Expected indicator position.
            let indicator_left = (rail_width - indicator_width) / 2.0;
            let indicator_right = (rail_width + indicator_width) / 2.0;
            let indicator_rect =
                Rect::from_ltrb(indicator_left, 0.0, indicator_right, indicator_height);
            let indicator_horizontal_padding = (rail_min_width - indicator_width) / 2.0; // 12.0

            assert!(paints_indicator_highlight(
                &rail_ink_ops(tester),
                indicator_rect,
                rrect(
                    indicator_horizontal_padding,
                    0.0,
                    indicator_horizontal_padding + indicator_width,
                    indicator_height,
                )
            ));
        });
    }

    #[test]
    fn navigation_rail_indicator_renders_properly_with_large_icon() {
        test_widgets(|tester| {
            // This is a regression test for https://github.com/flutter/flutter/issues/133799.
            let icon_size = 50.0;
            pump_navigation_rail_with(
                tester,
                NavigationRail::new(
                    vec![
                        destination(Icons::favorite_border(), Icons::favorite(), "ABC"),
                        destination(Icons::bookmark_border(), Icons::bookmark(), "DEF"),
                    ],
                    Some(1),
                )
                .label_type(NavigationRailLabelType::All),
                Pump {
                    navigation_rail_theme: Some(
                        NavigationRailThemeData::new()
                            .selected_icon_theme(IconThemeData::new().size(icon_size))
                            .unselected_icon_theme(IconThemeData::new().size(icon_size)),
                    ),
                    ..Pump::default()
                },
            );

            // Hover the first destination.
            hover_icon(tester, Icons::favorite_border());

            // Default values from M3 specification.
            let rail_min_width = 80.0;
            let indicator_height = 32.0;
            let destination_width = 72.0;
            let destination_horizontal_padding = 8.0;
            let indicator_width = destination_width - 2.0 * destination_horizontal_padding; // 56.0

            // The navigation rail width is the default one because labels are short.
            let rail_width = tester.get_size(rail_box(tester)).width();
            assert_eq!(rail_width, rail_min_width);

            // Expected indicator position.
            let indicator_left = (rail_width - indicator_width) / 2.0;
            let indicator_right = (rail_width + indicator_width) / 2.0;
            let indicator_top = (icon_size - indicator_height) / 2.0;
            let indicator_bottom = (icon_size + indicator_height) / 2.0;
            let indicator_rect = Rect::from_ltrb(
                indicator_left,
                indicator_top,
                indicator_right,
                indicator_bottom,
            );

            // Icon height is greater than indicator height so the indicator has a vertical
            // offset.
            let second_indicator_vertical_offset = (icon_size - indicator_height) / 2.0;

            assert!(paints_indicator_highlight(
                &rail_ink_ops(tester),
                // Hover highlight for the hovered destination (the one with 'favorite' icon).
                indicator_rect,
                // Indicator for the selected destination (the one with 'bookmark' icon).
                rrect(
                    indicator_left,
                    second_indicator_vertical_offset,
                    indicator_right,
                    second_indicator_vertical_offset + indicator_height,
                )
            ));
        });
    }

    #[test]
    fn navigation_rail_indicator_renders_properly_when_text_direction_is_rtl() {
        test_widgets(|tester| {
            // This is a regression test for https://github.com/flutter/flutter/issues/134361.
            pump_built_widget(
                tester,
                NavigationRail::new(
                    vec![
                        destination(Icons::favorite_border(), Icons::favorite(), "ABC"),
                        destination(Icons::bookmark_border(), Icons::bookmark(), "DEF"),
                    ],
                    Some(1),
                )
                .extended(true),
                true,
                true,
            );

            // Hover the first destination.
            hover_icon(tester, Icons::favorite_border());

            // Default values from M3 specification.
            let rail_min_extended_width = 256.0;
            let indicator_height = 32.0;
            let destination_width = 72.0;
            let destination_horizontal_padding = 8.0;
            let indicator_width = destination_width - 2.0 * destination_horizontal_padding; // 56.0
            let vertical_destination_spacing_m3 = 12.0;

            // The navigation rail width is the default one because labels are short.
            let rail_width = tester.get_size(rail_box(tester)).width();
            assert_eq!(rail_width, rail_min_extended_width);

            // Expected indicator position.
            let indicator_left =
                rail_width - (destination_width - destination_horizontal_padding / 2.0);
            let indicator_right = indicator_left + indicator_width;
            let indicator_rect = Rect::from_ltrb(
                indicator_left,
                vertical_destination_spacing_m3 / 2.0,
                indicator_right,
                vertical_destination_spacing_m3 / 2.0 + indicator_height,
            );

            // Compute the vertical position for the selected destination (the one with
            // 'bookmark' icon).
            let second_indicator_vertical_offset = vertical_destination_spacing_m3 / 2.0;

            assert!(paints_indicator_highlight(
                &rail_ink_ops(tester),
                // Hover highlight for the hovered destination (the one with 'favorite' icon).
                indicator_rect,
                // Indicator for the selected destination (the one with 'bookmark' icon).
                rrect(
                    indicator_left,
                    second_indicator_vertical_offset,
                    indicator_right,
                    second_indicator_vertical_offset + indicator_height,
                )
            ));
        });
    }

    #[test]
    fn navigation_rail_indicator_scale_transform() {
        test_widgets(|tester| {
            let build = |tester: &mut WidgetTester, selected_index: usize| {
                pump_navigation_rail(
                    tester,
                    NavigationRail::new(two_destinations(), Some(selected_index))
                        .label_type(NavigationRailLabelType::All),
                );
            };
            build(tester, 0);
            tester.pump_and_settle();
            // Dart's `.last` Transform under the indicators: the second destination's.
            let second_scale = |tester: &WidgetTester| {
                let indicator = find::by_type::<NavigationIndicator>().evaluate(tester)[1];
                let transform = *tester
                    .descendants_of_type::<waft_widgets::Transform>(indicator)
                    .last()
                    .expect("a Transform under the indicator");
                tester.widget(transform, |transform: &waft_widgets::Transform| {
                    f64::from(transform.transform.to_flutter_array()[0])
                })
            };
            assert_eq!(second_scale(tester), 0.0);

            build(tester, 1);
            tester.pump_by(Duration::from_millis(100));
            let scale = second_scale(tester);
            // Dart's `closeTo(.., precisionErrorTolerance)`, within the `f32` of valo's matrix.
            assert!((scale - 0.970_502_395_629_882_8).abs() < 1e-6, "{scale}");

            tester.pump_by(Duration::from_millis(100));
            assert_eq!(second_scale(tester), 1.0);
        });
    }

    /// Dart's `_getIndicatorDecoration`: the decoration of the first `Ink` under a
    /// `FadeTransition`, as a `ShapeDecoration`.
    fn indicator_decoration<R>(
        tester: &WidgetTester,
        read: impl FnOnce(&waft_painting::ShapeDecoration) -> R,
    ) -> R {
        let ink = find::by_type::<waft_widgets::FadeTransition>()
            .evaluate(tester)
            .into_iter()
            .find_map(|fade| {
                tester
                    .descendants_of_type::<crate::ink_decoration::Ink>(fade)
                    .first()
                    .copied()
            })
            .expect("an Ink under a FadeTransition");
        tester.widget(ink, |ink: &crate::ink_decoration::Ink| {
            read(
                ink.decoration
                    .as_deref()
                    .and_then(|decoration| decoration.as_any().downcast_ref())
                    .expect("a ShapeDecoration"),
            )
        })
    }

    #[test]
    fn navigation_destination_updates_indicator_color_and_shape() {
        test_widgets(|tester| {
            let color = Color::new(0xff0000ff);
            let shape = waft_painting::RoundedRectangleBorder::default();
            let build_navigation_rail = |tester: &mut WidgetTester,
                                         indicator: Option<(
                Color,
                waft_painting::RoundedRectangleBorder,
            )>| {
                let mut rail = NavigationRail::new(destinations(), Some(0)).use_indicator(true);
                if let Some((color, shape)) = indicator {
                    rail = rail.indicator_color(color).indicator_shape(shape);
                }
                pump_rail_in_app(tester, rail);
            };
            let theme = ThemeData::new(&tester.cell.borrow());
            build_navigation_rail(tester, None);

            // Test default indicator color and shape.
            assert_eq!(
                indicator_decoration(tester, |decoration| decoration.color.clone()),
                Some(theme.color_scheme.secondary_container().into())
            );
            assert!(indicator_decoration(tester, |decoration| {
                &*decoration.shape
                    == &waft_painting::StadiumBorder::new(waft_painting::BorderSide::NONE)
                        as &dyn ShapeBorder
            }));

            build_navigation_rail(tester, Some((color, shape)));

            // Test custom indicator color and shape.
            assert_eq!(
                indicator_decoration(tester, |decoration| decoration.color.clone()),
                Some(color.into())
            );
            assert!(indicator_decoration(tester, |decoration| {
                &*decoration.shape == &shape as &dyn ShapeBorder
            }));
        });
    }

    #[test]
    fn destination_s_respect_their_disabled_state() {
        test_widgets(|tester| {
            let selected_index = Rc::new(std::cell::Cell::new(None));
            let seen = Rc::clone(&selected_index);
            pump_navigation_rail(
                tester,
                NavigationRail::new(
                    vec![
                        destination(Icons::favorite_border(), Icons::favorite(), "Abc"),
                        destination(Icons::star_border(), Icons::star(), "Bcd"),
                        destination(Icons::bookmark_border(), Icons::bookmark(), "Cde")
                            .disabled(true),
                    ],
                    Some(0),
                )
                .on_destination_selected(move |_app, index| seen.set(Some(index)))
                .label_type(NavigationRailLabelType::All),
            );

            tester.tap_at(center_of_text(tester, "Abc"), 1);
            assert_eq!(selected_index.get(), Some(0));

            tester.tap_at(center_of_text(tester, "Bcd"), 2);
            assert_eq!(selected_index.get(), Some(1));

            tester.tap_at(center_of_text(tester, "Cde"), 3);
            assert_eq!(selected_index.get(), Some(1));

            // Wait for any pending shader compilation.
            tester.pump_and_settle();
        });
    }

    #[test]
    #[expect(
        deprecated,
        reason = "Dart's case reads the deprecated `Color.opacity`"
    )]
    fn destination_s_label_with_the_right_opacity_while_disabled() {
        test_widgets(|tester| {
            pump_navigation_rail(
                tester,
                NavigationRail::new(
                    vec![
                        destination(Icons::favorite_border(), Icons::favorite(), "Abc"),
                        destination(Icons::bookmark_border(), Icons::bookmark(), "Bcd")
                            .disabled(true),
                    ],
                    Some(0),
                )
                .on_destination_selected(|_app, _index| {})
                .label_type(NavigationRailLabelType::All),
            );

            tester.pump_and_settle();

            let default_text_style_opacity = |text: &str| {
                let element = tester
                    .ancestor_of_type::<DefaultTextStyle>(find::text(text).evaluate(tester)[0]);
                tester.widget(element, |style: &DefaultTextStyle| {
                    style.style.color.as_deref().map(|color| color.opacity())
                })
            };

            let abc_label_opacity = default_text_style_opacity("Abc");
            let bcd_label_opacity = default_text_style_opacity("Bcd");

            assert_eq!(abc_label_opacity, Some(1.0));
            let bcd = bcd_label_opacity.expect("a colour");
            assert!((bcd - 0.38).abs() <= 0.01, "{bcd}");
        });
    }

    #[test]
    fn navigation_rail_indicator_inkwell_can_be_transparent() {
        test_widgets(|tester| {
            // This is a regression test for https://github.com/flutter/flutter/issues/135866.
            let root = {
                let app = tester.cell.borrow();
                let mut color_scheme = crate::color_scheme::ColorScheme::light();
                color_scheme = color_scheme.with_primary(Colors::TRANSPARENT);
                let theme = ThemeData::builder()
                    .color_scheme(color_scheme)
                    // Material 3 defaults to InkSparkle which is not testable using paints.
                    .splash_factory(crate::ink_splash::InkSplash::splash_factory())
                    .build(&app);
                material_app(
                    theme,
                    Scaffold::new()
                        .body(
                            Row::new().children([
                                NavigationRail::new(
                                    vec![
                                        destination(
                                            Icons::favorite_border(),
                                            Icons::favorite(),
                                            "ABC",
                                        ),
                                        destination(
                                            Icons::bookmark_border(),
                                            Icons::bookmark(),
                                            "DEF",
                                        ),
                                    ],
                                    Some(1),
                                )
                                .label_type(NavigationRailLabelType::All)
                                .into_widget(),
                                Expanded::new(Text::new("body")).into_widget(),
                            ]),
                        )
                        .into_widget(),
                )
            };
            tester.pump_widget(root);

            let at = center_of_icon(tester, Icons::favorite_border());
            let mut mouse = TestPointer::mouse(1, waft_gestures::K_PRIMARY_BUTTON);
            tester.add_pointer(&mut mouse, Offset::ZERO);
            tester.move_to(&mut mouse, at, false);
            tester.pump_and_settle();

            // Dart's `paints..rect(color: Colors.transparent)`: Valo's canvas drops a draw whose
            // paint is transparent, so the hover highlight has no entry; the case asserts that
            // no rect is drawn instead, as a hover in the primary colour would draw one.
            let draws_rect = |ops: &[waft_embedder::valo::Op]| {
                ops.iter()
                    .any(|op| matches!(op, waft_embedder::valo::Op::DrawRect { .. }))
            };
            assert!(!draws_rect(&rail_ink_ops(tester)));

            tester.down(&mut mouse, at);
            tester.pump(); // Start the splash and highlight animations.
            // Wait for splash and highlight to be well under way.
            tester.pump_by(Duration::from_millis(800));

            // Dart's `paints..circle(color: Colors.transparent)`: likewise no splash circle is
            // drawn instead.
            let ops = rail_ink_ops(tester);
            let draws_circle = ops.iter().any(|op| {
                matches!(
                    op,
                    waft_embedder::valo::Op::DrawPath { path, .. } if path.as_oval().is_some()
                )
            });
            assert!(!draws_circle);
        });
    }

    #[test]
    fn navigation_rail_can_have_expanded_widgets_inside() {
        test_widgets(|tester| {
            pump_navigation_rail(
                tester,
                NavigationRail::new(
                    vec![destination(
                        Icons::favorite_border(),
                        Icons::favorite(),
                        "Abc",
                    )],
                    Some(0),
                )
                .trailing(Expanded::new(Icon::new(Some(Icons::search())))),
            );

            // Dart's `expect(tester.takeException(), isNull)`: the frame did not panic.
            tester.pump_and_settle();
        });
    }

    #[test]
    fn navigation_rail_labels_shall_not_overflow_if_longer_texts_provided_extended() {
        test_widgets(|tester| {
            // Regression test for https://github.com/flutter/flutter/issues/110901.
            // The navigation rail has a narrow width constraint. The text should wrap.
            let normal_label = "Abc";
            let long_label = "Very long bookmark text for navigation destination";
            let root = {
                let app = tester.cell.borrow();
                material_app(
                    ThemeData::new(&app),
                    Scaffold::new()
                        .body(
                            Row::new().children([
                                SizedBox::new()
                                    .width(140.0)
                                    .child(
                                        NavigationRail::new(
                                            vec![
                                                destination(
                                                    Icons::favorite_border(),
                                                    Icons::favorite(),
                                                    normal_label,
                                                ),
                                                destination(
                                                    Icons::bookmark_border(),
                                                    Icons::bookmark(),
                                                    long_label,
                                                ),
                                            ],
                                            Some(1),
                                        )
                                        .extended(true),
                                    )
                                    .into_widget(),
                                Expanded::new(Text::new("body")).into_widget(),
                            ]),
                        )
                        .into_widget(),
                )
            };
            tester.pump_widget(root);

            expect(
                tester,
                &find::by_type::<NavigationRail>(),
                finds_one_widget(),
            );
            expect(tester, &find::text(normal_label), finds_one_widget());
            expect(tester, &find::text(long_label), finds_one_widget());

            // If the widget manages to layout without throwing an overflow exception,
            // the test passes.
        });
    }

    #[test]
    fn navigation_rail_can_scroll_in_low_height() {
        test_widgets(|tester| {
            let root = {
                let app = tester.cell.borrow();
                material_app(
                    ThemeData::new(&app),
                    Builder::new(|app, context| {
                        MediaQuery::new(
                            // Set Screen height with 300
                            MediaQuery::of(app, context)
                                .copy_with()
                                .size(Size::new(800.0, 300.0)),
                            Scaffold::new().body(
                                Row::new().children([
                                    // Set NavigationRail height with 100
                                    SizedBox::new()
                                        .height(100.0)
                                        .child(
                                            NavigationRail::new(abc_def_ghi(), Some(0))
                                                .scrollable(true),
                                        )
                                        .into_widget(),
                                    Expanded::new(Text::new("body")).into_widget(),
                                ]),
                            ),
                        )
                        .into_widget()
                    })
                    .into_widget(),
                )
            };
            tester.pump_widget(root);

            let scrollable = find::by_type::<waft_widgets::Scrollable>().evaluate(tester)[0];
            let mut app = tester.cell.borrow_mut();
            let state = scrollable
                .state_handle::<waft_widgets::ScrollableState>(&app)
                .expect("a ScrollableState");
            let position = state.position(&app);
            position.jump_to(&mut app, 500.0);
            assert_eq!(position.pixels(&app), 500.0);
        });
    }

    /// The rail of the leading/trailing placement cases, 140 wide.
    fn pump_leading_trailing_rail(
        tester: &mut WidgetTester,
        configure: impl FnOnce(NavigationRail) -> NavigationRail,
    ) -> (GlobalKey, GlobalKey) {
        let leading_key = GlobalKey::new();
        let trailing_key = GlobalKey::new();
        let rail = configure(
            NavigationRail::new(
                vec![
                    NavigationRailDestination::new(
                        Icon::new(Some(Icons::favorite())),
                        Text::new("Abc"),
                    ),
                    NavigationRailDestination::new(
                        Icon::new(Some(Icons::bookmark())),
                        Text::new("Def"),
                    ),
                    NavigationRailDestination::new(
                        Icon::new(Some(Icons::star())),
                        Text::new("Ghi"),
                    ),
                ],
                Some(0),
            )
            .extended(true)
            .group_alignment(0.0)
            .leading(
                SizedBox::new()
                    .key(KeyRef::from(leading_key.clone()))
                    .height(50.0),
            )
            .trailing(
                SizedBox::new()
                    .key(KeyRef::from(trailing_key.clone()))
                    .height(50.0),
            ),
        );
        let root = {
            let app = tester.cell.borrow();
            material_app(
                ThemeData::new(&app),
                Scaffold::new()
                    .body(Row::new().children([
                        SizedBox::new().width(140.0).child(rail).into_widget(),
                        Expanded::new(Text::new("body")).into_widget(),
                    ]))
                    .into_widget(),
            )
        };
        tester.pump_widget(root);
        (leading_key, trailing_key)
    }

    /// Dart's `tester.getRect(find.ancestor(of: find.byIcon(icon), matching:
    /// find.byType(Semantics)).first)`.
    fn destination_rect(tester: &WidgetTester, icon: IconData) -> Rect {
        let semantics = tester
            .element(find::ancestor(find::by_icon(&icon), find::by_type::<Semantics>()).first());
        tester.get_rect(tester.render_box_of(semantics))
    }

    #[test]
    fn navigation_rail_leading_widget_is_at_top_and_trailing_widget_is_at_last_destination_defaults()
     {
        test_widgets(|tester| {
            let (leading_key, trailing_key) = pump_leading_trailing_rail(tester, |rail| rail);

            let leading_rect = tester.get_rect(render_box_of_key(tester, &leading_key));
            let trailing_rect = tester.get_rect(render_box_of_key(tester, &trailing_key));
            let first_dest_rect = destination_rect(tester, Icons::favorite());
            let last_dest_rect = destination_rect(tester, Icons::star());

            assert_eq!(leading_rect.top, 8.0);
            assert!(first_dest_rect.top - leading_rect.bottom > 100.0);
            assert_eq!(trailing_rect.top - last_dest_rect.bottom, 0.0);
            assert!(trailing_rect.bottom < 500.0);
        });
    }

    #[test]
    fn navigation_rail_leading_at_top_set_to_false_and_trailing_at_bottom_to_true() {
        test_widgets(|tester| {
            let (leading_key, trailing_key) = pump_leading_trailing_rail(tester, |rail| {
                rail.leading_at_top(false).trailing_at_bottom(true)
            });

            let leading_rect = tester.get_rect(render_box_of_key(tester, &leading_key));
            let trailing_rect = tester.get_rect(render_box_of_key(tester, &trailing_key));
            let first_dest_rect = destination_rect(tester, Icons::favorite());
            let last_dest_rect = destination_rect(tester, Icons::star());

            assert!(leading_rect.top > 100.0);
            assert_eq!(first_dest_rect.top - leading_rect.bottom, 8.0);
            assert!(trailing_rect.top - last_dest_rect.bottom > 100.0);
            assert_eq!(trailing_rect.bottom, 600.0);
        });
    }

    #[test]
    fn navigation_rail_does_not_crash_at_zero_area() {
        test_widgets(|tester| {
            let root = {
                let app = tester.cell.borrow();
                material_app(
                    ThemeData::new(&app),
                    Center::new()
                        .child(SizedBox::shrink().child(NavigationRail::new(
                            vec![NavigationRailDestination::new(
                                Icon::new(Some(Icons::abc())),
                                Text::new("X"),
                            )],
                            Some(0),
                        )))
                        .into_widget(),
                )
            };
            tester.pump_widget(root);
            assert_eq!(tester.get_size(rail_box(tester)), Size::ZERO);
        });
    }

    #[test]
    fn navigation_rail_respects_main_axis_alignment() {
        test_widgets(|tester| {
            pump_navigation_rail(
                tester,
                NavigationRail::new(destinations(), Some(0))
                    .main_axis_alignment(MainAxisAlignment::SpaceEvenly),
            );

            // Find the exact column by checking both alignment and size
            let columns = find::by_type::<Column>()
                .evaluate(tester)
                .into_iter()
                .filter(|element| {
                    tester.widget(*element, |column: &Column| {
                        column.main_axis_alignment == MainAxisAlignment::SpaceEvenly
                            && column.main_axis_size == MainAxisSize::Max
                    })
                })
                .count();
            assert_eq!(columns, 1);
        });
    }

    // These tests are only relevant for Material 2. Once Material 2
    // support is deprecated and the APIs are removed, these tests
    // can be deleted.

    fn m2() -> Pump {
        Pump {
            use_material3: false,
            ..Pump::default()
        }
    }

    fn m2_default_width(label_type: Option<NavigationRailLabelType>) {
        test_widgets(|tester| {
            let mut rail = NavigationRail::new(destinations(), Some(0));
            if let Some(label_type) = label_type {
                rail = rail.label_type(label_type);
            }
            pump_navigation_rail_with(tester, rail, m2());

            assert_eq!(tester.get_size(rail_box(tester)).width(), 72.0);
        });
    }

    #[test]
    fn material_2_renders_at_the_correct_default_width_label_type_none_default() {
        m2_default_width(None);
    }

    #[test]
    fn material_2_renders_at_the_correct_default_width_label_type_selected() {
        m2_default_width(Some(NavigationRailLabelType::Selected));
    }

    #[test]
    fn material_2_renders_at_the_correct_default_width_label_type_all() {
        m2_default_width(Some(NavigationRailLabelType::All));
    }

    /// The Material 2 icon-only destination spacing cases at `text_scale_factor`, `min_width`
    /// wide: Since the rail is icon only, its destinations should not be affected by
    /// textScaleFactor.
    fn m2_icon_only_spacing(text_scale_factor: f64, min_width: Option<f64>) {
        test_widgets(|tester| {
            let destination_width = min_width.unwrap_or(72.0);
            let mut rail = NavigationRail::new(destinations(), Some(0));
            if let Some(min_width) = min_width {
                rail = rail.min_width(min_width);
            }
            pump_navigation_rail_with(
                tester,
                rail,
                Pump {
                    text_scale_factor,
                    ..m2()
                },
            );

            assert_eq!(tester.get_size(rail_box(tester)).width(), destination_width);

            // The first destination is 8 from the top because of the default vertical
            // padding at the to of the rail; each next one is one width below the one before.
            expect_icon_column_in(
                tester,
                destination_width,
                destination_width,
                8.0,
                [destination_width; 3],
            );
        });
    }

    #[test]
    fn material_2_destination_spacing_is_correct_label_type_none_default_text_scale_factor_1_0_default()
     {
        m2_icon_only_spacing(1.0, None);
    }

    #[test]
    fn material_2_destination_spacing_is_correct_label_type_none_default_text_scale_factor_3_0() {
        m2_icon_only_spacing(3.0, None);
    }

    #[test]
    fn material_2_destination_spacing_is_correct_label_type_none_default_text_scale_factor_0_75() {
        m2_icon_only_spacing(0.75, None);
    }

    /// The Material 2 selected-label spacing cases whose rail keeps its 72 width (a
    /// textScaleFactor of 1.0 and 0.75: a smaller one will not reduce the default width of the
    /// rail since there is a minWidth).
    fn m2_selected_spacing(text_scale_factor: f64) {
        test_widgets(|tester| {
            pump_navigation_rail_with(
                tester,
                NavigationRail::new(destinations(), Some(0))
                    .label_type(NavigationRailLabelType::Selected),
                Pump {
                    text_scale_factor,
                    ..m2()
                },
            );

            assert_eq!(tester.get_size(rail_box(tester)).width(), 72.0);

            // The first destination is 8 from the top because of the default vertical
            // padding at the to of the rail.
            let next_destination_y = 8.0;
            let icon = icon_render_box(tester, Icons::favorite());
            let label = label_render_box(tester, "Abc");
            let icon_size = tester.get_size(icon);
            let label_size = tester.get_size(label);
            assert_offset(
                global_top_left(tester, icon),
                Offset::new(
                    (72.0 - icon_size.width()) / 2.0,
                    next_destination_y + (72.0 - icon_size.height() - label_size.height()) / 2.0,
                ),
            );
            assert_offset(
                global_top_left(tester, label),
                Offset::new(
                    (72.0 - label_size.width()) / 2.0,
                    next_destination_y + (72.0 + icon_size.height() - label_size.height()) / 2.0,
                ),
            );

            // The other destinations are 72 below the one before.
            let mut next_destination_y = next_destination_y;
            for icon in &icons_in_order()[1..] {
                next_destination_y += 72.0;
                expect_icon_at(
                    tester,
                    icon_render_box(tester, icon.clone()),
                    72.0,
                    72.0,
                    next_destination_y,
                );
            }
        });
    }

    #[test]
    fn material_2_destination_spacing_is_correct_label_type_selected_text_scale_factor_1_0_default()
    {
        m2_selected_spacing(1.0);
    }

    #[test]
    fn material_2_destination_spacing_is_correct_label_type_selected_text_scale_factor_0_75() {
        m2_selected_spacing(0.75);
    }

    /// The Material 2 labelled spacing cases at a textScaleFactor of 3.0: the rail and
    /// destinations sizes grow to fit the larger text labels.
    fn m2_large_text_labelled_spacing(label_type: NavigationRailLabelType) {
        test_widgets(|tester| {
            pump_navigation_rail_with(
                tester,
                NavigationRail::new(destinations(), Some(0)).label_type(label_type),
                Pump {
                    text_scale_factor: 3.0,
                    ..m2()
                },
            );

            assert_eq!(tester.get_size(rail_box(tester)).width(), 142.0);

            // The first destination is 8 from the top because of the default vertical
            // padding at the to of the rail.
            let mut next_destination_y = 8.0;
            for (i, (icon, label)) in icons_in_order()
                .into_iter()
                .zip(["Abc", "Def", "Ghi", "Jkl"])
                .enumerate()
            {
                let icon = icon_render_box(tester, icon);
                let icon_size = tester.get_size(icon);
                let labelled = i == 0 || label_type == NavigationRailLabelType::All;
                if !labelled {
                    // An unselected destination is 72 high with its icon 24 below its top.
                    assert_offset(
                        global_top_left(tester, icon),
                        Offset::new((142.0 - icon_size.width()) / 2.0, next_destination_y + 24.0),
                    );
                    next_destination_y += 72.0;
                    continue;
                }
                assert_offset(
                    global_top_left(tester, icon),
                    Offset::new((142.0 - icon_size.width()) / 2.0, next_destination_y + 16.0),
                );
                // The label sits right below the icon.
                let label = label_render_box(tester, label);
                let label_size = tester.get_size(label);
                assert_offset(
                    global_top_left(tester, label),
                    Offset::new(
                        (142.0 - label_size.width()) / 2.0,
                        next_destination_y + 16.0 + icon_size.height(),
                    ),
                );
                next_destination_y += 16.0 + icon_size.height() + label_size.height() + 16.0;
            }
        });
    }

    #[test]
    fn material_2_destination_spacing_is_correct_label_type_selected_text_scale_factor_3_0() {
        m2_large_text_labelled_spacing(NavigationRailLabelType::Selected);
    }

    #[test]
    fn material_2_destination_spacing_is_correct_label_type_all_text_scale_factor_3_0() {
        m2_large_text_labelled_spacing(NavigationRailLabelType::All);
    }

    #[test]
    fn material_2_destination_spacing_is_correct_label_type_all_text_scale_factor_1_0_default() {
        m2_all_spacing(1.0);
    }

    #[test]
    fn material_2_destination_spacing_is_correct_label_type_all_text_scale_factor_0_75() {
        m2_all_spacing(0.75);
    }

    /// The Material 2 all-labels spacing cases whose rail keeps its 72 width (a textScaleFactor
    /// of 1.0 and 0.75: a smaller one will not reduce the default size of the rail).
    fn m2_all_spacing(text_scale_factor: f64) {
        test_widgets(|tester| {
            pump_navigation_rail_with(
                tester,
                NavigationRail::new(destinations(), Some(0))
                    .label_type(NavigationRailLabelType::All),
                Pump {
                    text_scale_factor,
                    ..m2()
                },
            );

            assert_eq!(tester.get_size(rail_box(tester)).width(), 72.0);

            // The first destination is 8 from the top because of the default vertical
            // padding at the to of the rail; each next one is 72 below the one before.
            let mut next_destination_y = 8.0;
            for (icon, label) in icons_in_order()
                .into_iter()
                .zip(["Abc", "Def", "Ghi", "Jkl"])
            {
                let icon = icon_render_box(tester, icon);
                let label = label_render_box(tester, label);
                let icon_size = tester.get_size(icon);
                assert_offset(
                    global_top_left(tester, icon),
                    Offset::new((72.0 - icon_size.width()) / 2.0, next_destination_y + 16.0),
                );
                assert_offset(
                    global_top_left(tester, label),
                    Offset::new(
                        (72.0 - tester.get_size(label).width()) / 2.0,
                        next_destination_y + 16.0 + icon_size.height(),
                    ),
                );
                next_destination_y += 72.0;
            }
        });
    }

    fn m2_group_alignment(group_alignment: Option<f64>, first_y: f64) {
        test_widgets(|tester| {
            let mut rail = NavigationRail::new(destinations(), Some(0));
            if let Some(group_alignment) = group_alignment {
                rail = rail.group_alignment(group_alignment);
            }
            pump_navigation_rail_with(tester, rail, m2());

            // Each next destination is 72 below the one before.
            expect_icon_column_in(tester, 72.0, 72.0, first_y, [72.0; 3]);
        });
    }

    #[test]
    fn material_2_group_alignment_works_group_alignment_minus_1_0_default() {
        m2_group_alignment(None, 8.0);
    }

    #[test]
    fn material_2_group_alignment_works_group_alignment_0_0() {
        m2_group_alignment(Some(0.0), 160.0);
    }

    #[test]
    fn material_2_group_alignment_works_group_alignment_1_0() {
        m2_group_alignment(Some(1.0), 312.0);
    }

    #[test]
    fn material_2_destination_spacing_is_correct_for_a_compact_rail_preferred_width_56_text_scale_factor_1_0_default()
     {
        m2_icon_only_spacing(1.0, Some(56.0));
    }

    #[test]
    fn material_2_destination_spacing_is_correct_for_a_compact_rail_preferred_width_56_text_scale_factor_3_0()
     {
        m2_icon_only_spacing(3.0, Some(56.0));
    }

    /// Dart's case of this name pumps a textScaleFactor of 3.0, not 0.75.
    #[test]
    fn material_2_destination_spacing_is_correct_for_a_compact_rail_preferred_width_56_text_scale_factor_0_75()
     {
        m2_icon_only_spacing(3.0, Some(56.0));
    }

    #[test]
    fn material_2_extended_rail_final_width_can_be_changed() {
        test_widgets(|tester| {
            let rail = |extended: bool| {
                NavigationRail::new(destinations(), Some(0))
                    .min_extended_width(300.0)
                    .extended(extended)
            };
            pump_navigation_rail_with(tester, rail(false), m2());

            let rail_render = rail_box(tester);
            assert_eq!(tester.get_size(rail_render).width(), 72.0);

            pump_navigation_rail_with(tester, rail(true), m2());
            tester.pump_and_settle();
            assert_eq!(tester.get_size(rail_render).width(), 300.0);
        });
    }

    #[test]
    fn material_2_leading_and_trailing_spacing_is_correct_with_0_2_destinations() {
        test_widgets(|tester| {
            let leading_widget_key = GlobalKey::new();
            let trailing_widget_key = GlobalKey::new();
            let fab = |key: &GlobalKey| {
                FloatingActionButton::new(Some(Listener::new(|_| {})))
                    .key(KeyRef::from(key.clone()))
                    .into_widget()
            };
            let one = || {
                vec![destination(
                    Icons::favorite_border(),
                    Icons::favorite(),
                    "Abc",
                )]
            };
            let two = || {
                vec![
                    destination(Icons::favorite_border(), Icons::favorite(), "Abc"),
                    destination(Icons::bookmark_border(), Icons::bookmark(), "Longer Label"),
                ]
            };
            let key_at = |tester: &WidgetTester, key: &GlobalKey| {
                global_top_left(tester, render_box_of_key(tester, key))
            };
            let icon_at = |tester: &WidgetTester, icon: IconData| {
                global_top_left(tester, icon_render_box(tester, icon))
            };
            let label_at = |tester: &WidgetTester, text: &str| {
                global_top_left(tester, label_render_box(tester, text))
            };

            pump_rail_in_app_with(tester, NavigationRail::new(Vec::new(), None), false);

            // empty destinations and leading widget
            pump_rail_in_app_with(
                tester,
                NavigationRail::new(Vec::new(), None).leading(fab(&leading_widget_key)),
                false,
            );
            tester.pump_and_settle();
            assert_eq!(key_at(tester, &leading_widget_key), Offset::new(0.0, 8.0));

            // one destination and leading widget
            pump_rail_in_app_with(
                tester,
                NavigationRail::new(one(), None).leading(fab(&leading_widget_key)),
                false,
            );
            tester.pump_and_settle();
            assert_offset(
                icon_at(tester, Icons::favorite_border()),
                Offset::new(24.0, 96.0),
            );
            assert_offset(label_at(tester, "Abc"), Offset::new(0.0, 72.0));
            assert_offset(key_at(tester, &leading_widget_key), Offset::new(8.0, 8.0));

            // two destinations and leading widget
            pump_rail_in_app_with(
                tester,
                NavigationRail::new(two(), None).leading(fab(&leading_widget_key)),
                false,
            );
            tester.pump_and_settle();
            assert_offset(
                icon_at(tester, Icons::favorite_border()),
                Offset::new(24.0, 96.0),
            );
            assert_offset(label_at(tester, "Abc"), Offset::new(0.0, 72.0));
            assert_offset(
                icon_at(tester, Icons::bookmark_border()),
                Offset::new(24.0, 168.0),
            );
            assert_offset(label_at(tester, "Longer Label"), Offset::new(0.0, 144.0));
            assert_offset(key_at(tester, &leading_widget_key), Offset::new(8.0, 8.0));

            // empty destinations and trailing widget
            pump_rail_in_app_with(
                tester,
                NavigationRail::new(Vec::new(), None).trailing(fab(&trailing_widget_key)),
                false,
            );
            tester.pump_and_settle();
            assert_eq!(key_at(tester, &trailing_widget_key), Offset::new(0.0, 8.0));

            // one destination and trailing widget
            pump_rail_in_app_with(
                tester,
                NavigationRail::new(one(), None).trailing(fab(&trailing_widget_key)),
                false,
            );
            tester.pump_and_settle();
            assert_offset(
                icon_at(tester, Icons::favorite_border()),
                Offset::new(24.0, 32.0),
            );
            assert_offset(label_at(tester, "Abc"), Offset::new(0.0, 8.0));
            assert_offset(key_at(tester, &trailing_widget_key), Offset::new(8.0, 80.0));

            // two destinations and trailing widget
            pump_rail_in_app_with(
                tester,
                NavigationRail::new(two(), None).trailing(fab(&trailing_widget_key)),
                false,
            );
            tester.pump_and_settle();
            assert_offset(
                icon_at(tester, Icons::favorite_border()),
                Offset::new(24.0, 32.0),
            );
            assert_offset(label_at(tester, "Abc"), Offset::new(0.0, 8.0));
            assert_offset(
                icon_at(tester, Icons::bookmark_border()),
                Offset::new(24.0, 104.0),
            );
            assert_offset(label_at(tester, "Longer Label"), Offset::new(0.0, 80.0));
            assert_offset(
                key_at(tester, &trailing_widget_key),
                Offset::new(8.0, 152.0),
            );
        });
    }

    #[test]
    fn material_2_change_destinations_and_selected_index() {
        test_widgets(|tester| {
            let two = || {
                vec![
                    destination(Icons::favorite_border(), Icons::favorite(), "Abc"),
                    destination(Icons::bookmark_border(), Icons::bookmark(), "Longer Label"),
                ]
            };
            pump_rail_in_app_with(tester, NavigationRail::new(Vec::new(), None), false);

            assert_eq!(rail_widget(tester, |rail| rail.destinations.len()), 0);
            assert_eq!(rail_widget(tester, |rail| rail.selected_index), None);

            pump_rail_in_app_with(tester, NavigationRail::new(two(), None), false);
            tester.pump_and_settle();

            assert_eq!(rail_widget(tester, |rail| rail.destinations.len()), 2);
            assert_eq!(rail_widget(tester, |rail| rail.selected_index), None);

            pump_rail_in_app_with(tester, NavigationRail::new(two(), Some(0)), false);
            tester.pump_and_settle();

            assert_eq!(rail_widget(tester, |rail| rail.destinations.len()), 2);
            assert_eq!(rail_widget(tester, |rail| rail.selected_index), Some(0));

            pump_rail_in_app_with(
                tester,
                NavigationRail::new(
                    vec![destination(
                        Icons::favorite_border(),
                        Icons::favorite(),
                        "Abc",
                    )],
                    Some(0),
                ),
                false,
            );
            tester.pump_and_settle();

            assert_eq!(rail_widget(tester, |rail| rail.destinations.len()), 1);
            assert_eq!(rail_widget(tester, |rail| rail.selected_index), Some(0));
        });
    }

    #[test]
    fn material_2_leading_and_trailing_appear_in_the_correct_places() {
        test_widgets(|tester| {
            pump_navigation_rail_with(
                tester,
                NavigationRail::new(destinations(), Some(0))
                    .leading(fab())
                    .trailing(fab()),
                m2(),
            );

            let fabs = find::by_type::<FloatingActionButton>().evaluate(tester);
            let leading = tester.render_box_of(fabs[0]);
            let trailing = tester.render_box_of(fabs[1]);
            assert_eq!(
                global_top_left(tester, leading),
                Offset::new((72.0 - tester.get_size(leading).width()) / 2.0, 8.0)
            );
            assert_eq!(
                global_top_left(tester, trailing),
                Offset::new((72.0 - tester.get_size(trailing).width()) / 2.0, 360.0)
            );
        });
    }

    #[test]
    fn material_2_extended_rail_animates_the_width_and_labels_appear_text_direction_rtl() {
        test_widgets(|tester| {
            pump_rtl_rail_with(tester, NavigationRail::new(destinations(), Some(0)), false);

            let rail = rail_box(tester);
            assert_eq!(tester.get_size(rail).width(), 72.0);
            assert_eq!(global_top_left(tester, rail), Offset::new(728.0, 0.0));

            pump_rtl_rail_with(
                tester,
                NavigationRail::new(destinations(), Some(0)).extended(true),
                false,
            );
            tester.pump_by(Duration::from_millis(100));
            assert_eq!(tester.get_size(rail).width(), 164.0);
            assert_eq!(global_top_left(tester, rail), Offset::new(636.0, 0.0));

            tester.pump_and_settle();
            assert_eq!(tester.get_size(rail).width(), 256.0);
            assert_eq!(global_top_left(tester, rail), Offset::new(544.0, 0.0));

            // The first destination is 8 from the top because of the default vertical
            // padding at the to of the rail; each next one is 72 below the one before.
            let mut next_destination_y = 8.0;
            for (icon, label) in icons_in_order()
                .into_iter()
                .zip(["Abc", "Def", "Ghi", "Jkl"])
            {
                let icon = icon_render_box(tester, icon);
                let icon_size = tester.get_size(icon);
                assert_offset(
                    global_top_left(tester, icon),
                    Offset::new(
                        800.0 - (72.0 + icon_size.width()) / 2.0,
                        next_destination_y + (72.0 - icon_size.height()) / 2.0,
                    ),
                );
                let label = label_render_box(tester, label);
                let label_size = tester.get_size(label);
                assert_offset(
                    global_top_left(tester, label),
                    Offset::new(
                        800.0 - 72.0 - label_size.width(),
                        next_destination_y + (72.0 - label_size.height()) / 2.0,
                    ),
                );
                next_destination_y += 72.0;
            }
        });
    }

    #[test]
    fn material_2_extended_rail_gets_wider_with_longer_labels_are_larger_text_scale() {
        test_widgets(|tester| {
            let pump = |tester: &mut WidgetTester, extended: bool| {
                let root = {
                    let app = tester.cell.borrow();
                    material_app(
                        theme(&app, false),
                        Scaffold::new()
                            .body(
                                Row::new().children([
                                    MediaQuery::with_clamped_text_scaling(
                                        None,
                                        3.0,
                                        3.0,
                                        NavigationRail::new(abc_and_longer_label(), Some(0))
                                            .extended(extended),
                                    ),
                                    Expanded::new(Text::new("body")).into_widget(),
                                ]),
                            )
                            .into_widget(),
                    )
                };
                tester.pump_widget(root);
            };
            pump(tester, false);

            let rail = rail_box(tester);
            assert_eq!(tester.get_size(rail).width(), 72.0);

            pump(tester, true);
            tester.pump_by(Duration::from_millis(100));
            assert_eq!(tester.get_size(rail).width(), 328.0);

            tester.pump_and_settle();
            assert_eq!(tester.get_size(rail).width(), 584.0);
        });
    }

    /// Regression test for https://github.com/flutter/flutter/issues/65657
    #[test]
    fn material_2_extended_rail_transition_does_not_jump_from_the_beginning() {
        test_widgets(|tester| {
            pump_rail_in_app_with(
                tester,
                NavigationRail::new(abc_and_longer_label(), Some(0)),
                false,
            );

            // Before starting the animation, the rail has a width of 72.
            assert_eq!(tester.get_size(rail_box(tester)).width(), 72.0);

            pump_rail_in_app_with(
                tester,
                NavigationRail::new(abc_and_longer_label(), Some(0)).extended(true),
                false,
            );
            // Create very close to 0, but non-zero, animation value.
            tester.pump_by(Duration::from_millis(1));
            let width = tester.get_size(rail_box(tester)).width();
            // Expect that it has started to extend.
            assert!(width > 72.0, "{width}");
            // Expect that it has only extended by a small amount, or that the first
            // frame does not jump. This helps verify that it is a smooth animation.
            assert!((width - 72.0).abs() <= 1.0, "{width}");
        });
    }

    #[test]
    fn material_2_extended_rail_animates_the_width_and_labels_appear_text_direction_ltr() {
        test_widgets(|tester| {
            let pump = |tester: &mut WidgetTester, extended: bool| {
                let root = {
                    let app = tester.cell.borrow();
                    material_app(
                        theme(&app, false),
                        Scaffold::new()
                            .body(
                                Row::new().children([
                                    NavigationRail::new(destinations(), Some(0))
                                        .extended(extended)
                                        .into_widget(),
                                    Expanded::new(Text::new("body")).into_widget(),
                                ]),
                            )
                            .into_widget(),
                    )
                };
                tester.pump_widget(root);
            };
            pump(tester, false);

            let rail = rail_box(tester);
            assert_eq!(tester.get_size(rail).width(), 72.0);

            pump(tester, true);
            tester.pump_by(Duration::from_millis(100));
            assert_eq!(tester.get_size(rail).width(), 164.0);

            tester.pump_and_settle();
            assert_eq!(tester.get_size(rail).width(), 256.0);

            // The first destination is 8 from the top because of the default vertical
            // padding at the to of the rail; each next one is 72 below the one before.
            let mut next_destination_y = 8.0;
            for (icon, label) in icons_in_order()
                .into_iter()
                .zip(["Abc", "Def", "Ghi", "Jkl"])
            {
                expect_icon_at(
                    tester,
                    icon_render_box(tester, icon),
                    72.0,
                    72.0,
                    next_destination_y,
                );
                let label = label_render_box(tester, label);
                assert_offset(
                    global_top_left(tester, label),
                    Offset::new(
                        72.0,
                        next_destination_y + (72.0 - tester.get_size(label).height()) / 2.0,
                    ),
                );
                next_destination_y += 72.0;
            }
        });
    }

    #[test]
    fn material_2_navigation_rail_destination_adds_circular_indicator_when_no_labels_are_present() {
        test_widgets(|tester| {
            pump_navigation_rail_with(
                tester,
                NavigationRail::new(abc_def_ghi(), Some(0))
                    .use_indicator(true)
                    .label_type(NavigationRailLabelType::None),
                m2(),
            );

            let indicator = find::by_type::<NavigationIndicator>().evaluate(tester)[0];
            let (width, height) = tester.widget(indicator, |indicator: &NavigationIndicator| {
                (indicator.width, indicator.height)
            });
            assert_eq!(width, 56.0);
            assert_eq!(height, 56.0);
        });
    }

    #[test]
    fn material_2_navigation_rail_destination_has_center_aligned_indicator_label_type_none() {
        has_center_aligned_indicator(false, 24.0);
    }

    #[test]
    fn material_2_navigation_rail_respects_the_notch_system_navigation_bar_in_landscape_mode() {
        respects_the_notch(false, 72.0);
    }
}