waft-widgets 0.18.2

Widget framework and 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
//! Flutter counterpart: `widgets/routes.dart`.

use crate::widgets::actions::ActionRef;
use crate::widgets::navigator::RouteRef;
use crate::widgets::scroll_controller::ScrollControllerRef;
use std::any::Any;
use std::collections::HashMap;
use std::fmt::{self, Debug};
use std::rc::Rc;
use std::time::Duration;

use waft_animation::{
    Animatable, Animation, AnimationBehavior, AnimationController, AnimationRef, AnimationStatus,
    AnimationStatusListener, AnyAnimation, ColorTween, Curve, CurveTween, Curves, Drive,
    ProxyAnimation, TrainHoppingAnimation, k_always_complete_animation,
    k_always_dismissed_animation,
};
use waft_foundation::{
    App, Completer, CompleterFuture, DiagnosticPropertiesBuilder, FlagProperty, Handle, HandleId,
    Listener, MergingListenable, Retained, ValueListenable,
};
use waft_painting::Color;
use waft_physics::Simulation;
use waft_rendering::OrdinalSortKey;
use waft_scheduler::{FrameCallback, SchedulerBinding, SchedulerPhase, TickerFuture};

use crate::framework::{
    BuildContext, GlobalKey, InheritedModel, InheritedWidget, IntoWidget, KeyRef, Notification,
    State, StateData, StatefulWidget, WidgetRef,
};
use crate::view::View;
use crate::widgets::actions::{Action, ActionData, Actions, DismissAction, DismissIntent};
use crate::widgets::basic::{Builder, IgnorePointer, Offstage, RepaintBoundary, Semantics};
use crate::widgets::focus_manager::{FocusNodeLeaf, FocusScopeNode, TraversalEdgeBehavior};
use crate::widgets::focus_scope::FocusScope;
use crate::widgets::modal_barrier::{AnimatedModalBarrier, ModalBarrier};
use crate::widgets::navigator::{
    AnyRoute, NavigationNotification, Navigator, NavigatorObserver, NavigatorObserverData, Route,
    RouteBase, RoutePopDisposition, RoutePredicate, RouteResult, RouteSettingsRef,
};
use crate::widgets::overlay::OverlayEntry;
use crate::widgets::page_storage::{PageStorage, PageStorageBucket};
use crate::widgets::primary_scroll_controller::PrimaryScrollController;
use crate::widgets::restoration::RestorationScope;
use crate::widgets::scroll_controller::ScrollController;
use crate::widgets::scroll_controller::ScrollControllerLeaf;
use crate::widgets::transitions::{AnimatedBuilder, DelegatedTransitionBuilder, ListenableBuilder};
use waft_foundation::OptionRetained;
use waft_foundation::Ref;

// ---------------------------------------------------------------------------------------------
// OverlayRoute

/// The fields Dart's `OverlayRoute` declares; every overlay route carries this bag under the
/// field `overlay_route`.
pub struct OverlayRouteData {
    overlay_entries: Vec<Ref<OverlayEntry>>,
}

impl OverlayRouteData {
    /// The bag of a freshly created overlay route.
    pub fn new() -> OverlayRouteData {
        OverlayRouteData {
            overlay_entries: Vec::new(),
        }
    }
}

impl Default for OverlayRouteData {
    fn default() -> OverlayRouteData {
        OverlayRouteData::new()
    }
}

/// The accessors [`OverlayRoute`] asks for, for a struct whose bag is the field
/// `overlay_route`.
#[macro_export]
macro_rules! overlay_route_accessors {
    () => {
        fn overlay_route_data(
            self: ::waft_foundation::Handle<Self>,
            app: &::waft_foundation::App,
        ) -> &$crate::OverlayRouteData {
            &app.get(self).overlay_route
        }

        fn overlay_route_data_mut(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
        ) -> &mut $crate::OverlayRouteData {
            &mut app.get_mut(self).overlay_route
        }
    };
}

/// A route that displays widgets in the [`Navigator`]'s `Overlay`.
///
/// See also:
///
///  * [`Route`], which documents the meaning of Dart's `T` generic type argument.
pub trait OverlayRoute: Route {
    /// Dart's `OverlayRoute` fields, held under the field `overlay_route`
    /// ([`overlay_route_accessors!`](crate::overlay_route_accessors)).
    fn overlay_route_data(self: Handle<Self>, app: &App) -> &OverlayRouteData;

    /// See [`overlay_route_data`](Self::overlay_route_data).
    fn overlay_route_data_mut(self: Handle<Self>, app: &mut App) -> &mut OverlayRouteData;

    /// Subclasses should override this method to return the builders for the overlay.
    fn create_overlay_entries(self: Handle<Self>, app: &mut App) -> Vec<Ref<OverlayEntry>>;

    /// Dart's `OverlayRoute.overlayEntries`.
    fn overlay_entries(self: Handle<Self>, app: &App) -> Vec<Handle<OverlayEntry>> {
        self.overlay_route_data(app)
            .overlay_entries
            .iter()
            .map(Retained::handle)
            .collect()
    }

    /// Dart's `OverlayRoute.install`.
    fn install(self: Handle<Self>, app: &mut App) {
        debug_assert!(self.overlay_route_data(app).overlay_entries.is_empty());
        let entries = OverlayRoute::create_overlay_entries(self, app);
        self.overlay_route_data_mut(app)
            .overlay_entries
            .extend(entries);
        RouteBase::install(self, app);
    }

    /// Controls whether [`did_pop`](Self::did_pop) calls [`NavigatorState::finalize_route`](crate::NavigatorState::finalize_route).
    ///
    /// If true, this route removes its overlay entries during
    /// [`did_pop`](Route::did_pop). Subclasses can override this getter if they want to delay
    /// finalization (for example to animate the route's exit before removing it from the
    /// overlay).
    ///
    /// Subclasses that return false from `finished_when_popped` are responsible for calling
    /// [`NavigatorState::finalize_route`](crate::NavigatorState::finalize_route) themselves.
    fn finished_when_popped(self: Handle<Self>, app: &App) -> bool {
        let _ = app;
        true
    }

    /// Dart's `OverlayRoute.didPop`.
    fn did_pop(self: Handle<Self>, app: &mut App, result: RouteResult) -> bool {
        let return_value = RouteBase::did_pop(self, app, result);
        debug_assert!(return_value);
        if OverlayRoute::finished_when_popped(self, app) {
            let navigator = self
                .as_route()
                .navigator(app)
                .expect("a popped route is installed");
            navigator.finalize_route(app, self.as_route());
        }
        return_value
    }

    /// Dart's `OverlayRoute.dispose`.
    fn dispose(self: Handle<Self>, app: &mut App) {
        for entry in OverlayRoute::overlay_entries(self, app) {
            entry.dispose(app);
        }
        self.overlay_route_data_mut(app).overlay_entries.clear();
        RouteBase::dispose(self, app);
    }
}

// ---------------------------------------------------------------------------------------------
// TransitionRoute

/// The fields Dart's `TransitionRoute` declares; every transition route carries this bag under
/// the field `transition_route`.
pub struct TransitionRouteData {
    transition_completer: Completer<RouteResult>,
    pop_finalized: bool,
    animation: Option<AnimationRef<f64>>,
    controller: Option<Ref<AnimationController>>,
    secondary_animation: Ref<ProxyAnimation>,
    /// Whether to takeover the [`controller`](TransitionRoute::controller) created by
    /// [`create_animation_controller`](TransitionRoute::create_animation_controller).
    ///
    /// If true, this route will call `AnimationController::dispose` when the controller is no
    /// longer needed. If false, the controller should be disposed by whoever owned it.
    ///
    /// It defaults to `true`.
    pub will_dispose_animation_controller: bool,
    result: RouteResult,
    train_hopping_listener_remover: Option<TrainHoppingListenerRemover>,
}

/// Dart's `_trainHoppingListenerRemover`: disposes the running train-hopping animation and
/// removes its listener.
type TrainHoppingListenerRemover = Rc<dyn Fn(&mut App)>;

impl TransitionRouteData {
    /// The bag of a freshly created transition route.
    pub fn new(app: &mut App) -> TransitionRouteData {
        let dismissed = k_always_dismissed_animation(app);
        TransitionRouteData {
            transition_completer: Completer::new(),
            pop_finalized: false,
            animation: None,
            controller: None,
            secondary_animation: ProxyAnimation::new(app, Some(dismissed)),
            will_dispose_animation_controller: true,
            result: None,
            train_hopping_listener_remover: None,
        }
    }
}

/// The accessors [`TransitionRoute`] asks for, for a struct whose bag is the field
/// `transition_route`.
#[macro_export]
macro_rules! transition_route_accessors {
    () => {
        fn transition_route_data(
            self: ::waft_foundation::Handle<Self>,
            app: &::waft_foundation::App,
        ) -> &$crate::TransitionRouteData {
            &app.get(self).transition_route
        }

        fn transition_route_data_mut(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
        ) -> &mut $crate::TransitionRouteData {
            &mut app.get_mut(self).transition_route
        }
    };
}

/// An interface for a route that supports predictive back gestures.
pub trait PredictiveBackRoute: Route {
    /// Whether a pop gesture can be started by the user for this route.
    fn pop_gesture_enabled(self: Handle<Self>, app: &mut App) -> bool;

    /// Handles a predictive back gesture starting.
    ///
    /// The `progress` parameter indicates the progress of the gesture from 0.0 to 1.0.
    fn handle_start_back_gesture(self: Handle<Self>, app: &mut App, progress: f64);

    /// Handles a predictive back gesture updating as the user drags across the screen.
    ///
    /// The `progress` parameter indicates the progress of the gesture from 0.0 to 1.0.
    fn handle_update_back_gesture_progress(self: Handle<Self>, app: &mut App, progress: f64);

    /// Handles a predictive back gesture ending successfully.
    fn handle_commit_back_gesture(self: Handle<Self>, app: &mut App);

    /// Handles a predictive back gesture ending in cancellation.
    fn handle_cancel_back_gesture(self: Handle<Self>, app: &mut App);
}

/// A route with entrance and exit transitions.
///
/// See also:
///
///  * [`Route`], which documents the meaning of Dart's `T` generic type argument.
pub trait TransitionRoute: OverlayRoute + PredictiveBackRoute {
    /// Dart's `TransitionRoute` fields, held under the field `transition_route`
    /// ([`transition_route_accessors!`](crate::transition_route_accessors)).
    fn transition_route_data(self: Handle<Self>, app: &App) -> &TransitionRouteData;

    /// See [`transition_route_data`](Self::transition_route_data).
    fn transition_route_data_mut(self: Handle<Self>, app: &mut App) -> &mut TransitionRouteData;

    /// This route as the erased [`AnyTransitionRoute`].
    fn as_transition_route(self: Handle<Self>) -> AnyTransitionRoute {
        AnyTransitionRoute {
            id: self.id(),
            vtable: const { &TransitionRouteVTable::of::<Self>() },
        }
    }

    /// This future completes only once the transition itself has finished, after the overlay
    /// entries have been removed from the navigator's overlay.
    ///
    /// This future completes once the animation has been dismissed. That will be after
    /// [`popped`](Route::popped), because `popped` typically completes before the animation
    /// even starts, as soon as the route is popped.
    fn completed(self: Handle<Self>, app: &App) -> CompleterFuture<RouteResult> {
        self.transition_route_data(app)
            .transition_completer
            .future()
    }

    /// The duration the transition going forwards.
    ///
    /// See also:
    ///
    ///  * [`reverse_transition_duration`](Self::reverse_transition_duration), which controls
    ///    the duration of the transition when it is in reverse.
    fn transition_duration(self: Handle<Self>, app: &mut App) -> Duration;

    /// The duration the transition going in reverse.
    ///
    /// By default, the reverse transition duration is set to the value of the forwards
    /// [`transition_duration`](Self::transition_duration).
    fn reverse_transition_duration(self: Handle<Self>, app: &mut App) -> Duration {
        TransitionRoute::transition_duration(self, app)
    }

    /// Whether the route obscures previous routes when the transition is complete.
    ///
    /// When an opaque route's entrance transition is complete, the routes behind the opaque
    /// route will not be built to save resources.
    fn opaque(self: Handle<Self>, app: &App) -> bool;

    /// Whether the route transition will prefer to animate a snapshot of the entering and
    /// exiting routes.
    fn allow_snapshotting(self: Handle<Self>, app: &App) -> bool {
        let _ = app;
        true
    }

    /// Dart's `TransitionRoute.finishedWhenPopped`.
    ///
    /// This ensures that if we got to the dismissed state while still current, we will still be
    /// disposed when we are eventually popped.
    fn finished_when_popped(self: Handle<Self>, app: &App) -> bool {
        let controller = self
            .transition_route_data(app)
            .controller
            .handle()
            .expect("an installed route");
        controller.status(app).is_dismissed() && !self.transition_route_data(app).pop_finalized
    }

    /// The animation that drives the route's transition and the previous route's forward
    /// transition.
    fn animation(self: Handle<Self>, app: &App) -> Option<AnyAnimation<f64>> {
        self.transition_route_data(app).animation.handle()
    }

    /// The animation controller that the route uses to drive the transitions.
    ///
    /// The animation itself is exposed by [`animation`](Self::animation).
    fn controller(self: Handle<Self>, app: &App) -> Option<Handle<AnimationController>> {
        self.transition_route_data(app).controller.handle()
    }

    /// The animation for the route being pushed on top of this route.
    ///
    /// This animation lets this route coordinate with the entrance and exit transition of the
    /// route pushed on top of this route.
    fn secondary_animation(self: Handle<Self>, app: &App) -> Option<AnyAnimation<f64>> {
        Some(
            self.transition_route_data(app)
                .secondary_animation
                .as_animation(),
        )
    }

    /// Returns true if the transition has completed.
    ///
    /// It is equivalent to whether the future returned by [`completed`](Self::completed) has
    /// completed.
    ///
    /// This method only works when debug assertions are enabled. Otherwise it always returns
    /// false.
    fn debug_transition_completed(self: Handle<Self>, app: &App) -> bool {
        let mut disposed = false;
        if cfg!(debug_assertions) {
            disposed = self
                .transition_route_data(app)
                .transition_completer
                .is_completed();
        }
        disposed
    }

    /// Called to create the animation controller that will drive the transitions to this route
    /// from the previous one, and back to the previous route from this one.
    ///
    /// The returned controller will be disposed by `AnimationController::dispose` if
    /// [`will_dispose_animation_controller`](TransitionRouteData::will_dispose_animation_controller)
    /// is true.
    fn create_animation_controller(self: Handle<Self>, app: &mut App) -> Ref<AnimationController> {
        debug_assert!(
            !TransitionRoute::debug_transition_completed(self, app),
            "cannot reuse a route after disposing it"
        );
        let duration = TransitionRoute::transition_duration(self, app);
        let reverse_duration = TransitionRoute::reverse_transition_duration(self, app);
        let navigator = self
            .as_route()
            .navigator(app)
            .expect("an installed route has a navigator");
        AnimationController::new(
            app,
            None,
            Some(duration),
            Some(reverse_duration),
            0.0,
            1.0,
            AnimationBehavior::Normal,
            navigator,
        )
    }

    /// Called to create the animation that exposes the current progress of the transition
    /// controlled by the animation controller created by
    /// [`create_animation_controller`](Self::create_animation_controller).
    fn create_animation(self: Handle<Self>, app: &mut App) -> AnimationRef<f64> {
        TransitionRouteBase::create_animation(self, app)
    }

    /// Creates the simulation that drives the transition animation for this route.
    ///
    /// By default, this method returns `None`, indicating that the route doesn't use
    /// simulations, but initiates the transition by calling either `AnimationController::forward`
    /// or `AnimationController::reverse` with
    /// [`transition_duration`](Self::transition_duration) and the controller's curve.
    ///
    /// Subclasses can override this method to return a simulation. In that case the
    /// [`controller`](Self::controller) will instead use the provided simulation to animate the
    /// transition using `AnimationController::animate_with` or
    /// `AnimationController::animate_back_with`, and the simulation's `x` is forwarded to the
    /// value of [`animation`](Self::animation). The controller's curve and
    /// [`transition_duration`](Self::transition_duration) are ignored.
    ///
    /// This method is invoked each time the navigator pushes or pops this route. The `forward`
    /// parameter indicates the direction of the transition: true when the route is pushed, and
    /// false when it is popped.
    fn create_simulation(
        self: Handle<Self>,
        app: &mut App,
        forward: bool,
    ) -> Option<Box<dyn Simulation>> {
        let _ = forward;
        debug_assert!(
            TransitionRoute::transition_duration(self, app) >= Duration::ZERO,
            "the duration must be positive for a non-simulation animation"
        );
        None
    }

    /// Dart's `_createSimulationAndVerify`.
    fn create_simulation_and_verify(
        self: Handle<Self>,
        app: &mut App,
        forward: bool,
    ) -> Option<Box<dyn Simulation>> {
        let simulation = TransitionRoute::create_simulation(self, app, forward);
        debug_assert!(
            TransitionRoute::transition_duration(self, app) >= Duration::ZERO,
            "the duration must be positive for an animation that doesn't use a simulation; \
             either set transition_duration or set create_simulation"
        );
        simulation
    }

    /// Dart's `_handleStatusChanged`.
    fn handle_status_changed(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
        match status {
            AnimationStatus::Completed => {
                let entries = Route::overlay_entries(self, app);
                if let Some(first) = entries.first().copied() {
                    let opaque = TransitionRoute::opaque(self, app);
                    first.set_opaque(app, opaque);
                }
            }
            AnimationStatus::Forward | AnimationStatus::Reverse => {
                let entries = Route::overlay_entries(self, app);
                if let Some(first) = entries.first().copied() {
                    first.set_opaque(app, false);
                }
            }
            AnimationStatus::Dismissed => {
                // We might still be an active route if a subclass is controlling the
                // transition and hits the dismissed status. For example, the iOS back gesture
                // drives this animation to the dismissed status before removing the route and
                // disposing it.
                if !self.as_route().is_active(app) {
                    let navigator = self
                        .as_route()
                        .navigator(app)
                        .expect("an active route has a navigator");
                    navigator.finalize_route(app, self.as_route());
                    self.transition_route_data_mut(app).pop_finalized = true;
                }
            }
        }
    }

    /// Dart's `TransitionRoute.install`.
    fn install(self: Handle<Self>, app: &mut App) {
        debug_assert!(
            !TransitionRoute::debug_transition_completed(self, app),
            "cannot install a route after disposing it"
        );
        let controller = TransitionRoute::create_animation_controller(self, app);
        self.transition_route_data_mut(app).controller = Some(controller);
        let animation = TransitionRoute::create_animation(self, app);
        animation.add_status_listener(
            app,
            AnimationStatusListener::handle_method(self, Self::handle_status_changed),
        );
        let animation_handle = animation.handle();
        self.transition_route_data_mut(app).animation = Some(animation);
        OverlayRoute::install(self, app);
        let entries = Route::overlay_entries(self, app);
        if animation_handle.is_completed(app)
            && let Some(first) = entries.first().copied()
        {
            let opaque = TransitionRoute::opaque(self, app);
            first.set_opaque(app, opaque);
        }
    }

    /// Dart's `TransitionRoute.didPush`.
    fn did_push(self: Handle<Self>, app: &mut App) -> TickerFuture {
        debug_assert!(
            self.transition_route_data(app).controller.is_some(),
            "didPush called before install or after dispose"
        );
        debug_assert!(
            !TransitionRoute::debug_transition_completed(self, app),
            "cannot reuse a route after disposing it"
        );
        RouteBase::did_push(self, app);
        let simulation = TransitionRoute::create_simulation_and_verify(self, app, true);
        let controller = self
            .transition_route_data(app)
            .controller
            .handle()
            .expect("installed");
        match simulation {
            None => controller.forward(app, None),
            Some(simulation) => controller.animate_with(app, simulation),
        }
    }

    /// Dart's `TransitionRoute.didAdd`.
    fn did_add(self: Handle<Self>, app: &mut App) {
        debug_assert!(
            self.transition_route_data(app).controller.is_some(),
            "didAdd called before install or after dispose"
        );
        debug_assert!(
            !TransitionRoute::debug_transition_completed(self, app),
            "cannot reuse a route after disposing it"
        );
        RouteBase::did_add(self, app);
        let controller = self
            .transition_route_data(app)
            .controller
            .handle()
            .expect("installed");
        let upper_bound = app.get(controller).upper_bound;
        controller.set_value(app, upper_bound);
    }

    /// Dart's `TransitionRoute.didReplace`.
    fn did_replace(self: Handle<Self>, app: &mut App, old_route: Option<AnyRoute>) {
        debug_assert!(
            self.transition_route_data(app).controller.is_some(),
            "didReplace called before install or after dispose"
        );
        debug_assert!(
            !TransitionRoute::debug_transition_completed(self, app),
            "cannot reuse a route after disposing it"
        );
        if let Some(old) = old_route.and_then(|route| route.as_transition_route(app)) {
            let value = old.controller_value(app);
            let controller = self
                .transition_route_data(app)
                .controller
                .handle()
                .expect("installed");
            controller.set_value(app, value);
        }
        RouteBase::did_replace(self, app, old_route);
    }

    /// Dart's `TransitionRoute.didPop`.
    fn did_pop(self: Handle<Self>, app: &mut App, result: RouteResult) -> bool {
        debug_assert!(
            self.transition_route_data(app).controller.is_some(),
            "didPop called before install or after dispose"
        );
        debug_assert!(
            !self
                .transition_route_data(app)
                .transition_completer
                .is_completed(),
            "cannot reuse a route after disposing it"
        );
        self.transition_route_data_mut(app).result = result.clone();
        let simulation = TransitionRoute::create_simulation_and_verify(self, app, false);
        let controller = self
            .transition_route_data(app)
            .controller
            .handle()
            .expect("installed");
        match simulation {
            None => {
                controller.reverse(app, None);
            }
            Some(simulation) => {
                controller.animate_back_with(app, simulation);
            }
        }
        OverlayRoute::did_pop(self, app, result)
    }

    /// Dart's `TransitionRoute.didPopNext`.
    fn did_pop_next(self: Handle<Self>, app: &mut App, next_route: AnyRoute) {
        debug_assert!(
            self.transition_route_data(app).controller.is_some(),
            "didPopNext called before install or after dispose"
        );
        debug_assert!(
            !TransitionRoute::debug_transition_completed(self, app),
            "cannot reuse a route after disposing it"
        );
        TransitionRoute::update_secondary_animation(self, app, Some(next_route));
        RouteBase::did_pop_next(self, app, next_route);
    }

    /// Dart's `TransitionRoute.didChangeNext`.
    fn did_change_next(self: Handle<Self>, app: &mut App, next_route: Option<AnyRoute>) {
        debug_assert!(
            self.transition_route_data(app).controller.is_some(),
            "didChangeNext called before install or after dispose"
        );
        debug_assert!(
            !TransitionRoute::debug_transition_completed(self, app),
            "cannot reuse a route after disposing it"
        );
        TransitionRoute::update_secondary_animation(self, app, next_route);
        RouteBase::did_change_next(self, app, next_route);
    }

    /// Dart's `_updateSecondaryAnimation`.
    fn update_secondary_animation(self: Handle<Self>, app: &mut App, next_route: Option<AnyRoute>) {
        // There is an existing train hopping in progress. Unfortunately, we cannot dispose the
        // current train hopping animation until we replace it with a new animation.
        let previous_train_hopping_listener_remover = self
            .transition_route_data_mut(app)
            .train_hopping_listener_remover
            .take();

        let next = next_route.and_then(|route| route.as_transition_route(app));
        let coordinates = match next {
            Some(next) => {
                TransitionRoute::can_transition_to(self, app, next)
                    && next.can_transition_from(app, TransitionRoute::as_transition_route(self))
            }
            None => false,
        };

        if let (Some(next), true) = (next, coordinates) {
            let secondary = self.transition_route_data(app).secondary_animation.handle();
            match secondary.parent(app) {
                Some(current) => {
                    let current_train = match current.downcast::<TrainHoppingAnimation>(app) {
                        Some(hopping) => app.get(hopping).current_train().expect("a running train"),
                        None => current,
                    };
                    let next_train = next.underlying_animation(app).expect("an installed route");
                    if current_train.value(app) == next_train.value(app)
                        || !next_train.is_animating(app)
                    {
                        let next_train = next_train.keep(app);
                        TransitionRoute::set_secondary_animation(
                            self,
                            app,
                            Some(next_train),
                            Some(next.completed(app)),
                        );
                    } else {
                        // Two trains animate at different values. We have to do train hopping.
                        // There are three possibilities of train hopping:
                        //  1. We hop on the next train when two trains meet in the middle using
                        //     `TrainHoppingAnimation`.
                        //  2. There is no chance to hop on the next train because two trains
                        //     never cross each other. We have to directly set the animation to
                        //     the next train once the next train stops animating.
                        //  3. A new `update_secondary_animation` is called before train hopping
                        //     finishes. We leave a listener remover for the next call to
                        //     properly clean up the existing train hopping.
                        let slot: Rc<std::cell::RefCell<Option<Ref<TrainHoppingAnimation>>>> =
                            Rc::new(std::cell::RefCell::new(None));
                        // Registered on the next train, so it names that train and this route
                        // bare, and does nothing once either is no longer kept.
                        let jump_on_animation_end =
                            AnimationStatusListener::new(move |status: AnimationStatus, app| {
                                if status.is_animating() || self.upgrade(app).is_none() {
                                    return;
                                }
                                // The next train has stopped animating without train hopping.
                                // Directly sets the secondary animation and disposes the
                                // `TrainHoppingAnimation`.
                                let kept_train = next_train.upgrade(app);
                                TransitionRoute::set_secondary_animation(
                                    self,
                                    app,
                                    kept_train,
                                    Some(next.completed(app)),
                                );
                                if let Some(remover) = self
                                    .transition_route_data_mut(app)
                                    .train_hopping_listener_remover
                                    .take()
                                {
                                    remover(app);
                                }
                            });
                        // The remover holds the hopping animation, and lets go of it when it
                        // runs; the animation's own callback names it only weakly, or the two
                        // would keep each other.
                        let remover = {
                            let listener = jump_on_animation_end.clone();
                            let slot = Rc::clone(&slot);
                            Rc::new(move |app: &mut App| {
                                next_train.remove_status_listener(app, &listener);
                                let hopping = slot.borrow_mut().take();
                                if let Some(animation) = hopping {
                                    animation.dispose(app);
                                }
                            })
                        };
                        self.transition_route_data_mut(app)
                            .train_hopping_listener_remover = Some(remover);
                        next_train.add_status_listener(app, jump_on_animation_end);
                        let on_switched_train = {
                            let slot = Rc::downgrade(&slot);
                            Listener::new(move |app| {
                                let new_animation = slot
                                    .upgrade()
                                    .and_then(|slot| slot.borrow().as_ref().map(Retained::handle))
                                    .expect("the hopping animation, kept until the remover runs");
                                debug_assert!(
                                    self.transition_route_data(app)
                                        .secondary_animation
                                        .parent(app)
                                        == Some(new_animation.as_animation())
                                );
                                let current = app.get(new_animation).current_train();
                                debug_assert!(current == next.underlying_animation(app));
                                // We can hop on the next train, so we don't need to listen to
                                // whether the next train has stopped.
                                let current = current.and_then(|current| current.upgrade(app));
                                TransitionRoute::set_secondary_animation(
                                    self,
                                    app,
                                    current,
                                    Some(next.completed(app)),
                                );
                                if let Some(remover) = self
                                    .transition_route_data_mut(app)
                                    .train_hopping_listener_remover
                                    .take()
                                {
                                    remover(app);
                                }
                            })
                        };
                        let current_train = current_train.keep(app);
                        let kept_next_train = next_train.keep(app);
                        let new_animation = TrainHoppingAnimation::new(
                            app,
                            current_train,
                            Some(kept_next_train),
                            Some(on_switched_train),
                        );
                        let erased: AnimationRef<f64> = new_animation.erase();
                        *slot.borrow_mut() = Some(new_animation);
                        self.set_secondary_animation(app, Some(erased), Some(next.completed(app)));
                    }
                }
                None => {
                    let animation = next
                        .underlying_animation(app)
                        .and_then(|animation| animation.upgrade(app));
                    TransitionRoute::set_secondary_animation(
                        self,
                        app,
                        animation,
                        Some(next.completed(app)),
                    );
                }
            }
        } else {
            let dismissed = k_always_dismissed_animation(app);
            TransitionRoute::set_secondary_animation(self, app, Some(dismissed), None);
        }
        // Finally, we dispose any previous train hopping animation because it has been
        // successfully updated at this point.
        if let Some(remover) = previous_train_hopping_listener_remover {
            remover(app);
        }
    }

    /// Dart's `_setSecondaryAnimation`.
    fn set_secondary_animation(
        self: Handle<Self>,
        app: &mut App,
        animation: Option<AnimationRef<f64>>,
        disposed: Option<CompleterFuture<RouteResult>>,
    ) {
        let secondary = self.transition_route_data(app).secondary_animation.clone();
        let animation_handle = animation.handle();
        secondary.set_parent(app, animation);
        // Releases the reference to the next route's animation when that route is disposed.
        if let Some(disposed) = disposed {
            disposed.then(app, move |app, _| {
                if secondary.parent(app) == animation_handle {
                    let dismissed = k_always_dismissed_animation(app);
                    secondary.set_parent(app, Some(dismissed));
                    if let Some(animation) = animation_handle
                        && let Some(hopping) = animation.downcast::<TrainHoppingAnimation>(app)
                    {
                        hopping.dispose(app);
                    }
                }
            });
        }
    }

    /// Returns true if this route supports a transition animation that runs when `next_route`
    /// is pushed on top of it or when `next_route` is popped off of it.
    ///
    /// Subclasses can override this method to restrict the set of routes they need to
    /// coordinate transitions with.
    ///
    /// Returns true by default.
    fn can_transition_to(self: Handle<Self>, app: &App, next_route: AnyTransitionRoute) -> bool {
        let _ = (app, next_route);
        true
    }

    /// Returns true if `previous_route` should animate when this route is pushed on top of it
    /// or when this route is popped off of it.
    ///
    /// Subclasses can override this method to restrict the set of routes they need to
    /// coordinate transitions with.
    ///
    /// Returns true by default.
    fn can_transition_from(
        self: Handle<Self>,
        app: &App,
        previous_route: AnyTransitionRoute,
    ) -> bool {
        let _ = (app, previous_route);
        true
    }

    // ---- PredictiveBackRoute ----

    /// Dart's `TransitionRoute.handleStartBackGesture`.
    fn handle_start_back_gesture(self: Handle<Self>, app: &mut App, progress: f64) {
        debug_assert!(self.as_route().is_current(app));
        if let Some(controller) = self.transition_route_data(app).controller.handle() {
            controller.set_value(app, progress);
        }
        if let Some(navigator) = self.as_route().navigator(app) {
            navigator.did_start_user_gesture(app);
        }
    }

    /// Dart's `TransitionRoute.handleUpdateBackGestureProgress`.
    fn handle_update_back_gesture_progress(self: Handle<Self>, app: &mut App, progress: f64) {
        // If some other navigation happened during this gesture, don't mess with the transition
        // anymore.
        if !self.as_route().is_current(app) {
            return;
        }
        if let Some(controller) = self.transition_route_data(app).controller.handle() {
            controller.set_value(app, progress);
        }
    }

    /// Dart's `TransitionRoute.handleCancelBackGesture`.
    fn handle_cancel_back_gesture(self: Handle<Self>, app: &mut App) {
        TransitionRoute::handle_drag_end(self, app, true);
    }

    /// Dart's `TransitionRoute.handleCommitBackGesture`.
    fn handle_commit_back_gesture(self: Handle<Self>, app: &mut App) {
        TransitionRoute::handle_drag_end(self, app, false);
    }

    /// Dart's `_handleDragEnd`.
    fn handle_drag_end(self: Handle<Self>, app: &mut App, animate_forward: bool) {
        if self.as_route().is_current(app) {
            let controller = self
                .transition_route_data(app)
                .controller
                .handle()
                .expect("installed");
            if animate_forward {
                // Typically, `handle_update_back_gesture_progress` will have already completed
                // the animation. If not, animate to completion.
                if !controller.status(app).is_completed() {
                    controller.forward(app, None);
                }
            } else {
                // This route is destined to pop at this point. Reuse the navigator's pop.
                if let Some(navigator) = self.as_route().navigator(app) {
                    navigator.pop(app, None);
                }
                // The popping may have finished inline if already at the target destination.
                if let Some(controller) = self.transition_route_data(app).controller.handle()
                    && controller.is_animating(app)
                {
                    let upper_bound = app.get(controller).upper_bound;
                    controller.reverse(app, Some(upper_bound));
                }
            }
        }

        let controller = self.transition_route_data(app).controller.handle();
        let animating = match controller {
            Some(controller) => controller.is_animating(app),
            None => false,
        };
        if animating {
            // Keep `user_gesture_in_progress` true, since the Android back-gesture page
            // transition depends on it.
            let controller = controller.expect("an animating controller");
            // The listener removes itself, naming itself weakly: it lives in the controller's
            // list and goes with it.
            let me: Rc<std::cell::OnceCell<waft_animation::WeakAnimationStatusListener>> =
                Rc::default();
            let listener = {
                let me = Rc::clone(&me);
                AnimationStatusListener::new(move |_status, app| {
                    if let Some(navigator) = self.as_route().navigator(app) {
                        navigator.did_stop_user_gesture(app);
                    }
                    if let Some(registered) = me
                        .get()
                        .and_then(waft_animation::WeakAnimationStatusListener::upgrade)
                    {
                        controller.remove_status_listener(app, &registered);
                    }
                })
            };
            let _ = me.set(listener.downgrade());
            controller.add_status_listener(app, listener);
        } else if let Some(navigator) = self.as_route().navigator(app) {
            navigator.did_stop_user_gesture(app);
        }
    }

    /// Dart's `TransitionRoute.dispose`.
    fn dispose(self: Handle<Self>, app: &mut App) {
        debug_assert!(
            !self
                .transition_route_data(app)
                .transition_completer
                .is_completed(),
            "cannot dispose a route twice"
        );
        if let Some(animation) = self.transition_route_data(app).animation.handle() {
            animation.remove_status_listener(
                app,
                &AnimationStatusListener::handle_method(self, Self::handle_status_changed),
            );
        }
        if self
            .transition_route_data(app)
            .will_dispose_animation_controller
            && let Some(controller) = self.transition_route_data(app).controller.handle()
        {
            controller.dispose(app);
        }
        let result = self.transition_route_data(app).result.clone();
        let transition_completer = self.transition_route_data(app).transition_completer.clone();
        transition_completer.complete(app, result);
        OverlayRoute::dispose(self, app);
    }

    /// A short description of this route useful for debugging.
    fn debug_label(self: Handle<Self>) -> String {
        std::any::type_name::<Self>().to_string()
    }
}

/// Dart's `TransitionRoute` bodies an override reaches as `super`.
///
/// Every [`TransitionRoute`] implements it. An override that must run the inherited body calls
/// it trait-qualified, `TransitionRouteBase::create_animation(self, app)`, where Dart writes
/// `super.createAnimation()`; the [`TransitionRoute`] default runs the same body.
pub trait TransitionRouteBase: TransitionRoute {
    /// `TransitionRoute.createAnimation`: the controller itself, as an animation.
    fn create_animation(self: Handle<Self>, app: &mut App) -> AnimationRef<f64> {
        debug_assert!(
            !TransitionRoute::debug_transition_completed(self, app),
            "cannot reuse a route after disposing it"
        );
        // Dart's `controller!.view`: the controller itself, as an animation.
        self.transition_route_data(app)
            .controller
            .as_ref()
            .expect("createAnimationController ran first")
            .erase()
    }
}

impl<T: TransitionRoute> TransitionRouteBase for T {}

/// The vtable of an erased [`AnyTransitionRoute`]: one `&'static` table per route type, built
/// by [`TransitionRouteVTable::of`].
struct TransitionRouteVTable {
    type_name: fn() -> &'static str,
    route: fn(HandleId) -> AnyRoute,
    animation: fn(&App, HandleId) -> Option<AnyAnimation<f64>>,
    underlying_animation: fn(&App, HandleId) -> Option<AnyAnimation<f64>>,
    controller: fn(&App, HandleId) -> Option<Handle<AnimationController>>,
    controller_value: fn(&App, HandleId) -> f64,
    opaque: fn(&App, HandleId) -> bool,
    allow_snapshotting: fn(&App, HandleId) -> bool,
    transition_duration: fn(&mut App, HandleId) -> Duration,
    reverse_transition_duration: fn(&mut App, HandleId) -> Duration,
    can_transition_to: fn(&App, HandleId, AnyTransitionRoute) -> bool,
    can_transition_from: fn(&App, HandleId, AnyTransitionRoute) -> bool,
    completed: fn(&App, HandleId) -> CompleterFuture<RouteResult>,
    pop_gesture_enabled: fn(&mut App, HandleId) -> bool,
    handle_start_back_gesture: fn(&mut App, HandleId, f64),
    handle_update_back_gesture_progress: fn(&mut App, HandleId, f64),
    handle_commit_back_gesture: fn(&mut App, HandleId),
    handle_cancel_back_gesture: fn(&mut App, HandleId),
}

impl TransitionRouteVTable {
    /// The table for one transition route type.
    const fn of<R: TransitionRoute>() -> TransitionRouteVTable {
        TransitionRouteVTable {
            type_name: std::any::type_name::<R>,
            route: |id| Route::as_route(resolve::<R>(id)),
            animation: |app, id| R::animation(resolve(id), app),
            underlying_animation: |app, id| {
                R::transition_route_data(resolve::<R>(id), app)
                    .animation
                    .handle()
            },
            controller: |app, id| R::controller(resolve(id), app),
            controller_value: |app, id| {
                let controller = R::transition_route_data(resolve::<R>(id), app)
                    .controller
                    .handle()
                    .expect("an installed route");
                controller.value(app)
            },
            opaque: |app, id| R::opaque(resolve(id), app),
            allow_snapshotting: |app, id| R::allow_snapshotting(resolve(id), app),
            transition_duration: |app, id| R::transition_duration(resolve(id), app),
            reverse_transition_duration: |app, id| R::reverse_transition_duration(resolve(id), app),
            can_transition_to: |app, id, next| R::can_transition_to(resolve(id), app, next),
            can_transition_from: |app, id, prev| R::can_transition_from(resolve(id), app, prev),
            completed: |app, id| R::completed(resolve(id), app),
            pop_gesture_enabled: |app, id| {
                PredictiveBackRoute::pop_gesture_enabled(resolve::<R>(id), app)
            },
            handle_start_back_gesture: |app, id, progress| {
                PredictiveBackRoute::handle_start_back_gesture(resolve::<R>(id), app, progress)
            },
            handle_update_back_gesture_progress: |app, id, progress| {
                PredictiveBackRoute::handle_update_back_gesture_progress(
                    resolve::<R>(id),
                    app,
                    progress,
                )
            },
            handle_commit_back_gesture: |app, id| {
                PredictiveBackRoute::handle_commit_back_gesture(resolve::<R>(id), app)
            },
            handle_cancel_back_gesture: |app, id| {
                PredictiveBackRoute::handle_cancel_back_gesture(resolve::<R>(id), app)
            },
        }
    }
}

/// Erased [`TransitionRoute`]: what Dart's `route is TransitionRoute<dynamic>` produces.
#[derive(Clone, Copy)]
pub struct AnyTransitionRoute {
    id: HandleId,
    vtable: &'static TransitionRouteVTable,
}

/// A kept route as a [`RouteRef`], through [`Retained::erase`]: Dart's upcast.
impl From<AnyTransitionRoute> for AnyRoute {
    fn from(route: AnyTransitionRoute) -> AnyRoute {
        route.as_route()
    }
}

/// A field Dart types as the erased object, kept: AnyTransitionRoute with its count.
pub type TransitionRouteRef = Retained<AnyTransitionRoute>;

waft_foundation::erased_handle!(AnyTransitionRoute: TransitionRoute => TransitionRoute::as_transition_route);

impl Debug for AnyTransitionRoute {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
    }
}

impl AnyTransitionRoute {
    /// This transition route as the erased [`AnyRoute`].
    pub fn as_route(self) -> AnyRoute {
        (self.vtable.route)(self.id)
    }

    /// See [`TransitionRoute::animation`].
    pub fn animation(self, app: &App) -> Option<AnyAnimation<f64>> {
        (self.vtable.animation)(app, self.id)
    }

    /// Dart's `_animation`: the animation a route runs on, under whatever
    /// [`animation`](Self::animation) answers with.
    ///
    /// A [`ModalRoute`] answers with a proxy that reads complete while the route is
    /// offstage, which is exactly when the route ahead is put offstage to be measured. A
    /// route behind follows this one instead, so it stays where it is until the transition
    /// really runs.
    pub fn underlying_animation(self, app: &App) -> Option<AnyAnimation<f64>> {
        (self.vtable.underlying_animation)(app, self.id)
    }

    /// See [`TransitionRoute::controller`].
    pub fn controller(self, app: &App) -> Option<Handle<AnimationController>> {
        (self.vtable.controller)(app, self.id)
    }

    /// The value of Dart's `_controller`, which `didReplace` copies.
    pub fn controller_value(self, app: &App) -> f64 {
        (self.vtable.controller_value)(app, self.id)
    }

    /// See [`TransitionRoute::opaque`].
    pub fn opaque(self, app: &App) -> bool {
        (self.vtable.opaque)(app, self.id)
    }

    /// See [`TransitionRoute::allow_snapshotting`].
    pub fn allow_snapshotting(self, app: &App) -> bool {
        (self.vtable.allow_snapshotting)(app, self.id)
    }

    /// See [`TransitionRoute::transition_duration`].
    pub fn transition_duration(self, app: &mut App) -> Duration {
        (self.vtable.transition_duration)(app, self.id)
    }

    /// See [`TransitionRoute::reverse_transition_duration`].
    pub fn reverse_transition_duration(self, app: &mut App) -> Duration {
        (self.vtable.reverse_transition_duration)(app, self.id)
    }

    /// See [`TransitionRoute::can_transition_to`].
    pub fn can_transition_to(self, app: &App, next_route: AnyTransitionRoute) -> bool {
        (self.vtable.can_transition_to)(app, self.id, next_route)
    }

    /// See [`TransitionRoute::can_transition_from`].
    pub fn can_transition_from(self, app: &App, previous_route: AnyTransitionRoute) -> bool {
        (self.vtable.can_transition_from)(app, self.id, previous_route)
    }

    /// See [`TransitionRoute::completed`].
    pub fn completed(self, app: &App) -> CompleterFuture<RouteResult> {
        (self.vtable.completed)(app, self.id)
    }

    /// See [`PredictiveBackRoute::pop_gesture_enabled`].
    pub fn pop_gesture_enabled(self, app: &mut App) -> bool {
        (self.vtable.pop_gesture_enabled)(app, self.id)
    }

    /// See [`PredictiveBackRoute::handle_start_back_gesture`].
    pub fn handle_start_back_gesture(self, app: &mut App, progress: f64) {
        (self.vtable.handle_start_back_gesture)(app, self.id, progress)
    }

    /// See [`PredictiveBackRoute::handle_update_back_gesture_progress`].
    pub fn handle_update_back_gesture_progress(self, app: &mut App, progress: f64) {
        (self.vtable.handle_update_back_gesture_progress)(app, self.id, progress)
    }

    /// See [`PredictiveBackRoute::handle_commit_back_gesture`].
    pub fn handle_commit_back_gesture(self, app: &mut App) {
        (self.vtable.handle_commit_back_gesture)(app, self.id)
    }

    /// See [`PredictiveBackRoute::handle_cancel_back_gesture`].
    pub fn handle_cancel_back_gesture(self, app: &mut App) {
        (self.vtable.handle_cancel_back_gesture)(app, self.id)
    }
}

/// The typed handle for an erased id. Free: nothing is looked up; `get` checks the slot.
fn resolve<L: 'static>(id: HandleId) -> Handle<L> {
    Handle::from_id(id)
}

// ---------------------------------------------------------------------------------------------
// LocalHistoryEntry / LocalHistoryRoute

/// An entry in the history of a [`LocalHistoryRoute`].
///
/// A [`LocalHistoryEntry`] represents a "mini" navigation state within a route. It allows
/// widgets or UI components to handle the back button or pop operations locally without
/// affecting the main navigator stack.
///
/// It is typically used for widgets such as dialogs, bottom sheets, or inline expandable panels
/// that can be dismissed independently of the surrounding route.
///
/// When a local history entry is removed (e.g. via the back button), the
/// [`on_remove`](Self::on_remove) callback is called first. Only after all local history
/// entries have been removed will the route itself be popped.
///
/// See also:
///
///  * [`LocalHistoryRoute`], which manages a stack of local history entries.
///  * [`LocalHistoryRoute::add_local_history_entry`], which adds an entry to a route.
pub struct LocalHistoryEntry {
    /// Called when this entry is removed from the history of its associated
    /// [`LocalHistoryRoute`].
    pub on_remove: Option<Listener>,
    owner: Option<AnyRoute>,
    /// Whether an app bar in the route this entry belongs to should automatically add a back
    /// button or close button.
    ///
    /// Defaults to true.
    pub implies_app_bar_dismissal: bool,
}

impl LocalHistoryEntry {
    /// Creates an entry in the history of a [`LocalHistoryRoute`]; Dart's optional arguments
    /// are the setters.
    ///
    /// [`implies_app_bar_dismissal`](Self::implies_app_bar_dismissal) defaults to true.
    pub fn new(app: &mut App) -> Ref<LocalHistoryEntry> {
        app.create(LocalHistoryEntry {
            on_remove: None,
            owner: None,
            implies_app_bar_dismissal: true,
        })
    }

    /// Dart `LocalHistoryEntry(onRemove:)`.
    pub fn on_remove(self: Ref<Self>, app: &mut App, on_remove: Listener) -> Ref<Self> {
        app.get_mut(&self).on_remove = Some(on_remove);
        self
    }

    /// Dart `LocalHistoryEntry(impliesAppBarDismissal:)`.
    pub fn implies_app_bar_dismissal(
        self: Ref<Self>,
        app: &mut App,
        implies_app_bar_dismissal: bool,
    ) -> Ref<Self> {
        app.get_mut(&self).implies_app_bar_dismissal = implies_app_bar_dismissal;
        self
    }

    /// Remove this entry from the history of its associated [`LocalHistoryRoute`].
    pub fn remove(self: Handle<Self>, app: &mut App) {
        if let Some(owner) = app.get(self).owner {
            let modal = owner
                .as_modal_route(app)
                .expect("a local history entry belongs to a modal route");
            modal.remove_local_history_entry(app, self);
        }
        debug_assert!(app.get(self).owner.is_none());
    }

    fn notify_removed(self: Handle<Self>, app: &mut App) {
        if let Some(on_remove) = app.get(self).on_remove.clone() {
            on_remove.call(app);
        }
    }
}

impl Debug for LocalHistoryEntry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("LocalHistoryEntry")
    }
}

/// The fields Dart's `LocalHistoryRoute` mixin declares; every route that mixes it in carries
/// this bag under the field `local_history`.
pub struct LocalHistoryRouteData {
    local_history: Option<Vec<Ref<LocalHistoryEntry>>>,
    entries_implies_app_bar_dismissal: i64,
}

impl LocalHistoryRouteData {
    /// The bag of a route with no local history.
    pub fn new() -> LocalHistoryRouteData {
        LocalHistoryRouteData {
            local_history: None,
            entries_implies_app_bar_dismissal: 0,
        }
    }
}

impl Default for LocalHistoryRouteData {
    fn default() -> LocalHistoryRouteData {
        LocalHistoryRouteData::new()
    }
}

/// The accessors [`LocalHistoryRoute`] asks for, for a struct whose bag is the field
/// `local_history`.
#[macro_export]
macro_rules! local_history_route_accessors {
    () => {
        fn local_history_route_data(
            self: ::waft_foundation::Handle<Self>,
            app: &::waft_foundation::App,
        ) -> &$crate::LocalHistoryRouteData {
            &app.get(self).local_history
        }

        fn local_history_route_data_mut(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
        ) -> &mut $crate::LocalHistoryRouteData {
            &mut app.get_mut(self).local_history
        }
    };
}

/// A mixin used by routes to handle back navigations internally by popping a list.
///
/// When a [`Navigator`] is instructed to pop, the current route is given an opportunity to
/// handle the pop internally. A [`LocalHistoryRoute`] handles the pop internally if its list of
/// local history entries is non-empty. Rather than being removed as the current route, the most
/// recent [`LocalHistoryEntry`] is removed from the list and its
/// [`LocalHistoryEntry::on_remove`] is called.
pub trait LocalHistoryRoute: TransitionRoute {
    /// Dart's `LocalHistoryRoute` fields, held under the field `local_history`
    /// ([`local_history_route_accessors!`](crate::local_history_route_accessors)).
    fn local_history_route_data(self: Handle<Self>, app: &App) -> &LocalHistoryRouteData;

    /// See [`local_history_route_data`](Self::local_history_route_data).
    fn local_history_route_data_mut(
        self: Handle<Self>,
        app: &mut App,
    ) -> &mut LocalHistoryRouteData;

    /// Adds a local history entry to this route.
    ///
    /// When asked to pop, if this route has any local history entries, this route will handle
    /// the pop internally by removing the most recently added local history entry.
    ///
    /// The given local history entry must not already be part of another local history route.
    fn add_local_history_entry(self: Handle<Self>, app: &mut App, entry: Ref<LocalHistoryEntry>) {
        debug_assert!(app.get(&entry).owner.is_none());
        app.get_mut(&entry).owner = Some(self.as_route());
        let implies_app_bar_dismissal = app.get(&entry).implies_app_bar_dismissal;
        let data = self.local_history_route_data_mut(app);
        let history = data.local_history.get_or_insert_with(Vec::new);
        let was_empty = history.is_empty();
        history.push(entry);
        let mut internal_state_changed = false;
        if implies_app_bar_dismissal {
            let data = self.local_history_route_data_mut(app);
            internal_state_changed = data.entries_implies_app_bar_dismissal == 0;
            data.entries_implies_app_bar_dismissal += 1;
        }
        if was_empty || internal_state_changed {
            Route::changed_internal_state(self, app);
        }
    }

    /// Removes a local history entry from this route.
    ///
    /// The entry's [`LocalHistoryEntry::on_remove`] callback, if any, is called synchronously.
    fn remove_local_history_entry(
        self: Handle<Self>,
        app: &mut App,
        entry: Handle<LocalHistoryEntry>,
    ) {
        debug_assert!(app.get(entry).owner == Some(self.as_route()));
        let data = self.local_history_route_data_mut(app);
        let history = data.local_history.as_mut().expect("a local history");
        debug_assert!(history.iter().any(|held| held == entry));
        let position = history.iter().position(|held| held == entry);
        let mut internal_state_changed = false;
        if let Some(position) = position {
            history.remove(position);
            if app.get(entry).implies_app_bar_dismissal {
                let data = self.local_history_route_data_mut(app);
                data.entries_implies_app_bar_dismissal -= 1;
                internal_state_changed = data.entries_implies_app_bar_dismissal == 0;
            }
        }
        app.get_mut(entry).owner = None;
        entry.notify_removed(app);
        let data = self.local_history_route_data(app);
        if data.local_history.as_ref().is_some_and(Vec::is_empty) || internal_state_changed {
            debug_assert_eq!(
                self.local_history_route_data(app)
                    .entries_implies_app_bar_dismissal,
                0
            );
            if SchedulerBinding::scheduler_phase(app) == SchedulerPhase::PersistentCallbacks {
                // The local history might be removed as a result of disposing inactive elements
                // during `finalize_tree`. The state is locked at this moment, and we can only
                // notify that state has changed in the next frame.
                SchedulerBinding::add_post_frame_callback(
                    app,
                    FrameCallback::new(move |app, _duration| {
                        if self.upgrade(app).is_some() && self.as_route().is_active(app) {
                            Route::changed_internal_state(self, app);
                        }
                    }),
                    self.as_route()
                        .navigator(app)
                        .and_then(|navigator| View::maybe_id_of(app, navigator.context(app))),
                );
            } else {
                Route::changed_internal_state(self, app);
            }
        }
    }

    /// Dart's `LocalHistoryRoute.willPop`.
    fn will_pop(self: Handle<Self>, app: &mut App) -> RoutePopDisposition {
        if Route::will_handle_pop_internally(self, app) {
            return RoutePopDisposition::Pop;
        }
        RouteBase::will_pop(self, app)
    }

    /// Dart's `LocalHistoryRoute.popDisposition`.
    fn pop_disposition(self: Handle<Self>, app: &mut App) -> RoutePopDisposition {
        if Route::will_handle_pop_internally(self, app) {
            return RoutePopDisposition::Pop;
        }
        RouteBase::pop_disposition(self, app)
    }

    /// Dart's `LocalHistoryRoute.didPop`.
    fn did_pop(self: Handle<Self>, app: &mut App, result: RouteResult) -> bool {
        let last = self
            .local_history_route_data_mut(app)
            .local_history
            .as_mut()
            .and_then(Vec::pop);
        if let Some(entry) = last {
            debug_assert!(app.get(&entry).owner == Some(self.as_route()));
            app.get_mut(&entry).owner = None;
            entry.notify_removed(app);
            let mut internal_state_changed = false;
            if app.get(&entry).implies_app_bar_dismissal {
                let data = self.local_history_route_data_mut(app);
                data.entries_implies_app_bar_dismissal -= 1;
                internal_state_changed = data.entries_implies_app_bar_dismissal == 0;
            }
            let empty = self
                .local_history_route_data(app)
                .local_history
                .as_ref()
                .is_some_and(Vec::is_empty);
            if empty || internal_state_changed {
                Route::changed_internal_state(self, app);
            }
            return false;
        }
        TransitionRoute::did_pop(self, app, result)
    }

    /// Dart's `LocalHistoryRoute.willHandlePopInternally`.
    fn will_handle_pop_internally(self: Handle<Self>, app: &App) -> bool {
        self.local_history_route_data(app)
            .local_history
            .as_ref()
            .is_some_and(|history| !history.is_empty())
    }
}

// ---------------------------------------------------------------------------------------------
// _ModalScope

/// Dart's `_DismissModalAction`.
struct DismissModalAction {
    action: ActionData,
    context: BuildContext,
}

impl DismissModalAction {
    fn new(app: &mut App, context: BuildContext) -> Ref<DismissModalAction> {
        app.create(DismissModalAction {
            action: ActionData::new(),
            context,
        })
    }
}

impl Action for DismissModalAction {
    type Intent = DismissIntent;

    crate::action_accessors!();

    fn is_enabled(self: Handle<Self>, app: &mut App, _intent: &DismissIntent) -> bool {
        let context = app.get(self).context;
        let route = AnyModalRoute::of(app, context).expect("a dismiss action inside a modal route");
        route.barrier_dismissible(app)
    }

    fn invoke(self: Handle<Self>, app: &mut App, _intent: &DismissIntent) -> Option<Rc<dyn Any>> {
        let context = app.get(self).context;
        let popped = Navigator::of(app, context, false).maybe_pop(app, None);
        Some(Rc::new(popped))
    }
}

impl DismissAction for DismissModalAction {}

/// Dart's `_ModalRouteAspect`: the aspects of a [`ModalRoute`] a dependent can depend on.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
enum ModalRouteAspect {
    /// Specifies the aspect corresponding to [`AnyRoute::is_current`].
    IsCurrent,
    /// Specifies the aspect corresponding to [`ModalRoute::can_pop`].
    CanPop,
    /// Specifies the aspect corresponding to [`AnyRoute::settings`].
    Settings,
    /// Specifies the aspect corresponding to [`AnyRoute::is_active`].
    IsActive,
    /// Specifies the aspect corresponding to [`AnyRoute::is_first`].
    IsFirst,
    /// Specifies the aspect corresponding to [`TransitionRoute::opaque`].
    Opaque,
    /// Specifies the aspect corresponding to [`Route::pop_disposition`].
    PopDisposition,
}

/// Dart's `_ModalScopeStatus`.
#[derive(Debug)]
struct ModalScopeStatus {
    is_current: bool,
    can_pop: bool,
    implies_app_bar_dismissal: bool,
    opaque: bool,
    route: ModalRouteRef,
    child: WidgetRef,
}

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

    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
        properties.add(
            FlagProperty::new("isCurrent", Some(self.is_current))
                .if_true("active")
                .if_false("inactive"),
        );
        properties.add(FlagProperty::new("canPop", Some(self.can_pop)).if_true("can pop"));
        properties.add(
            FlagProperty::new(
                "impliesAppBarDismissal",
                Some(self.implies_app_bar_dismissal),
            )
            .if_true("implies app bar dismissal"),
        );
    }

    fn update_should_notify(&self, old: &ModalScopeStatus) -> bool {
        self.is_current != old.is_current
            || self.can_pop != old.can_pop
            || self.implies_app_bar_dismissal != old.implies_app_bar_dismissal
            || self.route != old.route
            || self.opaque != old.opaque
    }
}

impl ModalScopeStatus {
    /// The erased widget: an [`InheritedModel`] has two `IntoWidget` impls, so the kind is
    /// named here.
    fn into_widget(self) -> WidgetRef {
        IntoWidget::<crate::framework::InheritedModelKind>::into_widget(self)
    }
}

impl InheritedModel for ModalScopeStatus {
    type Aspect = ModalRouteAspect;

    fn update_should_notify_dependent(
        &self,
        old_widget: &ModalScopeStatus,
        dependencies: &std::collections::HashSet<ModalRouteAspect>,
    ) -> bool {
        // The aspects that read the route need the App; the widget cannot. The route-derived
        // aspects are compared through the aspect's own recorded value instead.
        dependencies.iter().any(|dependency| match dependency {
            ModalRouteAspect::IsCurrent => self.is_current != old_widget.is_current,
            ModalRouteAspect::CanPop => self.can_pop != old_widget.can_pop,
            ModalRouteAspect::Settings
            | ModalRouteAspect::IsActive
            | ModalRouteAspect::IsFirst
            | ModalRouteAspect::PopDisposition => self.route != old_widget.route,
            ModalRouteAspect::Opaque => self.opaque != old_widget.opaque,
        })
    }
}

/// Dart's `_ModalScope`.
#[derive(Debug)]
struct ModalScope {
    key: Option<KeyRef>,
    route: AnyModalRoute,
}

impl StatefulWidget for ModalScope {
    type State = ModalScopeState;

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

    fn create_state(&self) -> ModalScopeState {
        ModalScopeState {
            state: StateData::new(),
            page: None,
            listenable: None,
            focus_scope_node: None,
            primary_scroll_controller: None,
            no_gesture_in_progress: None,
        }
    }
}

/// Dart's `_ModalScopeState`.
struct ModalScopeState {
    state: StateData<ModalScope>,
    // We cache the result of calling the route's `build_page`, and clear the cache whenever the
    // dependencies change. This implements the contract described in the documentation for
    // `build_page`, namely that it gets called once, unless something like a `ModalRoute::of`
    // dependency triggers an update.
    page: Option<WidgetRef>,
    // This is the combination of the two animations for the route.
    listenable: Option<Rc<MergingListenable>>,
    focus_scope_node: Option<Ref<FocusScopeNode>>,
    primary_scroll_controller: Option<Ref<ScrollController>>,
    /// The notifier a scope whose route has no navigator listens to, where Dart makes a fresh
    /// `ValueNotifier<bool>(false)` in each build.
    no_gesture_in_progress: Option<Ref<waft_foundation::ValueNotifier<bool>>>,
}

impl ModalScopeState {
    /// The node this scope uses for its root `FocusScope` widget.
    fn focus_scope_node(self: Handle<Self>, app: &App) -> Handle<FocusScopeNode> {
        app.get(self)
            .focus_scope_node
            .handle()
            .expect("init_state has run")
    }

    fn route(self: Handle<Self>, app: &App) -> AnyModalRoute {
        self.widget(app).route
    }

    fn update_focus_scope_node(self: Handle<Self>, app: &mut App) {
        let route = self.route(app);
        let navigator = route
            .as_route()
            .navigator(app)
            .expect("a mounted scope has a navigator");
        let traversal_edge_behavior = match route.traversal_edge_behavior(app) {
            Some(behavior) => behavior,
            None => navigator.widget(app).route_traversal_edge_behavior,
        };
        let directional_traversal_edge_behavior =
            match route.directional_traversal_edge_behavior(app) {
                Some(behavior) => behavior,
                None => {
                    navigator
                        .widget(app)
                        .route_directional_traversal_edge_behavior
                }
            };
        let node = self.focus_scope_node(app);
        node.set_traversal_edge_behavior(app, traversal_edge_behavior);
        node.set_directional_traversal_edge_behavior(app, directional_traversal_edge_behavior);
        if route.as_route().is_current(app) && self.should_request_focus(app) {
            let focus_node = navigator.focus_node(app);
            if let Some(scope) = focus_node.as_node().enclosing_scope(app) {
                scope.set_first_focus(app, node);
            }
        }
    }

    fn force_rebuild_page(self: Handle<Self>, app: &mut App) {
        self.set_state(app, |state| {
            state.page = None;
        });
    }

    fn should_ignore_focus_request(self: Handle<Self>, app: &mut App) -> bool {
        let route = self.route(app);
        let reversing = route
            .animation(app)
            .is_some_and(|animation| animation.status(app) == AnimationStatus::Reverse);
        reversing
            || route
                .as_route()
                .navigator(app)
                .is_some_and(|navigator| navigator.user_gesture_in_progress(app))
    }

    fn should_request_focus(self: Handle<Self>, app: &App) -> bool {
        self.route(app).as_route().request_focus(app)
    }

    /// Dart's `_routeSetState`: wraps any change to the route's `is_current`, `can_pop` or
    /// `offstage`.
    fn route_set_state(self: Handle<Self>, app: &mut App, change: impl FnOnce(&mut App)) {
        let route = self.route(app);
        if route.as_route().is_current(app)
            && !self.should_ignore_focus_request(app)
            && self.should_request_focus(app)
        {
            let navigator = route.as_route().navigator(app).expect("a current route");
            let focus_node = navigator.focus_node(app);
            let node = self.focus_scope_node(app);
            if let Some(scope) = focus_node.as_node().enclosing_scope(app) {
                scope.set_first_focus(app, node);
            }
        }
        change(app);
        self.set_state(app, |_state| {});
    }
}

impl State for ModalScopeState {
    type Widget = ModalScope;
    crate::state_accessors!();

    fn init_state(self: Handle<Self>, app: &mut App) {
        let node = FocusScopeNode::new(app);
        node.as_node()
            .set_debug_label(app, Some("ModalScopeState Focus Scope".to_string()));
        app.get_mut(self).focus_scope_node = Some(node);
        app.get_mut(self).primary_scroll_controller =
            Some(ScrollController::new(app, 0.0, true, None, None, None));
        app.get_mut(self).no_gesture_in_progress =
            Some(app.create(waft_foundation::ValueNotifier::new(false)));
        let route = self.route(app);
        let as_listenable = |animation: AnyAnimation<f64>| {
            Rc::new(animation.keep(app)) as Rc<dyn waft_foundation::Listenable>
        };
        let animations: Vec<Option<Rc<dyn waft_foundation::Listenable>>> = vec![
            route.animation(app).map(as_listenable),
            route.secondary_animation(app).map(as_listenable),
        ];
        app.get_mut(self).listenable = Some(Rc::new(MergingListenable::new(animations)));
    }

    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &ModalScope) {
        debug_assert!(self.widget(app).route == old_widget.route);
        self.update_focus_scope_node(app);
    }

    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
        app.get_mut(self).page = None;
        self.update_focus_scope_node(app);
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        let node = self.focus_scope_node(app);
        node.dispose(app);
        let controller = app
            .get(self)
            .primary_scroll_controller
            .handle()
            .expect("init_state");
        ScrollController::dispose(controller.as_controller(), app);
    }

    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
        // The widgets built here keep the route, as Dart's closures over `widget.route` do.
        let route = self.route(app);
        let route_kept = route.keep(app);
        let node = app
            .get(self)
            .focus_scope_node
            .clone()
            .expect("init_state has run");
        // Only the top-most route can participate in focus traversal.
        let is_current = route.as_route().is_current(app);
        node.set_skip_traversal(app, !is_current);

        let page = match app.get(self).page.clone() {
            Some(page) => page,
            None => {
                let page_route = route_kept.clone();
                let page = RepaintBoundary::new()
                    .key(route.subtree_key(app).into())
                    .child(Builder::new(move |app, context| {
                        let (animation, secondary) = page_route.animations(app);
                        page_route.build_page(app, context, animation, secondary)
                    }))
                    .into_widget();
                app.get_mut(self).page = Some(page.clone());
                page
            }
        };

        let gesture_notifier: Rc<dyn waft_foundation::Listenable> = match route
            .as_route()
            .navigator(app)
        {
            Some(navigator) => Rc::new(navigator.user_gesture_in_progress_notifier(app).keep(app)),
            None => Rc::new(
                app.get(self)
                    .no_gesture_in_progress
                    .clone()
                    .expect("init_state"),
            ),
        };
        let listenable = app.get(self).listenable.clone().expect("init_state");

        let transitions_route = route_kept.clone();
        let transitions_node = node.clone();
        let transitions = ListenableBuilder::new(listenable, move |app, context, child| {
            let route = &transitions_route;
            let node = transitions_node.clone();
            let child = child.cloned().expect("the cached page");
            let (animation, secondary) = route.animations(app);
            // This additional builder is included because if the value of the user-gesture
            // notifier changes, it is only necessary to rebuild the `IgnorePointer` widget and
            // set the focus node's ability to focus.
            let ignoring = ListenableBuilder::new(Rc::clone(&gesture_notifier), {
                move |app: &mut App, _context: BuildContext, child: Option<&WidgetRef>| {
                    let ignore_events = self.should_ignore_focus_request(app);
                    node.set_can_request_focus(app, !ignore_events);
                    let mut widget = IgnorePointer::new().ignoring(ignore_events);
                    if let Some(child) = child {
                        widget = widget.child(child.clone());
                    }
                    widget.into_widget()
                }
            })
            .child(child)
            .into_widget();
            route.build_flexible_transitions(app, context, animation, secondary, ignoring)
        })
        .child(page)
        .into_widget();

        let scope_child = Builder::new(move |app, context| {
            let dismiss_action: ActionRef = DismissModalAction::new(app, context).into_erased();
            let mut actions = HashMap::new();
            actions.insert(
                <DismissModalAction as Action>::intent_type(),
                dismiss_action,
            );
            let controller: ScrollControllerRef = app
                .get(self)
                .primary_scroll_controller
                .as_ref()
                .expect("init_state")
                .erase();
            Actions::new(
                actions,
                PrimaryScrollController::new(
                    controller,
                    FocusScope::with_external_focus_node(
                        RepaintBoundary::new().child(transitions.clone()),
                        node.clone(),
                    ),
                ),
            )
            .into_widget()
        });

        let storage_bucket = route.storage_bucket(app).keep(app);
        let status = ModalScopeStatus {
            route: route_kept,
            // `route_set_state` is called if any of these update.
            is_current,
            can_pop: route.can_pop(app),
            opaque: route.opaque(app),
            implies_app_bar_dismissal: route.implies_app_bar_dismissal(app),
            child: Offstage::new()
                .offstage(route.offstage(app))
                .child(PageStorage::new(storage_bucket, scope_child))
                .into_widget(),
        };

        let restoration_scope_id = route.as_route().restoration_scope_id(app).keep(app);
        AnimatedBuilder::new(
            Rc::new(restoration_scope_id.clone()),
            move |app, _context, child| {
                let child = child.cloned().expect("the modal scope status");
                let id = app.get(&restoration_scope_id).value().clone();
                RestorationScope::new(id, child).into_widget()
            },
        )
        .child(status.into_widget())
        .into_widget()
    }
}

// ---------------------------------------------------------------------------------------------
// ModalRoute

/// The fields Dart's `ModalRoute` declares; every modal route carries this bag under the field
/// `modal_route`.
pub struct ModalRouteData {
    /// The filter to add to the barrier.
    ///
    /// If given, this filter is applied to the modal barrier using `BackdropFilter`. This
    /// allows blur effects, for example.
    pub filter: Option<waft_rendering::ImageFilterConfig>,
    /// Controls the transfer of focus beyond the first and the last items of a
    /// [`FocusScopeNode`].
    ///
    /// If `None`, [`Navigator::route_traversal_edge_behavior`] is used.
    pub traversal_edge_behavior: Option<TraversalEdgeBehavior>,
    /// Controls the directional transfer of focus beyond the first and the last items of a
    /// [`FocusScopeNode`].
    ///
    /// If `None`, [`Navigator::route_directional_traversal_edge_behavior`] is used.
    pub directional_traversal_edge_behavior: Option<TraversalEdgeBehavior>,
    /// The `DelegatedTransitionBuilder` received from the route above this one in the
    /// navigation stack.
    ///
    /// It uses the above route's [`ModalRoute::delegated_transition`] in order to show the
    /// right route transition when the above route either enters or leaves the navigation
    /// stack. If not `None`, it wraps the route content.
    pub received_transition: Option<DelegatedTransitionBuilder>,
    offstage: bool,
    animation_proxy: Option<Ref<ProxyAnimation>>,
    secondary_animation_proxy: Option<Ref<ProxyAnimation>>,
    pop_entries: Vec<Rc<dyn PopEntry>>,
    scope_key: GlobalKey,
    subtree_key: GlobalKey,
    storage_bucket: Ref<PageStorageBucket>,
    modal_barrier: Option<Ref<OverlayEntry>>,
    modal_scope: Option<Ref<OverlayEntry>>,
    modal_scope_cache: Option<WidgetRef>,
}

impl ModalRouteData {
    /// The bag of a freshly created modal route; Dart's constructor defaults.
    pub fn new(app: &mut App) -> ModalRouteData {
        ModalRouteData {
            filter: None,
            traversal_edge_behavior: None,
            directional_traversal_edge_behavior: None,
            received_transition: None,
            offstage: false,
            animation_proxy: None,
            secondary_animation_proxy: None,
            pop_entries: Vec::new(),
            scope_key: GlobalKey::new(),
            subtree_key: GlobalKey::new(),
            storage_bucket: PageStorageBucket::new(app),
            modal_barrier: None,
            modal_scope: None,
            modal_scope_cache: None,
        }
    }
}

/// The accessors [`ModalRoute`] asks for, for a struct whose bag is the field `modal_route`.
#[macro_export]
macro_rules! modal_route_accessors {
    () => {
        fn modal_route_data(
            self: ::waft_foundation::Handle<Self>,
            app: &::waft_foundation::App,
        ) -> &$crate::ModalRouteData {
            &app.get(self).modal_route
        }

        fn modal_route_data_mut(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
        ) -> &mut $crate::ModalRouteData {
            &mut app.get_mut(self).modal_route
        }
    };
}

/// A route that blocks interaction with previous routes.
///
/// [`ModalRoute`]s cover the entire [`Navigator`]. They are not necessarily
/// [`opaque`](TransitionRoute::opaque), however; for example, a pop-up menu uses a
/// [`ModalRoute`] but only shows the menu in a small box overlapping the previous route.
///
/// See also:
///
///  * [`Route`], which further documents the meaning of Dart's `T` generic type argument.
pub trait ModalRoute: LocalHistoryRoute {
    /// Dart's `ModalRoute` fields, held under the field `modal_route`
    /// ([`modal_route_accessors!`](crate::modal_route_accessors)).
    fn modal_route_data(self: Handle<Self>, app: &App) -> &ModalRouteData;

    /// See [`modal_route_data`](Self::modal_route_data).
    fn modal_route_data_mut(self: Handle<Self>, app: &mut App) -> &mut ModalRouteData;

    /// This route as the erased [`AnyModalRoute`].
    fn as_modal_route(self: Handle<Self>) -> AnyModalRoute {
        AnyModalRoute {
            id: self.id(),
            vtable: const { &ModalRouteVTable::of::<Self>() },
        }
    }

    /// Schedules a call to [`build_transitions`](Self::build_transitions).
    ///
    /// Whenever you need to change internal state for a [`ModalRoute`] object, make the change
    /// in the closure you pass to `set_state`. If you just change the state directly without
    /// calling `set_state`, then the route will not be scheduled for rebuilding, meaning that
    /// its rendering will not be updated.
    fn set_state(self: Handle<Self>, app: &mut App, change: impl FnOnce(&mut App)) {
        let key = self.modal_route_data(app).scope_key.clone();
        match key.current_state::<ModalScopeState>(app) {
            Some(state) => state.route_set_state(app, change),
            None => {
                // The route isn't currently visible, so we don't have to call its `set_state`
                // method, but we do still need to run the change, otherwise the state in the
                // route won't be updated.
                change(app);
            }
        }
    }

    /// Override this method to build the primary content of this route.
    ///
    /// The arguments have the following meanings:
    ///
    ///  * `context`: The context in which the route is being built.
    ///  * `animation`: The animation for this route's transition. When entering, the animation
    ///    runs forward from 0.0 to 1.0. When exiting, it runs backwards from 1.0 to 0.0.
    ///  * `secondary_animation`: The animation for the route being pushed on top of this route.
    ///
    /// This method is only called when the route is first built, and rarely thereafter. In
    /// particular, it is not automatically called again when the route's state changes unless
    /// it uses [`AnyModalRoute::of`]. For a builder that is called every time the route's state
    /// changes, consider [`build_transitions`](Self::build_transitions).
    fn build_page(
        self: Handle<Self>,
        app: &mut App,
        context: BuildContext,
        animation: AnimationRef<f64>,
        secondary_animation: AnimationRef<f64>,
    ) -> WidgetRef;

    /// Override this method to wrap the `child` with one or more transition widgets that define
    /// how the route arrives on and leaves the screen.
    ///
    /// By default, the child (which contains the widget returned by
    /// [`build_page`](Self::build_page)) is not wrapped in any transition widgets.
    ///
    /// This method, in contrast to [`build_page`](Self::build_page), is called each time the
    /// route's state changes while it is visible.
    fn build_transitions(
        self: Handle<Self>,
        app: &mut App,
        context: BuildContext,
        animation: AnimationRef<f64>,
        secondary_animation: AnimationRef<f64>,
        child: WidgetRef,
    ) -> WidgetRef {
        let _ = (app, context, animation, secondary_animation);
        child
    }

    /// The `DelegatedTransitionBuilder` provided to the route below this one in the navigation
    /// stack.
    ///
    /// Used for the purposes of coordinating transitions between two routes with different
    /// route transitions. When a route is added to the stack, the original topmost route will
    /// look for this transition, and if available, it will use it to animate off the screen.
    ///
    /// If the builder returns `None`, then by default the original transition of the routes
    /// will be used.
    ///
    /// The [`ModalRoute`] receiving this transition sets it as its
    /// [`received_transition`](ModalRouteData::received_transition).
    fn delegated_transition(self: Handle<Self>, app: &App) -> Option<DelegatedTransitionBuilder> {
        let _ = app;
        None
    }

    /// Dart's `_buildFlexibleTransitions`: wraps the transitions of this route with the
    /// [`received_transition`](ModalRouteData::received_transition), when there is one.
    fn build_flexible_transitions(
        self: Handle<Self>,
        app: &mut App,
        context: BuildContext,
        animation: AnimationRef<f64>,
        secondary_animation: AnimationRef<f64>,
        child: WidgetRef,
    ) -> WidgetRef {
        let received = self.modal_route_data(app).received_transition.clone();
        let Some(received) = received else {
            return ModalRoute::build_transitions(
                self,
                app,
                context,
                animation,
                secondary_animation,
                child,
            );
        };
        if secondary_animation.is_dismissed(app) {
            return ModalRoute::build_transitions(
                self,
                app,
                context,
                animation,
                secondary_animation,
                child,
            );
        }

        // Create a static proxy animation to suppress the original secondary transition.
        let proxy_animation: AnimationRef<f64> = ProxyAnimation::new(app, None).into_erased();
        let proxied_original_transitions = ModalRoute::build_transitions(
            self,
            app,
            context,
            animation.clone(),
            proxy_animation,
            child,
        );

        // If the received transition returns nothing, then we want the original transitions,
        // but with the secondary animation still proxied. This keeps a desynched animation from
        // playing.
        let allow_snapshotting = TransitionRoute::allow_snapshotting(self, app);
        received
            .call(
                app,
                context,
                animation,
                secondary_animation,
                allow_snapshotting,
                Some(&proxied_original_transitions),
            )
            .unwrap_or(proxied_original_transitions)
    }

    /// Dart's `ModalRoute.install`.
    fn install(self: Handle<Self>, app: &mut App) {
        TransitionRoute::install(self, app);
        let animation = self.transition_route_data(app).animation.clone();
        let secondary: AnimationRef<f64> =
            self.transition_route_data(app).secondary_animation.erase();
        self.modal_route_data_mut(app).animation_proxy = Some(ProxyAnimation::new(app, animation));
        self.modal_route_data_mut(app).secondary_animation_proxy =
            Some(ProxyAnimation::new(app, Some(secondary)));
    }

    /// Dart's `ModalRoute.didPush`.
    fn did_push(self: Handle<Self>, app: &mut App) -> TickerFuture {
        let key = self.modal_route_data(app).scope_key.clone();
        if let Some(state) = key.current_state::<ModalScopeState>(app) {
            let navigator = self.as_route().navigator(app).expect("an installed route");
            if navigator.widget(app).request_focus {
                let focus_node = navigator.focus_node(app);
                let scope_node = state.focus_scope_node(app);
                if let Some(scope) = focus_node.as_node().enclosing_scope(app) {
                    scope.set_first_focus(app, scope_node);
                }
            }
        }
        TransitionRoute::did_push(self, app)
    }

    /// Dart's `ModalRoute.didAdd`.
    fn did_add(self: Handle<Self>, app: &mut App) {
        let key = self.modal_route_data(app).scope_key.clone();
        if let Some(state) = key.current_state::<ModalScopeState>(app) {
            let navigator = self.as_route().navigator(app).expect("an installed route");
            if navigator.widget(app).request_focus {
                let focus_node = navigator.focus_node(app);
                let scope_node = state.focus_scope_node(app);
                if let Some(scope) = focus_node.as_node().enclosing_scope(app) {
                    scope.set_first_focus(app, scope_node);
                }
            }
        }
        TransitionRoute::did_add(self, app);
    }

    /// Whether you can dismiss this route by tapping the modal barrier.
    ///
    /// The modal barrier is the scrim that is rendered behind each route, which generally
    /// prevents the user from interacting with the route below the current route, and normally
    /// partially obscures such routes.
    ///
    /// If `barrier_dismissible` is true, then tapping this barrier, pressing the escape key on
    /// the keyboard, or calling route popping functions such as [`Navigator::pop`] will cause
    /// the current route to be popped with no value.
    ///
    /// If this getter would ever start returning a different value, either
    /// [`changed_internal_state`](Route::changed_internal_state) or
    /// [`changed_external_state`](Route::changed_external_state) should be invoked so that the
    /// change can take effect.
    fn barrier_dismissible(self: Handle<Self>, app: &App) -> bool;

    /// Whether the semantics of the modal barrier are included in the semantics tree.
    fn semantics_dismissible(self: Handle<Self>, app: &App) -> bool {
        let _ = app;
        true
    }

    /// The color to use for the modal barrier. If this is `None`, the barrier will be
    /// transparent.
    ///
    /// The color is ignored, and the barrier made invisible, when
    /// [`offstage`](Self::offstage) is true.
    ///
    /// While the route is animating into position, the color is animated from transparent to
    /// the specified color.
    fn barrier_color(self: Handle<Self>, app: &App) -> Option<Color>;

    /// The semantic label used for a dismissible barrier.
    fn barrier_label(self: Handle<Self>, app: &App) -> Option<String>;

    /// The curve that is used for animating the modal barrier in and out.
    ///
    /// It defaults to [`Curves::ease`].
    fn barrier_curve(self: Handle<Self>, app: &App) -> Rc<dyn Curve> {
        let _ = app;
        Curves::ease()
    }

    /// Whether the route should remain in memory when it is inactive.
    ///
    /// If this is true, then the route is maintained, so that any completions it is holding
    /// from the next route will properly resolve when the next route pops. If this is not
    /// necessary, this can be set to false to allow the framework to entirely discard the
    /// route's widget hierarchy when it is not visible.
    fn maintain_state(self: Handle<Self>, app: &App) -> bool;

    /// True if a back gesture (iOS-style back swipe or Android predictive back) is currently
    /// underway for this route.
    fn pop_gesture_in_progress(self: Handle<Self>, app: &App) -> bool {
        self.as_route()
            .navigator(app)
            .expect("an installed route")
            .user_gesture_in_progress(app)
    }

    /// Dart's `ModalRoute.popGestureEnabled`.
    fn pop_gesture_enabled(self: Handle<Self>, app: &mut App) -> bool {
        // If there's nothing to go back to, then obviously we don't support the back gesture.
        if self.as_route().is_first(app) {
            return false;
        }
        // If the route wouldn't actually pop if we popped it, then the gesture would be really
        // confusing (or would skip internal routes), so disallow it.
        if Route::will_handle_pop_internally(self, app) {
            return false;
        }
        // If attempts to dismiss this route might be vetoed, then do not allow the user to
        // dismiss the route with a swipe.
        if Route::pop_disposition(self, app) == RoutePopDisposition::DoNotPop {
            return false;
        }
        // If we're in an animation already, we cannot be manually swiped.
        let animation = TransitionRoute::animation(self, app).expect("an installed route");
        if !animation.is_completed(app) {
            return false;
        }
        // Looks like a back gesture would be welcome!
        true
    }

    /// Whether this route is currently offstage.
    ///
    /// On the first frame of a route's entrance transition, the route is built `Offstage` using
    /// an animation progress of 1.0. The route is invisible and non-interactive, but each
    /// widget has its final size and position. This mechanism lets the `HeroController`
    /// determine the final location of any hero widgets being animated as part of the
    /// transition.
    ///
    /// The modal barrier, if any, is not rendered if `offstage` is true.
    ///
    /// Whenever this changes value, [`changed_internal_state`](Route::changed_internal_state)
    /// is called.
    fn offstage(self: Handle<Self>, app: &App) -> bool {
        self.modal_route_data(app).offstage
    }

    /// Sets [`offstage`](Self::offstage).
    fn set_offstage(self: Handle<Self>, app: &mut App, value: bool) {
        if self.modal_route_data(app).offstage == value {
            return;
        }
        ModalRoute::set_state(self, app, |app| {
            self.modal_route_data_mut(app).offstage = value;
        });
        let offstage = self.modal_route_data(app).offstage;
        let animation_proxy = self
            .modal_route_data(app)
            .animation_proxy
            .handle()
            .expect("installed");
        let parent = if offstage {
            Some(k_always_complete_animation(app))
        } else {
            self.transition_route_data(app).animation.clone()
        };
        animation_proxy.set_parent(app, parent);
        let secondary_proxy = self
            .modal_route_data(app)
            .secondary_animation_proxy
            .handle()
            .expect("installed");
        let parent = if offstage {
            k_always_dismissed_animation(app)
        } else {
            self.transition_route_data(app).secondary_animation.erase()
        };
        secondary_proxy.set_parent(app, Some(parent));
        Route::changed_internal_state(self, app);
    }

    /// The build context for the subtree containing the primary content of this route.
    fn subtree_context(self: Handle<Self>, app: &mut App) -> Option<BuildContext> {
        let key = self.modal_route_data(app).subtree_key.clone();
        key.current_context(app)
    }

    /// Dart's `ModalRoute.animation`.
    fn animation(self: Handle<Self>, app: &App) -> Option<AnyAnimation<f64>> {
        self.modal_route_data(app)
            .animation_proxy
            .handle()
            .map(Animation::as_animation)
    }

    /// Dart's `ModalRoute.secondaryAnimation`.
    fn secondary_animation(self: Handle<Self>, app: &App) -> Option<AnyAnimation<f64>> {
        self.modal_route_data(app)
            .secondary_animation_proxy
            .handle()
            .map(Animation::as_animation)
    }

    /// Dart's `ModalRoute.popDisposition`.
    ///
    /// Returns [`RoutePopDisposition::DoNotPop`] if any of the [`PopEntry`] instances
    /// registered with [`register_pop_entry`](Self::register_pop_entry) have their
    /// [`PopEntry::can_pop_notifier`] set to false.
    fn pop_disposition(self: Handle<Self>, app: &mut App) -> RoutePopDisposition {
        for pop_entry in self.modal_route_data(app).pop_entries.clone() {
            if !*pop_entry.can_pop_notifier(app).value(app) {
                return RoutePopDisposition::DoNotPop;
            }
        }
        LocalHistoryRoute::pop_disposition(self, app)
    }

    /// Dart's `ModalRoute.onPopInvokedWithResult`.
    fn on_pop_invoked_with_result(
        self: Handle<Self>,
        app: &mut App,
        did_pop: bool,
        result: RouteResult,
    ) {
        for pop_entry in self.modal_route_data(app).pop_entries.clone() {
            pop_entry.on_pop_invoked_with_result(app, did_pop, result.clone());
        }
        RouteBase::on_pop_invoked_with_result(self, app, did_pop, result);
    }

    /// Registers the existence of a [`PopEntry`] in the route.
    ///
    /// [`PopEntry`] instances registered in this way will have their
    /// [`PopEntry::on_pop_invoked_with_result`] callbacks called when a route is popped or a
    /// pop is attempted. They will also be able to block pop operations with
    /// [`PopEntry::can_pop_notifier`] through this route's
    /// [`pop_disposition`](Self::pop_disposition) method.
    fn register_pop_entry(self: Handle<Self>, app: &mut App, pop_entry: Rc<dyn PopEntry>) {
        if !self
            .modal_route_data(app)
            .pop_entries
            .iter()
            .any(|held| Rc::ptr_eq(held, &pop_entry))
        {
            self.modal_route_data_mut(app)
                .pop_entries
                .push(Rc::clone(&pop_entry));
        }
        let notifier = pop_entry.can_pop_notifier(app);
        notifier.add_listener(
            app,
            Listener::handle_method(self, Self::maybe_dispatch_navigation_notification),
        );
        ModalRoute::maybe_dispatch_navigation_notification(self, app);
    }

    /// Unregisters a [`PopEntry`] in the route's widget subtree.
    fn unregister_pop_entry(self: Handle<Self>, app: &mut App, pop_entry: Rc<dyn PopEntry>) {
        self.modal_route_data_mut(app)
            .pop_entries
            .retain(|held| !Rc::ptr_eq(held, &pop_entry));
        let notifier = pop_entry.can_pop_notifier(app);
        notifier.remove_listener(
            app,
            &Listener::handle_method(self, Self::maybe_dispatch_navigation_notification),
        );
        ModalRoute::maybe_dispatch_navigation_notification(self, app);
    }

    /// Dart's `_maybeDispatchNavigationNotification`.
    fn maybe_dispatch_navigation_notification(self: Handle<Self>, app: &mut App) {
        if !self.as_route().is_current(app) {
            return;
        }
        // `can_handle_pop` indicates that the originator of the notification can handle a pop.
        // In the case of `PopScope`, it handles pops when `can_pop` is false. Hence the
        // seemingly backward logic here.
        let notification = NavigationNotification::new(
            Route::pop_disposition(self, app) == RoutePopDisposition::DoNotPop,
        );
        // Avoid dispatching a notification in the middle of a build.
        match SchedulerBinding::scheduler_phase(app) {
            SchedulerPhase::PostFrameCallbacks => {
                let context = ModalRoute::subtree_context(self, app);
                notification.dispatch(app, context);
            }
            SchedulerPhase::Idle
            | SchedulerPhase::MidFrameMicrotasks
            | SchedulerPhase::PersistentCallbacks
            | SchedulerPhase::TransientCallbacks => {
                let context = ModalRoute::subtree_context(self, app);
                SchedulerBinding::add_post_frame_callback(
                    app,
                    FrameCallback::new(move |app, _time_stamp| {
                        if self.upgrade(app).is_none() {
                            return;
                        }
                        let context = ModalRoute::subtree_context(self, app);
                        if !context.is_some_and(|context| context.mounted(app)) {
                            return;
                        }
                        notification.dispatch(app, context);
                    }),
                    context.and_then(|context| View::maybe_id_of(app, context)),
                );
            }
        }
    }

    /// Dart's `ModalRoute.didChangePrevious`.
    fn did_change_previous(self: Handle<Self>, app: &mut App, previous_route: Option<AnyRoute>) {
        RouteBase::did_change_previous(self, app, previous_route);
        Route::changed_internal_state(self, app);
    }

    /// Dart's `ModalRoute.didChangeNext`.
    fn did_change_next(self: Handle<Self>, app: &mut App, next_route: Option<AnyRoute>) {
        self.update_received_transition(app, next_route);
        TransitionRoute::did_change_next(self, app, next_route);
        Route::changed_internal_state(self, app);
    }

    /// Dart's `ModalRoute.didPopNext`.
    fn did_pop_next(self: Handle<Self>, app: &mut App, next_route: AnyRoute) {
        self.update_received_transition(app, Some(next_route));
        TransitionRoute::did_pop_next(self, app, next_route);
        Route::changed_internal_state(self, app);
        ModalRoute::maybe_dispatch_navigation_notification(self, app);
    }

    /// The `nextRoute is ModalRoute && canTransitionTo(nextRoute) && …` branch both
    /// [`did_change_next`](Self::did_change_next) and [`did_pop_next`](Self::did_pop_next) run.
    fn update_received_transition(self: Handle<Self>, app: &mut App, next_route: Option<AnyRoute>) {
        let next_modal = next_route.and_then(|route| route.as_modal_route(app));
        let received = match next_modal {
            Some(next) => {
                let next_transition = next
                    .as_route()
                    .as_transition_route(app)
                    .expect("a modal route is a transition route");
                let mine = ModalRoute::delegated_transition(self, app);
                let theirs = next.delegated_transition(app);
                let differs = mine != theirs;
                if TransitionRoute::can_transition_to(self, app, next_transition) && differs {
                    theirs
                } else {
                    None
                }
            }
            None => None,
        };
        self.modal_route_data_mut(app).received_transition = received;
    }

    /// Dart's `ModalRoute.changedInternalState`.
    fn changed_internal_state(self: Handle<Self>, app: &mut App) {
        RouteBase::changed_internal_state(self, app);
        // No need to mark dirty if this method is called during the build phase.
        if SchedulerBinding::scheduler_phase(app) != SchedulerPhase::PersistentCallbacks {
            ModalRoute::set_state(self, app, |_app| {
                // The internal state already changed.
            });
            let barrier = self
                .modal_route_data(app)
                .modal_barrier
                .handle()
                .expect("installed");
            barrier.mark_needs_build(app);
        }
        let maintain_state = ModalRoute::maintain_state(self, app);
        let scope = self
            .modal_route_data(app)
            .modal_scope
            .handle()
            .expect("installed");
        scope.set_maintain_state(app, maintain_state);
    }

    /// Dart's `ModalRoute.changedExternalState`.
    fn changed_external_state(self: Handle<Self>, app: &mut App) {
        RouteBase::changed_external_state(self, app);
        let barrier = self
            .modal_route_data(app)
            .modal_barrier
            .handle()
            .expect("installed");
        barrier.mark_needs_build(app);
        let key = self.modal_route_data(app).scope_key.clone();
        if let Some(state) = key.current_state::<ModalScopeState>(app) {
            state.force_rebuild_page(app);
        }
    }

    /// Whether this route can be popped.
    ///
    /// A route can be popped if there is at least one active route below it, or if
    /// [`will_handle_pop_internally`](Route::will_handle_pop_internally) returns true.
    fn can_pop(self: Handle<Self>, app: &mut App) -> bool {
        self.as_route().has_active_route_below(app) || Route::will_handle_pop_internally(self, app)
    }

    /// Whether an app bar in the route should automatically add a back button or close button.
    ///
    /// This returns true if there is at least one active route below it, or there is at least
    /// one [`LocalHistoryEntry`] with
    /// [`implies_app_bar_dismissal`](LocalHistoryEntry::implies_app_bar_dismissal) set to true.
    fn implies_app_bar_dismissal(self: Handle<Self>, app: &App) -> bool {
        self.as_route().has_active_route_below(app)
            || self
                .local_history_route_data(app)
                .entries_implies_app_bar_dismissal
                > 0
    }

    /// Whether this route is a full-screen dialog.
    fn fullscreen_dialog(self: Handle<Self>, app: &App) -> bool {
        let _ = app;
        false
    }

    /// Dart's `_buildModalBarrier`.
    fn build_modal_barrier_entry(
        self: Handle<Self>,
        app: &mut App,
        context: BuildContext,
    ) -> WidgetRef {
        let mut barrier = ModalRoute::build_modal_barrier(self, app, context);
        if let Some(filter) = self.modal_route_data(app).filter.clone() {
            barrier = crate::widgets::basic::BackdropFilter::new(filter)
                .child(barrier)
                .into_widget();
        }
        let animation = TransitionRoute::animation(self, app).expect("an installed route");
        // `changed_internal_state` is called when the animation status updates; dismissed is
        // possible when doing a manual pop gesture.
        barrier = IgnorePointer::new()
            .ignoring(!animation.is_forward_or_completed(app))
            .child(barrier)
            .into_widget();
        if ModalRoute::semantics_dismissible(self, app)
            && ModalRoute::barrier_dismissible(self, app)
        {
            // To be sorted after the _modalScope.
            barrier = Semantics::new()
                .sort_key(Rc::new(OrdinalSortKey::new(1.0)))
                .child(barrier)
                .into_widget();
        }
        barrier
    }

    /// Builds the barrier for this [`ModalRoute`]; subclasses can override this method to
    /// create their own barrier with customized features such as color or accessibility focus
    /// size, and reach this body through [`ModalRouteBase::build_modal_barrier`].
    fn build_modal_barrier(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
        ModalRouteBase::build_modal_barrier(self, app, context)
    }

    /// Dart's `_buildModalScope`: the part of the modal scope that does not change from frame
    /// to frame, cached so that the amount of building is minimized.
    fn build_modal_scope(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
        let _ = context;
        match self.modal_route_data(app).modal_scope_cache.clone() {
            Some(cache) => cache,
            None => {
                let key = self.modal_route_data(app).scope_key.clone();
                // To be sorted before the _modalBarrier.
                let scope = Semantics::new()
                    .sort_key(Rc::new(OrdinalSortKey::new(0.0)))
                    .child(ModalScope {
                        key: Some(key.into()),
                        route: ModalRoute::as_modal_route(self),
                    })
                    .into_widget();
                self.modal_route_data_mut(app).modal_scope_cache = Some(scope.clone());
                scope
            }
        }
    }

    /// Dart's `ModalRoute.createOverlayEntries`.
    fn create_overlay_entries(self: Handle<Self>, app: &mut App) -> Vec<Ref<OverlayEntry>> {
        let barrier = OverlayEntry::new(
            app,
            Rc::new(move |app, context| ModalRoute::build_modal_barrier_entry(self, app, context)),
            false,
            false,
            false,
        );
        self.modal_route_data_mut(app).modal_barrier = Some(barrier.clone());
        let maintain_state = ModalRoute::maintain_state(self, app);
        let opaque = TransitionRoute::opaque(self, app);
        let scope = OverlayEntry::new(
            app,
            Rc::new(move |app, context| ModalRoute::build_modal_scope(self, app, context)),
            false,
            maintain_state,
            opaque,
        );
        self.modal_route_data_mut(app).modal_scope = Some(scope.clone());
        vec![barrier, scope]
    }
}

/// The bodies of Dart's `ModalRoute` class that a subclass's override runs as `super`.
///
/// Every [`ModalRoute`] implementor gets these bodies, so an override on the leaf never reaches
/// them by accident.
pub trait ModalRouteBase: ModalRoute {
    /// Dart's `ModalRoute.buildModalBarrier`.
    fn build_modal_barrier(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
        let _ = context;
        let barrier_color = ModalRoute::barrier_color(self, app);
        let dismissible = ModalRoute::barrier_dismissible(self, app);
        let semantics_label = ModalRoute::barrier_label(self, app);
        let semantics_dismissible = ModalRoute::semantics_dismissible(self, app);
        match barrier_color {
            Some(barrier_color) if barrier_color.a != 0.0 && !ModalRoute::offstage(self, app) => {
                // `changed_internal_state` is called if the barrier color or offstage updates.
                let transparent = barrier_color.with_values(Some(0.0), None, None, None, None);
                debug_assert!(barrier_color != transparent);
                let animation = TransitionRoute::animation(self, app)
                    .expect("an installed route keeps its animation")
                    .keep(app);
                let curve = ModalRoute::barrier_curve(self, app);
                let color_tween = ColorTween::new(app, Some(transparent), Some(barrier_color));
                let curve_tween = CurveTween::new(app, curve);
                let color = animation.drive(app, color_tween.chain(curve_tween));
                AnimatedModalBarrier::new(color)
                    .dismissible(dismissible)
                    .barrier_semantics_dismissible(semantics_dismissible)
                    .maybe_semantics_label(semantics_label)
                    .into_widget()
            }
            _ => ModalBarrier::new()
                .dismissible(dismissible)
                .barrier_semantics_dismissible(semantics_dismissible)
                .maybe_semantics_label(semantics_label)
                .into_widget(),
        }
    }
}

impl<R: ModalRoute> ModalRouteBase for R {}

/// The [`ModalRouteVTable`] slot for [`ModalRoute::build_flexible_transitions`].
type BuildFlexibleTransitionsSlot = fn(
    &mut App,
    HandleId,
    BuildContext,
    AnimationRef<f64>,
    AnimationRef<f64>,
    WidgetRef,
) -> WidgetRef;

/// The vtable of an erased [`AnyModalRoute`]: one `&'static` table per route type, built by
/// [`ModalRouteVTable::of`].
struct ModalRouteVTable {
    type_name: fn() -> &'static str,
    route: fn(HandleId) -> AnyRoute,
    transition_route: fn(HandleId) -> AnyTransitionRoute,
    barrier_dismissible: fn(&App, HandleId) -> bool,
    barrier_color: fn(&App, HandleId) -> Option<Color>,
    barrier_label: fn(&App, HandleId) -> Option<String>,
    maintain_state: fn(&App, HandleId) -> bool,
    opaque: fn(&App, HandleId) -> bool,
    offstage: fn(&App, HandleId) -> bool,
    set_offstage: fn(&mut App, HandleId, bool),
    animation: fn(&App, HandleId) -> Option<AnyAnimation<f64>>,
    secondary_animation: fn(&App, HandleId) -> Option<AnyAnimation<f64>>,
    delegated_transition: fn(&App, HandleId) -> Option<DelegatedTransitionBuilder>,
    can_pop: fn(&mut App, HandleId) -> bool,
    implies_app_bar_dismissal: fn(&App, HandleId) -> bool,
    fullscreen_dialog: fn(&App, HandleId) -> bool,
    pop_gesture_in_progress: fn(&App, HandleId) -> bool,
    traversal_edge_behavior: fn(&App, HandleId) -> Option<TraversalEdgeBehavior>,
    directional_traversal_edge_behavior: fn(&App, HandleId) -> Option<TraversalEdgeBehavior>,
    storage_bucket: fn(&App, HandleId) -> Handle<PageStorageBucket>,
    subtree_key: fn(&App, HandleId) -> GlobalKey,
    subtree_context: fn(&mut App, HandleId) -> Option<BuildContext>,
    build_page:
        fn(&mut App, HandleId, BuildContext, AnimationRef<f64>, AnimationRef<f64>) -> WidgetRef,
    build_flexible_transitions: BuildFlexibleTransitionsSlot,
    add_local_history_entry: fn(&mut App, HandleId, Ref<LocalHistoryEntry>),
    remove_local_history_entry: fn(&mut App, HandleId, Handle<LocalHistoryEntry>),
    register_pop_entry: fn(&mut App, HandleId, Rc<dyn PopEntry>),
    unregister_pop_entry: fn(&mut App, HandleId, Rc<dyn PopEntry>),
}

impl ModalRouteVTable {
    /// The table for one modal route type.
    const fn of<R: ModalRoute>() -> ModalRouteVTable {
        ModalRouteVTable {
            type_name: std::any::type_name::<R>,
            route: |id| Route::as_route(resolve::<R>(id)),
            transition_route: |id| TransitionRoute::as_transition_route(resolve::<R>(id)),
            barrier_dismissible: |app, id| R::barrier_dismissible(resolve(id), app),
            barrier_color: |app, id| R::barrier_color(resolve(id), app),
            barrier_label: |app, id| R::barrier_label(resolve(id), app),
            maintain_state: |app, id| R::maintain_state(resolve(id), app),
            opaque: |app, id| TransitionRoute::opaque(resolve::<R>(id), app),
            offstage: |app, id| R::offstage(resolve(id), app),
            set_offstage: |app, id, value| R::set_offstage(resolve(id), app, value),
            animation: |app, id| ModalRoute::animation(resolve::<R>(id), app),
            secondary_animation: |app, id| ModalRoute::secondary_animation(resolve::<R>(id), app),
            delegated_transition: |app, id| R::delegated_transition(resolve(id), app),
            can_pop: |app, id| R::can_pop(resolve(id), app),
            implies_app_bar_dismissal: |app, id| R::implies_app_bar_dismissal(resolve(id), app),
            fullscreen_dialog: |app, id| R::fullscreen_dialog(resolve(id), app),
            pop_gesture_in_progress: |app, id| R::pop_gesture_in_progress(resolve(id), app),
            traversal_edge_behavior: |app, id| {
                R::modal_route_data(resolve::<R>(id), app).traversal_edge_behavior
            },
            directional_traversal_edge_behavior: |app, id| {
                R::modal_route_data(resolve::<R>(id), app).directional_traversal_edge_behavior
            },
            storage_bucket: |app, id| {
                R::modal_route_data(resolve::<R>(id), app)
                    .storage_bucket
                    .handle()
            },
            subtree_key: |app, id| {
                R::modal_route_data(resolve::<R>(id), app)
                    .subtree_key
                    .clone()
            },
            subtree_context: |app, id| R::subtree_context(resolve::<R>(id), app),
            build_page: |app, id, context, animation, secondary| {
                R::build_page(resolve(id), app, context, animation, secondary)
            },
            build_flexible_transitions: |app, id, context, animation, secondary, child| {
                R::build_flexible_transitions(
                    resolve(id),
                    app,
                    context,
                    animation,
                    secondary,
                    child,
                )
            },
            add_local_history_entry: |app, id, entry| {
                LocalHistoryRoute::add_local_history_entry(resolve::<R>(id), app, entry)
            },
            remove_local_history_entry: |app, id, entry| {
                LocalHistoryRoute::remove_local_history_entry(resolve::<R>(id), app, entry)
            },
            register_pop_entry: |app, id, entry| R::register_pop_entry(resolve(id), app, entry),
            unregister_pop_entry: |app, id, entry| R::unregister_pop_entry(resolve(id), app, entry),
        }
    }
}

/// Erased [`ModalRoute`]: what Dart's `ModalRoute.of(context)` returns and what
/// `route is ModalRoute<dynamic>` produces.
#[derive(Clone, Copy)]
pub struct AnyModalRoute {
    id: HandleId,
    vtable: &'static ModalRouteVTable,
}

/// A kept route as a [`RouteRef`], through [`Retained::erase`]: Dart's upcast.
impl From<AnyModalRoute> for AnyRoute {
    fn from(route: AnyModalRoute) -> AnyRoute {
        route.as_route()
    }
}

impl From<AnyModalRoute> for AnyTransitionRoute {
    fn from(route: AnyModalRoute) -> AnyTransitionRoute {
        route.as_transition_route()
    }
}

/// A field Dart types as the erased object, kept: AnyModalRoute with its count.
pub type ModalRouteRef = Retained<AnyModalRoute>;

waft_foundation::erased_handle!(AnyModalRoute: ModalRoute => ModalRoute::as_modal_route);

impl Debug for AnyModalRoute {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
    }
}

impl AnyModalRoute {
    /// The route's [`animation`](Self::animation) and
    /// [`secondary_animation`](Self::secondary_animation), kept, for the builders that take them.
    ///
    /// # Panics
    ///
    /// Before the route is installed.
    pub fn animations(self, app: &App) -> (AnimationRef<f64>, AnimationRef<f64>) {
        let kept = |animation: Option<AnyAnimation<f64>>| {
            animation
                .expect("an installed route keeps its animations")
                .keep(app)
        };
        (
            kept(self.animation(app)),
            kept(self.secondary_animation(app)),
        )
    }

    /// Returns the modal route most closely associated with the given context.
    ///
    /// Returns `None` if the given context is not associated with a modal route.
    ///
    /// The given [`BuildContext`] will be rebuilt if the state of the route changes while it is
    /// visible (specifically, if [`AnyRoute::is_current`] or [`can_pop`](Self::can_pop) change
    /// value).
    ///
    /// Dart's `ModalRoute.of(context)`.
    pub fn of(app: &mut App, context: BuildContext) -> Option<AnyModalRoute> {
        AnyModalRoute::of_aspect(app, context, None)
    }

    /// Dart's `ModalRoute._of`.
    fn of_aspect(
        app: &mut App,
        context: BuildContext,
        aspect: Option<ModalRouteAspect>,
    ) -> Option<AnyModalRoute> {
        ModalScopeStatus::inherit_from(app, context, aspect).map(|status| status.route.handle())
    }

    /// Returns [`AnyRoute::is_current`] for the modal route most closely associated with the
    /// given context, creating a dependency on that aspect.
    pub fn is_current_of(app: &mut App, context: BuildContext) -> Option<bool> {
        let route = AnyModalRoute::of_aspect(app, context, Some(ModalRouteAspect::IsCurrent))?;
        Some(route.as_route().is_current(app))
    }

    /// Returns [`can_pop`](Self::can_pop) for the modal route most closely associated with the
    /// given context, creating a dependency on that aspect.
    pub fn can_pop_of(app: &mut App, context: BuildContext) -> Option<bool> {
        let route = AnyModalRoute::of_aspect(app, context, Some(ModalRouteAspect::CanPop))?;
        Some(route.can_pop(app))
    }

    /// Returns [`AnyRoute::settings`] for the modal route most closely associated with the
    /// given context, creating a dependency on that aspect.
    pub fn settings_of(app: &mut App, context: BuildContext) -> Option<RouteSettingsRef> {
        let route = AnyModalRoute::of_aspect(app, context, Some(ModalRouteAspect::Settings))?;
        Some(route.as_route().settings(app))
    }

    /// Returns [`AnyRoute::is_active`] for the modal route most closely associated with the
    /// given context, creating a dependency on that aspect.
    pub fn is_active_of(app: &mut App, context: BuildContext) -> Option<bool> {
        let route = AnyModalRoute::of_aspect(app, context, Some(ModalRouteAspect::IsActive))?;
        Some(route.as_route().is_active(app))
    }

    /// Returns [`AnyRoute::is_first`] for the modal route most closely associated with the
    /// given context, creating a dependency on that aspect.
    pub fn is_first_of(app: &mut App, context: BuildContext) -> Option<bool> {
        let route = AnyModalRoute::of_aspect(app, context, Some(ModalRouteAspect::IsFirst))?;
        Some(route.as_route().is_first(app))
    }

    /// Returns [`opaque`](Self::opaque) for the modal route most closely associated with the
    /// given context, creating a dependency on that aspect.
    pub fn opaque_of(app: &mut App, context: BuildContext) -> Option<bool> {
        let route = AnyModalRoute::of_aspect(app, context, Some(ModalRouteAspect::Opaque))?;
        Some(route.opaque(app))
    }

    /// Returns [`AnyRoute::pop_disposition`] for the modal route most closely associated with
    /// the given context, creating a dependency on that aspect.
    pub fn pop_disposition_of(app: &mut App, context: BuildContext) -> Option<RoutePopDisposition> {
        let route = AnyModalRoute::of_aspect(app, context, Some(ModalRouteAspect::PopDisposition))?;
        Some(route.as_route().pop_disposition(app))
    }

    /// Returns a predicate that is true if the route has the specified name and if popping the
    /// route will not yield the same route, i.e. if the route's
    /// [`Route::will_handle_pop_internally`] is false.
    ///
    /// This function is typically used with [`NavigatorState::pop_until`](crate::NavigatorState::pop_until).
    pub fn with_name(name: &str) -> RoutePredicate {
        let name = name.to_string();
        Rc::new(move |app, route: AnyRoute| {
            !route.will_handle_pop_internally(app)
                && route.as_modal_route(app).is_some()
                && route.settings(app).name() == Some(name.as_str())
        })
    }

    /// This modal route as the erased [`AnyRoute`].
    pub fn as_route(self) -> AnyRoute {
        (self.vtable.route)(self.id)
    }

    /// This modal route as the erased [`AnyTransitionRoute`].
    pub fn as_transition_route(self) -> AnyTransitionRoute {
        (self.vtable.transition_route)(self.id)
    }

    /// See [`ModalRoute::barrier_dismissible`].
    pub fn barrier_dismissible(self, app: &App) -> bool {
        (self.vtable.barrier_dismissible)(app, self.id)
    }

    /// See [`ModalRoute::barrier_color`].
    pub fn barrier_color(self, app: &App) -> Option<Color> {
        (self.vtable.barrier_color)(app, self.id)
    }

    /// See [`ModalRoute::barrier_label`].
    pub fn barrier_label(self, app: &App) -> Option<String> {
        (self.vtable.barrier_label)(app, self.id)
    }

    /// See [`ModalRoute::maintain_state`].
    pub fn maintain_state(self, app: &App) -> bool {
        (self.vtable.maintain_state)(app, self.id)
    }

    /// See [`TransitionRoute::opaque`].
    pub fn opaque(self, app: &App) -> bool {
        (self.vtable.opaque)(app, self.id)
    }

    /// See [`ModalRoute::offstage`].
    pub fn offstage(self, app: &App) -> bool {
        (self.vtable.offstage)(app, self.id)
    }

    /// See [`ModalRoute::set_offstage`].
    pub fn set_offstage(self, app: &mut App, value: bool) {
        (self.vtable.set_offstage)(app, self.id, value)
    }

    /// See [`ModalRoute::animation`].
    pub fn animation(self, app: &App) -> Option<AnyAnimation<f64>> {
        (self.vtable.animation)(app, self.id)
    }

    /// See [`ModalRoute::secondary_animation`].
    pub fn secondary_animation(self, app: &App) -> Option<AnyAnimation<f64>> {
        (self.vtable.secondary_animation)(app, self.id)
    }

    /// See [`ModalRoute::delegated_transition`].
    pub fn delegated_transition(self, app: &App) -> Option<DelegatedTransitionBuilder> {
        (self.vtable.delegated_transition)(app, self.id)
    }

    /// See [`ModalRoute::can_pop`].
    pub fn can_pop(self, app: &mut App) -> bool {
        (self.vtable.can_pop)(app, self.id)
    }

    /// See [`ModalRoute::implies_app_bar_dismissal`].
    pub fn implies_app_bar_dismissal(self, app: &App) -> bool {
        (self.vtable.implies_app_bar_dismissal)(app, self.id)
    }

    /// See [`ModalRoute::fullscreen_dialog`].
    pub fn fullscreen_dialog(self, app: &App) -> bool {
        (self.vtable.fullscreen_dialog)(app, self.id)
    }

    /// See [`ModalRoute::pop_gesture_in_progress`].
    pub fn pop_gesture_in_progress(self, app: &App) -> bool {
        (self.vtable.pop_gesture_in_progress)(app, self.id)
    }

    /// See [`ModalRouteData::traversal_edge_behavior`].
    pub fn traversal_edge_behavior(self, app: &App) -> Option<TraversalEdgeBehavior> {
        (self.vtable.traversal_edge_behavior)(app, self.id)
    }

    /// See [`ModalRouteData::directional_traversal_edge_behavior`].
    pub fn directional_traversal_edge_behavior(self, app: &App) -> Option<TraversalEdgeBehavior> {
        (self.vtable.directional_traversal_edge_behavior)(app, self.id)
    }

    /// Dart's `ModalRoute._storageBucket`.
    pub fn storage_bucket(self, app: &App) -> Handle<PageStorageBucket> {
        (self.vtable.storage_bucket)(app, self.id)
    }

    /// Dart's `ModalRoute._subtreeKey`.
    pub fn subtree_key(self, app: &App) -> GlobalKey {
        (self.vtable.subtree_key)(app, self.id)
    }

    /// See [`ModalRoute::subtree_context`].
    pub fn subtree_context(self, app: &mut App) -> Option<BuildContext> {
        (self.vtable.subtree_context)(app, self.id)
    }

    /// See [`ModalRoute::build_page`].
    pub fn build_page(
        self,
        app: &mut App,
        context: BuildContext,
        animation: AnimationRef<f64>,
        secondary_animation: AnimationRef<f64>,
    ) -> WidgetRef {
        (self.vtable.build_page)(app, self.id, context, animation, secondary_animation)
    }

    /// See [`ModalRoute::build_flexible_transitions`].
    pub fn build_flexible_transitions(
        self,
        app: &mut App,
        context: BuildContext,
        animation: AnimationRef<f64>,
        secondary_animation: AnimationRef<f64>,
        child: WidgetRef,
    ) -> WidgetRef {
        (self.vtable.build_flexible_transitions)(
            app,
            self.id,
            context,
            animation,
            secondary_animation,
            child,
        )
    }

    /// See [`LocalHistoryRoute::add_local_history_entry`].
    pub fn add_local_history_entry(self, app: &mut App, entry: Ref<LocalHistoryEntry>) {
        (self.vtable.add_local_history_entry)(app, self.id, entry)
    }

    /// See [`LocalHistoryRoute::remove_local_history_entry`].
    pub fn remove_local_history_entry(self, app: &mut App, entry: Handle<LocalHistoryEntry>) {
        (self.vtable.remove_local_history_entry)(app, self.id, entry)
    }

    /// See [`ModalRoute::register_pop_entry`].
    pub fn register_pop_entry(self, app: &mut App, pop_entry: Rc<dyn PopEntry>) {
        (self.vtable.register_pop_entry)(app, self.id, pop_entry)
    }

    /// See [`ModalRoute::unregister_pop_entry`].
    pub fn unregister_pop_entry(self, app: &mut App, pop_entry: Rc<dyn PopEntry>) {
        (self.vtable.unregister_pop_entry)(app, self.id, pop_entry)
    }
}

// ---------------------------------------------------------------------------------------------
// PopupRoute

/// A modal route that overlays a widget over the current route.
///
/// See also:
///
///  * [`ModalRoute`], which is the base of this trait.
///  * [`NavigatorState::pop`](crate::NavigatorState::pop), which is used to dismiss the route.
pub trait PopupRoute: ModalRoute {
    /// Dart's `PopupRoute.opaque`.
    fn opaque(self: Handle<Self>, app: &App) -> bool {
        let _ = app;
        false
    }

    /// Dart's `PopupRoute.maintainState`.
    fn maintain_state(self: Handle<Self>, app: &App) -> bool {
        let _ = app;
        true
    }

    /// Dart's `PopupRoute.allowSnapshotting`.
    fn allow_snapshotting(self: Handle<Self>, app: &App) -> bool {
        let _ = app;
        false
    }
}

// ---------------------------------------------------------------------------------------------
// The forwarders a modal-route leaf writes

/// The `Route` overrides a [`ModalRoute`] leaf inherits, plus
/// [`route_accessors!`](crate::route_accessors). Write it inside `impl Route for MyRoute { .. }`.
#[macro_export]
macro_rules! modal_route_overrides {
    () => {
        $crate::route_accessors!();

        fn as_transition_route(
            self: ::waft_foundation::Handle<Self>,
        ) -> ::std::option::Option<$crate::AnyTransitionRoute> {
            ::std::option::Option::Some($crate::TransitionRoute::as_transition_route(self))
        }

        fn as_modal_route(
            self: ::waft_foundation::Handle<Self>,
        ) -> ::std::option::Option<$crate::AnyModalRoute> {
            ::std::option::Option::Some($crate::ModalRoute::as_modal_route(self))
        }

        fn overlay_entries(
            self: ::waft_foundation::Handle<Self>,
            app: &::waft_foundation::App,
        ) -> ::std::vec::Vec<::waft_foundation::Handle<$crate::OverlayEntry>> {
            $crate::OverlayRoute::overlay_entries(self, app)
        }

        fn install(self: ::waft_foundation::Handle<Self>, app: &mut ::waft_foundation::App) {
            $crate::ModalRoute::install(self, app)
        }

        fn did_push(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
        ) -> ::waft_scheduler::TickerFuture {
            $crate::ModalRoute::did_push(self, app)
        }

        fn did_add(self: ::waft_foundation::Handle<Self>, app: &mut ::waft_foundation::App) {
            $crate::ModalRoute::did_add(self, app)
        }

        fn did_replace(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
            old_route: ::std::option::Option<$crate::AnyRoute>,
        ) {
            $crate::TransitionRoute::did_replace(self, app, old_route)
        }

        fn will_pop(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
        ) -> $crate::RoutePopDisposition {
            $crate::LocalHistoryRoute::will_pop(self, app)
        }

        fn pop_disposition(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
        ) -> $crate::RoutePopDisposition {
            $crate::ModalRoute::pop_disposition(self, app)
        }

        fn on_pop_invoked_with_result(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
            did_pop: bool,
            result: $crate::RouteResult,
        ) {
            $crate::ModalRoute::on_pop_invoked_with_result(self, app, did_pop, result)
        }

        fn will_handle_pop_internally(
            self: ::waft_foundation::Handle<Self>,
            app: &::waft_foundation::App,
        ) -> bool {
            $crate::LocalHistoryRoute::will_handle_pop_internally(self, app)
        }

        fn did_pop(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
            result: $crate::RouteResult,
        ) -> bool {
            $crate::LocalHistoryRoute::did_pop(self, app, result)
        }

        fn did_pop_next(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
            next_route: $crate::AnyRoute,
        ) {
            $crate::ModalRoute::did_pop_next(self, app, next_route)
        }

        fn did_change_next(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
            next_route: ::std::option::Option<$crate::AnyRoute>,
        ) {
            $crate::ModalRoute::did_change_next(self, app, next_route)
        }

        fn did_change_previous(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
            previous_route: ::std::option::Option<$crate::AnyRoute>,
        ) {
            $crate::ModalRoute::did_change_previous(self, app, previous_route)
        }

        fn changed_internal_state(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
        ) {
            $crate::ModalRoute::changed_internal_state(self, app)
        }

        fn changed_external_state(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
        ) {
            $crate::ModalRoute::changed_external_state(self, app)
        }

        fn dispose(self: ::waft_foundation::Handle<Self>, app: &mut ::waft_foundation::App) {
            $crate::TransitionRoute::dispose(self, app)
        }
    };
}

/// The `OverlayRoute` overrides a [`ModalRoute`] leaf inherits, plus
/// [`overlay_route_accessors!`](crate::overlay_route_accessors). Write it inside
/// `impl OverlayRoute for MyRoute { .. }`.
#[macro_export]
macro_rules! modal_overlay_route_overrides {
    () => {
        $crate::overlay_route_accessors!();

        fn create_overlay_entries(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
        ) -> ::std::vec::Vec<::waft_foundation::Ref<$crate::OverlayEntry>> {
            $crate::ModalRoute::create_overlay_entries(self, app)
        }

        fn finished_when_popped(
            self: ::waft_foundation::Handle<Self>,
            app: &::waft_foundation::App,
        ) -> bool {
            $crate::TransitionRoute::finished_when_popped(self, app)
        }
    };
}

/// The `PredictiveBackRoute` implementation a [`ModalRoute`] leaf inherits. Write it inside
/// `impl PredictiveBackRoute for MyRoute { .. }`.
#[macro_export]
macro_rules! modal_predictive_back_route_overrides {
    ($pop_gesture_enabled:path) => {
        fn pop_gesture_enabled(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
        ) -> bool {
            $pop_gesture_enabled(self, app)
        }

        fn handle_start_back_gesture(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
            progress: f64,
        ) {
            $crate::TransitionRoute::handle_start_back_gesture(self, app, progress)
        }

        fn handle_update_back_gesture_progress(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
            progress: f64,
        ) {
            $crate::TransitionRoute::handle_update_back_gesture_progress(self, app, progress)
        }

        fn handle_commit_back_gesture(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
        ) {
            $crate::TransitionRoute::handle_commit_back_gesture(self, app)
        }

        fn handle_cancel_back_gesture(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
        ) {
            $crate::TransitionRoute::handle_cancel_back_gesture(self, app)
        }
    };
}

/// The `TransitionRoute` overrides a [`ModalRoute`] leaf inherits, plus
/// [`transition_route_accessors!`](crate::transition_route_accessors). Write it inside
/// `impl TransitionRoute for MyRoute { .. }`, next to the leaf's own `opaque`,
/// `transition_duration` and `allow_snapshotting`.
#[macro_export]
macro_rules! modal_transition_route_overrides {
    () => {
        $crate::transition_route_accessors!();

        fn animation(
            self: ::waft_foundation::Handle<Self>,
            app: &::waft_foundation::App,
        ) -> ::std::option::Option<::waft_animation::AnyAnimation<f64>> {
            $crate::ModalRoute::animation(self, app)
        }

        fn secondary_animation(
            self: ::waft_foundation::Handle<Self>,
            app: &::waft_foundation::App,
        ) -> ::std::option::Option<::waft_animation::AnyAnimation<f64>> {
            $crate::ModalRoute::secondary_animation(self, app)
        }
    };
}

// ---------------------------------------------------------------------------------------------
// RouteObserver / RouteAware

/// A [`Navigator`] observer that notifies [`RouteAware`]s of changes to the state of their
/// [`Route`].
///
/// [`RouteObserver`] informs subscribers whenever a route the `matches` predicate accepts is
/// pushed on top of their own matching route or popped from it. This is for example useful to
/// keep track of page transitions: a `RouteObserver` built with `AnyRoute::as_page_route` will
/// inform subscribed [`RouteAware`]s whenever the user navigates away from the current page
/// route to another page route.
///
/// See also:
///
///  * [`RouteAware`], which is used with [`RouteObserver`] to make a widget aware of changes to
///    the [`Navigator`]'s session history.
pub struct RouteObserver {
    navigator_observer: NavigatorObserverData,
    matches: RoutePredicate,
    listeners: Vec<(RouteRef, Vec<Rc<dyn RouteAware>>)>,
}

impl RouteObserver {
    /// Creates an observer of the routes `matches` accepts; Dart's type argument `R`.
    pub fn new(app: &mut App, matches: RoutePredicate) -> Ref<RouteObserver> {
        app.create(RouteObserver {
            navigator_observer: NavigatorObserverData::new(),
            matches,
            listeners: Vec::new(),
        })
    }

    /// Whether this observer is managing changes for the specified route.
    ///
    /// If debug assertions are disabled, this method always returns false.
    pub fn debug_observing_route(self: Handle<Self>, app: &App, route: AnyRoute) -> bool {
        let mut contained = false;
        if cfg!(debug_assertions) {
            contained = app
                .get(self)
                .listeners
                .iter()
                .any(|(held, _)| held == route);
        }
        contained
    }

    /// Subscribes `route_aware` to be informed about changes to `route`.
    ///
    /// Going forward, `route_aware` will be informed about qualifying changes to `route`, e.g.
    /// when `route` is covered by another route or when `route` is popped off the [`Navigator`]
    /// stack.
    pub fn subscribe(
        self: Handle<Self>,
        app: &mut App,
        route_aware: Rc<dyn RouteAware>,
        route: AnyRoute,
    ) {
        let kept = route.keep(app);
        let listeners = &mut app.get_mut(self).listeners;
        let subscribers = match listeners.iter_mut().find(|(held, _)| held == route) {
            Some((_, subscribers)) => subscribers,
            None => {
                listeners.push((kept, Vec::new()));
                &mut listeners.last_mut().expect("just pushed").1
            }
        };
        if subscribers
            .iter()
            .any(|held| Rc::ptr_eq(held, &route_aware))
        {
            return;
        }
        subscribers.push(Rc::clone(&route_aware));
        route_aware.did_push(app);
    }

    /// Unsubscribes `route_aware`.
    ///
    /// `route_aware` is no longer informed about changes to its route. If the given argument
    /// was subscribed to multiple routes, this unregisters it (once) from each.
    pub fn unsubscribe(self: Handle<Self>, app: &mut App, route_aware: Rc<dyn RouteAware>) {
        let listeners = &mut app.get_mut(self).listeners;
        for (_, subscribers) in listeners.iter_mut() {
            subscribers.retain(|held| !Rc::ptr_eq(held, &route_aware));
        }
        listeners.retain(|(_, subscribers)| !subscribers.is_empty());
    }

    fn subscribers_of(
        self: Handle<Self>,
        app: &App,
        route: AnyRoute,
    ) -> Option<Vec<Rc<dyn RouteAware>>> {
        app.get(self)
            .listeners
            .iter()
            .find(|(held, _)| held == route)
            .map(|(_, subscribers)| subscribers.clone())
    }

    fn matches(self: Handle<Self>, app: &mut App, route: Option<AnyRoute>) -> bool {
        let Some(route) = route else {
            return false;
        };
        let matches = Rc::clone(&app.get(self).matches);
        matches(app, route)
    }
}

impl NavigatorObserver for RouteObserver {
    crate::navigator_observer_accessors!();

    fn did_pop(
        self: Handle<Self>,
        app: &mut App,
        route: AnyRoute,
        previous_route: Option<AnyRoute>,
    ) {
        if !self.matches(app, Some(route)) || !self.matches(app, previous_route) {
            return;
        }
        let previous_route = previous_route.expect("matched above");
        if let Some(previous_subscribers) = self.subscribers_of(app, previous_route) {
            for route_aware in previous_subscribers {
                route_aware.did_pop_next(app);
            }
        }
        if let Some(subscribers) = self.subscribers_of(app, route) {
            for route_aware in subscribers {
                route_aware.did_pop(app);
            }
        }
    }

    fn did_push(
        self: Handle<Self>,
        app: &mut App,
        route: AnyRoute,
        previous_route: Option<AnyRoute>,
    ) {
        if !self.matches(app, Some(route)) || !self.matches(app, previous_route) {
            return;
        }
        let previous_route = previous_route.expect("matched above");
        if let Some(previous_subscribers) = self.subscribers_of(app, previous_route) {
            for route_aware in previous_subscribers {
                route_aware.did_push_next(app);
            }
        }
    }
}

/// An interface for objects that are aware of their current [`Route`].
///
/// This is used with [`RouteObserver`] to make a widget aware of changes to the [`Navigator`]'s
/// session history.
///
/// What Dart types as `RouteAware` becomes an `Rc<dyn RouteAware>`; an arena object implements
/// [`RouteAwareObject`], and `Rc::new(handle)` is its erased form. A [`RouteObserver`] compares
/// subscribers by identity, so a subscriber keeps the `Rc` it subscribed with to unsubscribe.
pub trait RouteAware {
    /// Called when the top route has been popped off, and the current route shows up.
    fn did_pop_next(&self, app: &mut App);

    /// Called when the current route has been pushed.
    fn did_push(&self, app: &mut App);

    /// Called when the current route has been popped off.
    fn did_pop(&self, app: &mut App);

    /// Called when a new route has been pushed on top of this route, temporarily obscuring it.
    ///
    /// This method is called synchronously during the push operation, before the transition
    /// animation completes. The current route may still be partially visible as it animates
    /// out.
    fn did_push_next(&self, app: &mut App);
}

/// The object side of [`RouteAware`]: an arena object a [`RouteObserver`] informs. Implementing
/// it makes `Handle<Self>` a [`RouteAware`]; Dart's empty default bodies are the defaults here.
pub trait RouteAwareObject: Sized + 'static {
    /// See [`RouteAware::did_pop_next`].
    fn did_pop_next(self: Handle<Self>, app: &mut App) {
        let _ = app;
    }

    /// See [`RouteAware::did_push`].
    fn did_push(self: Handle<Self>, app: &mut App) {
        let _ = app;
    }

    /// See [`RouteAware::did_pop`].
    fn did_pop(self: Handle<Self>, app: &mut App) {
        let _ = app;
    }

    /// See [`RouteAware::did_push_next`].
    fn did_push_next(self: Handle<Self>, app: &mut App) {
        let _ = app;
    }
}

impl<T: RouteAwareObject> RouteAware for Handle<T> {
    fn did_pop_next(&self, app: &mut App) {
        T::did_pop_next(*self, app);
    }

    fn did_push(&self, app: &mut App) {
        T::did_push(*self, app);
    }

    fn did_pop(&self, app: &mut App) {
        T::did_pop(*self, app);
    }

    fn did_push_next(&self, app: &mut App) {
        T::did_push_next(*self, app);
    }
}

// ---------------------------------------------------------------------------------------------
// RawDialogRoute and its callbacks

/// Signature for the function that builds a route's primary contents.
///
/// Used in `PageRouteBuilder` and [`ShowGeneralDialog`].
///
/// See [`ModalRoute::build_page`] for the complete definition of the parameters.
pub type RoutePageBuilder =
    Rc<dyn Fn(&mut App, BuildContext, AnimationRef<f64>, AnimationRef<f64>) -> WidgetRef>;

/// Signature for the function that builds a route's transitions.
///
/// Used in `PageRouteBuilder` and [`ShowGeneralDialog`].
///
/// The `animation` argument drives this route's transition when it is pushed onto or popped off
/// the [`Navigator`]. The `secondary_animation` argument lets this route coordinate with the
/// transition of the route above it: when a new route is pushed on top of this one, this
/// route's `secondary_animation` runs from 0.0 to 1.0, and when that route is popped it runs
/// from 1.0 to 0.0.
///
/// A route only receives a running `secondary_animation` when this route's
/// [`TransitionRoute::can_transition_to`] and the next route's
/// [`TransitionRoute::can_transition_from`] both return true. Otherwise `secondary_animation`
/// remains `k_always_dismissed_animation`.
///
/// See [`ModalRoute::build_transitions`] for the complete definition of the parameters.
pub type RouteTransitionsBuilder = Rc<
    dyn Fn(&mut App, BuildContext, AnimationRef<f64>, AnimationRef<f64>, WidgetRef) -> WidgetRef,
>;

/// Configuration details for a custom modal barrier.
///
/// Passed to a [`RouteBarrierBuilder`] by the routing framework to provide the ambient
/// variables associated with the route's modal barrier.
#[derive(Clone, Debug)]
pub struct RouteBarrierDetails {
    /// An animation that drives the route's transition.
    ///
    /// Typically used to animate the barrier's opacity from 0.0 to 1.0 when the route is
    /// pushed.
    pub animation: AnimationRef<f64>,
    /// The color to paint behind the route.
    ///
    /// If `None`, the barrier will be transparent.
    pub barrier_color: Option<Color>,
    /// The semantic label used for the barrier.
    pub barrier_label: Option<String>,
    /// Whether touching the barrier will pop the current route off the [`Navigator`].
    pub barrier_dismissible: bool,
}

impl RouteBarrierDetails {
    /// Creates an object that contains the configuration for a modal barrier; Dart's optional
    /// arguments are the setters.
    pub fn new(animation: AnimationRef<f64>, barrier_dismissible: bool) -> RouteBarrierDetails {
        RouteBarrierDetails {
            animation,
            barrier_color: None,
            barrier_label: None,
            barrier_dismissible,
        }
    }

    /// Dart `RouteBarrierDetails(barrierColor:)`.
    pub fn barrier_color(mut self, barrier_color: Color) -> RouteBarrierDetails {
        self.barrier_color = Some(barrier_color);
        self
    }

    /// Dart `RouteBarrierDetails(barrierLabel:)`.
    pub fn barrier_label(mut self, barrier_label: String) -> RouteBarrierDetails {
        self.barrier_label = Some(barrier_label);
        self
    }
}

/// Signature for the function that builds a custom modal barrier for a route.
///
/// Used by [`RawDialogRoute::barrier_builder`] and [`ShowGeneralDialog`] to wrap or replace
/// the default modal barrier.
///
/// The `barrier` parameter is the default [`ModalBarrier`] (or [`AnimatedModalBarrier`])
/// constructed by the framework. Custom builders should typically return a widget that wraps
/// this `barrier`, rather than replacing it entirely, to preserve the built-in semantics and
/// gestures.
pub type RouteBarrierBuilder =
    Rc<dyn Fn(&mut App, BuildContext, &RouteBarrierDetails, WidgetRef) -> WidgetRef>;

/// A callback type for informing that a navigation pop has been invoked, whether or not it was
/// handled successfully.
///
/// Accepts a `did_pop` boolean indicating whether or not back navigation succeeded.
///
/// The `result` contains the pop result.
pub type PopInvokedWithResultCallback = Rc<dyn Fn(&mut App, bool, RouteResult)>;

/// Allows listening to and preventing pops.
///
/// Can be registered in a [`ModalRoute`] to listen to pops with
/// [`on_pop_invoked_with_result`](Self::on_pop_invoked_with_result) or to enable and disable
/// them with [`can_pop_notifier`](Self::can_pop_notifier).
///
/// See also:
///
///  * `PopScope`, which provides similar functionality in a widget.
///  * [`ModalRoute::register_pop_entry`], which registers instances of this.
///  * [`ModalRoute::unregister_pop_entry`], which unregisters instances of this.
///
/// What Dart types as `PopEntry` becomes an `Rc<dyn PopEntry>`; an arena object implements
/// [`PopEntryObject`], and `Rc::new(handle)` is its erased form. A [`ModalRoute`] compares
/// entries by identity, so an entry keeps the `Rc` it registered to unregister it.
pub trait PopEntry {
    /// Called after a route pop was handled.
    fn on_pop_invoked_with_result(&self, app: &mut App, did_pop: bool, result: RouteResult);

    /// When false, blocks the current route from being popped.
    fn can_pop_notifier(&self, app: &App) -> Rc<dyn ValueListenable<bool>>;
}

/// The object side of [`PopEntry`]: an arena object a [`ModalRoute`] registers. Implementing it
/// makes `Handle<Self>` a [`PopEntry`].
pub trait PopEntryObject: Sized + 'static {
    /// See [`PopEntry::on_pop_invoked_with_result`].
    fn on_pop_invoked_with_result(
        self: Handle<Self>,
        app: &mut App,
        did_pop: bool,
        result: RouteResult,
    );

    /// See [`PopEntry::can_pop_notifier`].
    fn can_pop_notifier(self: Handle<Self>, app: &App) -> Rc<dyn ValueListenable<bool>>;
}

impl<T: PopEntryObject> PopEntry for Handle<T> {
    fn on_pop_invoked_with_result(&self, app: &mut App, did_pop: bool, result: RouteResult) {
        T::on_pop_invoked_with_result(*self, app, did_pop, result);
    }

    fn can_pop_notifier(&self, app: &App) -> Rc<dyn ValueListenable<bool>> {
        T::can_pop_notifier(*self, app)
    }
}

/// The fields of Dart's `RawDialogRoute`, which its subclasses carry.
pub struct RawDialogRouteData {
    /// Used to build the route's primary contents.
    pub page_builder: RoutePageBuilder,
    /// Whether touching the modal barrier pops the route; see
    /// [`ModalRoute::barrier_dismissible`].
    pub barrier_dismissible: bool,
    /// The semantic label of the modal barrier; see [`ModalRoute::barrier_label`].
    pub barrier_label: Option<String>,
    /// The color painted behind the dialog; see [`ModalRoute::barrier_color`].
    pub barrier_color: Option<Color>,
    /// How long the route takes to arrive on and leave off the screen; see
    /// [`TransitionRoute::transition_duration`].
    pub transition_duration: Duration,
    /// Used to define how the route arrives on and leaves off the screen.
    ///
    /// If `None`, the transition is a linear fade of the page's contents.
    pub transition_builder: Option<RouteTransitionsBuilder>,
    /// Used to define how the route's modal barrier is built.
    ///
    /// If not `None`, this builder is used to wrap or replace the default [`ModalBarrier`].
    pub barrier_builder: Option<RouteBarrierBuilder>,
    /// Whether this route is a full-screen dialog.
    ///
    /// In Material and Cupertino, being fullscreen has the effects of making the app bars have
    /// a close button instead of a back button.
    pub fullscreen_dialog: bool,
}

impl RawDialogRouteData {
    /// The bag of a freshly created dialog route; Dart's constructor defaults.
    pub fn new(page_builder: RoutePageBuilder) -> RawDialogRouteData {
        RawDialogRouteData {
            page_builder,
            barrier_dismissible: true,
            barrier_label: None,
            barrier_color: Some(Color::new(0x8000_0000)),
            transition_duration: Duration::from_millis(200),
            transition_builder: None,
            barrier_builder: None,
            fullscreen_dialog: false,
        }
    }
}

/// The accessors [`RawDialogRouteLeaf`] asks for, for a struct whose bag is the field
/// `raw_dialog_route`.
#[macro_export]
macro_rules! raw_dialog_route_accessors {
    () => {
        fn raw_dialog_route_data(
            self: ::waft_foundation::Handle<Self>,
            app: &::waft_foundation::App,
        ) -> &$crate::RawDialogRouteData {
            &app.get(self).raw_dialog_route
        }

        fn raw_dialog_route_data_mut(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
        ) -> &mut $crate::RawDialogRouteData {
            &mut app.get_mut(self).raw_dialog_route
        }
    };
}

/// A [`PopupRoute`] with the fields Dart's `RawDialogRoute` declares and the members it
/// overrides.
///
/// The shared bodies are associated functions on [`RawDialogRoute`]; an override calls one
/// where Dart writes `super.…`.
///
/// A leaf writes [`raw_dialog_route_modal_route_overrides!`](crate::raw_dialog_route_modal_route_overrides)
/// and [`raw_dialog_route_transition_route_overrides!`](crate::raw_dialog_route_transition_route_overrides)
/// to route the `ModalRoute` and `TransitionRoute` virtuals here.
pub trait RawDialogRouteLeaf: PopupRoute {
    /// Dart's `RawDialogRoute` fields, held under the field `raw_dialog_route`
    /// ([`raw_dialog_route_accessors!`](crate::raw_dialog_route_accessors)).
    fn raw_dialog_route_data(self: Handle<Self>, app: &App) -> &RawDialogRouteData;

    /// See [`raw_dialog_route_data`](Self::raw_dialog_route_data).
    fn raw_dialog_route_data_mut(self: Handle<Self>, app: &mut App) -> &mut RawDialogRouteData;

    /// Dart's `RawDialogRoute.barrierDismissible`.
    fn barrier_dismissible(self: Handle<Self>, app: &App) -> bool {
        self.raw_dialog_route_data(app).barrier_dismissible
    }

    /// Dart's `RawDialogRoute.barrierLabel`.
    fn barrier_label(self: Handle<Self>, app: &App) -> Option<String> {
        self.raw_dialog_route_data(app).barrier_label.clone()
    }

    /// Dart's `RawDialogRoute.barrierColor`.
    fn barrier_color(self: Handle<Self>, app: &App) -> Option<Color> {
        self.raw_dialog_route_data(app).barrier_color
    }

    /// Dart's `RawDialogRoute.transitionDuration`.
    fn transition_duration(self: Handle<Self>, app: &App) -> Duration {
        self.raw_dialog_route_data(app).transition_duration
    }

    /// Dart's `RawDialogRoute.fullscreenDialog`.
    fn fullscreen_dialog(self: Handle<Self>, app: &App) -> bool {
        self.raw_dialog_route_data(app).fullscreen_dialog
    }

    /// Dart's `RawDialogRoute.buildPage`.
    fn build_page(
        self: Handle<Self>,
        app: &mut App,
        context: BuildContext,
        animation: AnimationRef<f64>,
        secondary_animation: AnimationRef<f64>,
    ) -> WidgetRef {
        RawDialogRoute::build_page(self, app, context, animation, secondary_animation)
    }

    /// Dart's `RawDialogRoute.buildTransitions`.
    fn build_transitions(
        self: Handle<Self>,
        app: &mut App,
        context: BuildContext,
        animation: AnimationRef<f64>,
        secondary_animation: AnimationRef<f64>,
        child: WidgetRef,
    ) -> WidgetRef {
        RawDialogRoute::build_transitions(self, app, context, animation, secondary_animation, child)
    }

    /// Dart's `RawDialogRoute.buildModalBarrier`.
    fn build_modal_barrier(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
        RawDialogRoute::build_modal_barrier(self, app, context)
    }
}

/// The `ModalRoute` overrides a [`RawDialogRouteLeaf`] inherits, plus
/// [`modal_route_accessors!`](crate::modal_route_accessors). Write it inside
/// `impl ModalRoute for MyRoute { .. }`.
#[macro_export]
macro_rules! raw_dialog_route_modal_route_overrides {
    () => {
        $crate::modal_route_accessors!();

        fn barrier_dismissible(
            self: ::waft_foundation::Handle<Self>,
            app: &::waft_foundation::App,
        ) -> bool {
            $crate::RawDialogRouteLeaf::barrier_dismissible(self, app)
        }

        fn barrier_label(
            self: ::waft_foundation::Handle<Self>,
            app: &::waft_foundation::App,
        ) -> ::std::option::Option<::std::string::String> {
            $crate::RawDialogRouteLeaf::barrier_label(self, app)
        }

        fn barrier_color(
            self: ::waft_foundation::Handle<Self>,
            app: &::waft_foundation::App,
        ) -> ::std::option::Option<::waft_painting::Color> {
            $crate::RawDialogRouteLeaf::barrier_color(self, app)
        }

        fn maintain_state(
            self: ::waft_foundation::Handle<Self>,
            app: &::waft_foundation::App,
        ) -> bool {
            $crate::PopupRoute::maintain_state(self, app)
        }

        fn fullscreen_dialog(
            self: ::waft_foundation::Handle<Self>,
            app: &::waft_foundation::App,
        ) -> bool {
            $crate::RawDialogRouteLeaf::fullscreen_dialog(self, app)
        }

        fn build_page(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
            context: $crate::BuildContext,
            animation: ::waft_animation::AnimationRef<f64>,
            secondary_animation: ::waft_animation::AnimationRef<f64>,
        ) -> $crate::WidgetRef {
            $crate::RawDialogRouteLeaf::build_page(
                self,
                app,
                context,
                animation,
                secondary_animation,
            )
        }

        fn build_transitions(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
            context: $crate::BuildContext,
            animation: ::waft_animation::AnimationRef<f64>,
            secondary_animation: ::waft_animation::AnimationRef<f64>,
            child: $crate::WidgetRef,
        ) -> $crate::WidgetRef {
            $crate::RawDialogRouteLeaf::build_transitions(
                self,
                app,
                context,
                animation,
                secondary_animation,
                child,
            )
        }

        fn build_modal_barrier(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
            context: $crate::BuildContext,
        ) -> $crate::WidgetRef {
            $crate::RawDialogRouteLeaf::build_modal_barrier(self, app, context)
        }
    };
}

/// The `TransitionRoute` overrides a [`RawDialogRouteLeaf`] inherits, plus
/// [`modal_transition_route_overrides!`](crate::modal_transition_route_overrides). Write it
/// inside `impl TransitionRoute for MyRoute { .. }`.
#[macro_export]
macro_rules! raw_dialog_route_transition_route_overrides {
    () => {
        $crate::modal_transition_route_overrides!();

        fn transition_duration(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
        ) -> ::std::time::Duration {
            $crate::RawDialogRouteLeaf::transition_duration(self, app)
        }

        fn opaque(self: ::waft_foundation::Handle<Self>, app: &::waft_foundation::App) -> bool {
            $crate::PopupRoute::opaque(self, app)
        }

        fn allow_snapshotting(
            self: ::waft_foundation::Handle<Self>,
            app: &::waft_foundation::App,
        ) -> bool {
            $crate::PopupRoute::allow_snapshotting(self, app)
        }
    };
}

/// A general dialog route which allows for customization of the dialog popup.
///
/// It is used internally by [`ShowGeneralDialog`] or can be directly pushed onto the
/// [`Navigator`] stack to enable state restoration.
///
/// This route takes a [`page_builder`](RawDialogRouteData::page_builder), which typically
/// builds a dialog. Content below the dialog is dimmed with a [`ModalBarrier`].
///
/// It is also the base class `CupertinoDialogRoute` extends: its fields are the
/// [`RawDialogRouteData`] bag, the members it overrides are [`RawDialogRouteLeaf`]'s, and the
/// shared bodies are the associated functions below.
pub struct RawDialogRoute {
    route: crate::widgets::navigator::RouteData,
    overlay_route: OverlayRouteData,
    transition_route: TransitionRouteData,
    local_history: LocalHistoryRouteData,
    modal_route: ModalRouteData,
    raw_dialog_route: RawDialogRouteData,
}

impl RawDialogRoute {
    /// A general dialog route which allows for customization of the dialog popup; Dart's
    /// optional arguments are the setters.
    ///
    /// Dart's defaults: `barrier_dismissible` true, `barrier_color` `0x80000000`,
    /// `transition_duration` 200 ms, `fullscreen_dialog` false.
    pub fn new(app: &mut App, page_builder: RoutePageBuilder) -> Ref<RawDialogRoute> {
        let route = crate::widgets::navigator::RouteData::new(app, None, None);
        let transition_route = TransitionRouteData::new(app);
        let modal_route = ModalRouteData::new(app);
        app.create(RawDialogRoute {
            route,
            overlay_route: OverlayRouteData::new(),
            transition_route,
            local_history: LocalHistoryRouteData::new(),
            modal_route,
            raw_dialog_route: RawDialogRouteData::new(page_builder),
        })
    }

    /// Dart `RawDialogRoute(settings:)`.
    pub fn settings(self: Ref<Self>, app: &mut App, settings: RouteSettingsRef) -> Ref<Self> {
        self.route_data_mut(app).set_settings(settings);
        self
    }

    /// Dart `RawDialogRoute(requestFocus:)`.
    pub fn request_focus(self: Ref<Self>, app: &mut App, request_focus: bool) -> Ref<Self> {
        self.route_data_mut(app)
            .set_request_focus(Some(request_focus));
        self
    }

    /// Dart `RawDialogRoute(barrierDismissible:)`.
    pub fn barrier_dismissible(
        self: Ref<Self>,
        app: &mut App,
        barrier_dismissible: bool,
    ) -> Ref<Self> {
        self.raw_dialog_route_data_mut(app).barrier_dismissible = barrier_dismissible;
        self
    }

    /// Dart `RawDialogRoute(barrierColor:)`.
    pub fn barrier_color(
        self: Ref<Self>,
        app: &mut App,
        barrier_color: Option<Color>,
    ) -> Ref<Self> {
        self.raw_dialog_route_data_mut(app).barrier_color = barrier_color;
        self
    }

    /// Dart `RawDialogRoute(barrierLabel:)`.
    pub fn barrier_label(self: Ref<Self>, app: &mut App, barrier_label: String) -> Ref<Self> {
        self.raw_dialog_route_data_mut(app).barrier_label = Some(barrier_label);
        self
    }

    /// Dart `RawDialogRoute(transitionDuration:)`.
    pub fn transition_duration(
        self: Ref<Self>,
        app: &mut App,
        transition_duration: Duration,
    ) -> Ref<Self> {
        self.raw_dialog_route_data_mut(app).transition_duration = transition_duration;
        self
    }

    /// Dart `RawDialogRoute(transitionBuilder:)`.
    pub fn transition_builder(
        self: Ref<Self>,
        app: &mut App,
        transition_builder: RouteTransitionsBuilder,
    ) -> Ref<Self> {
        self.raw_dialog_route_data_mut(app).transition_builder = Some(transition_builder);
        self
    }

    /// Dart `RawDialogRoute(barrierBuilder:)`.
    pub fn barrier_builder(
        self: Ref<Self>,
        app: &mut App,
        barrier_builder: RouteBarrierBuilder,
    ) -> Ref<Self> {
        self.raw_dialog_route_data_mut(app).barrier_builder = Some(barrier_builder);
        self
    }

    /// Dart `RawDialogRoute(traversalEdgeBehavior:)`.
    pub fn traversal_edge_behavior(
        self: Ref<Self>,
        app: &mut App,
        behavior: TraversalEdgeBehavior,
    ) -> Ref<Self> {
        self.modal_route_data_mut(app).traversal_edge_behavior = Some(behavior);
        self
    }

    /// Dart `RawDialogRoute(directionalTraversalEdgeBehavior:)`.
    pub fn directional_traversal_edge_behavior(
        self: Ref<Self>,
        app: &mut App,
        behavior: TraversalEdgeBehavior,
    ) -> Ref<Self> {
        self.modal_route_data_mut(app)
            .directional_traversal_edge_behavior = Some(behavior);
        self
    }

    /// Dart `RawDialogRoute(fullscreenDialog:)`.
    pub fn fullscreen_dialog(self: Ref<Self>, app: &mut App, fullscreen_dialog: bool) -> Ref<Self> {
        self.raw_dialog_route_data_mut(app).fullscreen_dialog = fullscreen_dialog;
        self
    }

    /// Dart's `RawDialogRoute.buildPage`, which a leaf's
    /// [`RawDialogRouteLeaf::build_page`] calls.
    pub fn build_page<R: RawDialogRouteLeaf>(
        this: Handle<R>,
        app: &mut App,
        context: BuildContext,
        animation: AnimationRef<f64>,
        secondary_animation: AnimationRef<f64>,
    ) -> WidgetRef {
        let page_builder = Rc::clone(&this.raw_dialog_route_data(app).page_builder);
        Semantics::new()
            .scopes_route(true)
            .explicit_child_nodes(true)
            .child(page_builder(app, context, animation, secondary_animation))
            .into_widget()
    }

    /// Dart's `RawDialogRoute.buildTransitions`, which a leaf's
    /// [`RawDialogRouteLeaf::build_transitions`] calls.
    pub fn build_transitions<R: RawDialogRouteLeaf>(
        this: Handle<R>,
        app: &mut App,
        context: BuildContext,
        animation: AnimationRef<f64>,
        secondary_animation: AnimationRef<f64>,
        child: WidgetRef,
    ) -> WidgetRef {
        match this.raw_dialog_route_data(app).transition_builder.clone() {
            // Some default transition.
            None => crate::widgets::transitions::FadeTransition::new(animation)
                .child(child)
                .into_widget(),
            Some(transition_builder) => {
                transition_builder(app, context, animation, secondary_animation, child)
            }
        }
    }

    /// Dart's `RawDialogRoute.buildModalBarrier`, which a leaf's
    /// [`RawDialogRouteLeaf::build_modal_barrier`] calls.
    pub fn build_modal_barrier<R: RawDialogRouteLeaf>(
        this: Handle<R>,
        app: &mut App,
        context: BuildContext,
    ) -> WidgetRef {
        let barrier = ModalRouteBase::build_modal_barrier(this, app, context);
        let Some(barrier_builder) = this.raw_dialog_route_data(app).barrier_builder.clone() else {
            return barrier;
        };
        Builder::new(move |app, context| {
            let animation = TransitionRoute::animation(this, app)
                .expect("an installed route keeps its animation")
                .keep(app);
            let mut details =
                RouteBarrierDetails::new(animation, ModalRoute::barrier_dismissible(this, app));
            if let Some(color) = ModalRoute::barrier_color(this, app) {
                details = details.barrier_color(color);
            }
            if let Some(label) = ModalRoute::barrier_label(this, app) {
                details = details.barrier_label(label);
            }
            barrier_builder(app, context, &details, barrier.clone())
        })
        .into_widget()
    }
}

impl Route for RawDialogRoute {
    crate::modal_route_overrides!();
}

impl OverlayRoute for RawDialogRoute {
    crate::modal_overlay_route_overrides!();
}

impl PredictiveBackRoute for RawDialogRoute {
    crate::modal_predictive_back_route_overrides!(ModalRoute::pop_gesture_enabled);
}

impl TransitionRoute for RawDialogRoute {
    crate::raw_dialog_route_transition_route_overrides!();
}

impl LocalHistoryRoute for RawDialogRoute {
    crate::local_history_route_accessors!();
}

impl ModalRoute for RawDialogRoute {
    crate::raw_dialog_route_modal_route_overrides!();
}

impl PopupRoute for RawDialogRoute {}

impl RawDialogRouteLeaf for RawDialogRoute {
    crate::raw_dialog_route_accessors!();
}

/// Displays a dialog above the current contents of the app.
///
/// This function allows for customization of aspects of the dialog popup.
///
/// The `context` argument is used to look up the [`Navigator`] for the dialog. It is only used
/// when the method is called. Its corresponding widget can be safely removed from the tree
/// before the dialog is closed.
///
/// The `use_root_navigator` argument is used to determine whether to push the dialog to the
/// [`Navigator`] furthest from or nearest to the given `context`.
///
/// Returns a future that resolves to the value (if any) that was passed to [`Navigator::pop`]
/// when the dialog was closed.
///
/// See also:
///
///  * [`RawDialogRoute`], the route this pushes.
pub struct ShowGeneralDialog {
    page_builder: RoutePageBuilder,
    barrier_dismissible: bool,
    barrier_label: Option<String>,
    barrier_color: Color,
    transition_duration: Duration,
    transition_builder: Option<RouteTransitionsBuilder>,
    barrier_builder: Option<RouteBarrierBuilder>,
    use_root_navigator: bool,
    fullscreen_dialog: bool,
    route_settings: Option<RouteSettingsRef>,
    request_focus: Option<bool>,
}

impl ShowGeneralDialog {
    /// Creates a builder for a general dialog; Dart's `showGeneralDialog` required argument is
    /// the page builder, and every other argument is a setter.
    pub fn new(page_builder: RoutePageBuilder) -> ShowGeneralDialog {
        ShowGeneralDialog {
            page_builder,
            barrier_dismissible: false,
            barrier_label: None,
            barrier_color: Color::new(0x8000_0000),
            transition_duration: Duration::from_millis(200),
            transition_builder: None,
            barrier_builder: None,
            use_root_navigator: true,
            fullscreen_dialog: false,
            route_settings: None,
            request_focus: None,
        }
    }

    /// Whether tapping the barrier dismisses the dialog. Defaults to `false`.
    pub fn barrier_dismissible(mut self, barrier_dismissible: bool) -> ShowGeneralDialog {
        self.barrier_dismissible = barrier_dismissible;
        self
    }

    /// The semantic label of the dialog's modal barrier.
    pub fn barrier_label(mut self, barrier_label: impl Into<String>) -> ShowGeneralDialog {
        self.barrier_label = Some(barrier_label.into());
        self
    }

    /// The color of the dialog's modal barrier.
    pub fn barrier_color(mut self, barrier_color: Color) -> ShowGeneralDialog {
        self.barrier_color = barrier_color;
        self
    }

    /// The duration of the dialog's transition.
    pub fn transition_duration(mut self, transition_duration: Duration) -> ShowGeneralDialog {
        self.transition_duration = transition_duration;
        self
    }

    /// Builds the dialog's transition.
    pub fn transition_builder(
        mut self,
        transition_builder: RouteTransitionsBuilder,
    ) -> ShowGeneralDialog {
        self.transition_builder = Some(transition_builder);
        self
    }

    /// Builds the dialog's barrier.
    pub fn barrier_builder(mut self, barrier_builder: RouteBarrierBuilder) -> ShowGeneralDialog {
        self.barrier_builder = Some(barrier_builder);
        self
    }

    /// Whether to push the dialog to the root navigator. Defaults to `true`.
    pub fn use_root_navigator(mut self, use_root_navigator: bool) -> ShowGeneralDialog {
        self.use_root_navigator = use_root_navigator;
        self
    }

    /// Whether this is a fullscreen dialog. Defaults to `false`.
    pub fn fullscreen_dialog(mut self, fullscreen_dialog: bool) -> ShowGeneralDialog {
        self.fullscreen_dialog = fullscreen_dialog;
        self
    }

    /// The route settings passed to the dialog's route.
    pub fn route_settings(mut self, route_settings: RouteSettingsRef) -> ShowGeneralDialog {
        self.route_settings = Some(route_settings);
        self
    }

    /// Whether the dialog's route requests focus when it is pushed.
    pub fn request_focus(mut self, request_focus: bool) -> ShowGeneralDialog {
        self.request_focus = Some(request_focus);
        self
    }

    /// Displays the dialog and returns a future that resolves when it closes.
    pub fn show(self, app: &mut App, context: BuildContext) -> CompleterFuture<RouteResult> {
        let ShowGeneralDialog {
            page_builder,
            barrier_dismissible,
            barrier_label,
            barrier_color,
            transition_duration,
            transition_builder,
            barrier_builder,
            use_root_navigator,
            fullscreen_dialog,
            route_settings,
            request_focus,
        } = self;

        debug_assert!(!barrier_dismissible || barrier_label.is_some());
        let mut route = RawDialogRoute::new(app, page_builder)
            .barrier_dismissible(app, barrier_dismissible)
            .barrier_color(app, Some(barrier_color))
            .transition_duration(app, transition_duration)
            .fullscreen_dialog(app, fullscreen_dialog);
        if let Some(barrier_label) = barrier_label {
            route = route.barrier_label(app, barrier_label);
        }
        if let Some(transition_builder) = transition_builder {
            route = route.transition_builder(app, transition_builder);
        }
        if let Some(barrier_builder) = barrier_builder {
            route = route.barrier_builder(app, barrier_builder);
        }
        if let Some(route_settings) = route_settings {
            route = route.settings(app, route_settings);
        }
        if let Some(request_focus) = request_focus {
            route = route.request_focus(app, request_focus);
        }
        let navigator = Navigator::of(app, context, use_root_navigator);
        navigator.push(app, route.into_erased())
    }
}

#[cfg(test)]
mod tests {
    use std::cell::{Cell, RefCell};

    use waft_embedder::{Offset, TextDirection};
    use waft_painting::AlignmentGeometry;

    use super::*;
    use crate::framework::{IntoWidget, StatelessWidget};
    use crate::testing::{WidgetTester, test_widgets};
    use crate::widgets::basic::{Align, Directionality, SizedBox};
    use crate::widgets::navigator::{NavigatorState, RouteSettings};
    use crate::widgets::pages::PageRouteBuilder;
    use crate::widgets::pop_scope::PopScope;

    /// A page whose content is a 10x10 box in the top-left corner, so a tap in the middle of
    /// the view falls through to whatever is below it.
    fn corner_page(child: Option<WidgetRef>) -> RoutePageBuilder {
        Rc::new(move |_app, _context, _animation, _secondary| {
            let box_widget = match child.clone() {
                Some(child) => SizedBox::new().width(10.0).height(10.0).child(child),
                None => SizedBox::new().width(10.0).height(10.0),
            };
            Align::new()
                .alignment(AlignmentGeometry::TOP_LEFT)
                .child(box_widget)
                .into_widget()
        })
    }

    fn page_route(app: &mut App, child: Option<WidgetRef>, name: &str) -> Ref<PageRouteBuilder> {
        PageRouteBuilder::new(app, corner_page(child))
            .settings(app, RouteSettings::new().name(name.to_string()).into())
    }

    /// A navigator whose initial route is a plain page, under a `Directionality` the overlay's
    /// theater needs.
    fn navigator(
        key: &GlobalKey,
        on_generate_route: impl Fn(&mut App, &RouteSettings) -> Option<RouteRef> + 'static,
    ) -> WidgetRef {
        Directionality::new(
            TextDirection::Ltr,
            Navigator::new()
                .key(key.clone().into())
                .on_generate_route(on_generate_route),
        )
        .into_widget()
    }

    fn state(key: &GlobalKey, tester: &WidgetTester) -> Handle<NavigatorState> {
        key.current_state::<NavigatorState>(&tester.cell.borrow())
            .expect("a mounted navigator")
    }

    /// A navigator whose initial route is a plain page named "/", pumped and settled.
    fn mount_navigator(tester: &mut WidgetTester, key: &GlobalKey) -> Handle<NavigatorState> {
        tester.pump_widget(navigator(key, |app, _settings| {
            Some(page_route(app, None, "/").into_erased())
        }));
        let navigator_state = state(key, tester);
        tester.pump_and_settle();
        navigator_state
    }

    /// A stateless widget that runs `read` on every build.
    type ProbeRead = Rc<dyn Fn(&mut App, BuildContext)>;

    struct Probe {
        read: ProbeRead,
    }

    impl Debug for Probe {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("Probe")
        }
    }

    impl StatelessWidget for Probe {
        fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
            (self.read)(app, context);
            SizedBox::new().into_widget()
        }
    }

    fn probe(read: impl Fn(&mut App, BuildContext) + 'static) -> WidgetRef {
        Probe {
            read: Rc::new(read),
        }
        .into_widget()
    }

    // ---- the tests ----

    #[test]
    fn pushing_a_page_route_runs_its_transition_to_completion_and_popping_runs_it_back() {
        test_widgets(|tester| {
            let key = GlobalKey::new();
            let navigator_state = mount_navigator(tester, &key);

            let pushed: RouteRef =
                tester.update(|app| page_route(app, None, "second").into_erased());
            tester.update(|app| navigator_state.push(app, pushed.clone()));
            tester.pump();
            let animation = {
                let app = tester.cell.borrow();
                let animation = pushed
                    .as_transition_route(&app)
                    .expect("a page route is a transition route")
                    .animation(&app)
                    .expect("an installed route");
                assert!(animation.value(&app) < 1.0, "the transition starts at 0");
                animation
            };

            tester.pump_and_settle();
            {
                let app = tester.cell.borrow();
                assert_eq!(animation.value(&app), 1.0);
                assert!(pushed.is_current(&app));
                assert!(!pushed.is_first(&app));
            }

            let popped = Rc::new(Cell::new(false));
            tester.update(|app| {
                pushed.popped(app).then(app, {
                    let popped = Rc::clone(&popped);
                    move |_app, _result| popped.set(true)
                });
                navigator_state.pop(app, None);
                app.drain_microtasks();
            });
            assert!(popped.get(), "the popped future resolves at once");

            tester.pump_and_settle();
            assert_eq!(animation.value(&tester.cell.borrow()), 0.0);
        });
    }

    #[test]
    fn modal_route_of_reports_is_current_and_is_first() {
        test_widgets(|tester| {
            let key = GlobalKey::new();
            let seen: Rc<RefCell<Vec<(bool, bool)>>> = Rc::new(RefCell::new(Vec::new()));
            let watcher = probe({
                let seen = Rc::clone(&seen);
                move |app, context| {
                    let route = AnyModalRoute::of(app, context).expect("a modal route");
                    let is_current = route.as_route().is_current(app);
                    let is_first = route.as_route().is_first(app);
                    seen.borrow_mut().push((is_current, is_first));
                }
            });
            tester.pump_widget(navigator(&key, move |app, _settings| {
                Some(page_route(app, Some(watcher.clone()), "/").into_erased())
            }));
            let navigator_state = state(&key, tester);
            tester.pump_and_settle();
            assert_eq!(seen.borrow().last().copied(), Some((true, true)));

            tester.update(|app| {
                let second: RouteRef = page_route(app, None, "second").into_erased();
                navigator_state.push(app, second);
            });
            tester.pump_and_settle();
            assert_eq!(
                seen.borrow().last().copied(),
                Some((false, true)),
                "the first route is no longer current once another is pushed"
            );
        });
    }

    #[test]
    fn a_pop_scope_with_can_pop_false_blocks_maybe_pop() {
        test_widgets(|tester| {
            let key = GlobalKey::new();
            let blocked = Rc::new(Cell::new(false));
            let scope = PopScope::new(SizedBox::new())
                .can_pop(false)
                .on_pop_invoked_with_result({
                    let blocked = Rc::clone(&blocked);
                    Rc::new(move |_app, did_pop, _result| blocked.set(!did_pop))
                })
                .into_widget();
            let navigator_state = mount_navigator(tester, &key);

            let second: RouteRef =
                tester.update(|app| page_route(app, Some(scope), "second").into_erased());
            tester.update(|app| navigator_state.push(app, second.clone()));
            tester.pump_and_settle();
            assert!(second.is_current(&tester.cell.borrow()));

            assert!(
                tester.update(|app| navigator_state.maybe_pop(app, None)),
                "the pop is handled — by being refused — rather than bubbling"
            );
            tester.pump_and_settle();
            assert!(
                second.is_current(&tester.cell.borrow()),
                "the route is still on top"
            );
            assert!(blocked.get(), "the pop was reported as not having happened");
        });
    }

    #[test]
    fn tapping_the_barrier_dismisses_a_dismissible_popup_route() {
        test_widgets(|tester| {
            let key = GlobalKey::new();
            let navigator_state = mount_navigator(tester, &key);

            let dialog: RouteRef = tester.update(|app| {
                RawDialogRoute::new(app, corner_page(None))
                    .barrier_dismissible(app, true)
                    .barrier_label(app, "dismiss".to_string())
                    .into_erased()
            });
            tester.update(|app| navigator_state.push(app, dialog.clone()));
            tester.pump_and_settle();
            assert!(dialog.is_current(&tester.cell.borrow()));

            // The dialog's own content is the 10x10 box in the corner, so a tap away from it
            // is on the barrier.
            tester.tap_at(Offset::new(150.0, 100.0), 1);
            tester.pump();
            tester.pump_and_settle();
            assert!(
                !dialog.is_active(&tester.cell.borrow()),
                "the barrier popped the dialog"
            );
        });
    }

    /// Not a Dart case: Dart's collector frees the tweens and the colour animation each build
    /// of a modal barrier replaces; here the route keeps the last ones and frees what they
    /// replace.
    #[test]
    fn rebuilding_a_coloured_barrier_leaves_no_new_arena_objects() {
        test_widgets(|tester| {
            let key = GlobalKey::new();
            let navigator_state = mount_navigator(tester, &key);
            let dialog = tester.update(|app| {
                RawDialogRoute::new(app, corner_page(None))
                    .barrier_color(app, Some(Color::new(0x80000000)))
            });
            tester.update(|app| navigator_state.push(app, dialog.clone().into_erased()));
            tester.pump_and_settle();
            tester.assert_leaves_nothing_behind(|tester| {
                tester.update(|app| ModalRoute::changed_internal_state(dialog.handle(), app));
                tester.pump_by(Duration::from_millis(20));
            });
        });
    }

    /// Not a Dart case: Dart's collector frees a popped route, and what its barrier drove, once
    /// nothing reaches it; here the checkpoint after its entry goes frees it.
    #[test]
    fn a_popped_route_is_freed_once_its_entry_goes() {
        test_widgets(|tester| {
            let key = GlobalKey::new();
            let navigator_state = mount_navigator(tester, &key);
            let dialog = {
                let dialog = tester.update(|app| {
                    RawDialogRoute::new(app, corner_page(None))
                        .barrier_color(app, Some(Color::new(0x80000000)))
                });
                let named = dialog.handle();
                tester.update(|app| navigator_state.push(app, dialog.clone().into_erased()));
                tester.pump_and_settle();
                tester.update(|app| navigator_state.pop(app, None));
                tester.pump_and_settle();
                assert!(
                    named
                        .transition_route_data(&tester.cell.borrow())
                        .transition_completer
                        .is_completed(),
                    "the route is disposed"
                );
                named
            };
            tester.cell.checkpoint();
            assert!(
                !tester.cell.borrow().contains(dialog),
                "the popped route is freed"
            );
        });
    }

    /// Dart's 'secondary animation is kDismissed after train hopping finishes and pop', with
    /// linear routes: Dart's third route curves its animation (`easeOutExpo`), which a
    /// `PageRouteBuilder` here cannot be given, so the trains never meet and the hop ends when
    /// the replacing route's push does, through the remover. The hopping animation is freed
    /// once it is done with, as Dart's collector would.
    #[test]
    fn a_finished_train_hop_leaves_the_secondary_animation_on_the_new_route_and_frees_it() {
        test_widgets(|tester| {
            let key = GlobalKey::new();
            let navigator_state = mount_navigator(tester, &key);

            let one = tester.update(|app| page_route(app, None, "one"));
            let one_route = one.handle();
            tester.update(|app| navigator_state.push(app, one.into_erased()));
            tester.pump_and_settle();
            let secondary_parent = |tester: &WidgetTester| {
                let app = tester.cell.borrow();
                one_route
                    .transition_route_data(&app)
                    .secondary_animation
                    .parent(&app)
            };
            let dismissed = tester.update(|app| k_always_dismissed_animation(app).handle());
            assert_eq!(secondary_parent(tester), Some(dismissed));

            let two: RouteRef = tester.update(|app| page_route(app, None, "two").into_erased());
            tester.update(|app| navigator_state.push(app, two.clone()));
            tester.pump();
            tester.pump_by(Duration::from_millis(100));
            let two_animation = {
                let app = tester.cell.borrow();
                two.as_transition_route(&app)
                    .and_then(|route| route.underlying_animation(&app))
            };
            assert_eq!(secondary_parent(tester), two_animation);

            let three: RouteRef = tester.update(|app| page_route(app, None, "three").into_erased());
            tester.update(|app| navigator_state.push_replacement(app, three.clone(), None));
            tester.pump();
            tester.pump_by(Duration::from_millis(1));
            let hopper = {
                let app = tester.cell.borrow();
                let hopper = one_route
                    .transition_route_data(&app)
                    .secondary_animation
                    .parent(&app)
                    .and_then(|parent| parent.downcast::<TrainHoppingAnimation>(&app))
                    .expect("the secondary animation hops trains");
                assert_eq!(app.get(hopper).current_train(), two_animation);
                hopper
            };

            tester.pump_and_settle();
            let three_animation = {
                let app = tester.cell.borrow();
                three
                    .as_transition_route(&app)
                    .and_then(|route| route.underlying_animation(&app))
            };
            assert_eq!(secondary_parent(tester), three_animation);
            tester.cell.checkpoint();
            assert!(
                !tester.cell.borrow().contains(hopper),
                "the finished hop's animation is freed"
            );

            tester.update(|app| navigator_state.pop(app, None));
            tester.pump_and_settle();
            assert_eq!(secondary_parent(tester), Some(dismissed));
        });
    }

    #[test]
    fn a_non_dismissible_barrier_keeps_the_route() {
        test_widgets(|tester| {
            let key = GlobalKey::new();
            let navigator_state = mount_navigator(tester, &key);

            let dialog: RouteRef = tester.update(|app| {
                RawDialogRoute::new(app, corner_page(None))
                    .barrier_dismissible(app, false)
                    .into_erased()
            });
            tester.update(|app| navigator_state.push(app, dialog.clone()));
            tester.pump_and_settle();

            tester.tap_at(Offset::new(150.0, 100.0), 1);
            tester.pump();
            tester.pump_and_settle();
            assert!(
                dialog.is_current(&tester.cell.borrow()),
                "the tap did nothing"
            );
        });
    }

    #[test]
    fn local_history_entries_are_popped_before_the_route() {
        test_widgets(|tester| {
            let key = GlobalKey::new();
            let navigator_state = mount_navigator(tester, &key);

            let second = tester.update(|app| page_route(app, None, "second"));
            tester.update(|app| navigator_state.push(app, second.clone().into_erased()));
            tester.pump_and_settle();

            let removed = Rc::new(Cell::new(false));
            tester.update(|app| {
                let entry = LocalHistoryEntry::new(app).on_remove(app, {
                    let removed = Rc::clone(&removed);
                    Listener::new(move |_app| removed.set(true))
                });
                LocalHistoryRoute::add_local_history_entry(second.handle(), app, entry);
                assert!(Route::will_handle_pop_internally(second.handle(), app));
                navigator_state.pop(app, None);
            });
            tester.pump();
            assert!(removed.get(), "the local history entry was removed");
            assert!(
                second.as_route().is_current(&tester.cell.borrow()),
                "the route itself is still on top"
            );

            tester.update(|app| navigator_state.pop(app, None));
            tester.pump_and_settle();
            assert!(
                !second.as_route().is_active(&tester.cell.borrow()),
                "the route popped next"
            );
        });
    }

    struct Watcher {
        pushed: Cell<usize>,
        pushed_next: Cell<usize>,
        popped: Cell<usize>,
        popped_next: Cell<usize>,
    }

    impl RouteAwareObject for Watcher {
        fn did_push(self: Handle<Self>, app: &mut App) {
            let count = app.get(self).pushed.get();
            app.get(self).pushed.set(count + 1);
        }

        fn did_push_next(self: Handle<Self>, app: &mut App) {
            let count = app.get(self).pushed_next.get();
            app.get(self).pushed_next.set(count + 1);
        }

        fn did_pop(self: Handle<Self>, app: &mut App) {
            let count = app.get(self).popped.get();
            app.get(self).popped.set(count + 1);
        }

        fn did_pop_next(self: Handle<Self>, app: &mut App) {
            let count = app.get(self).popped_next.get();
            app.get(self).popped_next.set(count + 1);
        }
    }

    #[test]
    fn a_route_observer_notifies_its_route_aware() {
        test_widgets(|tester| {
            let key = GlobalKey::new();
            let observer = tester.update(|app| {
                RouteObserver::new(
                    app,
                    Rc::new(|app, route: AnyRoute| route.as_page_route(app).is_some()),
                )
            });
            let initial: Rc<Cell<Option<AnyRoute>>> = Rc::new(Cell::new(None));
            tester.pump_widget(Directionality::new(
                TextDirection::Ltr,
                Navigator::new()
                    .key(key.clone().into())
                    .on_generate_route({
                        let initial = Rc::clone(&initial);
                        move |app, _settings| {
                            let route: RouteRef = page_route(app, None, "/").into_erased();
                            initial.set(Some(route.handle()));
                            Some(route)
                        }
                    })
                    .observers(vec![observer.erase()]),
            ));
            let navigator_state = state(&key, tester);
            tester.pump_and_settle();

            let first = initial.get().expect("the initial route");
            let watcher = tester.update(|app| {
                app.create(Watcher {
                    pushed: Cell::new(0),
                    pushed_next: Cell::new(0),
                    popped: Cell::new(0),
                    popped_next: Cell::new(0),
                })
            });
            tester.update(|app| observer.subscribe(app, Rc::new(watcher.handle()), first));
            assert_eq!(tester.cell.borrow().get(&watcher).pushed.get(), 1);

            tester.update(|app| {
                let second: RouteRef = page_route(app, None, "second").into_erased();
                navigator_state.push(app, second);
            });
            tester.pump_and_settle();
            assert_eq!(tester.cell.borrow().get(&watcher).pushed_next.get(), 1);

            tester.update(|app| navigator_state.pop(app, None));
            tester.pump_and_settle();
            let app = tester.cell.borrow();
            assert_eq!(app.get(&watcher).popped_next.get(), 1);
            assert_eq!(app.get(&watcher).popped.get(), 0);
        });
    }
}