frust-material 0.6.0

Material 3 (Expressive) design-system catalog for Frust: HCT seed-color tokens, shape morphing, icons, widgets and bundled Roboto fonts.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
// Ported from `frust-shadcn`'s `plugins/shadcn/src/overlay/modal.rs` (in-repo
// sibling catalog; itself a port of shadcn/ui v4 rev
// `d4fc45b1fbabfccb7a6a4333d8004cf19481caa9`, MIT © shadcn, over Radix's dialog
// and vaul's drawer). A sibling port, never a dependency — see `super`'s header.
// Porting decisions: the panel geometry, the staged-exit machine and the
// drag/snap-point gesture are carried over verbatim; the chrome resolves
// Material roles (32% scrim, `surfaceContainer*` fill, `shape.extra_large`
// corners, the M3 32×4dp drag handle, the M3 `close` icon) and the motion
// resolves `crate::tokens` presets. The one structural change is the back-press
// tier: this host sits on `crate::sheet`'s `BackPolicy::DismissAnimated` +
// `PushOptions::dismiss_signal` seam, and — unlike that sheet, which pops
// immediately — routes a back press into the *same* staged exit as every other
// dismiss gesture (`crate::dialog`'s simpler `push_transparent_for_result` path
// has no back seam at all, which is why it is not the one reused here).

//! The modal overlay host: the M3 32% scrim plus one panel, as a single widget
//! the modal families (dialog, alert dialog, bottom sheet, side sheet,
//! full-screen search, picker) configure rather than re-derive.
//!
//! Upstream these are wrappers over the *same* two elements — a full-area
//! overlay and a positioned content panel — differing only in where the content
//! is pinned, which corners it rounds, which edge it borders, and how it
//! animates in. [`OverlayModalConfig`] is exactly that difference list, so a
//! component module contributes its chrome config plus the composed content view
//! and nothing else.
//!
//! # Architecture
//!
//! Mirrors [`mod@crate::dialog`]/[`crate::sheet`] end to end (see [`super`]'s
//! mounting note): the scrim belongs to *this* widget rather than to the
//! navigator, the panel is a modal barrier that swallows every input its content
//! did not take, dismissal is the app's `on_dismiss` (wired to
//! `controller.pop()` by [`show_overlay_modal`]), and an action inside the
//! content pops with a value through the navigator's own pop-result machinery.
//!
//! Three pointer dismiss gestures, each independently disableable:
//!
//! * a **scrim tap** — a press *and* release outside the panel, when
//!   [`OverlayModalConfig::scrim_dismiss`] is on (an alert dialog turns it off:
//!   it demands an explicit choice);
//! * the **close button** — the top-trailing M3 `close` icon, when
//!   [`OverlayModalConfig::close_button`] is on;
//! * the **drag handle** — the M3 32×4dp bar, when
//!   [`OverlayModalConfig::handle`] is on. A press and release on it dismisses;
//!   with [`OverlayModalConfig::drag`] on it is also the drag affordance
//!   (below).
//!
//! plus **Escape**, once the modal holds focus — claimed on every `Down`, the
//! [`mod@crate::dialog`]/[`crate::sheet`] opt-in, with the same documented gap:
//! there is no auto-focus-on-appear hook in the framework, so a caller must
//! complete one pointer interaction with the modal before Escape does anything.
//!
//! [`OverlayModalView::dismissable`] (default `true`) is the one flag over all
//! of them: `false` disables the scrim tap, the close button, the handle, the
//! drag commit, Escape *and* the back press together, leaving only an explicit
//! control the app wires inside its own content.
//!
//! # The barrier swallows keys too
//!
//! The panel is a modal barrier for *every* input class, not just pointers: a
//! key the content did not take is reported [`EventResult::Handled`] rather than
//! falling through to whatever sits behind the modal. Content-first routing is
//! unchanged — a focused field inside the panel sees every keystroke, and only
//! what it declines reaches the barrier, where Escape dismisses and everything
//! else is absorbed.
//!
//! # Motion
//!
//! [`OverlayEntrance::FadeScale`] composites the panel through a
//! [`PaintScene::push_layer`] at the ramp's alpha, under a scale about its own
//! centre. [`OverlayEntrance::Slide`] moves the panel's origin in **layout** so
//! hit-testing follows the panel rather than lagging behind a paint-only
//! transform — which is also why a running slide asks for `request_layout`, not
//! a bare `request_frame`. The scrim fades with either.
//!
//! The source's Tailwind timings map onto `crate::tokens`' M3 presets:
//!
//! | Source class | Material preset |
//! |---|---|
//! | `duration-200` (dialog content) | [`MaterialMotion::SHORT_4`] (200ms) |
//! | `duration-500` (sheet content) | [`MaterialMotion::LONG_2`] (500ms) |
//! | `ease-out` (fade/zoom in) | [`MaterialMotion::EMPHASIZED_DECELERATE`] |
//! | `ease-in-out` (slide in) | [`MaterialMotion::EMPHASIZED`] |
//! | (either, on the way out) | [`MaterialMotion::EMPHASIZED_ACCELERATE`] — M3's curve for elements leaving |
//! | `zoom-in-95` | [`SCALE_FROM`], carried over verbatim (a visual constant, not a token) |
//!
//! An exit runs the same ramp backwards over the same duration scaled by how
//! much travel is left, so a half-open drawer closes in half the time.
//!
//! `Theme.motion.reduce_motion` collapses both to a jump: the ramp is stopped
//! and progress snaps to its rest value on the first paint, one frame after the
//! modal mounts (the pass that sets it is a paint, and the geometry it feeds is
//! a layout) — so a reduced-motion modal appears whole on its second frame
//! rather than animating on its first.
//!
//! # Exit motion, and why the close hook is state-free
//!
//! Every dismiss trigger — scrim tap, Escape, the close button, the handle, a
//! drag past its threshold, **an Android back press** — stages an **exit**
//! instead of firing the app's dismissal on the spot: the same `progress` ramp
//! runs back down to `0.0`, the barrier keeps swallowing input the whole way, a
//! second trigger mid-exit is a no-op, and only when the ramp settles is the
//! dismissal fired — from `paint`, which is sound because
//! [`NavigatorController::pop`] merely *enqueues* an op applied on the next
//! rebuild (the [`crate::sheet`]/`frust_glyph::dialog` precedent; the same paint
//! asks for one more frame so that rebuild is guaranteed to come).
//!
//! Firing from paint is why the staged path's callback is
//! [`OverlayModalView::on_close`] — a plain `Fn()` — and not the
//! `Fn(&mut State)` [`OverlayModalView::on_dismiss`] takes: `PaintCtx` carries
//! no app state. [`show_overlay_modal`] wires `on_close` to `controller.pop()`
//! for every component, so the navigator path animates out with no app
//! involvement, and app state rides the navigator's own `on_result` (delivered
//! with `&mut State` after the pop) exactly as before. **A modal with no
//! `on_close` wired** — a `Stack` mount that only set `on_dismiss` — keeps the
//! immediate, unstaged dismissal: there is no state-bearing pass to defer into,
//! so staging one would leave an invisible barrier standing. `reduce_motion`
//! collapses the exit the same way it collapses the entrance.
//!
//! Deferring the pop by a whole ramp is also why the hook is a [`StagedPop`]
//! rather than a bare `Fn()`: a pop takes the *top* page, so a page pushed while
//! the ramp runs would be popped instead of this one. The hook is armed with the
//! stack's identity when the exit is staged and refuses to fire if it moved —
//! and the refusal is reported, so a refused exit ramps back open instead of
//! latching `closed` over a page it never removed.
//!
//! # App-initiated dismiss: the [`ModalDismiss`] handle
//!
//! The staged exit above is the *host's* to trigger — its own chrome (scrim,
//! close button, handle, Escape, back) reaches it, the caller-built content
//! inside the panel does not. A panel's own action button ("Apply", "Save",
//! "Cancel") therefore used to have exactly one route open to it, a direct
//! [`NavigatorController::pop`], which dismisses **unstaged**: the same panel
//! closed two different ways played two different exit motions.
//!
//! [`ModalDismiss`] is that missing seam. An app mints one, installs it with
//! [`OverlayModalView::dismiss_handle`] (or a family wrapper's own forward of
//! it), clones it into whatever control it likes, and
//! [`dismiss`](ModalDismiss::dismiss) then runs the **same** staged exit the
//! chrome gestures run — [`stage_dismiss`](OverlayModalWidget::stage_dismiss)
//! is the one staging core all of them share, so there is no second exit path
//! to keep in step.
//!
//! Three decisions worth stating outright:
//!
//! * **An app dismiss is not a *user* dismissal, so it ignores
//!   [`dismissable`](OverlayModalView::dismissable).** That flag exists to take
//!   the *user's* exits away (a sheet that demands an explicit choice) —
//!   leaving only "an explicit control the app wires inside its own content",
//!   which is precisely this handle. Gating the handle on it would make the
//!   one documented escape hatch the one thing that cannot close a
//!   non-dismissable panel.
//! * **It can carry the pop result.**
//!   [`dismiss_with`](ModalDismiss::dismiss_with) hands a [`PopResult`] to the
//!   deferred pop, so a staged "Apply" still reaches the pusher's `on_result`
//!   — the payload rides the [`StagedPop`], which is the only thing that knows
//!   whether a navigator is behind the hook at all (an app-wired
//!   [`OverlayModalView::on_close`] takes no payload, and drops it).
//! * **Mint it outside the page builder.** `show_*`'s `build` closure re-runs
//!   on every navigator rebuild; a handle minted *inside* it would be a fresh
//!   cell each pass. The widget defends against that anyway (it re-seeds on a
//!   handle whose identity changed, see
//!   [`OverlayModalView::rebuild`]) — but a handle the app cannot also hold
//!   from outside is of no use to the control it was minted for.
//!
//! A request is observed in **both** passes, latched by generation so it acts
//! exactly once: in `event`, right after the content routing that likely raised
//! it (so the dismissal stages in the very pass that asked for it), and in
//! `paint` as the backstop for a request raised anywhere else (an async
//! completion, a timer).
//!
//! ## What a request consumes
//!
//! An observation *peeks* the generation, puts the request through
//! [`stage_dismiss`](OverlayModalWidget::stage_dismiss), and only then decides
//! what it consumed — four rules, all edge paths of the same seam:
//!
//! * **The generation is latched by whichever pass saw the request**, accepted
//!   or refused, so it acts exactly once. A refusal ("already exiting, already
//!   closed") is spent, not deferred: the ramp in flight *is* the dismissal,
//!   and holding the request open to re-stage after that ramp ends would arm a
//!   fresh pop against a stack the refusal already told us had moved.
//! * **The payload is taken only by the observation that accepted the
//!   dismissal.** A refused request leaves its [`PopResult`] with the handle,
//!   so a shared handle's "OK" pressed during a "Cancel" ramp cannot retarget
//!   that ramp's own pop (`show_date_picker` shares exactly one handle between
//!   the two), and a payload-free `dismiss()` after an unobserved
//!   `dismiss_with(..)` pops empty rather than delivering the stale value (the
//!   handle stamps each payload with the generation that raised it — see
//!   [`ModalDismiss`]). What the accepted request's payload *is* scoped to is
//!   [`OverlayModalWidget::pending_result`]'s own contract: the exit it staged,
//!   and no later one.
//! * **The one pass that latches nothing is the `paint` backstop with no
//!   `on_close` wired.** `PaintCtx` carries no app state, so that pass cannot
//!   reach [`OverlayModalView::on_dismiss`] and has nothing else to fire;
//!   swallowing the request there would make a handle on a `Stack`-mounted
//!   panel silently inert. It leaves the request pending instead, for the
//!   `event` pass's own `on_dismiss` fallback — which is what makes
//!   `.dismiss_handle(..)` work identically on both mounts, and identically to
//!   [`crate::sheet`]'s host, whose unstaged route already fell back this way.
//! * **A request left pending that way still dismisses only once**, because the
//!   unstaged `on_dismiss` route is itself one-shot: the first delivery latches
//!   it ([`OverlayModalWidget::dismissed`], `closed`'s twin for a mount with no
//!   staged pop) and every dismissal route — scrim tap, close affordance,
//!   handle, `Escape`, back, the handle's own request — is refused afterwards.
//!   Without it a pending request and a user dismissal landing before the app's
//!   teardown are *two* dismissals: `Escape` over a standing request fires
//!   `on_dismiss` in the observation and again in the key arm of the same event
//!   pass, with no rebuild in between. [`crate::sheet`]'s host latches the
//!   identical rule (`BottomSheetWidget::dismissed`, read by its
//!   `refuses_dismiss` guard), so the two seams stay interchangeable here too.
//!
//! # Back-dismiss: the `DismissAnimated` tier
//!
//! [`show_overlay_modal`] pushes its transparent page with
//! [`frust::BackPolicy::DismissAnimated`] when the modal is
//! [`dismissable`](OverlayModalView::dismissable) and
//! [`frust::BackPolicy::Veto`] when it is not — the same tier
//! [`crate::sheet`] uses, and the reason this host does *not* reuse
//! [`mod@crate::dialog`]'s plain `push_transparent_for_result` path (which has no
//! back seam). A back press therefore never pops the page itself: the navigator
//! bumps the shared [`PushOptions::dismiss_signal`] generation cell, this
//! widget observes the bump on its next paint
//! ([`observe_dismiss_signal`](OverlayModalWidget::observe_dismiss_signal)) and
//! stages the ordinary exit ramp, which pops on settle. A `Veto` page is pushed
//! with no cell at all, so a back press is consumed and does nothing.
//!
//! **The drain gotcha** (documented on [`crate::sheet`]'s own observer, and the
//! reason both fire paths request a frame): `pop()` only *enqueues* a nav op and
//! writes no tracked signal, so nothing else schedules the frame whose rebuild
//! drains it. Without a [`PaintCtx::request_frame`] from the very paint that
//! fires, a dirty-driven desktop shell (`ControlFlow::Wait`) idles and the
//! mobile frame gate skips, leaving the dismissal dead until an unrelated later
//! frame.
//!
//! # Drag-to-close and snap points
//!
//! [`OverlayModalConfig::drag`] turns an edge-pinned panel into a draggable
//! sheet: a press on the handle — or anywhere on the panel the content did not
//! take — captures, each move scrubs `progress` along the panel's own axis so
//! the panel tracks the pointer (the scrim dims with it), and the release picks
//! the nearest resting point, with a fast flick ([`OVERLAY_FLING_VELOCITY`])
//! nudging to the next one in the direction of travel. Landing on `0.0`
//! continues into the exit ramp above rather than snapping shut. A press that
//! never passes [`TOUCH_SLOP`] is a *tap*: on the handle it dismisses, anywhere
//! else it is swallowed like any other barrier press.
//!
//! [`OverlayModalView::snap_points`]: a value in `0..=1` is a fraction of the
//! panel's own extent, a value above `1` is logical px. The panel opens to the
//! **first** point (fully open with none given), and the resting set the release
//! snaps to is those points plus `0.0` (closed) — so with no snap points at all
//! the two candidates are `0.0` and `1.0` and "nearest" is exactly the
//! conventional drag-past-the-midpoint commit ([`crate::sheet`]'s own
//! `DRAG_DISMISS_FRACTION` of `0.5`, arrived at from the other direction). A
//! first point that itself normalizes to `0.0` is the one exception:
//! [`OverlayModalWidget::open_progress`] floors it to fully open rather than
//! authoring a panel with nothing to open to. The panel is laid out at its full
//! extent and translated to expose the active fraction, so a partially-open
//! sheet carries a proportionally lighter scrim rather than a full-strength one.
//!
//! # Dragging a non-dismissable panel
//!
//! [`OverlayModalConfig::drag`] stays on whether or not the panel is
//! dismissable — the *gesture* is never gated on whether a close callback
//! exists, only the *outcome* is. A drag past the closing threshold on a panel
//! that cannot dismiss springs back to
//! [`open_progress`](OverlayModalWidget::open_progress) instead of continuing
//! into the exit ramp ([`settle_drag`](OverlayModalWidget::settle_drag)) — the
//! same reachability rule the Escape handler applies.
//!
//! # Clamp discipline
//!
//! `f64::clamp` panics if `min > max` or either bound is NaN — a hard abort
//! under `panic = "abort"`, not a catchable error (see [`crate::slider`]'s own
//! core for the same rule stated at length, which this one mirrors).
//! [`OverlayModalView::snap_points`] is the one place caller input enters
//! this module, and it drops any non-finite point right there — the rest of
//! the module (`normalize_snap`, `snap_targets`, `open_progress`) trusts
//! [`OverlayModalWidget::snap_points`] to already be all-finite rather than
//! re-checking. That leaves two clamp shapes in the module tree:
//!
//! - **Bounds are literal `0.0`/`1.0`** (`normalize_snap`'s two clamps,
//!   [`begin_ramp`](OverlayModalWidget::begin_ramp)'s fraction clamp) —
//!   trivially ordered, never a hazard.
//! - **A computed bound clamped with the ordering-visible `.max()`/`.min()`
//!   shape instead of `.clamp()`** —
//!   [`drag_move`](OverlayModalWidget::drag_move)'s scrub target against the
//!   live `open` snap-target bound: `f64::max`/`f64::min` can't panic even if
//!   a NaN somehow reached one side (IEEE `minNum`/`maxNum` semantics return
//!   the other, non-NaN operand), which `clamp`'s internal
//!   `assert!(min <= max)` would.
//!
//! A new clamp against a computed bound must fit one of these two shapes, not
//! introduce a third.

use std::cell::Cell;
use std::rc::Rc;
use std::time::Duration;

use frust::authoring::{
    Affine, AnyView, BezPath, BoxConstraints, Brush, BuildCtx, ChangeFlags, ChildPod, Color,
    CornerRadii, CursorIcon, ErasedCallback, EventCtx, EventResult, InputEvent, Key, LayoutCtx,
    NamedKey, PaintCtx, PaintScene, Point, PointerPhase, Rect, Role, SemanticsCtx, Size, View,
    Widget, any, build_child, erase_callback, rebuild_child, route_event_single, teardown_child,
    visit_children,
};
use frust::input::{TOUCH_SLOP, VelocityTracker};
use frust::{
    AnimationController, BackPolicy, Curve, FrameTime, IconData, NavigatorController, PopResult,
    PushOptions, Theme, TransitionSpec,
};

use super::{OverlayContainer, OverlayElevation, OverlaySide, finite_or_zero, reduce_motion};
use crate::press::presses;
use crate::tokens::{MaterialMotion, MaterialSpacing};

/// Minimum dialog panel width, in logical px (M3 dialog spec; the same bound
/// [`mod@crate::dialog`] clamps to).
pub const OVERLAY_DIALOG_MIN_WIDTH: f64 = 280.0;
/// Maximum dialog panel width, in logical px (M3 dialog spec).
pub const OVERLAY_DIALOG_MAX_WIDTH: f64 = 560.0;
/// The margin a centred panel keeps on *each* side of the viewport —
/// [`MaterialSpacing::LG`] (16dp), where the source's own
/// `max-w-[calc(100%-2rem)]` lands.
const CENTERED_MARGIN: f64 = MaterialSpacing::LG;
/// A side sheet's share of the viewport width (the source's `w-3/4`).
pub const OVERLAY_EDGE_FRACTION: f64 = 0.75;
/// Maximum side-sheet width, in logical px (M3 side sheets span 256–400dp).
pub const OVERLAY_SIDE_SHEET_MAX_WIDTH: f64 = 400.0;
/// A bottom sheet's share of the viewport height, for a config that caps it.
pub const OVERLAY_SHEET_MAX_HEIGHT_FRACTION: f64 = 0.8;

/// The scale a [`OverlayEntrance::FadeScale`] entrance starts from (the
/// source's `zoom-in-95`, carried over verbatim — a visual constant with no
/// Material token to resolve against; the same value
/// [`super::ANCHORED_ENTER_SCALE`] carries for the anchored host).
pub const SCALE_FROM: f64 = 0.95;
/// Progress difference below which a ramp counts as settled.
const PROGRESS_EPSILON: f64 = 1e-4;

/// Release speed, in logical px/s along the drag axis, at or above which a drag
/// commits in the direction it was flung rather than to whichever resting point
/// is nearest.
///
/// **Community-approximate**: Material publishes no fling threshold for a sheet
/// dismiss. 400 px/s (0.4 px/ms) is a deliberate flick — an order of magnitude
/// above `frust::input::FLING_STOP`'s 30 px/s "this fling is over" floor, and
/// well under the speed of a full-screen swipe.
pub const OVERLAY_FLING_VELOCITY: f64 = 400.0;

/// The close affordance's inset from the panel's top/trailing edges —
/// [`MaterialSpacing::LG`] (16dp).
const CLOSE_INSET: f64 = MaterialSpacing::LG;
/// The close icon's painted size, in logical px (the M3 24dp icon box).
const CLOSE_ICON: f64 = 24.0;
/// The close affordance's **hit** box, in logical px: the M3 48dp minimum touch
/// target centred on the 24dp icon. Chrome-only — it changes no layout and no
/// painted pixel.
const CLOSE_HIT: f64 = 48.0;

/// Drag-handle visual indicator width, in logical px (M3 token
/// `m3_comp_sheet_bottom_docked_drag_handle_width`; [`crate::sheet`]'s own).
const HANDLE_WIDTH: f64 = 32.0;
/// Drag-handle visual indicator height, in logical px (M3 token
/// `m3_comp_sheet_bottom_docked_drag_handle_height`).
const HANDLE_HEIGHT: f64 = 4.0;
/// The M3 48dp minimum touch target the handle is hit-tested and laid out
/// against ([`crate::sheet`]'s handle strip).
const HANDLE_TOUCH_TARGET: f64 = 48.0;

/// The vertical space a drag handle occupies at the top of a panel — the inset
/// a sheet's own content reserves for it, since the handle is painted as panel
/// chrome rather than laid out as a child.
pub const OVERLAY_HANDLE_RESERVE: f64 = HANDLE_TOUCH_TARGET;

/// How far outside the panel its elevation shadow may reach, in logical px —
/// the bound the fade layer is inflated by so the shadow is not clipped out of
/// it.
const SHADOW_SPILL: f64 = 48.0;

/// How much of an axis a panel takes.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum OverlayExtent {
    /// A fraction of the area's own extent on that axis.
    Fraction(f64),
    /// Whatever the content asks for.
    Content,
}

/// An upper bound on a resolved [`OverlayExtent`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum OverlayLimit {
    /// No cap beyond the area itself.
    None,
    /// A fixed cap in logical px.
    Px(f64),
    /// A cap as a fraction of the area's extent.
    Fraction(f64),
}

impl OverlayLimit {
    /// Apply this cap to `value`, given the area's extent on the same axis.
    fn apply(self, value: f64, area: f64) -> f64 {
        let cap = match self {
            OverlayLimit::None => area,
            OverlayLimit::Px(px) => px.min(area),
            OverlayLimit::Fraction(f) => area * f,
        };
        value.min(cap)
    }
}

/// Where the panel sits inside the host area.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum OverlayGeometry {
    /// Centred both ways, content-tall, capped at `max_width` (the M3 dialog
    /// shape).
    Centered {
        /// The width cap, in logical px.
        max_width: f64,
    },
    /// Pinned to one edge, full-bleed on the cross axis (the M3 bottom-sheet
    /// and side-sheet shapes).
    Edge {
        /// The edge the panel is pinned to (and slides in from).
        side: OverlaySide,
        /// The panel's extent *along* that edge's axis (its thickness).
        extent: OverlayExtent,
        /// The cap on that extent.
        limit: OverlayLimit,
    },
}

/// Which of the panel's corners are rounded (all at the theme's
/// `shape.extra_large`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum OverlayCorners {
    /// All four — the M3 dialog.
    #[default]
    All,
    /// Square — a full-height side sheet meeting three screen edges.
    None,
    /// The top two — an M3 bottom sheet.
    Top,
    /// The bottom two — a top sheet.
    Bottom,
    /// The leading two — a trailing-edge side sheet.
    Start,
    /// The trailing two — a leading-edge side sheet.
    End,
}

impl OverlayCorners {
    /// The per-corner radii for a `radius`-sized corner.
    fn radii(self, radius: f64) -> CornerRadii {
        let (tl, tr, br, bl) = match self {
            OverlayCorners::All => (radius, radius, radius, radius),
            OverlayCorners::None => (0.0, 0.0, 0.0, 0.0),
            OverlayCorners::Top => (radius, radius, 0.0, 0.0),
            OverlayCorners::Bottom => (0.0, 0.0, radius, radius),
            OverlayCorners::Start => (radius, 0.0, 0.0, radius),
            OverlayCorners::End => (0.0, radius, radius, 0.0),
        };
        CornerRadii::new(tl, tr, br, bl)
    }
}

/// Which of the panel's edges carry a 1dp outline.
///
/// M3 gives neither a dialog nor a sheet a border by default (elevation and the
/// container role separate them from the scrim), so both presets below leave
/// this [`OverlayBorder::None`]; the arms exist for a component that needs a
/// divider against an opaque background.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum OverlayBorder {
    /// No border at all.
    #[default]
    None,
    /// All four edges.
    All,
    /// One edge only — a side sheet's *inner* edge.
    Edge(OverlaySide),
}

/// The 1dp hairline weight an [`OverlayBorder`] strokes at.
const BORDER_WIDTH: f64 = 1.0;

/// How the panel enters.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum OverlayEntrance {
    /// Fade plus a scale about the panel's centre — paint-only.
    #[default]
    FadeScale,
    /// Slide in off the geometry's own edge — driven in layout.
    Slide,
    /// No entrance: the panel is at rest on its first frame.
    None,
}

impl OverlayEntrance {
    /// This entrance's ramp duration (see the module docs' motion table).
    fn duration(self) -> Duration {
        match self {
            OverlayEntrance::FadeScale => MaterialMotion::SHORT_4,
            OverlayEntrance::Slide => MaterialMotion::LONG_2,
            OverlayEntrance::None => Duration::ZERO,
        }
    }

    /// This entrance's easing, per direction: M3's decelerate/standard curves
    /// entering, its accelerate curve leaving.
    fn curve(self, exiting: bool) -> Curve {
        if exiting {
            return MaterialMotion::EMPHASIZED_ACCELERATE;
        }
        match self {
            OverlayEntrance::Slide => MaterialMotion::EMPHASIZED,
            _ => MaterialMotion::EMPHASIZED_DECELERATE,
        }
    }

    /// Whether the entrance moves the panel's *geometry* (and therefore needs a
    /// relayout per frame rather than a repaint).
    fn is_layout_affecting(self) -> bool {
        matches!(self, OverlayEntrance::Slide)
    }
}

/// The accessibility role the modal reports.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum OverlayRole {
    /// A dialog box (`Role::Dialog`) — also the role
    /// [`mod@crate::dialog`]/[`crate::sheet`] report, accesskit having no
    /// dedicated sheet role.
    #[default]
    Dialog,
    /// An alert dialog demanding a response (`Role::AlertDialog`).
    AlertDialog,
}

impl OverlayRole {
    /// The accesskit role.
    fn role(self) -> Role {
        match self {
            OverlayRole::Dialog => Role::Dialog,
            OverlayRole::AlertDialog => Role::AlertDialog,
        }
    }
}

/// The chrome differences between the modal families — see the [module
/// docs](self).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct OverlayModalConfig {
    /// Where the panel sits.
    pub geometry: OverlayGeometry,
    /// Which corners round.
    pub corners: OverlayCorners,
    /// Which edges carry an outline.
    pub border: OverlayBorder,
    /// The `surfaceContainer*` rung the panel fills with.
    pub container: OverlayContainer,
    /// The panel's elevation rung.
    pub elevation: OverlayElevation,
    /// How the panel enters.
    pub entrance: OverlayEntrance,
    /// Whether a press+release outside the panel dismisses.
    pub scrim_dismiss: bool,
    /// Whether the close affordance is shown.
    pub close_button: bool,
    /// Whether the drag-handle bar is shown (and dismisses on release).
    pub handle: bool,
    /// Whether the panel can be dragged along its own edge axis to close (see
    /// the [module docs](self)). Meaningful only for an
    /// [`OverlayGeometry::Edge`] panel.
    pub drag: bool,
    /// The accessibility role.
    pub role: OverlayRole,
}

impl OverlayModalConfig {
    /// The M3 dialog chrome: a centred, fully-rounded `surfaceContainerHigh`
    /// panel at elevation 3, capped at `max_width`, fading and scaling in.
    pub fn centered(max_width: f64) -> Self {
        OverlayModalConfig {
            geometry: OverlayGeometry::Centered { max_width },
            corners: OverlayCorners::All,
            border: OverlayBorder::None,
            container: OverlayContainer::High,
            elevation: OverlayElevation::Level3,
            entrance: OverlayEntrance::FadeScale,
            scrim_dismiss: true,
            close_button: false,
            handle: false,
            drag: false,
            role: OverlayRole::Dialog,
        }
    }

    /// The M3 sheet chrome on `side`: a `surfaceContainerLow` panel at
    /// elevation 1 pinned to that edge, rounded on the two corners facing into
    /// the screen, sliding in.
    ///
    /// A left/right side sheet is [`OVERLAY_EDGE_FRACTION`] of the width capped
    /// at [`OVERLAY_SIDE_SHEET_MAX_WIDTH`] and full height; a top/bottom sheet
    /// is content-tall and full width.
    pub fn edge(side: OverlaySide) -> Self {
        let (extent, limit) = if side.is_vertical() {
            (OverlayExtent::Content, OverlayLimit::None)
        } else {
            (
                OverlayExtent::Fraction(OVERLAY_EDGE_FRACTION),
                OverlayLimit::Px(OVERLAY_SIDE_SHEET_MAX_WIDTH),
            )
        };
        let corners = match side {
            OverlaySide::Bottom => OverlayCorners::Top,
            OverlaySide::Top => OverlayCorners::Bottom,
            OverlaySide::Left => OverlayCorners::End,
            OverlaySide::Right => OverlayCorners::Start,
        };
        OverlayModalConfig {
            geometry: OverlayGeometry::Edge {
                side,
                extent,
                limit,
            },
            corners,
            border: OverlayBorder::None,
            container: OverlayContainer::Low,
            elevation: OverlayElevation::Level1,
            entrance: OverlayEntrance::Slide,
            scrim_dismiss: true,
            close_button: false,
            handle: false,
            drag: false,
            role: OverlayRole::Dialog,
        }
    }

    /// Replace the panel's extent along its own axis (an
    /// [`OverlayGeometry::Edge`] config only; a no-op on a centred one).
    pub fn extent(mut self, extent: OverlayExtent, limit: OverlayLimit) -> Self {
        if let OverlayGeometry::Edge {
            extent: e,
            limit: l,
            ..
        } = &mut self.geometry
        {
            *e = extent;
            *l = limit;
        }
        self
    }

    /// Set which corners round.
    pub fn corners(mut self, corners: OverlayCorners) -> Self {
        self.corners = corners;
        self
    }

    /// Set which edges carry an outline.
    pub fn border(mut self, border: OverlayBorder) -> Self {
        self.border = border;
        self
    }

    /// Set the panel's container rung.
    pub fn container(mut self, container: OverlayContainer) -> Self {
        self.container = container;
        self
    }

    /// Set the panel's elevation rung.
    pub fn elevation(mut self, elevation: OverlayElevation) -> Self {
        self.elevation = elevation;
        self
    }

    /// Set the entrance.
    pub fn entrance(mut self, entrance: OverlayEntrance) -> Self {
        self.entrance = entrance;
        self
    }

    /// Enable or disable scrim-tap dismissal.
    pub fn scrim_dismiss(mut self, scrim_dismiss: bool) -> Self {
        self.scrim_dismiss = scrim_dismiss;
        self
    }

    /// Show or hide the close affordance.
    pub fn close_button(mut self, close_button: bool) -> Self {
        self.close_button = close_button;
        self
    }

    /// Show or hide the drag handle.
    pub fn handle(mut self, handle: bool) -> Self {
        self.handle = handle;
        self
    }

    /// Enable or disable drag-to-close (see [`OverlayModalConfig::drag`]).
    pub fn drag(mut self, drag: bool) -> Self {
        self.drag = drag;
        self
    }

    /// Set the accessibility role.
    pub fn role(mut self, role: OverlayRole) -> Self {
        self.role = role;
        self
    }
}

/// A view-held, typed dismiss callback (erased on build).
type OnDismiss<State> = Rc<dyn Fn(&mut State)>;

/// A state-free close hook, fired from `paint` when an exit ramp settles (see
/// the [module docs](self)) — a [`StagedPop`], so a deferred navigator pop can
/// refuse to fire onto a stack that moved under it.
pub type OnClose = Rc<StagedPop>;

/// The state-free close a staged exit fires on settle, paired with the navigator
/// stack identity the exit was staged against.
///
/// Staging puts a whole exit ramp — hundreds of milliseconds — between the
/// *decision* to dismiss and the [`NavigatorController::pop`] that carries it
/// out, and a pop always takes the **top** page. Anything pushed inside that
/// window (a deep link, an async completion landing) therefore ends up popped
/// *instead of* this panel — and since nav ops drain FIFO, the deferred pop
/// queues up behind that push rather than racing it, so it loses every time.
/// `arm` snapshots the stack the exit was staged against; `fire` re-reads it and
/// refuses the pop if it moved, *reporting* the refusal so the widget can
/// recover instead of latching itself closed over a page it never removed.
///
/// **Why depth, not `route_generation`.** Both are public identities on
/// [`NavigatorController`], but what makes a deferred pop wrong here is
/// precisely that a page was pushed *on top of* this one — and a push is exactly
/// what moves [`NavigatorController::depth`]. Nothing else can change this
/// widget's standing while it is alive to fire at all: a pop takes this very
/// page and tears the widget down with it, and a page below cannot be removed
/// out from under it.
/// [`route_generation`](NavigatorController::route_generation) answers a
/// different question — whether the stack's *route content* changed — which is a
/// superset signal here (it also moves for a route edit that leaves this page on
/// top). Both share the same advisory staleness: they publish at the last
/// rebuild, so a push enqueued *after* the rebuild preceding the settling paint
/// is still invisible. That narrows the exposure from the ramp's whole length to
/// a single frame; it does not erase it.
///
/// Public only because it names the [`OnClose`] alias; it is built for a caller
/// by [`show_overlay_modal`], by [`crate::sheet`]'s own `show_bottom_sheet`, or
/// by [`OverlayModalView::on_close`] wrapping an app's hook — never directly.
pub struct StagedPop {
    /// Reads the navigator's live page-stack depth — `None` for a hook with no
    /// navigator behind it (an app-wired [`OverlayModalView::on_close`] on a
    /// `Stack` mount), whose close is always authoritative.
    depth: Option<Box<dyn Fn() -> usize>>,
    /// The close itself: `controller.pop_with_result(..)` on the navigator
    /// path, which is `pop()` exactly when the payload is
    /// [`PopResult::empty`]. A hook with no navigator behind it takes no
    /// payload and drops it (see [`unguarded`](Self::unguarded)).
    close: Box<dyn Fn(PopResult)>,
    /// The depth [`arm`](Self::arm) last snapshotted; `None` until it runs.
    staged_depth: Cell<Option<usize>>,
}

impl StagedPop {
    /// A navigator pop, guarded by the stack identity above, carrying whatever
    /// payload [`fire_with`](Self::fire_with) is handed (empty for every
    /// gesture dismissal — only [`ModalDismiss::dismiss_with`] supplies one).
    pub(crate) fn navigator_pop<State: 'static>(controller: &NavigatorController<State>) -> Self {
        let depth_ctrl = controller.clone();
        let pop_ctrl = controller.clone();
        Self {
            depth: Some(Box::new(move || depth_ctrl.depth())),
            close: Box::new(move |result| pop_ctrl.pop_with_result(result)),
            staged_depth: Cell::new(None),
        }
    }

    /// A close hook with no navigator identity to check — an app's own
    /// [`OverlayModalView::on_close`], which may be a signal write rather than a
    /// pop at all and is not this module's to second-guess. It takes no
    /// argument, so a [`ModalDismiss::dismiss_with`] payload has nowhere to go
    /// on this path and is dropped: there is no pusher `on_result` behind a
    /// `Stack` mount to deliver it to.
    pub(crate) fn unguarded<F: Fn() + 'static>(close: F) -> Self {
        Self {
            depth: None,
            close: Box::new(move |_result| close()),
            staged_depth: Cell::new(None),
        }
    }

    /// Snapshot the stack this exit is being staged against.
    ///
    /// Called by the widget the moment a trigger stages an exit — deliberately
    /// **not** at construction: the page builder re-runs on every navigator
    /// rebuild, so a construction-time snapshot would simply be re-taken after
    /// the very push it exists to catch.
    pub(crate) fn arm(&self) {
        self.staged_depth
            .set(self.depth.as_ref().map(|depth| depth()));
    }

    /// Fire the close, handing it `result`'s payload, unless the stack moved
    /// since [`arm`](Self::arm) — returns whether it actually fired.
    ///
    /// An unarmed hook fires unconditionally: an unstaged close lands in the same
    /// turn its trigger arrives, leaving no window for the stack to move.
    ///
    /// `result` is taken **only when the pop actually happens**: a refused pop
    /// removed no page and delivered no result, so the payload is left with the
    /// caller — which drops it, since it was scoped to the exit that did not
    /// land (the panel ramps back open rather than closing; see
    /// [`OverlayModalWidget::pending_result`]).
    #[must_use]
    pub(crate) fn fire_with(&self, result: &mut Option<PopResult>) -> bool {
        if let (Some(depth), Some(staged)) = (&self.depth, self.staged_depth.get())
            && depth() != staged
        {
            return false;
        }
        (self.close)(result.take().unwrap_or_else(PopResult::empty));
        true
    }
}

/// A cloneable handle an app triggers to dismiss a modal **through the host's
/// own staged exit ramp** — the public half of a machine whose triggers were
/// otherwise all host-chrome-internal (see the [module docs](self)'
/// app-initiated dismiss section).
///
/// Mint one per presentation, install it on the modal view with
/// [`OverlayModalView::dismiss_handle`] (or the family wrapper's forward of
/// it), and clone it into the panel's own controls:
///
/// ```ignore
/// let dismiss = ModalDismiss::new();
/// let apply = dismiss.clone();
/// show_side_sheet(
///     &nav,
///     move || {
///         side_sheet(
///             "Filters",
///             body(),
///             filled_button("Apply", move |_: &mut State| {
///                 apply.dismiss_with(PopResult::of(Filters::current()))
///             }),
///         )
///         .dismiss_handle(dismiss.clone())
///     },
///     |state: &mut State, result: PopResult| { /* ... */ },
/// );
/// ```
///
/// A request is a generation bump on a shared cell, not a callback: the widget
/// latches the last generation it saw, so a trigger fires exactly once however
/// many passes observe it, and a bump raised before the widget existed is not a
/// request aimed at it. Triggering while an exit is already staging is a no-op
/// — the ramp in flight is the dismissal, and it keeps its own payload (see the
/// [module docs](self)' *What a request consumes*).
#[derive(Clone, Default)]
pub struct ModalDismiss(Rc<DismissRequest>);

/// [`ModalDismiss`]' shared cell: the request counter, plus the payload the
/// next staged pop carries — stamped with the generation that raised it.
///
/// **Why the stamp.** A payload belongs to *its own* request and to no other:
/// an unobserved [`ModalDismiss::dismiss_with`] followed by a payload-free
/// [`ModalDismiss::dismiss`] must pop empty rather than deliver the first
/// one's value. [`ModalDismiss::request`] enforces that from the writing side
/// (the newer request displaces the stash outright) and
/// [`ModalDismiss::take_result`] from the reading side (an observer only takes
/// a payload stamped with the very generation it is acting on).
///
/// **Why a [`Cell`], not a `RefCell`.** A payload is app-owned data whose own
/// `Drop` may reach back into this handle (it can hold a clone of it); a
/// `RefCell` would have a live borrow for such a re-entrant write to trip into
/// a `BorrowMutError` panic. A `Cell` has no borrow flag at all, and every
/// mutation below completes *before* the value it displaced is dropped.
#[derive(Default)]
struct DismissRequest {
    generation: Cell<u64>,
    result: Cell<Option<(u64, PopResult)>>,
}

impl ModalDismiss {
    /// A fresh handle, with no request raised on it yet.
    pub fn new() -> Self {
        Self::default()
    }

    /// Ask the modal to dismiss itself, animating out, popping with an empty
    /// result.
    pub fn dismiss(&self) {
        self.request(None);
    }

    /// Ask the modal to dismiss itself, animating out, popping with `result`
    /// for the pusher's own `on_result` callback (`show_*`'s third argument).
    ///
    /// A payload only reaches an `on_result` where a navigator is behind the
    /// modal; a `Stack`-mounted modal's app-wired
    /// [`OverlayModalView::on_close`] takes none and drops it
    /// ([`StagedPop::unguarded`]), and a mount with only
    /// [`OverlayModalView::on_dismiss`] (no close hook at all) still dismisses
    /// but leaves the payload undelivered — `&mut State` is that route's own
    /// channel back to the app.
    ///
    /// Raised while an exit is already staging, this is the same no-op
    /// [`Self::dismiss`] is: the in-flight ramp keeps whatever payload it was
    /// staged with, and this one is not delivered (see the [module docs](self)'
    /// *What a request consumes*).
    pub fn dismiss_with(&self, result: PopResult) {
        self.request(Some(result));
    }

    /// Stash any payload against the generation about to be raised, then bump
    /// the generation the widget latches against. The bump is last so a paint
    /// racing the write can never see the request without its payload.
    ///
    /// The stash is *replaced*, never merged into: a payload-free
    /// [`Self::dismiss`] clears whatever an earlier, still-unobserved
    /// [`Self::dismiss_with`] left there. The newest request is the live one,
    /// and a plain dismissal asks to pop with nothing.
    fn request(&self, result: Option<PopResult>) {
        let next = self.0.generation.get().wrapping_add(1);
        // Displace first, drop second: the superseded payload's own `Drop` runs
        // with the cell already in its new state (see [`DismissRequest`]).
        let superseded = self.0.result.replace(result.map(|result| (next, result)));
        drop(superseded);
        self.0.generation.set(next);
    }

    /// The live request generation.
    ///
    /// `pub(crate)` (not private) so [`crate::sheet`] can mirror this same
    /// observe pattern against its own staged-exit path rather than minting
    /// a second handle type (see that module's own `ModalDismiss` adoption).
    pub(crate) fn generation(&self) -> u64 {
        self.0.generation.get()
    }

    /// Take the payload `generation`'s own request stashed, if it carried one.
    ///
    /// Keyed on the generation so a payload can only ever ride the request that
    /// raised it (see [`DismissRequest`]): an observation of a *later* request
    /// finds nothing here rather than delivering a value the app attached to an
    /// earlier one.
    ///
    /// `pub(crate)` for the same cross-module reason as [`Self::generation`].
    pub(crate) fn take_result(&self, generation: u64) -> Option<PopResult> {
        match self.0.result.take() {
            Some((stamp, result)) if stamp == generation => Some(result),
            // Not this request's payload: put it back exactly as found (the
            // cell is empty right now, so nothing is dropped here either).
            other => {
                self.0.result.set(other);
                None
            }
        }
    }

    /// Whether both handles share one cell — an *identity* check, not an
    /// equality one (see [`OverlayModalView::rebuild`]'s re-seed).
    ///
    /// `pub(crate)` for the same cross-module reason as [`Self::generation`].
    pub(crate) fn same_cell(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.0, &other.0)
    }
}

/// A modal component that [`show_overlay_modal`] can wire a navigator pop into.
///
/// A modal component implements it by storing the callback in its own
/// `on_dismiss` slot and reporting its own `dismissable` flag; the trait exists
/// so one push helper serves every family rather than each component
/// re-deriving the same `push_with_options` call.
///
/// Its element is the shared [`OverlayModalWidget`] by definition — a modal
/// component *is* a pre-configured modal host — which is what lets
/// [`show_overlay_modal`] install the staged-exit close hook and the back-press
/// dismiss signal on whatever component it was handed, with no per-component
/// setter.
pub trait OverlayModalContent<State: 'static>:
    View<State, Element = OverlayModalWidget> + Sized + 'static
{
    /// Install the dismiss callback, replacing any the builder already set.
    fn on_modal_dismiss(self, on_dismiss: OnDismiss<State>) -> Self;

    /// Whether this modal may be dismissed by the user at all — read once, at
    /// push time, to pick the page's [`BackPolicy`].
    fn modal_dismissable(&self) -> bool;
}

/// Build a modal host: `content` inside a panel shaped by `config`, over the M3
/// 32% scrim.
///
/// The content view owns all of the panel's padding and layout — the panel
/// itself contributes only chrome (fill, outline, corners, elevation) plus the
/// optional close affordance and drag handle, which sit *over* the content.
pub fn overlay_modal<State: 'static, V: View<State>>(
    content: V,
    config: OverlayModalConfig,
) -> OverlayModalView<State> {
    OverlayModalView {
        content: any(content),
        config,
        label: None,
        dismissable: true,
        on_dismiss: None,
        on_close: None,
        dismiss_handle: None,
        snap_points: Vec::new(),
    }
}

/// A declarative modal host. See [`overlay_modal`].
///
/// The fields are crate-visible so the catalog's modal components can wrap one
/// and adjust its config in their own builders (a dialog *is* a pre-configured
/// modal host); an app outside the crate configures it through
/// [`overlay_modal`]'s `config` argument and the builders below.
pub struct OverlayModalView<State: 'static> {
    pub(crate) content: AnyView<State>,
    pub(crate) config: OverlayModalConfig,
    pub(crate) label: Option<String>,
    pub(crate) dismissable: bool,
    pub(crate) on_dismiss: Option<OnDismiss<State>>,
    pub(crate) on_close: Option<OnClose>,
    pub(crate) dismiss_handle: Option<ModalDismiss>,
    pub(crate) snap_points: Vec<f64>,
}

impl<State: 'static> OverlayModalView<State> {
    /// Label the modal's accessibility node (its title text).
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Whether the user can dismiss this modal at all — the scrim tap, the
    /// close affordance, the handle, a drag commit, `Escape`, and an Android
    /// back press (default `true`; see the [module docs](self)). `false`
    /// disables all six; only an explicit control the app wires through its own
    /// content still dismisses it.
    pub fn dismissable(mut self, dismissable: bool) -> Self {
        self.dismissable = dismissable;
        self
    }

    /// Set the **unstaged** dismiss callback — delivered with `&mut State`
    /// during the event pass.
    ///
    /// Used only when no [`on_close`](Self::on_close) hook is wired: with one,
    /// the dismissal is staged behind the exit ramp and fired from `paint`,
    /// where no app state exists (see the [module docs](self)).
    pub fn on_dismiss<F: Fn(&mut State) + 'static>(mut self, on_dismiss: F) -> Self {
        self.on_dismiss = Some(Rc::new(on_dismiss));
        self
    }

    /// Set the state-free close hook fired when the exit ramp settles — the
    /// staged-dismissal path. [`show_overlay_modal`] wires this to
    /// `controller.pop()`; a `Stack`-mounted modal wires its own (a signal
    /// write, a navigator pop).
    ///
    /// Pinned at `build`: a directly constructed (non-staged) view's later
    /// rebuilds neither update nor clear this hook once installed — see
    /// [`OverlayModalWidget`]'s `on_close` field doc for why.
    ///
    /// An app hook is wrapped *unguarded*: only the navigator pop
    /// [`show_overlay_modal`] wires has a stack identity to check.
    pub fn on_close<F: Fn() + 'static>(mut self, on_close: F) -> Self {
        self.on_close = Some(Rc::new(StagedPop::unguarded(on_close)));
        self
    }

    /// Install the app-triggered staged-dismiss handle: the panel's own
    /// content can then close it through the very ramp the host chrome uses,
    /// instead of the raw, unstaged `controller.pop()` that was its only route
    /// before (see the [module docs](self)' app-initiated dismiss section, and
    /// [`ModalDismiss`] for the worked example).
    ///
    /// Mint the handle *outside* a `show_*` page builder and clone it in — the
    /// builder re-runs on every navigator rebuild.
    pub fn dismiss_handle(mut self, dismiss: ModalDismiss) -> Self {
        self.dismiss_handle = Some(dismiss);
        self
    }

    /// Set the drag's snap points: `0..=1` a fraction of the panel's own
    /// extent, above `1` logical px (see the [module docs](self)). The panel
    /// opens to the first point — **except** a first point of `0.0` itself,
    /// which [`OverlayModalWidget::open_progress`] treats as absent (fully
    /// open) rather than authoring a panel that opens already closed.
    ///
    /// A non-finite point (NaN or infinite — never a meaningful fraction or
    /// px extent) is dropped here, at the boundary, rather than stored: this
    /// is the one place caller input enters the widget, and every downstream
    /// consumer (`normalize_snap`, `snap_targets`, `open_progress`) trusts
    /// [`OverlayModalWidget::snap_points`] to already be all-finite rather
    /// than re-checking (see the [module docs](self)'s Clamp Discipline
    /// section). A caller-authored NaN/∞ behaves as if that point were never
    /// passed at all.
    pub fn snap_points(mut self, points: &[f64]) -> Self {
        self.snap_points = points.iter().copied().filter(|p| p.is_finite()).collect();
        self
    }
}

impl<State: 'static> OverlayModalContent<State> for OverlayModalView<State> {
    fn on_modal_dismiss(mut self, on_dismiss: OnDismiss<State>) -> Self {
        self.on_dismiss = Some(on_dismiss);
        self
    }

    fn modal_dismissable(&self) -> bool {
        self.dismissable
    }
}

/// Push `build`'s modal as a transparent navigator page and register
/// `on_result` for the value it pops with — the shared push behind every modal
/// component's `show_*` wrapper.
///
/// The modal's dismissal is wired to `controller.pop()` (an *empty*
/// [`PopResult`], overriding any `on_dismiss` the builder set); an action inside
/// the content pops with a value via `controller.pop_with_result(..)`. The
/// navigator transition is [`TransitionSpec::NONE`] on purpose: the modal stages
/// its own entrance *and exit* ([`OverlayEntrance`]), so a page transition on
/// top of it would animate the same thing twice.
///
/// The back-press policy is peeked once, here, from
/// [`OverlayModalContent::modal_dismissable`] — the push-time `PushOptions`
/// contract fixes it for the life of the page, exactly as
/// [`crate::sheet`]'s own `show_bottom_sheet` peek does, even though `build` is
/// re-invoked on every later navigator rebuild to diff the page's content.
///
/// The pop is wired **twice, by design**: as the staged
/// [`OverlayModalView::on_close`] hook the exit ramp fires on settle (the path
/// every dismissal actually takes here), and as the unstaged
/// [`OverlayModalContent::on_modal_dismiss`] callback, which only runs for a
/// config with no entrance to reverse. Exactly one of the two fires per
/// dismissal.
pub fn show_overlay_modal<State, V, B, R>(
    controller: &NavigatorController<State>,
    build: B,
    on_result: R,
) where
    State: 'static,
    V: OverlayModalContent<State>,
    B: Fn() -> V + 'static,
    R: Fn(&mut State, PopResult) + 'static,
{
    let dismiss_ctrl = controller.clone();
    // Built **once**, outside the page builder, and only cloned into each build:
    // the builder re-runs on every navigator rebuild, and a fresh hook per pass
    // would throw away the identity an in-flight exit armed (see [`StagedPop`]).
    let staged: OnClose = Rc::new(StagedPop::navigator_pop(controller));
    let dismissable = build().modal_dismissable();
    // A `Veto` page is pushed with no cell at all: the navigator consumes the
    // back press and fires nothing.
    let signal = dismissable.then(|| Rc::new(Cell::new(0u64)));
    let widget_signal = signal.clone();
    let mut options = PushOptions::transparent()
        .transition(TransitionSpec::NONE)
        .back(if dismissable {
            BackPolicy::DismissAnimated
        } else {
            BackPolicy::Veto
        })
        .on_result(on_result);
    if let Some(sig) = &signal {
        options = options.dismiss_signal(sig.clone());
    }
    controller.push_with_options(
        move || {
            let ctrl = dismiss_ctrl.clone();
            any::<State, _>(StagedExit {
                inner: build().on_modal_dismiss(Rc::new(move |_state: &mut State| ctrl.pop())),
                on_close: staged.clone(),
                dismiss_signal: widget_signal.clone(),
            })
        },
        options,
    );
}

/// A modal component with the staged-exit close hook and the back-press
/// dismiss-signal cell installed on the [`OverlayModalWidget`] it builds.
///
/// [`show_overlay_modal`] is generic over every modal component, so it cannot
/// reach the [`OverlayModalView`] each of them wraps privately; every one of
/// them *does* build the shared [`OverlayModalWidget`]
/// ([`OverlayModalContent`]'s element bound), so this thin pass-through installs
/// both on the built widget instead — the same place [`OverlayModalView`]'s own
/// `on_close` lands. [`OverlayModalView::rebuild`] never writes either field
/// itself, so `StagedExit::rebuild`'s own reinstall below (which runs *after*
/// `inner.rebuild`) is the sole rebuild-time writer on this path — it always
/// wins rather than merely winning last.
struct StagedExit<V> {
    inner: V,
    on_close: OnClose,
    dismiss_signal: Option<Rc<Cell<u64>>>,
}

impl<State: 'static, V: View<State, Element = OverlayModalWidget>> View<State> for StagedExit<V> {
    type Element = OverlayModalWidget;

    fn build(&self, ctx: &mut BuildCtx<'_>) -> OverlayModalWidget {
        let mut widget = self.inner.build(ctx);
        widget.on_close = Some(self.on_close.clone());
        // Seeded from the cell's *current* generation: a bump that predates
        // this widget is not a back press aimed at it.
        widget.last_seen_dismiss = self.dismiss_signal.as_ref().map_or(0, |s| s.get());
        widget.dismiss_signal = self.dismiss_signal.clone();
        widget
    }

    fn rebuild(
        &self,
        prev: &Self,
        element: &mut OverlayModalWidget,
        ctx: &mut BuildCtx<'_>,
    ) -> ChangeFlags {
        let flags = self.inner.rebuild(&prev.inner, element, ctx);
        element.on_close = Some(self.on_close.clone());
        // The cell's identity is fixed at push time, so reinstalling it never
        // disturbs `last_seen_dismiss`.
        element.dismiss_signal = self.dismiss_signal.clone();
        flags
    }

    fn teardown(&self, element: &mut OverlayModalWidget, ctx: &mut BuildCtx<'_>) {
        self.inner.teardown(element, ctx);
    }
}

/// Who asked for a dismissal, the one thing
/// [`OverlayModalWidget::stage_dismiss`] treats differently between triggers.
#[derive(Clone, Copy, PartialEq, Eq)]
enum DismissSource {
    /// A user gesture, or a back press — gated on
    /// [`OverlayModalView::dismissable`].
    User,
    /// The app's own [`ModalDismiss`] handle, which that flag does not gate
    /// (see the module docs' app-initiated dismiss section).
    App,
}

/// What a [`OverlayModalWidget::stage_dismiss`] attempt left for its caller to
/// finish, since only the caller knows which pass it holds.
enum DismissStage {
    /// Nothing to do: already exiting, already closed, or not permitted.
    Refused,
    /// The exit ramp is running — ask for the pass its motion needs.
    Ramping,
    /// Nothing to stage (no close hook to fire from `paint`, or no entrance to
    /// reverse): the caller dismisses on the spot, however its own pass can.
    Unstaged,
}

/// The retained widget for an [`OverlayModalView`].
pub struct OverlayModalWidget {
    content: ChildPod,
    config: OverlayModalConfig,
    label: Option<String>,
    dismissable: bool,
    on_dismiss: Option<ErasedCallback>,
    /// The state-free close hook the exit ramp fires on settle (see the module
    /// docs); `None` leaves dismissal unstaged.
    ///
    /// Installed at [`OverlayModalView::build`] and, on the staged navigator
    /// path, reinstalled after every rebuild by [`StagedExit`] — the sole
    /// rebuild-time writer. [`OverlayModalView::rebuild`] itself never touches
    /// this field: a directly constructed, non-staged view (one no `StagedExit`
    /// wraps) therefore has its `on_close` pinned at whatever `build` installed
    /// for the widget's whole mounted lifetime — a later rebuild neither updates
    /// nor clears it, since only the staged wrapper needs a live reinstall (its
    /// own hook is a fixed `controller.pop()` closure that never changes across
    /// rebuilds anyway).
    on_close: Option<OnClose>,
    /// The shared back-press dismiss-signal cell (the `DismissAnimated` seam;
    /// see [`Self::observe_dismiss_signal`]), installed by [`StagedExit`].
    dismiss_signal: Option<Rc<Cell<u64>>>,
    /// The last generation observed from `dismiss_signal` (0 with no signal
    /// wired — a `Stack` mount, or a `Veto` page).
    last_seen_dismiss: u64,
    /// The app's own staged-dismiss handle, installed by
    /// [`OverlayModalView::dismiss_handle`] (see the module docs'
    /// app-initiated dismiss section).
    dismiss_handle: Option<ModalDismiss>,
    /// The last request generation observed from `dismiss_handle` — seeded from
    /// the handle's own generation at build, so a request raised before this
    /// widget existed is not aimed at it.
    last_seen_request: u64,
    /// The payload a [`ModalDismiss::dismiss_with`] request armed, handed to
    /// the staged pop when the exit settles.
    ///
    /// **Scoped to the exit its own request staged, and to no other.** It is
    /// taken from the handle only by the observation that *accepted* the
    /// request ([`Self::accept_dismiss_request`]), and dropped by every leg
    /// that ends that exit without a landed pop: a refused staged pop (the
    /// stack moved — see [`StagedPop::fire_with`]), a drag that catches the
    /// closing panel ([`Self::scrub`]), any ramp aimed back open
    /// ([`Self::begin_ramp`]). A payload left standing across one of those
    /// would be delivered by whatever dismissal happened to land next — a
    /// scrim tap, `Escape`, a back press, a payload-free `dismiss()` — handing
    /// the pusher's `on_result` a value it was never dismissed with.
    pending_result: Option<PopResult>,
    /// The drag's resting points, as authored (see
    /// [`OverlayModalView::snap_points`]).
    snap_points: Vec<f64>,
    /// The panel rect in the widget's own coordinate space (computed at layout,
    /// hit-tested at event time).
    panel: Rect,
    /// The ramp driver, the endpoints it interpolates between, and the progress
    /// `layout` last used: `progress = from + (to − from) · anim.value()`.
    anim: AnimationController,
    ramp: (f64, f64),
    progress: f64,
    /// Whether the first paint has seeded the ramp (see the module docs'
    /// `reduce_motion` note).
    started: bool,
    /// Whether the running ramp ends in a dismissal.
    exiting: bool,
    /// One-shot latch set the instant `on_close` fires (settle, or the
    /// immediate no-ramp path in [`Self::request_dismiss`]). Terminal for this
    /// widget's mounted lifetime: the hook only *enqueues* a navigator pop, so
    /// the widget stays mounted and still a barrier for one or more frames
    /// after firing, during which a further dismiss trigger must not re-fire it
    /// — that would pop whatever page is now underneath this one.
    /// `request_dismiss` refuses every trigger once set; nothing ever clears it
    /// back to `false`.
    ///
    /// Set only when the hook actually closed: a [`StagedPop`] that *refused*
    /// its pop removed no page, so latching here would brick a still-live
    /// widget rather than record a finished dismissal.
    closed: bool,
    /// [`Self::closed`]'s twin for the *unstaged* route: the one-shot latch set
    /// the instant [`OverlayModalView::on_dismiss`] is actually invoked (see
    /// [`Self::fire_dismiss_now`]).
    ///
    /// A mount with no close hook has no `closed` to latch — its dismissal is
    /// the app callback itself — and the app tears the panel down from its own
    /// state, so this widget stays mounted and dismissable for the rebuild or
    /// two that takes. Without this latch a second trigger inside that window
    /// dismisses the same panel twice: a pending [`ModalDismiss`] request the
    /// `paint` backstop deliberately left standing (see the [module
    /// docs](self)' *What a request consumes*) plus the `Escape` that arrives
    /// before the next rebuild are two triggers of exactly that shape, one
    /// event pass apart or none. Terminal like `closed`, and for the same
    /// reason: nothing ever clears it back to `false`.
    dismissed: bool,
    /// A scrim/panel-background press is in flight (the modal barrier).
    scrim_captured: bool,
    /// Whether that press started outside the panel — only an outside press
    /// released outside dismisses.
    scrim_down_outside: bool,
    /// The close affordance's latched hover/press state.
    close_hovered: bool,
    close_captured: bool,
    /// The drag handle's latched hover/press state.
    handle_hovered: bool,
    handle_captured: bool,
    /// A drag along the panel's own axis is in flight, where it started (axis
    /// position and the progress it began from), whether it began on the handle,
    /// and whether it has passed [`TOUCH_SLOP`] into a real drag.
    drag_captured: bool,
    drag_start: f64,
    drag_from: f64,
    drag_on_handle: bool,
    drag_moved: bool,
    /// The release-velocity estimator, clocked from the last painted frame —
    /// pointer events carry no timestamp of their own (`frust_widgets::scroll`'s
    /// precedent).
    tracker: VelocityTracker,
    last_frame_time: FrameTime,
}

impl OverlayModalWidget {
    /// The panel rect in the widget's own coordinate space.
    pub fn panel_rect(&self) -> Rect {
        self.panel
    }

    /// The close affordance's hit box, when the config shows one.
    pub fn close_rect(&self) -> Option<Rect> {
        self.config.close_button.then(|| {
            let center = Point::new(
                self.panel.x1 - CLOSE_INSET - CLOSE_ICON / 2.0,
                self.panel.y0 + CLOSE_INSET + CLOSE_ICON / 2.0,
            );
            Rect::from_center_size(center, Size::new(CLOSE_HIT, CLOSE_HIT))
        })
    }

    /// The drag handle's hit box, when the config shows one.
    pub fn handle_rect(&self) -> Option<Rect> {
        self.config
            .handle
            .then(|| Rect::from_center_size(self.handle_center(), Size::new(CLOSE_HIT, CLOSE_HIT)))
    }

    /// The centre of the handle indicator, in the widget's own space.
    fn handle_center(&self) -> Point {
        Point::new(
            self.panel.center().x,
            self.panel.y0 + HANDLE_TOUCH_TARGET / 2.0,
        )
    }

    /// The handle's painted bar (a subset of its hit box — see [`CLOSE_HIT`]).
    fn handle_bar(&self) -> Rect {
        Rect::from_center_size(self.handle_center(), Size::new(HANDLE_WIDTH, HANDLE_HEIGHT))
    }

    /// The ramp's progress: `0.0` off-screen/transparent, `1.0` fully shown.
    pub fn progress(&self) -> f64 {
        self.progress
    }

    /// Whether an exit ramp is running (the panel is on its way out, and the
    /// barrier is still swallowing input).
    pub fn is_exiting(&self) -> bool {
        self.exiting
    }

    /// The progress an open panel rests at: the first snap point, or fully open
    /// with none authored.
    ///
    /// Floored above [`PROGRESS_EPSILON`]: a first point that normalizes to
    /// `0.0` (an explicit `snap_points(&[0.0])`, or a `0.0`-fraction point on an
    /// as-yet-unmeasured extent) is treated as **absent** rather than as "open
    /// to closed" — the entrance ramp always has a nonzero target to animate
    /// toward, matching [`Self::settle_drag`]'s own floor for a panel that
    /// cannot dismiss. There is no fallible surface here
    /// ([`OverlayModalView::snap_points`] is a plain builder call), so an
    /// unreachable configuration silently falls back to fully open instead of
    /// panicking.
    pub fn open_progress(&self) -> f64 {
        self.snap_points
            .first()
            .map(|p| self.normalize_snap(*p))
            .filter(|p| *p > PROGRESS_EPSILON)
            .unwrap_or(1.0)
    }

    /// A snap point in progress space: `0..=1` is already a fraction of the
    /// panel's extent, anything larger is logical px against that extent.
    /// Clamped into `0..=1`, and treated as fully open while no extent has been
    /// laid out yet.
    fn normalize_snap(&self, point: f64) -> f64 {
        if point <= 1.0 {
            return point.clamp(0.0, 1.0);
        }
        let extent = self.extent();
        if extent <= 0.0 {
            return 1.0;
        }
        (point / extent).clamp(0.0, 1.0)
    }

    /// The resting points a release snaps to, ascending: every snap point plus
    /// `0.0` (closed). With none authored the set is `{0.0, 1.0}`, so "nearest"
    /// is the drag-past-the-midpoint commit.
    fn snap_targets(&self) -> Vec<f64> {
        let mut targets: Vec<f64> = std::iter::once(0.0)
            .chain(self.snap_points.iter().map(|p| self.normalize_snap(*p)))
            .collect();
        if targets.len() == 1 {
            targets.push(1.0);
        }
        targets.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
        targets
    }

    /// The panel's extent along its own slide axis (its thickness).
    fn extent(&self) -> f64 {
        match self.config.geometry {
            OverlayGeometry::Edge { side, .. } if side.is_vertical() => self.panel.height(),
            OverlayGeometry::Edge { .. } => self.panel.width(),
            OverlayGeometry::Centered { .. } => 0.0,
        }
    }

    /// The panel's slide axis, and which way along it closes: `+1.0` when the
    /// panel leaves toward growing coordinates (bottom/right), `-1.0` otherwise.
    fn close_sign(&self) -> f64 {
        match self.config.geometry {
            OverlayGeometry::Edge {
                side: OverlaySide::Bottom | OverlaySide::Right,
                ..
            } => 1.0,
            _ => -1.0,
        }
    }

    /// `position` projected onto the panel's slide axis.
    fn axis_pos(&self, position: Point) -> f64 {
        match self.config.geometry {
            OverlayGeometry::Edge { side, .. } if side.is_vertical() => position.y,
            _ => position.x,
        }
    }

    /// The last painted frame time in milliseconds — the event pass's clock,
    /// since a pointer event carries none.
    fn event_time_ms(&self) -> f64 {
        self.last_frame_time.as_secs_f64() * 1000.0
    }

    /// Whether a dismissal can actually be delivered: the user-facing
    /// [`dismissable`](OverlayModalView::dismissable) flag *and* a hook to fire.
    fn can_dismiss(&self) -> bool {
        self.dismissable && (self.on_dismiss.is_some() || self.on_close.is_some())
    }

    /// Start a ramp from the current progress to `to`, over the entrance's own
    /// duration scaled by how much of the travel is left, eased by its own
    /// direction's curve.
    ///
    /// The one choke point every staging path goes through, so it is also where
    /// the staged pop is armed against the stack as it stands right now (see
    /// [`StagedPop`]); a leg aimed anywhere but closed is not a dismissal and
    /// arms nothing — it *ends* whatever exit was staged, and the payload that
    /// exit was carrying goes with it (see [`Self::pending_result`]).
    fn begin_ramp(&mut self, to: f64, exiting: bool) {
        let from = self.progress;
        self.ramp = (from, to);
        self.exiting = exiting;
        if exiting {
            if let Some(on_close) = &self.on_close {
                on_close.arm();
            }
        } else {
            self.pending_result = None;
        }
        let fraction = (to - from).abs().clamp(0.0, 1.0);
        let duration = self.config.entrance.duration().mul_f64(fraction);
        self.anim =
            AnimationController::new(duration).with_curve(self.config.entrance.curve(exiting));
        self.anim.forward();
        self.started = true;
    }

    /// The progress the running ramp is at.
    fn ramp_value(&self) -> f64 {
        let (from, to) = self.ramp;
        from + (to - from) * self.anim.value_clamped()
    }

    /// Ask for the pass a moving ramp needs: a relayout when the motion moves
    /// the panel's geometry (`request_layout` implies a frame), a bare frame
    /// otherwise.
    fn request_continuation(&self, ctx: &mut PaintCtx) {
        if self.config.entrance.is_layout_affecting() {
            ctx.request_layout();
        } else {
            ctx.request_frame();
        }
    }

    /// Whether a staged exit is possible at all: something to fire from `paint`,
    /// and an entrance to reverse.
    fn stageable(&self) -> bool {
        self.on_close.is_some() && self.config.entrance != OverlayEntrance::None
    }

    /// Stage the dismissal — the one staging core **every** trigger goes
    /// through: the pointer/key gestures ([`Self::request_dismiss`]), the back
    /// press ([`Self::observe_dismiss_signal`]), and the app's own
    /// [`ModalDismiss`] handle ([`Self::observe_dismiss_request`]).
    ///
    /// A trigger arriving while an exit is already running, or after this
    /// widget has dismissed once — `on_close` fired ([`Self::closed`]) or
    /// `on_dismiss` did ([`Self::dismissed`]) — is a no-op. Both latches guard
    /// the same window: the dismissal is enqueued (a navigator pop) or
    /// delegated (the app's own state), and the widget stays mounted across the
    /// rebuild or two that takes, where a second trigger would otherwise
    /// dismiss it twice. A *user* trigger on a non-dismissable modal is a no-op
    /// too; an app one is not (the module docs' app-initiated dismiss section
    /// states why).
    ///
    /// What it cannot do is finish an unstaged dismissal, since only the caller
    /// knows which pass it holds — hence [`DismissStage::Unstaged`].
    fn stage_dismiss(&mut self, source: DismissSource) -> DismissStage {
        if self.exiting || self.closed || self.dismissed {
            return DismissStage::Refused;
        }
        if source == DismissSource::User && !self.dismissable {
            return DismissStage::Refused;
        }
        if !self.stageable() {
            return DismissStage::Unstaged;
        }
        self.begin_ramp(0.0, true);
        DismissStage::Ramping
    }

    /// Fire the state-free close hook now, with any payload a
    /// [`ModalDismiss::dismiss_with`] request armed — the unstaged close, in
    /// the same turn its trigger arrived, so the hook is unarmed and always
    /// closes (see [`StagedPop::fire_with`]). Returns whether it fired.
    fn fire_close_now(&mut self) -> bool {
        let Some(on_close) = self.on_close.clone() else {
            return false;
        };
        let fired = on_close.fire_with(&mut self.pending_result);
        self.closed = fired;
        fired
    }

    /// Fire the state-bearing [`OverlayModalView::on_dismiss`] now — the
    /// unstaged close's twin for a mount that wired no `on_close` at all — and
    /// latch the route shut behind it ([`Self::dismissed`]), so however many
    /// triggers land before the app's own teardown lands, exactly one
    /// dismissal reaches the app. Returns whether it fired.
    fn fire_dismiss_now(&mut self, ctx: &mut EventCtx) -> bool {
        let Some(on_dismiss) = self.on_dismiss.as_mut() else {
            return false;
        };
        on_dismiss(ctx);
        self.dismissed = true;
        true
    }

    /// Stage the dismissal from a user gesture (a scrim tap, the close
    /// affordance, the handle, `Escape`), falling back to firing
    /// [`OverlayModalView::on_dismiss`] on the spot when there is nothing to
    /// stage — no close hook to fire from `paint`, or no entrance to reverse.
    fn request_dismiss(&mut self, ctx: &mut EventCtx) {
        match self.stage_dismiss(DismissSource::User) {
            DismissStage::Refused => {}
            DismissStage::Ramping => ctx.request_redraw(),
            DismissStage::Unstaged => {
                if !self.fire_dismiss_now(ctx) {
                    self.fire_close_now();
                }
            }
        }
    }

    /// The [`ModalDismiss`] handle's live request generation, when a request
    /// this widget has not seen before is pending — the *peek* half of the
    /// observe pattern (see the [module docs](self)' *What a request
    /// consumes*).
    ///
    /// Peeking is deliberately separate from latching: only the caller, having
    /// put the request through [`Self::stage_dismiss`], knows what became of
    /// it, and a payload must never be taken by an observation that did not
    /// accept the dismissal it belongs to.
    fn pending_dismiss_request(&self) -> Option<u64> {
        let handle = self.dismiss_handle.as_ref()?;
        let current = handle.generation();
        (current != self.last_seen_request).then_some(current)
    }

    /// Record `generation` as seen — so the request acts exactly once however
    /// many passes observe it — **without** taking its payload.
    ///
    /// This is what a *refused* request gets (an exit already in flight, or a
    /// widget already closed): the trigger is spent, since the ramp in flight
    /// is the dismissal and re-staging it later would arm a pop against a stack
    /// that has moved on. Its payload stays with the handle rather than
    /// retargeting an exit that was never asked to carry it — a shared handle's
    /// "OK" pressed during a "Cancel" ramp must not make the cancelled panel
    /// pop confirmed.
    fn latch_dismiss_request(&mut self, generation: u64) {
        self.last_seen_request = generation;
    }

    /// Latch `generation` *and* take the payload it carried — the accepted
    /// request's own value, handed to whichever close this dismissal fires
    /// (see [`Self::pending_result`]).
    ///
    /// The payload is taken here, at acceptance, rather than at the settle that
    /// consumes it: the handle is the app's and may be re-armed for a later
    /// presentation, while this exit's payload belongs to this exit.
    fn accept_dismiss_request(&mut self, generation: u64) {
        self.latch_dismiss_request(generation);
        // Assigned wholesale: an accepted request's payload *is* this exit's
        // payload, and nothing else may still be pending here (every leg that
        // ends a staged exit without a landed pop clears it).
        self.pending_result = self
            .dismiss_handle
            .as_ref()
            .and_then(|handle| handle.take_result(generation));
    }

    /// Observe the app's [`ModalDismiss`] handle in the *event* pass, right
    /// after the content routing that most likely raised the request (a panel
    /// action button), so an app dismissal stages in the very pass that asked
    /// for it rather than waiting on a paint nothing scheduled.
    fn observe_dismiss_request(&mut self, ctx: &mut EventCtx) {
        let Some(request) = self.pending_dismiss_request() else {
            return;
        };
        match self.stage_dismiss(DismissSource::App) {
            DismissStage::Refused => self.latch_dismiss_request(request),
            DismissStage::Ramping => {
                self.accept_dismiss_request(request);
                ctx.request_redraw();
            }
            DismissStage::Unstaged => {
                // `on_close` first: it is the only unstaged route that can
                // carry this request's payload, so it is the only one that
                // takes it. `on_dismiss` is the fallback for a mount that wired
                // no close hook at all — a `Stack`-mounted dialog or side
                // sheet, whose handle would otherwise be inert (the same
                // fallback [`crate::sheet`]'s host applies, so both hosts
                // behave identically here) — and it carries no payload, which
                // therefore stays with the handle, undelivered.
                if self.on_close.is_some() {
                    self.accept_dismiss_request(request);
                    self.fire_close_now();
                } else {
                    self.latch_dismiss_request(request);
                    self.fire_dismiss_now(ctx);
                }
            }
        }
    }

    /// The paint-pass twin of [`Self::observe_dismiss_request`] — the backstop
    /// for a request raised outside an event (an async completion, a timer).
    /// Firing an unstaged close from here must itself request the frame whose
    /// rebuild drains the enqueued pop (the drain gotcha the module docs spell
    /// out).
    fn observe_paint_dismiss_request(&mut self, ctx: &mut PaintCtx) {
        let Some(request) = self.pending_dismiss_request() else {
            return;
        };
        match self.stage_dismiss(DismissSource::App) {
            DismissStage::Refused => self.latch_dismiss_request(request),
            DismissStage::Ramping => {
                self.accept_dismiss_request(request);
                self.request_continuation(ctx);
            }
            // Only the state-free `on_close` is reachable from a paint, the
            // same limit [`Self::observe_dismiss_signal`] works under. With one
            // wired this fires it; with none, this pass can do *nothing* at all
            // with the request, so it is deliberately left unlatched for the
            // event pass's `on_dismiss` fallback rather than swallowed here.
            // Nothing was staged either way, so a request left pending costs a
            // peek per frame and no state.
            DismissStage::Unstaged => {
                if self.on_close.is_some() {
                    self.accept_dismiss_request(request);
                    if self.fire_close_now() {
                        ctx.request_frame();
                    }
                }
            }
        }
    }

    /// Observe the shared back-press dismiss-signal cell and stage the exit
    /// exactly once per bump — the [`BackPolicy::DismissAnimated`] seam's
    /// widget-side half (see the module docs' back-dismiss section). A back
    /// request flags `PAINT`, so this always runs before the next frame is
    /// shown.
    ///
    /// The paint-pass twin of [`Self::request_dismiss`]: the same
    /// [`Self::stage_dismiss`] core, except that the unstaged fallback can only
    /// reach the state-free `on_close` (no `&mut State` exists here), and
    /// firing it must itself request the frame whose rebuild drains the
    /// enqueued pop — the drain gotcha the module docs spell out.
    fn observe_dismiss_signal(&mut self, ctx: &mut PaintCtx) {
        let Some(signal) = &self.dismiss_signal else {
            return;
        };
        let current = signal.get();
        if current == self.last_seen_dismiss {
            return;
        }
        self.last_seen_dismiss = current;
        match self.stage_dismiss(DismissSource::User) {
            DismissStage::Refused => {}
            DismissStage::Ramping => self.request_continuation(ctx),
            DismissStage::Unstaged => {
                if self.fire_close_now() {
                    ctx.request_frame();
                }
            }
        }
    }

    /// Move the panel to `progress` without animating — the drag scrub. The
    /// panel keeps the extent layout gave it and only its origin moves, so no
    /// relayout is owed.
    ///
    /// A live drag takes the panel over from whatever ramp was running,
    /// including an exit: catching a closing sheet cancels its dismissal —
    /// payload included, the same rule [`Self::begin_ramp`]'s reopening legs
    /// apply — and the release decides again from where the finger left it.
    fn scrub(&mut self, ctx: &mut EventCtx, progress: f64) {
        if (progress - self.progress).abs() < PROGRESS_EPSILON {
            return;
        }
        self.anim.stop();
        self.exiting = false;
        self.pending_result = None;
        self.progress = progress;
        self.ramp = (progress, progress);
        self.reposition(ctx.size());
        ctx.request_redraw();
    }

    /// Re-place an edge-pinned panel (and its content) for the current progress,
    /// inside an area of `area`.
    fn reposition(&mut self, area: Size) {
        let OverlayGeometry::Edge { side, .. } = self.config.geometry else {
            return;
        };
        let size = self.panel.size();
        let origin = edge_origin(side, area, size, self.progress);
        self.panel = Rect::from_origin_size(origin, size);
        self.content.set_origin(origin);
    }

    /// Open a drag from `position`, remembering where along the axis it started
    /// and what progress it started from.
    fn begin_drag(&mut self, ctx: &mut EventCtx, position: Point, on_handle: bool) {
        self.drag_captured = true;
        self.drag_on_handle = on_handle;
        self.drag_moved = false;
        self.drag_start = self.axis_pos(position);
        self.drag_from = self.progress;
        self.tracker.clear();
        self.tracker.record(self.event_time_ms(), self.drag_start);
        ctx.capture_pointer();
    }

    /// Track a captured drag: sample the velocity, and once the gesture has
    /// passed [`TOUCH_SLOP`] scrub the panel to follow the pointer.
    ///
    /// The scrub measures from the `Down`, slop included — unlike
    /// `frust_widgets::scroll`, which re-baselines when it *takes the gesture
    /// over* from a child. Nothing is taken over here (the panel captured the
    /// press outright; the slop only separates a tap from a drag), so
    /// re-baselining would leave the panel trailing the finger for the rest of
    /// the gesture.
    fn drag_move(&mut self, ctx: &mut EventCtx, position: Point) {
        let axis = self.axis_pos(position);
        self.tracker.record(self.event_time_ms(), axis);
        let delta = axis - self.drag_start;
        if !self.drag_moved && delta.abs() > TOUCH_SLOP {
            self.drag_moved = true;
        }
        if !self.drag_moved {
            return;
        }
        let extent = self.extent();
        if extent <= 0.0 {
            return;
        }
        // Dragging toward the closing edge lowers progress; the panel can be
        // pushed no further open than its own furthest resting point.
        let open = self.snap_targets().last().copied().unwrap_or(1.0);
        let target = self.drag_from - self.close_sign() * delta / extent;
        // Ordered explicitly rather than `clamp`: `open` is computed from the
        // live snap targets, and clamp bounds must be provably ordered and
        // finite (see the [module docs](self)'s Clamp Discipline section).
        // `f64::max`/`f64::min` also can't panic the way `clamp`'s internal
        // `assert!(min <= max)` would if a NaN ever reached `open`.
        self.scrub(ctx, target.max(0.0).min(open));
    }

    /// The resting point a release settles to: the nearest one, or — past
    /// [`OVERLAY_FLING_VELOCITY`] — the next one along the direction of travel.
    fn release_target(&self, velocity: f64) -> f64 {
        let targets = self.snap_targets();
        let nearest = |p: f64| {
            targets
                .iter()
                .copied()
                .min_by(|a, b| {
                    (a - p)
                        .abs()
                        .partial_cmp(&(b - p).abs())
                        .unwrap_or(std::cmp::Ordering::Equal)
                })
                .unwrap_or(0.0)
        };
        if velocity.abs() >= OVERLAY_FLING_VELOCITY {
            // A flick toward the closing edge takes the next point down, one
            // away from it the next point up.
            let opening = velocity * self.close_sign() < 0.0;
            let next = if opening {
                targets.iter().copied().find(|t| *t > self.progress)
            } else {
                targets.iter().rev().copied().find(|t| *t < self.progress)
            };
            if let Some(next) = next {
                return next;
            }
        }
        nearest(self.progress)
    }

    /// Settle a released drag: continue into the exit ramp when it landed
    /// closed, otherwise ramp back to the point it snapped to.
    ///
    /// A closed landing on a panel that cannot dismiss springs back to
    /// [`Self::open_progress`] instead of staging an exit:
    /// [`Self::request_dismiss`] no-ops there, and by the time a drag settles
    /// `progress` has already tracked the pointer down near `0.0` (unlike the
    /// tap-to-dismiss paths, which never move it) — a bare no-op would leave the
    /// panel resting there, an invisible full-window input barrier with nothing
    /// to recover it.
    fn settle_drag(&mut self, ctx: &mut EventCtx, target: f64) {
        if target <= PROGRESS_EPSILON {
            if self.can_dismiss() {
                self.request_dismiss(ctx);
            } else {
                self.begin_ramp(self.open_progress(), false);
                ctx.request_redraw();
            }
        } else {
            self.begin_ramp(target, false);
            ctx.request_redraw();
        }
    }
}

impl<State: 'static> View<State> for OverlayModalView<State> {
    type Element = OverlayModalWidget;

    fn build(&self, ctx: &mut BuildCtx<'_>) -> OverlayModalWidget {
        let settled = self.config.entrance == OverlayEntrance::None;
        OverlayModalWidget {
            content: build_child(&self.content, ctx),
            config: self.config,
            label: self.label.clone(),
            dismissable: self.dismissable,
            on_dismiss: self.on_dismiss.as_ref().map(erase_callback),
            on_close: self.on_close.clone(),
            dismiss_signal: None,
            last_seen_dismiss: 0,
            // Seeded from the handle's *current* generation: a request raised
            // before this widget existed is not aimed at it (the same rule
            // `StagedExit` applies to the back-press cell).
            last_seen_request: self
                .dismiss_handle
                .as_ref()
                .map_or(0, ModalDismiss::generation),
            dismiss_handle: self.dismiss_handle.clone(),
            pending_result: None,
            snap_points: self.snap_points.clone(),
            panel: Rect::ZERO,
            anim: AnimationController::new(self.config.entrance.duration())
                .with_curve(self.config.entrance.curve(false)),
            // The entrance's target resolves on the first paint, not here: a
            // snap point in logical px needs the extent layout has yet to
            // measure.
            ramp: (0.0, 1.0),
            progress: if settled { 1.0 } else { 0.0 },
            started: settled,
            exiting: false,
            closed: false,
            dismissed: false,
            scrim_captured: false,
            scrim_down_outside: false,
            close_hovered: false,
            close_captured: false,
            handle_hovered: false,
            handle_captured: false,
            drag_captured: false,
            drag_start: 0.0,
            drag_from: 0.0,
            drag_on_handle: false,
            drag_moved: false,
            tracker: VelocityTracker::new(),
            last_frame_time: FrameTime::ZERO,
        }
    }

    fn rebuild(
        &self,
        prev: &Self,
        element: &mut OverlayModalWidget,
        ctx: &mut BuildCtx<'_>,
    ) -> ChangeFlags {
        let mut flags = rebuild_child(&prev.content, &self.content, &mut element.content, ctx);
        if element.config != self.config {
            element.config = self.config;
            flags |= ChangeFlags::LAYOUT | ChangeFlags::PAINT;
        }
        if element.label != self.label {
            element.label = self.label.clone();
            flags |= ChangeFlags::PAINT;
        }
        if element.dismissable != self.dismissable {
            element.dismissable = self.dismissable;
        }
        if element.snap_points != self.snap_points {
            element.snap_points = self.snap_points.clone();
            flags |= ChangeFlags::LAYOUT | ChangeFlags::PAINT;
        }
        // The app's dismiss handle follows the view whenever the view still
        // carries one: an app that mints one per page-builder pass (rather than
        // once, outside it — see `ModalDismiss`) would otherwise leave the
        // widget latched to the first pass's dead cell while its buttons bump
        // the newest one. Re-seeding is gated on *identity*, so the live
        // request generation survives every rebuild that hands the same handle
        // back; a view that stopped carrying one leaves the installed handle
        // standing, the same pinning `on_close` documents.
        if let Some(handle) = &self.dismiss_handle
            && !element
                .dismiss_handle
                .as_ref()
                .is_some_and(|installed| installed.same_cell(handle))
        {
            element.last_seen_request = handle.generation();
            element.dismiss_handle = Some(handle.clone());
        }
        // `on_dismiss` is reinstalled unconditionally (cheap — closures aren't
        // comparable, so this is what every interactive widget does).
        // `on_close` and `dismiss_signal` are deliberately left untouched here —
        // see `OverlayModalWidget::on_close`'s field doc for why.
        element.on_dismiss = self.on_dismiss.as_ref().map(erase_callback);
        flags
    }

    fn teardown(&self, element: &mut OverlayModalWidget, ctx: &mut BuildCtx<'_>) {
        teardown_child(&self.content, &mut element.content, ctx);
    }
}

/// Lay the panel out and place the content inside it.
///
/// Split out of [`Widget::layout`] so the geometry is one readable expression
/// per [`OverlayGeometry`] arm; returns the panel rect (already offset by the
/// slide progress, if any).
fn layout_panel(
    content: &mut ChildPod,
    ctx: &mut LayoutCtx,
    config: OverlayModalConfig,
    area: Size,
    progress: f64,
) -> Rect {
    match config.geometry {
        OverlayGeometry::Centered { max_width } => {
            let available = (area.width - 2.0 * CENTERED_MARGIN).max(0.0);
            // The M3 [280, 560] clamp, with the viewport margin winning on a
            // window too narrow for the minimum.
            let width = max_width
                .min(available)
                .max(OVERLAY_DIALOG_MIN_WIDTH.min(available));
            let max_height = (area.height - 2.0 * CENTERED_MARGIN).max(0.0);
            // A tight width, a loose height: the panel is as tall as its
            // content, up to the area.
            let measured = content.layout_child(
                ctx,
                &BoxConstraints::new(Size::new(width, 0.0), Size::new(width, max_height)),
            );
            let height = measured.height.min(max_height);
            let origin = Point::new(
                ((area.width - width) / 2.0).max(0.0),
                ((area.height - height) / 2.0).max(0.0),
            );
            let panel = Rect::from_origin_size(origin, Size::new(width, height));
            content.set_origin(panel.origin());
            panel
        }
        OverlayGeometry::Edge {
            side,
            extent,
            limit,
        } => {
            let (axis_area, cross) = if side.is_vertical() {
                (area.height, area.width)
            } else {
                (area.width, area.height)
            };
            let cap = limit.apply(axis_area, axis_area);
            let thickness = match extent {
                OverlayExtent::Fraction(f) => limit.apply(axis_area * f, axis_area),
                OverlayExtent::Content => {
                    let bc = if side.is_vertical() {
                        BoxConstraints::new(Size::new(cross, 0.0), Size::new(cross, cap))
                    } else {
                        BoxConstraints::new(Size::new(0.0, cross), Size::new(cap, cross))
                    };
                    let measured = content.layout_child(ctx, &bc);
                    let along = if side.is_vertical() {
                        measured.height
                    } else {
                        measured.width
                    };
                    along.min(cap)
                }
            };
            let size = if side.is_vertical() {
                Size::new(cross, thickness)
            } else {
                Size::new(thickness, cross)
            };
            if extent != OverlayExtent::Content {
                content.layout_child(ctx, &BoxConstraints::tight(size));
            }
            let origin = edge_origin(side, area, size, progress);
            let panel = Rect::from_origin_size(origin, size);
            content.set_origin(panel.origin());
            panel
        }
    }
}

/// Where an edge-pinned panel of `size` sits inside `area` at `progress`: at
/// `0.0` entirely outside its own edge, at `1.0` flush against it, in between
/// the fraction of it the slide (or a drag) has brought in.
///
/// Shared by [`layout_panel`] and the drag scrub, which moves the panel between
/// layout passes and must place it identically.
fn edge_origin(side: OverlaySide, area: Size, size: Size, progress: f64) -> Point {
    let thickness = if side.is_vertical() {
        size.height
    } else {
        size.width
    };
    let out = thickness * (1.0 - progress);
    match side {
        OverlaySide::Top => Point::new(0.0, -out),
        OverlaySide::Bottom => Point::new(0.0, area.height - thickness + out),
        OverlaySide::Left => Point::new(-out, 0.0),
        OverlaySide::Right => Point::new(area.width - thickness + out, 0.0),
    }
}

/// Stroke the panel's outline per [`OverlayBorder`].
fn paint_border(
    scene: &mut dyn PaintScene,
    origin: Point,
    size: Size,
    border: OverlayBorder,
    color: Color,
) {
    let half = BORDER_WIDTH / 2.0;
    let (from, to) = match border {
        OverlayBorder::None => return,
        OverlayBorder::All => {
            // Inset by half the stroke width so the hairline paints fully
            // inside the panel's own bounds (a stroke is centred on its path) —
            // the `crate::card` outlined precedent.
            let mut path = BezPath::new();
            path.move_to(Point::new(half, half));
            path.line_to(Point::new(size.width - half, half));
            path.line_to(Point::new(size.width - half, size.height - half));
            path.line_to(Point::new(half, size.height - half));
            path.close_path();
            scene.stroke_path(origin, &path, BORDER_WIDTH, &Brush::Solid(color));
            return;
        }
        OverlayBorder::Edge(OverlaySide::Top) => {
            (Point::new(0.0, half), Point::new(size.width, half))
        }
        OverlayBorder::Edge(OverlaySide::Bottom) => (
            Point::new(0.0, size.height - half),
            Point::new(size.width, size.height - half),
        ),
        OverlayBorder::Edge(OverlaySide::Left) => {
            (Point::new(half, 0.0), Point::new(half, size.height))
        }
        OverlayBorder::Edge(OverlaySide::Right) => (
            Point::new(size.width - half, 0.0),
            Point::new(size.width - half, size.height),
        ),
    };
    let mut path = BezPath::new();
    path.move_to(from);
    path.line_to(to);
    scene.stroke_path(origin, &path, BORDER_WIDTH, &Brush::Solid(color));
}

/// Return `color` with its own alpha scaled by `factor` — how the scrim rides
/// the ramp.
fn scale_alpha(color: Color, factor: f32) -> Color {
    let c = color.components;
    Color::new([c[0], c[1], c[2], c[3] * factor])
}

/// Whether `pos` falls inside an optional hit box (`false` when the box is not
/// shown at all).
fn hit(rect: Option<Rect>, pos: Point) -> bool {
    rect.is_some_and(|r| r.contains(pos))
}

impl Widget for OverlayModalWidget {
    fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
        let area = Size::new(
            finite_or_zero(bc.max().width),
            finite_or_zero(bc.max().height),
        );
        self.panel = layout_panel(&mut self.content, ctx, self.config, area, self.progress);
        bc.constrain(area)
    }

    fn paint(&mut self, ctx: &mut PaintCtx, scene: &mut dyn PaintScene) {
        // The back-press seam, first: a bump staged here rides the very same
        // ramp the pointer/key gestures below drive. The app's own handle is
        // observed alongside it, as the backstop for a request raised outside
        // an event pass.
        self.observe_dismiss_signal(ctx);
        self.observe_paint_dismiss_request(ctx);
        // Authoritative hover read: a pointer that left this widget sends it no
        // event at all, so the chrome's latched flags are cleared whenever the
        // hover path no longer runs through here. It cannot *set* them — the
        // path is true for a hovered content child too — which is what the
        // per-region latches in `event` are for.
        if !ctx.is_hovered() {
            self.close_hovered = false;
            self.handle_hovered = false;
        }
        let (origin, size) = (ctx.origin(), ctx.size());
        let now = ctx.frame_time();
        // Every theme read in one scope: the `&Theme` borrows the context, and
        // the child paint plus the frame requests below need it mutably.
        let (reduce, radius, scrim, fill, border, ink, handle_color, shadow) = {
            let theme = Theme::from_paint_ctx(ctx);
            (
                reduce_motion(theme),
                super::radius(theme),
                super::scrim(theme),
                super::container(theme, self.config.container),
                super::outline_variant(theme),
                super::on_surface(theme),
                super::on_surface_variant(theme),
                super::shadow(theme, self.config.elevation),
            )
        };

        // The event pass has no clock of its own; this is the one it reads.
        self.last_frame_time = now;

        // Advance (or collapse) the running ramp. The entrance's target
        // resolves here, on the first paint, because a snap point in logical px
        // needs the extent the layout before it measured.
        if !self.started {
            self.started = true;
            self.ramp = (0.0, self.open_progress());
            if !reduce {
                self.anim.forward();
            }
        }
        let next = if reduce {
            if self.anim.is_animating() {
                self.anim.stop();
            }
            self.ramp.1
        } else if self.anim.is_animating() {
            // `advance`'s first call after `forward()` only seeds the clock
            // (zero delta, but still truthy) — the continuation has to be
            // requested on every truthy advance, not just the ones that moved
            // `progress`, or a slide's seeding paint never schedules the frame
            // that would carry it off zero.
            if self.anim.advance(now) {
                self.request_continuation(ctx);
            }
            self.ramp_value()
        } else {
            self.progress
        };
        if (next - self.progress).abs() > PROGRESS_EPSILON {
            self.progress = next;
            self.request_continuation(ctx);
        }
        // A settled exit is where the deferred dismissal is finally fired. The
        // hook only *enqueues* a navigator pop (it writes no tracked signal), so
        // this paint asks for the frame whose rebuild drains it — otherwise a
        // `ControlFlow::Wait` desktop shell idles and the modal never leaves.
        if self.exiting && !self.anim.is_animating() && self.progress <= PROGRESS_EPSILON {
            self.exiting = false;
            self.progress = 0.0;
            // Cloned out of `self` so the recovery arm below can take `&mut
            // self`; it is an `Rc`, and this runs once per exit.
            if let Some(on_close) = self.on_close.clone() {
                // With whatever payload an app dismissal armed.
                if on_close.fire_with(&mut self.pending_result) {
                    self.closed = true;
                    ctx.request_frame();
                } else {
                    // The stack moved under the staged pop, so it was refused
                    // ([`StagedPop`]). Do **not** latch `closed`: that latch is
                    // terminal and would leave an invisible, undismissable
                    // barrier standing over a page this widget never removed.
                    // Ramp back open instead — the panel is recoverable, and a
                    // later dismiss stages a fresh, correctly-armed exit. That
                    // reopening leg also drops the payload this exit was
                    // carrying (`begin_ramp`): it was scoped to a pop that
                    // never happened, and must not ride the next dismissal.
                    self.begin_ramp(self.open_progress(), false);
                    self.request_continuation(ctx);
                }
            }
        }
        let progress = self.progress;

        // The scrim fades with the panel, and covers the whole area.
        scene.fill_rect(origin, size, scale_alpha(scrim, progress as f32));

        let panel_origin = Point::new(origin.x + self.panel.x0, origin.y + self.panel.y0);
        let panel_size = self.panel.size();
        let radii = self.config.corners.radii(radius);
        let fade_scale = self.config.entrance == OverlayEntrance::FadeScale && progress < 1.0;
        if fade_scale {
            // Composite the panel at the ramp's alpha. The layer rect is
            // inflated so the elevation shadow, which reaches outside the panel,
            // is not clipped out of it.
            let layer = Rect::from_origin_size(panel_origin, panel_size)
                .inflate(SHADOW_SPILL, SHADOW_SPILL);
            scene.push_layer(layer.origin(), layer.size(), progress as f32);
            // …and scale about the panel's own centre.
            let c = Rect::from_origin_size(panel_origin, panel_size).center();
            let scale = SCALE_FROM + (1.0 - SCALE_FROM) * progress;
            scene.push_transform(
                Affine::translate(c.to_vec2())
                    * Affine::scale(scale)
                    * Affine::translate(-c.to_vec2()),
            );
        }

        if let Some((blur, y_offset, color)) = shadow {
            scene.draw_shadow(
                Point::new(panel_origin.x, panel_origin.y + y_offset),
                panel_size,
                radii.largest(),
                blur,
                color,
            );
        }
        scene.fill_rounded_rect_radii(panel_origin, panel_size, radii, fill);

        // The content is clipped to the panel: a scrolling panel needs it, and
        // it is what keeps a too-tall panel's content inside the window.
        scene.push_clip_rounded_radii(panel_origin, panel_size, radii);
        self.content.paint_child(ctx, scene);
        scene.pop_clip();

        paint_border(scene, panel_origin, panel_size, self.config.border, border);

        if self.config.close_button {
            // M3 has no rest-state opacity ramp on an icon (a state layer does
            // the hover work): the affordance sits in `onSurfaceVariant` and
            // steps up to `onSurface` when hovered — the source's
            // `opacity-70 hover:opacity-100`, re-expressed in roles.
            let color = if self.close_hovered {
                ink
            } else {
                handle_color
            };
            let (path, design) = IconData::from(crate::icons::CLOSE).resolve();
            let scale = if design > 0.0 {
                CLOSE_ICON / design
            } else {
                1.0
            };
            let icon_origin = Point::new(
                origin.x + self.panel.x1 - CLOSE_INSET - CLOSE_ICON,
                origin.y + self.panel.y0 + CLOSE_INSET,
            );
            scene.fill_path(
                icon_origin,
                &(Affine::scale(scale) * path),
                &Brush::Solid(color),
            );
        }
        if self.config.handle {
            let bar = self.handle_bar();
            scene.fill_rounded_rect(
                Point::new(origin.x + bar.x0, origin.y + bar.y0),
                bar.size(),
                bar.height() / 2.0,
                handle_color,
            );
        }

        if fade_scale {
            scene.pop_transform();
            scene.pop_layer();
        }
    }

    fn event(&mut self, ctx: &mut EventCtx, event: &InputEvent) -> EventResult {
        // Claim focus on every `Down` — the `crate::dialog`/`crate::sheet`
        // opt-in that makes Escape reachable, and what keeps the root's focus
        // session alive while the modal is up (re-claiming while focused is a
        // no-op; a claim-once guard would kill the session on the second tap).
        if matches!(event, InputEvent::Pointer(p) if p.phase == PointerPhase::Down) {
            ctx.request_focus();
        }
        // Content first: an action inside the panel owns its own events, and
        // this widget's own hover claims come after the routing — *unless* this
        // widget already holds the gesture. A capture recorded here (a barrier
        // press, a live drag) means the content declined the `Down` that opened
        // it, so re-routing its `Move`s would let a control the pointer happens
        // to travel over steal a drag mid-flight. Broadcasts and focus-routed
        // events are never short-circuited.
        let captured = self.close_captured
            || self.handle_captured
            || self.scrim_captured
            || self.drag_captured;
        let own_gesture = captured && matches!(event, InputEvent::Pointer(_));
        if !own_gesture {
            let handled = route_event_single(&mut self.content, ctx, event) == EventResult::Handled;
            // An action the content just ran may have asked to dismiss through
            // the app's own handle: stage it in this pass rather than leaving
            // it to a paint the content did not necessarily schedule.
            //
            // Observed whatever the routing reported, not only on `Handled`:
            // this is also the *state-bearing* pass a request raised anywhere
            // else (an async completion, a timer) waits for when the panel has
            // no staged close hook to fire from `paint` — see the module docs'
            // *What a request consumes*. [`crate::sheet`]'s host observes as
            // broadly, which is what keeps the two seams interchangeable.
            self.observe_dismiss_request(ctx);
            if handled {
                return EventResult::Handled;
            }
        }
        if let InputEvent::Key(key) = event {
            if key.key == Key::Named(NamedKey::Escape) {
                self.request_dismiss(ctx);
            }
            // The barrier swallows every other key too: nothing behind a modal
            // may act on a keystroke its content declined.
            return EventResult::Handled;
        }
        let InputEvent::Pointer(p) = event else {
            return EventResult::Ignored;
        };
        // A secondary press is swallowed like every other one — a modal blocks
        // the page behind it whatever button pressed — but it operates nothing:
        // no close press, no drag, no scrim-dismiss arming. Only the primary
        // button does any of that (the catalog's press rule), and the panel's
        // own content, routed above, has already had its chance at the event (a
        // context menu inside the panel still opens).
        if !presses(p) && p.phase != PointerPhase::Move {
            return EventResult::Handled;
        }
        let (close, handle) = (self.close_rect(), self.handle_rect());
        match p.phase {
            PointerPhase::Move => {
                if self.drag_captured {
                    // A captured drag re-asks for its cursor from its own arm,
                    // so the shape survives the pointer leaving the panel.
                    ctx.set_cursor(CursorIcon::Grabbing);
                    self.drag_move(ctx, p.position);
                    return EventResult::Handled;
                }
                if self.close_captured || self.handle_captured || self.scrim_captured {
                    if self.close_captured || self.handle_captured {
                        ctx.set_cursor(CursorIcon::Pointer);
                    }
                    return EventResult::Handled;
                }
                let over_close = hit(close, p.position);
                let over_handle = hit(handle, p.position);
                if over_close || over_handle {
                    // Claimed *after* the content routing above.
                    ctx.claim_hover();
                    if over_handle && self.config.drag {
                        // A draggable handle advertises the gesture.
                        ctx.set_cursor(CursorIcon::Grab);
                    } else {
                        ctx.set_cursor(CursorIcon::Pointer);
                    }
                }
                if self.close_hovered != over_close {
                    self.close_hovered = over_close;
                    ctx.request_redraw();
                }
                if self.handle_hovered != over_handle {
                    self.handle_hovered = over_handle;
                    ctx.request_redraw();
                }
                EventResult::Ignored
            }
            PointerPhase::Down => {
                if hit(close, p.position) {
                    self.close_captured = true;
                    ctx.capture_pointer();
                    return EventResult::Handled;
                }
                // A draggable panel takes the press as a drag — from the handle
                // or from the panel's own surface — and still resolves it as a
                // tap if it never moves.
                if self.config.drag && (hit(handle, p.position) || self.panel.contains(p.position))
                {
                    self.begin_drag(ctx, p.position, hit(handle, p.position));
                    return EventResult::Handled;
                }
                if hit(handle, p.position) {
                    self.handle_captured = true;
                    ctx.capture_pointer();
                    return EventResult::Handled;
                }
                // An invisible panel absorbs nothing — `super::anchored`'s own
                // closed-state gate, ported: a widget still mounted behind an
                // enqueued pop (or one whose entrance has not drawn its first
                // frame) paints no scrim and no panel, and a barrier that
                // swallows what it does not show is an invisible input trap.
                if self.progress <= PROGRESS_EPSILON {
                    return EventResult::Ignored;
                }
                // The modal barrier: swallow, and remember whether the press
                // started outside the panel.
                self.scrim_captured = true;
                self.scrim_down_outside = !self.panel.contains(p.position);
                ctx.capture_pointer();
                EventResult::Handled
            }
            PointerPhase::Up => {
                if self.close_captured {
                    self.close_captured = false;
                    if hit(close, p.position) {
                        self.request_dismiss(ctx);
                    }
                    return EventResult::Handled;
                }
                if self.handle_captured {
                    self.handle_captured = false;
                    if hit(handle, p.position) {
                        self.request_dismiss(ctx);
                    }
                    return EventResult::Handled;
                }
                if self.drag_captured {
                    self.drag_captured = false;
                    if !self.drag_moved {
                        // A tap, not a drag: on the handle it dismisses, on the
                        // panel it is an ordinary swallowed barrier press.
                        if self.drag_on_handle && hit(handle, p.position) {
                            self.request_dismiss(ctx);
                        }
                        return EventResult::Handled;
                    }
                    let target = self.release_target(self.tracker.velocity());
                    self.settle_drag(ctx, target);
                    return EventResult::Handled;
                }
                if !self.scrim_captured {
                    return EventResult::Ignored;
                }
                self.scrim_captured = false;
                let released_outside = !self.panel.contains(p.position);
                if self.config.scrim_dismiss && self.scrim_down_outside && released_outside {
                    self.request_dismiss(ctx);
                }
                EventResult::Handled
            }
            PointerPhase::Cancel => {
                // A `Cancel` arm never touches app state — flags only, plus the
                // ramp back to where the drag started.
                self.close_captured = false;
                self.handle_captured = false;
                self.scrim_captured = false;
                if self.drag_captured {
                    self.drag_captured = false;
                    if self.drag_moved {
                        self.begin_ramp(self.drag_from, false);
                        ctx.request_redraw();
                    }
                }
                EventResult::Handled
            }
        }
    }

    fn semantics(&self, ctx: &mut SemanticsCtx) {
        let label = self.label.clone();
        ctx.push_container(
            self.config.role.role(),
            |node| {
                node.set_modal();
                if let Some(label) = &label {
                    node.set_label(label.as_str());
                }
            },
            |ctx| self.content.semantics_child(ctx),
        );
    }

    visit_children!(content);
}

#[cfg(test)]
mod tests {
    use super::*;
    use frust::authoring::text::TextContext;
    use frust::authoring::{
        KeyEvent, Modifiers, PointerButton, PointerEvent, Shape, any as core_any,
    };
    use frust::{Brightness, NavigatorView};
    use frust_core::RenderRoot;
    use frust_widgets::navigator;
    use std::any::Any;

    /// The window every modal test lays out in.
    const WINDOW: Size = Size::new(400.0, 600.0);

    /// A recording `PaintScene`: the fills, paths, strokes, clips, shadows and
    /// fade layers a modal emits.
    #[derive(Default)]
    struct Recorder {
        /// `fill_rect` calls — the scrim is the first of them.
        rects: Vec<(Point, Size, Color)>,
        /// `fill_rounded_rect_radii` calls — the panel.
        panels: Vec<(Point, Size, CornerRadii, Color)>,
        /// `fill_rounded_rect` calls — the drag handle.
        rrects: Vec<(Point, Size, f64, Color)>,
        /// `fill_path` calls, as `(origin, bounding box, color)` — the close
        /// icon.
        paths: Vec<(Point, Rect, Color)>,
        /// `stroke_path` calls, as `(bounding box, width, color)`.
        strokes: Vec<(Rect, f64, Color)>,
        /// `draw_shadow` calls.
        shadows: Vec<(Point, Size, f64, f64, Color)>,
        /// `push_clip*` calls.
        clips: Vec<(Point, Size)>,
        /// `push_layer` alphas — the fade.
        layers: Vec<f32>,
        /// `push_transform` affines — the scale.
        transforms: Vec<Affine>,
    }

    impl PaintScene for Recorder {
        fn fill_rect(&mut self, origin: Point, size: Size, color: Color) {
            self.rects.push((origin, size, color));
        }
        fn draw_text(&mut self, _origin: Point, _text: &str) {}
        fn fill_rounded_rect(&mut self, origin: Point, size: Size, radius: f64, color: Color) {
            self.rrects.push((origin, size, radius, color));
        }
        fn fill_rounded_rect_radii(
            &mut self,
            origin: Point,
            size: Size,
            radii: CornerRadii,
            color: Color,
        ) {
            self.panels.push((origin, size, radii, color));
        }
        fn fill_path(&mut self, origin: Point, path: &BezPath, brush: &Brush) {
            let color = match brush {
                Brush::Solid(c) => *c,
                _ => Color::TRANSPARENT,
            };
            self.paths.push((origin, path.bounding_box(), color));
        }
        fn stroke_path(&mut self, origin: Point, path: &BezPath, width: f64, brush: &Brush) {
            let color = match brush {
                Brush::Solid(c) => *c,
                _ => Color::TRANSPARENT,
            };
            self.strokes
                .push((path.bounding_box() + origin.to_vec2(), width, color));
        }
        fn draw_shadow(
            &mut self,
            origin: Point,
            size: Size,
            radius: f64,
            std_dev: f64,
            color: Color,
        ) {
            self.shadows.push((origin, size, radius, std_dev, color));
        }
        fn push_clip(&mut self, origin: Point, size: Size) {
            self.clips.push((origin, size));
        }
        fn push_clip_rounded(&mut self, origin: Point, size: Size, _radius: f64) {
            self.clips.push((origin, size));
        }
        fn push_clip_rounded_radii(&mut self, origin: Point, size: Size, _radii: CornerRadii) {
            self.clips.push((origin, size));
        }
        fn pop_clip(&mut self) {}
        fn push_layer(&mut self, _origin: Point, _size: Size, alpha: f32) {
            self.layers.push(alpha);
        }
        fn pop_layer(&mut self) {}
        fn push_transform(&mut self, transform: Affine) {
            self.transforms.push(transform);
        }
        fn pop_transform(&mut self) {}
    }

    /// A fixed-size leaf generic over the app state, for a modal's content.
    struct Block(Size);

    /// The retained half of [`Block`].
    struct BlockWidget(Size);

    impl<S: 'static> View<S> for Block {
        type Element = BlockWidget;
        fn build(&self, _ctx: &mut BuildCtx<'_>) -> BlockWidget {
            BlockWidget(self.0)
        }
        fn rebuild(
            &self,
            _prev: &Self,
            element: &mut BlockWidget,
            _ctx: &mut BuildCtx<'_>,
        ) -> ChangeFlags {
            element.0 = self.0;
            ChangeFlags::NONE
        }
    }

    impl Widget for BlockWidget {
        fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            bc.constrain(self.0)
        }
        fn paint(&mut self, _ctx: &mut PaintCtx, _scene: &mut dyn PaintScene) {}
    }

    /// A frame time `ms` milliseconds in.
    fn ft_ms(ms: f64) -> FrameTime {
        FrameTime::from_nanos((ms * 1_000_000.0) as u64)
    }

    /// A pointer event at `(x, y)`.
    fn pointer(phase: PointerPhase, x: f64, y: f64) -> InputEvent {
        InputEvent::Pointer(PointerEvent {
            phase,
            position: Point::new(x, y),
            button: PointerButton::Primary,
        })
    }

    /// An Escape key event.
    fn escape() -> InputEvent {
        InputEvent::Key(KeyEvent {
            key: Key::Named(NamedKey::Escape),
            modifiers: Modifiers::default(),
            repeat: false,
        })
    }

    #[derive(Default)]
    struct Flags {
        dismissed: u32,
    }

    fn build(view: &OverlayModalView<Flags>) -> OverlayModalWidget {
        let mut counter = 0u64;
        View::<Flags>::build(view, &mut BuildCtx::new(&mut counter))
    }

    fn rebuild(
        view: &OverlayModalView<Flags>,
        prev: &OverlayModalView<Flags>,
        w: &mut OverlayModalWidget,
    ) {
        let mut counter = 0u64;
        View::<Flags>::rebuild(view, prev, w, &mut BuildCtx::new(&mut counter));
    }

    fn layout(w: &mut OverlayModalWidget) -> Size {
        let mut tcx = TextContext::new();
        let mut lctx = LayoutCtx::with_text_context(&mut tcx as &mut dyn Any);
        w.layout(&mut lctx, &BoxConstraints::tight(WINDOW))
    }

    fn dispatch(w: &mut OverlayModalWidget, state: &mut Flags, event: &InputEvent) -> EventResult {
        let state_any: &mut dyn Any = state;
        let mut ctx = EventCtx::new(state_any, Point::ZERO, WINDOW);
        w.event(&mut ctx, event)
    }

    fn view(config: OverlayModalConfig) -> OverlayModalView<Flags> {
        overlay_modal(Block(Size::new(200.0, 120.0)), config)
            .on_dismiss(|s: &mut Flags| s.dismissed += 1)
    }

    /// A modal wired the way [`show_overlay_modal`] wires one: a state-free
    /// close hook (here a counter) alongside the unstaged `on_dismiss`, so the
    /// staged exit path is the one taken.
    fn staged(config: OverlayModalConfig) -> (OverlayModalView<Flags>, Rc<Cell<u32>>) {
        let closed = Rc::new(Cell::new(0u32));
        let hook = closed.clone();
        let view = view(config).on_close(move || hook.set(hook.get() + 1));
        (view, closed)
    }

    /// Paint one frame at `ms` and return what it drew.
    fn frame(w: &mut OverlayModalWidget, ms: f64) -> Recorder {
        let mut rec = Recorder::default();
        let mut ctx = PaintCtx::for_test(Point::ORIGIN, WINDOW, ft_ms(ms));
        w.paint(&mut ctx, &mut rec);
        rec
    }

    /// Paint (and relay out) until the running ramp is over.
    fn run_ramp(w: &mut OverlayModalWidget, from_ms: f64) {
        frame(w, from_ms);
        layout(w);
        frame(w, from_ms + 2000.0);
        layout(w);
    }

    fn settled(config: OverlayModalConfig) -> OverlayModalConfig {
        config.entrance(OverlayEntrance::None)
    }

    // ---- geometry -----------------------------------------------------------

    #[test]
    fn a_centered_panel_is_capped_centred_and_content_tall() {
        let mut w = build(&view(settled(OverlayModalConfig::centered(
            OVERLAY_DIALOG_MAX_WIDTH,
        ))));
        let size = layout(&mut w);
        assert_eq!(size, WINDOW, "the host fills its area (the scrim)");
        let panel = w.panel_rect();
        // The viewport margin bites before the 560dp cap in a 400px window.
        assert_eq!(panel.width(), WINDOW.width - 2.0 * CENTERED_MARGIN);
        assert_eq!(panel.height(), 120.0, "content-tall");
        assert!((panel.center().x - WINDOW.width / 2.0).abs() < 1e-9);
        assert!((panel.center().y - WINDOW.height / 2.0).abs() < 1e-9);
        assert_eq!(w.content.origin(), panel.origin());
    }

    #[test]
    fn a_centered_panel_holds_the_m3_minimum_width_where_it_fits() {
        // A cap below the M3 minimum still yields a 280dp panel — the clamp is
        // `[280, max]`, not "whatever the cap says".
        let mut w = build(&view(settled(OverlayModalConfig::centered(120.0))));
        layout(&mut w);
        assert_eq!(w.panel_rect().width(), OVERLAY_DIALOG_MIN_WIDTH);
    }

    #[test]
    fn an_edge_panel_pins_to_its_side_at_three_quarters_capped_at_the_side_sheet_max() {
        for side in [OverlaySide::Left, OverlaySide::Right] {
            let mut w = build(&view(settled(OverlayModalConfig::edge(side))));
            layout(&mut w);
            let panel = w.panel_rect();
            assert_eq!(
                panel.width(),
                (WINDOW.width * OVERLAY_EDGE_FRACTION).min(OVERLAY_SIDE_SHEET_MAX_WIDTH)
            );
            assert_eq!(panel.height(), WINDOW.height, "full height");
            match side {
                OverlaySide::Left => assert_eq!(panel.x0, 0.0),
                _ => assert_eq!(panel.x1, WINDOW.width),
            }
        }
        for side in [OverlaySide::Top, OverlaySide::Bottom] {
            let mut w = build(&view(settled(OverlayModalConfig::edge(side))));
            layout(&mut w);
            let panel = w.panel_rect();
            assert_eq!(panel.width(), WINDOW.width, "full width");
            assert_eq!(panel.height(), 120.0, "content-tall");
            match side {
                OverlaySide::Top => assert_eq!(panel.y0, 0.0),
                _ => assert_eq!(panel.y1, WINDOW.height),
            }
        }
    }

    #[test]
    fn each_edge_preset_rounds_only_the_corners_facing_the_screen() {
        let r = 28.0;
        assert_eq!(
            OverlayModalConfig::edge(OverlaySide::Bottom)
                .corners
                .radii(r),
            CornerRadii::new(r, r, 0.0, 0.0)
        );
        assert_eq!(
            OverlayModalConfig::edge(OverlaySide::Right)
                .corners
                .radii(r),
            CornerRadii::new(r, 0.0, 0.0, r)
        );
        assert_eq!(
            OverlayCorners::None.radii(r),
            CornerRadii::new(0.0, 0.0, 0.0, 0.0)
        );
    }

    #[test]
    fn a_limit_caps_an_edge_panel() {
        let config = settled(OverlayModalConfig::edge(OverlaySide::Bottom).extent(
            OverlayExtent::Content,
            OverlayLimit::Fraction(OVERLAY_SHEET_MAX_HEIGHT_FRACTION),
        ));
        let mut w = build(&overlay_modal(Block(Size::new(200.0, 5000.0)), config));
        layout(&mut w);
        assert_eq!(
            w.panel_rect().height(),
            WINDOW.height * OVERLAY_SHEET_MAX_HEIGHT_FRACTION
        );
    }

    #[test]
    fn an_unbounded_height_collapses_the_host_and_its_panel_to_nothing() {
        // The documented mounts (a navigator page, a full-area `Stack`) are
        // bounded; a host put inside a scroll view is not, and this is what
        // that costs — pinned, not fixed here: the coercion cannot invent an
        // extent nobody offered, so the fix belongs at the mount site.
        let mut w = build(&view(settled(OverlayModalConfig::centered(
            OVERLAY_DIALOG_MAX_WIDTH,
        ))));
        let mut tcx = TextContext::new();
        let mut lctx = LayoutCtx::with_text_context(&mut tcx as &mut dyn Any);
        let scrolled = BoxConstraints::new(
            Size::new(WINDOW.width, 0.0),
            Size::new(WINDOW.width, f64::INFINITY),
        );
        let size = w.layout(&mut lctx, &scrolled);
        assert_eq!(size.height, 0.0, "no vertical area to fill");
        assert_eq!(
            w.panel_rect().height(),
            0.0,
            "the panel is a hairline, while the barrier still takes presses"
        );
        // The same host under the contract's own constraints is unharmed.
        let bounded = w.layout(&mut lctx, &BoxConstraints::tight(WINDOW));
        assert_eq!(bounded, WINDOW);
        assert_eq!(w.panel_rect().height(), 120.0);
    }

    // ---- chrome -------------------------------------------------------------

    #[test]
    fn the_themed_chrome_is_material_roles_end_to_end() {
        let theme = crate::baseline().with_brightness(Brightness::Light);
        let scheme = theme.scheme();
        let mut w = build(&view(
            settled(OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH))
                .close_button(true)
                .border(OverlayBorder::All),
        ));
        let size = layout(&mut w);
        let mut rec = Recorder::default();
        let mut ctx =
            PaintCtx::for_test(Point::ORIGIN, size, FrameTime::ZERO).with_theme(&theme as &dyn Any);
        w.paint(&mut ctx, &mut rec);

        assert_eq!(rec.rects[0].1, size, "the scrim covers the area");
        assert_eq!(
            rec.rects[0].2,
            super::super::with_alpha(scheme.scrim, super::super::OVERLAY_SCRIM_ALPHA),
            "the M3 32% scrim"
        );
        assert_eq!(
            rec.panels[0].3, scheme.surface_container_high,
            "the dialog container role"
        );
        assert_eq!(
            rec.panels[0].2,
            CornerRadii::uniform(theme.shape.extra_large),
            "`shape.extra_large` on all four corners"
        );
        let level3 = theme.elevation.level3.shadow(theme.brightness);
        assert_eq!(rec.shadows[0].3, level3.blur_std_dev, "the level-3 rung");
        assert_eq!(rec.strokes[0].2, scheme.outline_variant, "the hairline");
        assert_eq!(
            rec.paths[0].2, scheme.on_surface_variant,
            "the close icon's rest role"
        );
        assert_eq!(rec.clips.len(), 1, "the content is clipped to the panel");
    }

    #[test]
    fn the_unthemed_chrome_falls_back_to_the_m3_baseline_light_values() {
        let mut w = build(&view(
            settled(OverlayModalConfig::edge(OverlaySide::Bottom)).handle(true),
        ));
        layout(&mut w);
        let rec = frame(&mut w, 0.0);
        assert_eq!(rec.rects[0].2, super::super::scrim(None));
        assert_eq!(
            rec.panels[0].3,
            super::super::container(None, OverlayContainer::Low)
        );
        // The M3 32×4dp handle indicator, fully rounded, in the drag-handle
        // color role.
        let handle = rec
            .rrects
            .iter()
            .find(|(_, s, _, _)| *s == Size::new(HANDLE_WIDTH, HANDLE_HEIGHT))
            .expect("the drag handle is painted");
        assert_eq!(handle.2, HANDLE_HEIGHT / 2.0);
        assert_eq!(handle.3, super::super::on_surface_variant(None));
        assert!(rec.strokes.is_empty(), "no border by default");
    }

    #[test]
    fn the_close_and_handle_hit_boxes_are_the_m3_touch_target() {
        let mut w = build(&view(
            settled(OverlayModalConfig::edge(OverlaySide::Bottom))
                .close_button(true)
                .handle(true),
        ));
        layout(&mut w);
        let close = w.close_rect().expect("a close box");
        assert_eq!(close.size(), Size::new(CLOSE_HIT, CLOSE_HIT));
        assert_eq!(
            close.center().x,
            w.panel_rect().x1 - CLOSE_INSET - CLOSE_ICON / 2.0
        );
        let handle = w.handle_rect().expect("a handle box");
        assert_eq!(handle.size(), Size::new(CLOSE_HIT, CLOSE_HIT));
        assert_eq!(handle.center().x, w.panel_rect().center().x);
        assert_eq!(OVERLAY_HANDLE_RESERVE, HANDLE_TOUCH_TARGET);
    }

    // ---- dismissal ----------------------------------------------------------

    #[test]
    fn a_scrim_press_and_release_outside_the_panel_dismisses() {
        let mut w = build(&view(settled(OverlayModalConfig::centered(
            OVERLAY_DIALOG_MAX_WIDTH,
        ))));
        layout(&mut w);
        let mut state = Flags::default();
        assert_eq!(
            dispatch(&mut w, &mut state, &pointer(PointerPhase::Down, 5.0, 5.0)),
            EventResult::Handled,
            "the barrier swallows the press"
        );
        dispatch(&mut w, &mut state, &pointer(PointerPhase::Up, 5.0, 5.0));
        assert_eq!(state.dismissed, 1);
    }

    #[test]
    fn a_press_on_the_panel_background_is_swallowed_without_dismissing() {
        let mut w = build(&view(settled(OverlayModalConfig::centered(
            OVERLAY_DIALOG_MAX_WIDTH,
        ))));
        layout(&mut w);
        let c = w.panel_rect().center();
        let mut state = Flags::default();
        assert_eq!(
            dispatch(&mut w, &mut state, &pointer(PointerPhase::Down, c.x, c.y)),
            EventResult::Handled
        );
        dispatch(&mut w, &mut state, &pointer(PointerPhase::Up, c.x, c.y));
        assert_eq!(state.dismissed, 0);
    }

    #[test]
    fn scrim_dismiss_off_ignores_the_same_gesture_but_escape_still_works() {
        let mut w = build(&view(
            settled(OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH)).scrim_dismiss(false),
        ));
        layout(&mut w);
        let mut state = Flags::default();
        dispatch(&mut w, &mut state, &pointer(PointerPhase::Down, 5.0, 5.0));
        dispatch(&mut w, &mut state, &pointer(PointerPhase::Up, 5.0, 5.0));
        assert_eq!(state.dismissed, 0);
        // Escape still works — the alert dialog's own escape hatch.
        dispatch(&mut w, &mut state, &escape());
        assert_eq!(state.dismissed, 1);
    }

    #[test]
    fn dismissable_false_gates_every_gesture_at_once() {
        let mut w = build(
            &view(
                settled(OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH)).close_button(true),
            )
            .dismissable(false),
        );
        layout(&mut w);
        let mut state = Flags::default();
        dispatch(&mut w, &mut state, &pointer(PointerPhase::Down, 5.0, 5.0));
        dispatch(&mut w, &mut state, &pointer(PointerPhase::Up, 5.0, 5.0));
        dispatch(&mut w, &mut state, &escape());
        let close = w.close_rect().expect("a close box").center();
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Down, close.x, close.y),
        );
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Up, close.x, close.y),
        );
        assert_eq!(
            state.dismissed, 0,
            "the scrim tap, Escape and the close affordance are all gated together"
        );
    }

    #[test]
    fn the_close_affordance_fires_on_release_inside_and_hovers() {
        let mut w = build(&view(
            settled(OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH)).close_button(true),
        ));
        layout(&mut w);
        let close = w.close_rect().expect("a close box");
        let c = close.center();
        let mut state = Flags::default();
        dispatch(&mut w, &mut state, &pointer(PointerPhase::Move, c.x, c.y));
        assert!(w.close_hovered, "the latch follows the hit test");
        dispatch(&mut w, &mut state, &pointer(PointerPhase::Down, c.x, c.y));
        assert_eq!(state.dismissed, 0, "never on down");
        dispatch(&mut w, &mut state, &pointer(PointerPhase::Up, c.x, c.y));
        assert_eq!(state.dismissed, 1);

        // A release outside the box fires nothing, and the press is not a scrim
        // press either.
        dispatch(&mut w, &mut state, &pointer(PointerPhase::Down, c.x, c.y));
        dispatch(&mut w, &mut state, &pointer(PointerPhase::Up, 5.0, 5.0));
        assert_eq!(state.dismissed, 1);
    }

    #[test]
    fn a_hovered_close_affordance_steps_up_to_the_on_surface_role() {
        // A real `RenderRoot` is the only harness that can exercise hover at
        // all: the link is recorded by the root's event pass and read back
        // through `PaintCtx::is_hovered`, which the paint arm treats as
        // authoritative (a bare paint reads `false` and clears the latch, by
        // design). The `crate::list_item` hover-harness precedent.
        let config =
            settled(OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH)).close_button(true);
        // The geometry is deterministic, so a throwaway widget answers where
        // the close box lands.
        let mut probe = build(&view(config));
        layout(&mut probe);
        let c = probe.close_rect().expect("a close box").center();

        let mut root: RenderRoot<Flags, OverlayModalView<Flags>> = RenderRoot::new();
        let mut state = Flags::default();
        let mut tcx = TextContext::new();
        let mut app = move |_s: &mut Flags| overlay_modal(Block(Size::new(200.0, 120.0)), config);
        let theme = crate::baseline().with_brightness(Brightness::Light);
        root.set_theme(Box::new(theme.clone()));
        root.rebuild(&mut app, &mut state);
        root.layout_with_text(WINDOW, &mut tcx as &mut dyn Any);

        let mut rest = Recorder::default();
        root.paint(&mut rest, FrameTime::ZERO);
        assert_eq!(
            rest.paths[0].2,
            theme.scheme().on_surface_variant,
            "at rest the affordance sits in the muted ink role"
        );

        root.event(&mut state, &pointer(PointerPhase::Move, c.x, c.y));
        let mut hovered = Recorder::default();
        root.paint(&mut hovered, FrameTime::ZERO);
        assert_eq!(
            hovered.paths[0].2,
            theme.scheme().on_surface,
            "a hovered affordance steps up to the panel's own ink"
        );
    }

    #[test]
    fn the_drag_handle_dismisses_on_release() {
        let mut w = build(&view(
            settled(OverlayModalConfig::edge(OverlaySide::Bottom)).handle(true),
        ));
        layout(&mut w);
        let handle = w.handle_rect().expect("a handle box");
        let c = handle.center();
        let mut state = Flags::default();
        dispatch(&mut w, &mut state, &pointer(PointerPhase::Down, c.x, c.y));
        dispatch(&mut w, &mut state, &pointer(PointerPhase::Up, c.x, c.y));
        assert_eq!(state.dismissed, 1);
    }

    #[test]
    fn a_cancelled_press_clears_every_latch_without_dismissing() {
        let mut w = build(&view(
            settled(OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH)).close_button(true),
        ));
        layout(&mut w);
        let c = w.close_rect().unwrap().center();
        let mut state = Flags::default();
        dispatch(&mut w, &mut state, &pointer(PointerPhase::Down, c.x, c.y));
        dispatch(&mut w, &mut state, &pointer(PointerPhase::Cancel, c.x, c.y));
        assert_eq!(state.dismissed, 0);
        assert!(!w.close_captured && !w.scrim_captured);
    }

    #[test]
    fn the_barrier_swallows_a_key_the_content_did_not_take() {
        let mut w = build(&view(settled(OverlayModalConfig::centered(
            OVERLAY_DIALOG_MAX_WIDTH,
        ))));
        layout(&mut w);
        let mut state = Flags::default();
        let tab = InputEvent::Key(KeyEvent {
            key: Key::Named(NamedKey::Tab),
            modifiers: Modifiers::default(),
            repeat: false,
        });
        assert_eq!(
            dispatch(&mut w, &mut state, &tab),
            EventResult::Handled,
            "a modal barrier absorbs keys as well as pointers"
        );
        assert_eq!(state.dismissed, 0, "and only Escape dismisses");
    }

    // ---- motion -------------------------------------------------------------

    #[test]
    fn the_fade_scale_entrance_ramps_alpha_and_scale_then_settles() {
        let mut w = build(&view(OverlayModalConfig::centered(
            OVERLAY_DIALOG_MAX_WIDTH,
        )));
        layout(&mut w);
        let first = frame(&mut w, 0.0);
        assert_eq!(first.layers, vec![0.0], "starts transparent");
        assert_eq!(first.rects[0].2.components[3], 0.0, "so does the scrim");
        let mid = frame(&mut w, MaterialMotion::SHORT_4.as_millis() as f64 / 2.0);
        let alpha = mid.layers[0];
        assert!(alpha > 0.0 && alpha < 1.0, "mid-fade: {alpha}");
        assert_eq!(mid.transforms.len(), 1, "and a scale transform");
        let done = frame(&mut w, 1000.0);
        assert!(
            done.layers.is_empty() && done.transforms.is_empty(),
            "a settled panel composites plainly"
        );
        assert!((w.progress() - 1.0).abs() < 1e-9);
    }

    #[test]
    fn the_entrance_durations_are_the_mapped_material_presets() {
        assert_eq!(
            OverlayEntrance::FadeScale.duration(),
            MaterialMotion::SHORT_4
        );
        assert_eq!(OverlayEntrance::Slide.duration(), MaterialMotion::LONG_2);
        assert_eq!(OverlayEntrance::None.duration(), Duration::ZERO);
        assert_eq!(
            OverlayEntrance::FadeScale.curve(false),
            MaterialMotion::EMPHASIZED_DECELERATE
        );
        assert_eq!(
            OverlayEntrance::Slide.curve(false),
            MaterialMotion::EMPHASIZED
        );
        assert_eq!(
            OverlayEntrance::Slide.curve(true),
            MaterialMotion::EMPHASIZED_ACCELERATE,
            "either entrance leaves on M3's accelerate curve"
        );
    }

    #[test]
    fn reduce_motion_collapses_the_entrance_to_a_jump() {
        let mut theme = crate::baseline().with_brightness(Brightness::Light);
        theme.motion.reduce_motion = true;
        let mut w = build(&view(OverlayModalConfig::centered(
            OVERLAY_DIALOG_MAX_WIDTH,
        )));
        let size = layout(&mut w);
        let mut rec = Recorder::default();
        let mut ctx =
            PaintCtx::for_test(Point::ORIGIN, size, FrameTime::ZERO).with_theme(&theme as &dyn Any);
        w.paint(&mut ctx, &mut rec);
        assert!((w.progress() - 1.0).abs() < 1e-9, "settled on the spot");
        assert!(rec.layers.is_empty(), "no fade layer");
        assert_eq!(
            rec.rects[0].2,
            super::super::with_alpha(theme.scheme().scrim, super::super::OVERLAY_SCRIM_ALPHA),
            "a full-strength scrim"
        );
    }

    #[test]
    fn the_slide_entrance_moves_the_panel_in_layout() {
        let mut w = build(&view(OverlayModalConfig::edge(OverlaySide::Right)));
        layout(&mut w);
        assert_eq!(
            w.panel_rect().x0,
            WINDOW.width,
            "starts entirely off the right edge"
        );
        let step = |w: &mut OverlayModalWidget, ms: f64| {
            frame(w, ms);
            layout(w);
        };
        step(&mut w, 0.0);
        step(&mut w, MaterialMotion::LONG_2.as_millis() as f64 / 2.0);
        let mid = w.panel_rect();
        assert!(
            mid.x0 > WINDOW.width - mid.width() && mid.x0 < WINDOW.width,
            "mid-slide: {}",
            mid.x0
        );
        step(&mut w, 2000.0);
        assert_eq!(w.panel_rect().x1, WINDOW.width, "flush at rest");
    }

    #[test]
    fn each_entrances_seeding_paint_asks_for_the_pass_its_own_motion_needs() {
        // `AnimationController::advance`'s first truthy call after `forward()`
        // only seeds the clock — `progress` is still 0.0 after it. The
        // continuation has to be requested on that seeding paint too, or a
        // layout-affecting entrance never schedules the frame that would carry
        // it off zero, and the panel sits permanently off-screen under a
        // `ControlFlow::Wait` shell.
        for (config, layout_affecting) in [
            (OverlayModalConfig::edge(OverlaySide::Right), true),
            (
                OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH),
                false,
            ),
        ] {
            let mut w = build(&view(config));
            let size = layout(&mut w);
            let mut ctx = PaintCtx::for_test(Point::ORIGIN, size, ft_ms(0.0));
            w.paint(&mut ctx, &mut Recorder::default());
            assert!(
                w.progress().abs() < 1e-9,
                "the seeding paint leaves progress at zero"
            );
            assert!(
                ctx.needs_frame(),
                "the seeding paint must schedule the frame that ramps progress off zero"
            );
            assert_eq!(
                ctx.needs_layout(),
                layout_affecting,
                "only a layout-affecting entrance asks for a layout pass"
            );
        }
    }

    // ---- the staged exit ----------------------------------------------------

    #[test]
    fn a_dismiss_ramps_the_panel_out_and_closes_only_when_it_settles() {
        let (view, closed) = staged(OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH));
        let mut w = build(&view);
        layout(&mut w);
        run_ramp(&mut w, 0.0);
        assert!((w.progress() - 1.0).abs() < 1e-9, "entered");

        let mut state = Flags::default();
        dispatch(&mut w, &mut state, &pointer(PointerPhase::Down, 5.0, 5.0));
        dispatch(&mut w, &mut state, &pointer(PointerPhase::Up, 5.0, 5.0));
        assert_eq!(state.dismissed, 0, "the unstaged callback stays unused");
        assert_eq!(closed.get(), 0, "and the close is deferred");
        assert!(w.is_exiting());

        // Mid-ramp: still visible, still nothing fired.
        frame(&mut w, 3000.0);
        let mid = frame(
            &mut w,
            3000.0 + MaterialMotion::SHORT_4.as_millis() as f64 / 2.0,
        );
        assert!(w.progress() > 0.0 && w.progress() < 1.0, "{}", w.progress());
        let alpha = mid.layers[0];
        assert!(alpha > 0.0 && alpha < 1.0, "the panel fades out: {alpha}");
        assert!(
            mid.rects[0].2.components[3] < super::super::OVERLAY_SCRIM_ALPHA,
            "and the scrim rides the ramp down"
        );
        assert_eq!(closed.get(), 0);

        // Settled: progress at zero, and the close fires exactly once.
        frame(&mut w, 5000.0);
        assert_eq!(w.progress(), 0.0);
        assert_eq!(closed.get(), 1);
        assert!(!w.is_exiting());
        assert_eq!(state.dismissed, 0);
    }

    /// A panel that has finished its exit paints nothing — the scrim's alpha
    /// rides `progress` and a `FadeScale` panel composites at it — but stays
    /// mounted until the enqueued pop drains. It must not go on swallowing
    /// presses there: an invisible barrier is an input trap with nothing on
    /// screen to explain it (the `super::anchored` gate, ported).
    #[test]
    fn a_panel_that_has_finished_its_exit_swallows_no_press() {
        let (view, closed) = staged(OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH));
        let mut w = build(&view);
        layout(&mut w);
        run_ramp(&mut w, 0.0);
        let over_panel = w.panel_rect().center();

        let mut state = Flags::default();
        dispatch(&mut w, &mut state, &escape());
        frame(&mut w, 3000.0);
        frame(&mut w, 5000.0);
        assert_eq!(closed.get(), 1, "the staged close fired");
        assert_eq!(w.progress(), 0.0, "and the panel paints nothing");

        let result = dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Down, over_panel.x, over_panel.y),
        );
        assert_eq!(
            result,
            EventResult::Ignored,
            "an invisible panel absorbs nothing"
        );
        assert!(!w.scrim_captured, "and arms no scrim dismiss either");
    }

    #[test]
    fn the_staged_close_hook_survives_a_rebuild_and_still_fires_exactly_once() {
        // `OverlayModalView::rebuild` never writes `element.on_close` at all
        // (see its doc comment); `StagedExit::rebuild` — which runs
        // `inner.rebuild` first and reinstalls its own hook after — must still
        // be the writer that wins on the staged (`show_overlay_modal`) path,
        // through as many rebuilds as the page sees before it's popped.
        let closed = Rc::new(Cell::new(0u32));
        let config = OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH);
        let hook1 = closed.clone();
        let v1 = StagedExit {
            inner: view(config),
            on_close: Rc::new(StagedPop::unguarded(move || hook1.set(hook1.get() + 1))),
            dismiss_signal: None,
        };
        let mut counter = 0u64;
        let mut w = View::<Flags>::build(&v1, &mut BuildCtx::new(&mut counter));
        layout(&mut w);
        run_ramp(&mut w, 0.0);

        // A second rebuild pass through the wrapper, as the navigator's pushed
        // page sees on every frame it stays mounted.
        let hook2 = closed.clone();
        let v2 = StagedExit {
            inner: view(config),
            on_close: Rc::new(StagedPop::unguarded(move || hook2.set(hook2.get() + 1))),
            dismiss_signal: None,
        };
        View::<Flags>::rebuild(&v2, &v1, &mut w, &mut BuildCtx::new(&mut counter));

        let mut state = Flags::default();
        dispatch(&mut w, &mut state, &escape());
        frame(&mut w, 3000.0);
        frame(&mut w, 5000.0);
        assert_eq!(
            closed.get(),
            1,
            "the reinstalled hook still fires exactly once"
        );
    }

    #[test]
    fn a_rebuild_never_resurrects_or_clears_a_bare_views_on_close_hook() {
        // Pinned behavior, not last-writer-wins: a directly constructed,
        // non-staged view's `on_close` is installed once at `build` and never
        // touched by a later `rebuild`. A rebuild carrying `None` must not clear
        // the hook the widget already has installed.
        let closed = Rc::new(Cell::new(0u32));
        let hook = closed.clone();
        let v1 = view(OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH))
            .on_close(move || hook.set(hook.get() + 1));
        let mut w = build(&v1);
        layout(&mut w);
        run_ramp(&mut w, 0.0);

        // Rebuild with a view whose own `on_close` is unset.
        let v2 = view(OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH));
        rebuild(&v2, &v1, &mut w);

        let mut state = Flags::default();
        dispatch(&mut w, &mut state, &escape());
        frame(&mut w, 3000.0);
        frame(&mut w, 5000.0);
        assert_eq!(
            closed.get(),
            1,
            "the build-time hook is still installed and still fires — pinned, not cleared"
        );
    }

    #[test]
    fn the_exit_keeps_asking_for_the_pass_its_own_motion_needs() {
        for (config, layout_affecting) in [
            (OverlayModalConfig::edge(OverlaySide::Bottom), true),
            (
                OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH),
                false,
            ),
        ] {
            let (view, _closed) = staged(config);
            let mut w = build(&view);
            layout(&mut w);
            run_ramp(&mut w, 0.0);
            let mut state = Flags::default();
            dispatch(&mut w, &mut state, &pointer(PointerPhase::Down, 5.0, 5.0));
            dispatch(&mut w, &mut state, &pointer(PointerPhase::Up, 5.0, 5.0));

            let mut ctx = PaintCtx::for_test(Point::ORIGIN, WINDOW, ft_ms(3000.0));
            w.paint(&mut ctx, &mut Recorder::default());
            assert!(
                ctx.needs_frame(),
                "the exit's seeding paint schedules its own continuation"
            );
            assert_eq!(
                ctx.needs_layout(),
                layout_affecting,
                "only a layout-affecting exit asks for a layout pass"
            );
        }
    }

    #[test]
    fn reduce_motion_closes_on_the_spot_with_no_ramp() {
        let mut theme = crate::baseline().with_brightness(Brightness::Light);
        theme.motion.reduce_motion = true;
        let (view, closed) = staged(OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH));
        let mut w = build(&view);
        let size = layout(&mut w);
        let paint = |w: &mut OverlayModalWidget, ms: f64| {
            let mut ctx =
                PaintCtx::for_test(Point::ORIGIN, size, ft_ms(ms)).with_theme(&theme as &dyn Any);
            w.paint(&mut ctx, &mut Recorder::default());
        };
        paint(&mut w, 0.0);
        assert!((w.progress() - 1.0).abs() < 1e-9, "no entrance ramp");

        let mut state = Flags::default();
        dispatch(&mut w, &mut state, &escape());
        paint(&mut w, 16.0);
        assert_eq!(w.progress(), 0.0, "the exit is a jump, not a ramp");
        assert_eq!(closed.get(), 1);
    }

    #[test]
    fn a_second_dismiss_while_exiting_is_a_no_op() {
        let (view, closed) = staged(OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH));
        let mut w = build(&view);
        layout(&mut w);
        run_ramp(&mut w, 0.0);
        let mut state = Flags::default();
        dispatch(&mut w, &mut state, &escape());
        let first = w.progress();
        frame(&mut w, 3000.0);
        frame(
            &mut w,
            3000.0 + MaterialMotion::SHORT_4.as_millis() as f64 / 2.0,
        );
        let mid = w.progress();
        assert!(mid < first, "the ramp is running");

        // A second trigger neither restarts the ramp nor fires anything.
        dispatch(&mut w, &mut state, &escape());
        assert_eq!(w.progress(), mid, "the ramp is untouched");
        frame(&mut w, 5000.0);
        assert_eq!(closed.get(), 1, "one close for two triggers");
        assert_eq!(state.dismissed, 0);
    }

    #[test]
    fn a_dismiss_trigger_after_settle_does_not_fire_on_close_again() {
        // The hazard: `on_close` only *enqueues* `controller.pop()`, so the
        // widget stays mounted — and still a barrier — for at least one frame
        // after the exit ramp settles. A trigger landing in that window would
        // otherwise re-enter `request_dismiss` with `progress` already at zero:
        // a zero-duration ramp settling on its very next paint, firing
        // `on_close` a second time and popping the page underneath this modal.
        let (view, closed) = staged(OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH));
        let mut w = build(&view);
        layout(&mut w);
        run_ramp(&mut w, 0.0);
        let mut state = Flags::default();
        dispatch(&mut w, &mut state, &escape());
        frame(&mut w, 3000.0);
        frame(&mut w, 5000.0);
        assert_eq!(w.progress(), 0.0, "settled closed");
        assert_eq!(closed.get(), 1, "on_close fired once on settle");
        assert!(!w.is_exiting());

        // The enqueued pop hasn't drained yet, so the widget is still mounted. A
        // further dismiss trigger must be a pure no-op.
        dispatch(&mut w, &mut state, &escape());
        frame(&mut w, 7000.0);
        assert_eq!(closed.get(), 1, "on_close does not fire a second time");
        assert_eq!(state.dismissed, 0);
    }

    #[test]
    fn without_a_close_hook_the_dismissal_stays_unstaged() {
        // A `Stack`-mounted modal that only wired `on_dismiss` has no
        // state-bearing pass to defer into, so it keeps the immediate path
        // rather than leaving an invisible barrier standing.
        let mut w = build(&view(OverlayModalConfig::centered(
            OVERLAY_DIALOG_MAX_WIDTH,
        )));
        layout(&mut w);
        run_ramp(&mut w, 0.0);
        let mut state = Flags::default();
        dispatch(&mut w, &mut state, &escape());
        assert_eq!(state.dismissed, 1);
        assert!(!w.is_exiting());
        assert!((w.progress() - 1.0).abs() < 1e-9, "nothing animates out");
    }

    // ---- the back-press (`DismissAnimated`) tier ----------------------------

    /// A staged modal wired the way [`show_overlay_modal`] wires one, plus the
    /// dismiss-signal cell the navigator bumps on a back press.
    fn back_wired(
        config: OverlayModalConfig,
    ) -> (OverlayModalWidget, Rc<Cell<u64>>, Rc<Cell<u32>>) {
        let closed = Rc::new(Cell::new(0u32));
        let hook = closed.clone();
        let signal = Rc::new(Cell::new(0u64));
        let staged = StagedExit {
            inner: view(config),
            on_close: Rc::new(StagedPop::unguarded(move || hook.set(hook.get() + 1))),
            dismiss_signal: Some(signal.clone()),
        };
        let mut counter = 0u64;
        let mut w = View::<Flags>::build(&staged, &mut BuildCtx::new(&mut counter));
        layout(&mut w);
        run_ramp(&mut w, 0.0);
        (w, signal, closed)
    }

    #[test]
    fn a_dismiss_signal_bump_stages_the_same_exit_ramp_every_gesture_takes() {
        let (mut w, signal, closed) =
            back_wired(OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH));
        assert!((w.progress() - 1.0).abs() < 1e-9, "entered");

        // The navigator's back press: bump the shared generation cell.
        signal.set(signal.get() + 1);
        frame(&mut w, 3000.0);
        assert!(w.is_exiting(), "the back press stages the exit, not a pop");
        assert_eq!(closed.get(), 0, "and fires nothing yet");
        frame(
            &mut w,
            3000.0 + MaterialMotion::SHORT_4.as_millis() as f64 / 2.0,
        );
        assert!(w.progress() > 0.0 && w.progress() < 1.0, "mid-exit");
        frame(&mut w, 5000.0);
        assert_eq!(closed.get(), 1, "the pop fires when the ramp settles");

        // A stale re-observation of the same generation changes nothing.
        frame(&mut w, 6000.0);
        assert_eq!(closed.get(), 1);
    }

    #[test]
    fn a_back_press_on_an_unstageable_modal_fires_the_pop_and_schedules_its_drain() {
        // No entrance to reverse: the close fires on the spot, and the very
        // paint that fires it must request the frame whose rebuild drains the
        // enqueued pop (the drain gotcha).
        let (mut w, signal, closed) = back_wired(settled(OverlayModalConfig::centered(
            OVERLAY_DIALOG_MAX_WIDTH,
        )));
        signal.set(signal.get() + 1);
        let mut ctx = PaintCtx::for_test(Point::ORIGIN, WINDOW, ft_ms(3000.0));
        w.paint(&mut ctx, &mut Recorder::default());
        assert_eq!(closed.get(), 1);
        assert!(
            ctx.needs_frame(),
            "the firing paint schedules the draining frame"
        );
    }

    #[test]
    fn a_non_dismissable_modal_ignores_a_dismiss_signal_bump() {
        // `show_overlay_modal` pushes such a page with `BackPolicy::Veto` and no
        // cell at all; the widget-side guard is belt-and-braces for a modal
        // whose flag flips after the push.
        let closed = Rc::new(Cell::new(0u32));
        let hook = closed.clone();
        let signal = Rc::new(Cell::new(0u64));
        let staged = StagedExit {
            inner: view(OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH)).dismissable(false),
            on_close: Rc::new(StagedPop::unguarded(move || hook.set(hook.get() + 1))),
            dismiss_signal: Some(signal.clone()),
        };
        let mut counter = 0u64;
        let mut w = View::<Flags>::build(&staged, &mut BuildCtx::new(&mut counter));
        layout(&mut w);
        run_ramp(&mut w, 0.0);
        signal.set(signal.get() + 1);
        frame(&mut w, 3000.0);
        assert!(!w.is_exiting());
        frame(&mut w, 5000.0);
        assert_eq!(closed.get(), 0, "a Veto-shaped modal never self-pops");
    }

    #[test]
    fn a_bump_that_predates_the_widget_is_not_a_back_press_aimed_at_it() {
        let closed = Rc::new(Cell::new(0u32));
        let hook = closed.clone();
        let signal = Rc::new(Cell::new(7u64));
        let staged = StagedExit {
            inner: view(OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH)),
            on_close: Rc::new(StagedPop::unguarded(move || hook.set(hook.get() + 1))),
            dismiss_signal: Some(signal.clone()),
        };
        let mut counter = 0u64;
        let mut w = View::<Flags>::build(&staged, &mut BuildCtx::new(&mut counter));
        layout(&mut w);
        run_ramp(&mut w, 0.0);
        assert!(
            !w.is_exiting(),
            "the pre-existing generation is the baseline"
        );
        assert_eq!(closed.get(), 0);
    }

    // ---- the app-initiated dismiss (`ModalDismiss`) seam --------------------

    /// A staged modal (wired the way [`show_overlay_modal`] wires one) with an
    /// app dismiss handle installed, already fully entered — plus that handle
    /// and the close counter.
    fn app_dismissable(
        config: OverlayModalConfig,
        dismissable: bool,
    ) -> (OverlayModalWidget, ModalDismiss, Rc<Cell<u32>>) {
        let (view, closed) = staged(config);
        let dismiss = ModalDismiss::new();
        let view = view
            .dismissable(dismissable)
            .dismiss_handle(dismiss.clone());
        let mut w = build(&view);
        layout(&mut w);
        run_ramp(&mut w, 0.0);
        (w, dismiss, closed)
    }

    #[test]
    fn a_dismiss_request_stages_the_same_exit_ramp_every_gesture_takes() {
        let (mut w, dismiss, closed) =
            app_dismissable(OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH), true);
        assert!((w.progress() - 1.0).abs() < 1e-9, "entered");

        dismiss.dismiss();
        frame(&mut w, 3000.0);
        assert!(w.is_exiting(), "the request stages the exit, not a pop");
        assert_eq!(closed.get(), 0, "and fires nothing yet");
        frame(
            &mut w,
            3000.0 + MaterialMotion::SHORT_4.as_millis() as f64 / 2.0,
        );
        assert!(w.progress() > 0.0 && w.progress() < 1.0, "mid-exit");
        frame(&mut w, 5000.0);
        assert_eq!(closed.get(), 1, "the pop fires when the ramp settles");

        // A stale re-observation of the same generation changes nothing.
        frame(&mut w, 6000.0);
        assert_eq!(closed.get(), 1);
    }

    #[test]
    fn a_second_dismiss_request_while_exiting_is_a_no_op() {
        let (mut w, dismiss, closed) =
            app_dismissable(OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH), true);
        dismiss.dismiss();
        frame(&mut w, 3000.0);
        frame(
            &mut w,
            3000.0 + MaterialMotion::SHORT_4.as_millis() as f64 / 2.0,
        );
        let mid = w.progress();
        assert!(mid < 1.0, "the ramp is running");

        // A double-tapped action button: the second request neither restarts
        // the ramp nor fires a second pop — nor swaps its own payload into the
        // exit already in flight, which was staged to pop with something else.
        dismiss.dismiss_with(PopResult::of(5));
        frame(
            &mut w,
            3000.0 + MaterialMotion::SHORT_4.as_millis() as f64 / 2.0,
        );
        assert!(w.is_exiting(), "still the one exit");
        assert!(
            dismiss.take_result(dismiss.generation()).is_some(),
            "the refused request's payload stays with the handle"
        );
        frame(&mut w, 5000.0);
        assert_eq!(closed.get(), 1, "one close for two requests");

        // …and one more after the settle, in the window before the enqueued pop
        // drains, is refused by the `closed` latch like every other trigger.
        dismiss.dismiss();
        frame(&mut w, 7000.0);
        assert_eq!(closed.get(), 1);
    }

    #[test]
    fn a_dismiss_request_closes_a_non_dismissable_modal() {
        // The decision the module docs state: `dismissable(false)` takes the
        // *user's* exits away and leaves "an explicit control the app wires
        // inside its own content" — which is exactly this handle. A back-press
        // bump on the same modal stays refused (see the back-press tier).
        let (mut w, dismiss, closed) = app_dismissable(
            OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH),
            false,
        );
        let mut state = Flags::default();
        dispatch(&mut w, &mut state, &escape());
        assert!(!w.is_exiting(), "the user's own exits are still gone");

        dismiss.dismiss();
        frame(&mut w, 3000.0);
        assert!(w.is_exiting(), "but the app's own control still closes it");
        frame(&mut w, 5000.0);
        assert_eq!(closed.get(), 1);
        assert_eq!(state.dismissed, 0);
    }

    #[test]
    fn a_request_that_predates_the_widget_is_not_aimed_at_it() {
        let (view, closed) = staged(OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH));
        let dismiss = ModalDismiss::new();
        // A handle re-used from an earlier presentation: its generation is
        // already non-zero when this modal mounts.
        dismiss.dismiss();
        dismiss.dismiss();
        let mut w = build(&view.dismiss_handle(dismiss.clone()));
        layout(&mut w);
        run_ramp(&mut w, 0.0);
        assert!(!w.is_exiting(), "the standing generation is the baseline");
        assert_eq!(closed.get(), 0);

        // The next request is, though.
        dismiss.dismiss();
        frame(&mut w, 3000.0);
        assert!(w.is_exiting());
    }

    #[test]
    fn an_unstageable_modal_fires_the_request_at_once_and_schedules_its_drain() {
        // No entrance to reverse: the close fires on the spot, and the very
        // paint that fires it must request the frame whose rebuild drains the
        // enqueued pop (the drain gotcha).
        let (view, closed) = staged(settled(OverlayModalConfig::centered(
            OVERLAY_DIALOG_MAX_WIDTH,
        )));
        let dismiss = ModalDismiss::new();
        let mut w = build(&view.dismiss_handle(dismiss.clone()));
        layout(&mut w);
        dismiss.dismiss();
        let mut ctx = PaintCtx::for_test(Point::ORIGIN, WINDOW, ft_ms(3000.0));
        w.paint(&mut ctx, &mut Recorder::default());
        assert_eq!(closed.get(), 1);
        assert!(
            ctx.needs_frame(),
            "the firing paint schedules the draining frame"
        );
    }

    /// Panel content that dismisses through the app handle when pressed — an
    /// action button's shape, minus the button (it captures the `Down` and
    /// acts on the `Up`, so the host never takes the gesture for itself).
    struct Trigger(ModalDismiss);

    /// The retained half of [`Trigger`].
    struct TriggerWidget(ModalDismiss);

    impl<S: 'static> View<S> for Trigger {
        type Element = TriggerWidget;
        fn build(&self, _ctx: &mut BuildCtx<'_>) -> TriggerWidget {
            TriggerWidget(self.0.clone())
        }
        fn rebuild(
            &self,
            _prev: &Self,
            element: &mut TriggerWidget,
            _ctx: &mut BuildCtx<'_>,
        ) -> ChangeFlags {
            element.0 = self.0.clone();
            ChangeFlags::NONE
        }
    }

    impl Widget for TriggerWidget {
        fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            bc.constrain(Size::new(200.0, 120.0))
        }
        fn paint(&mut self, _ctx: &mut PaintCtx, _scene: &mut dyn PaintScene) {}
        fn event(&mut self, _ctx: &mut EventCtx, event: &InputEvent) -> EventResult {
            let InputEvent::Pointer(p) = event else {
                return EventResult::Ignored;
            };
            match p.phase {
                PointerPhase::Down => EventResult::Handled,
                PointerPhase::Up => {
                    self.0.dismiss();
                    EventResult::Handled
                }
                _ => EventResult::Ignored,
            }
        }
    }

    #[test]
    fn a_content_action_stages_its_dismiss_in_the_same_event_pass() {
        // The event-pass observation: the content handled the press, so no
        // paint is owed by anything else — the host must still see the request
        // and ask for the frame its ramp needs.
        let closed = Rc::new(Cell::new(0u32));
        let hook = closed.clone();
        let dismiss = ModalDismiss::new();
        let view = overlay_modal::<Flags, _>(
            Trigger(dismiss.clone()),
            OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH),
        )
        .on_close(move || hook.set(hook.get() + 1))
        .dismiss_handle(dismiss);
        let mut w = build(&view);
        layout(&mut w);
        run_ramp(&mut w, 0.0);

        let hit = w.panel_rect().center();
        let mut state = Flags::default();
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Down, hit.x, hit.y),
        );
        let state_any: &mut dyn Any = &mut state;
        let mut ctx = EventCtx::new(state_any, Point::ZERO, WINDOW);
        let result = w.event(&mut ctx, &pointer(PointerPhase::Up, hit.x, hit.y));
        assert_eq!(result, EventResult::Handled);
        assert!(w.is_exiting(), "staged inside the pass that asked for it");
        assert!(
            ctx.needs_redraw(),
            "and the ramp's first frame is asked for"
        );
        assert_eq!(closed.get(), 0, "nothing pops mid-ramp");

        frame(&mut w, 3000.0);
        frame(&mut w, 5000.0);
        assert_eq!(closed.get(), 1);
        assert_eq!(state.dismissed, 0, "the staged path, not the unstaged one");
    }

    #[test]
    fn a_stack_mounted_panels_handle_reaches_the_unstaged_on_dismiss() {
        // The shape a `Stack`-mounted `DialogView`/`SideSheetView` builds: an
        // `on_dismiss` and no staged close hook at all. The handle must still
        // dismiss the panel, through the one route such a mount has — and it
        // is the *event* pass that has it, since `PaintCtx` carries no state.
        let dismiss = ModalDismiss::new();
        let view = view(OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH))
            .dismiss_handle(dismiss.clone());
        let mut w = build(&view);
        layout(&mut w);
        run_ramp(&mut w, 0.0);

        dismiss.dismiss();
        // The paint backstop can reach neither `on_dismiss` (no app state) nor
        // an `on_close` (none wired): it must leave the request pending rather
        // than consume it, or the handle is silently inert on this mount.
        frame(&mut w, 3000.0);
        let mut state = Flags::default();
        assert_eq!(state.dismissed, 0, "nothing dismisses from a paint");

        // …so the next event pass is what delivers it.
        dispatch(&mut w, &mut state, &pointer(PointerPhase::Move, 5.0, 5.0));
        assert_eq!(
            state.dismissed, 1,
            "a `Stack` mount's handle is not inert — it dismisses unstaged"
        );
        assert!(!w.is_exiting(), "there was nothing to stage");

        // Exactly once, however many further passes observe the same request.
        frame(&mut w, 3100.0);
        dispatch(&mut w, &mut state, &pointer(PointerPhase::Move, 6.0, 6.0));
        assert_eq!(state.dismissed, 1);
    }

    #[test]
    fn escape_with_a_pending_unobserved_request_dismisses_exactly_once() {
        // Two dismissal routes meeting inside one event pass: an async
        // `dismiss()` the paint backstop deliberately left pending (it can
        // reach neither hook on this mount), and the `Escape` that arrives
        // before any rebuild. The event pass observes the request first and
        // dismisses unstaged; the keypress that follows must find that route
        // already spent rather than dismiss the same panel a second time.
        let dismiss = ModalDismiss::new();
        let view = view(OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH))
            .dismiss_handle(dismiss.clone());
        let mut w = build(&view);
        layout(&mut w);
        run_ramp(&mut w, 0.0);

        dismiss.dismiss();
        frame(&mut w, 3000.0);
        let mut state = Flags::default();
        assert_eq!(state.dismissed, 0, "nothing dismisses from a paint");

        assert_eq!(
            dispatch(&mut w, &mut state, &escape()),
            EventResult::Handled,
            "the barrier still swallows the key"
        );
        assert_eq!(
            state.dismissed, 1,
            "one keypress over a pending request is one dismissal, not two"
        );
    }

    #[test]
    fn a_stack_mounted_dialog_view_dismisses_through_its_installed_handle() {
        // The same gap through the public API that reaches it: every dialog
        // variant forwards `.dismiss_handle(..)` to this host and composes no
        // `on_close`, so a `Stack`-mounted one had no dismissal route at all.
        let dismiss = ModalDismiss::new();
        let view = crate::dialog::dialog::<Flags>()
            .title("Discard draft?")
            .on_dismiss(|s: &mut Flags| s.dismissed += 1)
            .dismiss_handle(dismiss.clone());
        let mut counter = 0u64;
        let mut w = View::<Flags>::build(&view, &mut BuildCtx::new(&mut counter));
        layout(&mut w);
        run_ramp(&mut w, 0.0);

        dismiss.dismiss();
        let mut state = Flags::default();
        dispatch(&mut w, &mut state, &pointer(PointerPhase::Move, 5.0, 5.0));
        assert_eq!(state.dismissed, 1);
    }

    #[test]
    fn a_rebuild_that_swaps_the_handle_relatches_against_the_new_cell() {
        // An app that mints its handle *inside* the page builder hands the
        // widget a fresh cell every rebuild; the widget follows the newest one
        // rather than latching onto a dead cell (and re-seeds, so the swap
        // itself is not read as a request).
        let (first_view, closed) = staged(OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH));
        let first = ModalDismiss::new();
        let first_view = first_view.dismiss_handle(first.clone());
        let mut w = build(&first_view);
        layout(&mut w);
        run_ramp(&mut w, 0.0);

        let second = ModalDismiss::new();
        second.dismiss();
        let second_view = view(OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH))
            .dismiss_handle(second.clone());
        rebuild(&second_view, &first_view, &mut w);
        frame(&mut w, 3000.0);
        assert!(!w.is_exiting(), "the swap itself is not a request");

        // The stale handle is inert…
        first.dismiss();
        frame(&mut w, 3100.0);
        assert!(!w.is_exiting());
        // …and the live one drives the exit.
        second.dismiss();
        frame(&mut w, 3200.0);
        assert!(w.is_exiting());
        frame(&mut w, 6000.0);
        assert_eq!(closed.get(), 1);
    }

    // ---- navigator integration ---------------------------------------------

    #[derive(Default)]
    struct NavState {
        results: Vec<Option<i32>>,
    }

    /// A minimal opaque page for the navigator integration tests.
    struct BgPage(Size);

    /// The retained half of [`BgPage`].
    struct BgPageWidget(Size);

    impl View<NavState> for BgPage {
        type Element = BgPageWidget;
        fn build(&self, _c: &mut BuildCtx<'_>) -> BgPageWidget {
            BgPageWidget(self.0)
        }
        fn rebuild(&self, _p: &Self, _e: &mut BgPageWidget, _c: &mut BuildCtx<'_>) -> ChangeFlags {
            ChangeFlags::NONE
        }
    }

    impl Widget for BgPageWidget {
        fn layout(&mut self, _c: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            bc.constrain(self.0)
        }
        fn paint(&mut self, ctx: &mut PaintCtx, scene: &mut dyn PaintScene) {
            scene.fill_rect(ctx.origin(), ctx.size(), Color::BLACK);
        }
    }

    /// A navigator rooted on an opaque page, plus the controller driving it.
    struct NavHarness {
        controller: NavigatorController<NavState>,
        root: RenderRoot<NavState, NavigatorView<NavState>>,
        state: NavState,
        tcx: TextContext,
    }

    impl NavHarness {
        fn new() -> Self {
            let controller: NavigatorController<NavState> = NavigatorController::new();
            let mut h = NavHarness {
                controller,
                root: RenderRoot::new(),
                state: NavState::default(),
                tcx: TextContext::new(),
            };
            h.pass();
            h
        }

        fn app(&self) -> impl FnMut(&mut NavState) -> NavigatorView<NavState> + use<> {
            let ctrl = self.controller.clone();
            move |_: &mut NavState| navigator(&ctrl, || core_any::<NavState, _>(BgPage(WINDOW)))
        }

        fn pass(&mut self) {
            let mut app = self.app();
            self.root.rebuild(&mut app, &mut self.state);
            self.root
                .layout_with_text(WINDOW, &mut self.tcx as &mut dyn Any);
        }

        fn paint(&mut self, ms: u64) -> bool {
            self.root
                .paint(&mut Recorder::default(), ft_ms(ms as f64))
                .needs_frame
        }

        /// Drive rebuild → layout → paint until nothing asks for another frame
        /// (bounded), the shape a real shell's loop takes.
        fn drive(&mut self, from_ms: u64) {
            for i in 0..20u64 {
                self.pass();
                if !self.paint(from_ms + i * 100) {
                    return;
                }
            }
            panic!("the frame loop never settled");
        }
    }

    #[test]
    fn show_overlay_modal_pushes_a_transparent_page_that_pops_on_a_staged_dismiss() {
        let mut h = NavHarness::new();
        show_overlay_modal(
            &h.controller,
            || {
                overlay_modal(
                    Block(Size::new(200.0, 120.0)),
                    OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH),
                )
            },
            |state: &mut NavState, result: PopResult| {
                state.results.push(result.take::<i32>());
            },
        );
        h.pass();
        h.drive(0);
        assert_eq!(h.controller.depth(), 2, "the modal is up");

        // A scrim tap stages the exit; the pop lands once it settles.
        h.root
            .event(&mut h.state, &pointer(PointerPhase::Down, 5.0, 5.0));
        h.root
            .event(&mut h.state, &pointer(PointerPhase::Up, 5.0, 5.0));
        assert_eq!(
            h.controller.depth(),
            2,
            "nothing pops during the exit ramp itself"
        );
        h.drive(3000);
        assert_eq!(h.state.results, vec![None], "popped with an empty result");
        assert_eq!(h.controller.depth(), 1);
    }

    /// The staged pop waits out a whole exit ramp, and a navigator pop always
    /// takes the *top* page: a page the app pushes inside that window must not
    /// be popped in the modal's place, and the modal must stay dismissible
    /// afterwards rather than latching `closed` over a page it never removed.
    #[test]
    fn a_page_pushed_during_the_exit_ramp_is_not_popped_in_the_modals_place() {
        let mut h = NavHarness::new();
        show_overlay_modal(
            &h.controller,
            || {
                overlay_modal(
                    Block(Size::new(200.0, 120.0)),
                    OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH),
                )
            },
            |state: &mut NavState, result: PopResult| {
                state.results.push(result.take::<i32>());
            },
        );
        h.pass();
        h.drive(0);

        // A scrim tap stages the exit…
        h.root
            .event(&mut h.state, &pointer(PointerPhase::Down, 5.0, 5.0));
        h.root
            .event(&mut h.state, &pointer(PointerPhase::Up, 5.0, 5.0));

        // …and one frame into the ramp the app pushes a page of its own (a deep
        // link, an async completion landing). Transparent, so the modal keeps
        // painting underneath it and its ramp really does reach the settle that
        // fires the staged pop; an opaque page would cull the modal's paint and
        // the pop would never fire at all.
        h.pass();
        h.paint(3000);
        h.controller
            .push_transparent(|| core_any::<NavState, _>(BgPage(Size::new(400.0, 100.0))));
        h.drive(3100);

        assert_eq!(
            h.controller.depth(),
            3,
            "the pushed page survives — the staged pop was refused, not aimed at it"
        );
        assert!(
            h.state.results.is_empty(),
            "and nothing reported a dismissal"
        );

        // Recoverable, not bricked: back out of the pushed page, then dismiss
        // the modal again — the fresh exit is staged against the stack it
        // actually pops.
        h.controller.request_back();
        h.drive(6000);
        assert_eq!(
            h.controller.depth(),
            2,
            "the pushed page backs out normally"
        );
        h.controller.request_back();
        h.drive(9000);
        assert_eq!(
            h.state.results,
            vec![None],
            "the modal is still dismissible after the refused pop"
        );
        assert_eq!(h.controller.depth(), 1);
    }

    #[test]
    fn a_back_request_dismisses_a_dismissable_modal_through_the_navigator() {
        let mut h = NavHarness::new();
        show_overlay_modal(
            &h.controller,
            || {
                overlay_modal(
                    Block(Size::new(200.0, 120.0)),
                    OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH),
                )
            },
            |state: &mut NavState, result: PopResult| {
                state.results.push(result.take::<i32>());
            },
        );
        h.pass();
        h.drive(0);
        assert!(
            h.controller.back_interest(),
            "a dismissable modal claims back interest"
        );

        h.controller.request_back();
        h.pass();
        assert_eq!(
            h.controller.depth(),
            2,
            "DismissAnimated: the stack is unchanged immediately"
        );
        // The back-press rebuild flagged PAINT; this paint observes the bumped
        // signal and stages the exit — which pops only once it settles.
        assert!(
            h.paint(3000),
            "the staging paint schedules its own continuation"
        );
        assert_eq!(h.controller.depth(), 2, "still up, mid-ramp");
        h.drive(4000);
        assert_eq!(
            h.state.results,
            vec![None],
            "a back request dismisses the modal"
        );
        assert_eq!(h.controller.depth(), 1);
    }

    #[test]
    fn a_back_request_on_a_non_dismissable_modal_is_vetoed() {
        let mut h = NavHarness::new();
        show_overlay_modal(
            &h.controller,
            || {
                overlay_modal(
                    Block(Size::new(200.0, 120.0)),
                    OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH),
                )
                .dismissable(false)
            },
            |state: &mut NavState, result: PopResult| {
                state.results.push(result.take::<i32>());
            },
        );
        h.pass();
        h.drive(0);
        assert!(
            h.controller.back_interest(),
            "a Veto modal still claims the back press"
        );

        h.controller.request_back();
        h.pass();
        h.paint(3000);
        h.paint(6000);
        assert!(
            h.state.results.is_empty(),
            "a non-dismissable modal never pops on a back request"
        );
        assert_eq!(h.controller.depth(), 2);
    }

    #[test]
    fn a_dismiss_request_pops_with_its_result_only_once_the_ramp_settles() {
        let mut h = NavHarness::new();
        let dismiss = ModalDismiss::new();
        let installed = dismiss.clone();
        show_overlay_modal(
            &h.controller,
            move || {
                overlay_modal(
                    Block(Size::new(200.0, 120.0)),
                    OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH),
                )
                .dismiss_handle(installed.clone())
            },
            |state: &mut NavState, result: PopResult| {
                state.results.push(result.take::<i32>());
            },
        );
        h.pass();
        h.drive(0);
        assert_eq!(h.controller.depth(), 2, "the modal is up");

        // The panel's own "Apply": a staged dismissal carrying a value.
        dismiss.dismiss_with(PopResult::of(7));
        h.pass();
        h.paint(3000);
        assert_eq!(
            h.controller.depth(),
            2,
            "nothing pops during the exit ramp itself"
        );
        h.drive(3100);
        assert_eq!(
            h.state.results,
            vec![Some(7)],
            "the payload rides the staged pop to the pusher's on_result"
        );
        assert_eq!(h.controller.depth(), 1);
    }

    /// One handle shared by two panel actions is `show_date_picker`'s exact
    /// shape: "Cancel" dismisses empty, "OK" dismisses with the pick. An OK
    /// pressed *during* the cancel ramp is the documented no-op — it must not
    /// retarget the exit already in flight, or the cancelled panel pops
    /// confirmed.
    #[test]
    fn a_request_refused_mid_ramp_never_retargets_the_exit_it_found() {
        let mut h = NavHarness::new();
        let dismiss = ModalDismiss::new();
        let installed = dismiss.clone();
        show_overlay_modal(
            &h.controller,
            move || {
                overlay_modal(
                    Block(Size::new(200.0, 120.0)),
                    OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH),
                )
                .dismiss_handle(installed.clone())
            },
            |state: &mut NavState, result: PopResult| {
                state.results.push(result.take::<i32>());
            },
        );
        h.pass();
        h.drive(0);

        // "Cancel": an empty staged dismissal.
        dismiss.dismiss();
        h.pass();
        h.paint(3000);
        // …then "OK" lands one frame into its ramp.
        dismiss.dismiss_with(PopResult::of(7));
        h.drive(3100);
        assert_eq!(
            h.state.results,
            vec![None],
            "the ramp in flight is the dismissal, and it keeps its own empty result"
        );
        assert_eq!(h.controller.depth(), 1);

        // The refused request left its payload with the handle rather than in
        // a widget that has since gone — and a re-presentation neither
        // inherits it nor is wedged by it: a fresh request supersedes the
        // stashed value and pops empty again.
        let re_presented = dismiss.clone();
        show_overlay_modal(
            &h.controller,
            move || {
                overlay_modal(
                    Block(Size::new(200.0, 120.0)),
                    OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH),
                )
                .dismiss_handle(re_presented.clone())
            },
            |state: &mut NavState, result: PopResult| {
                state.results.push(result.take::<i32>());
            },
        );
        h.pass();
        h.drive(6000);
        assert_eq!(h.controller.depth(), 2, "the modal is up again");
        dismiss.dismiss();
        h.pass();
        h.drive(9000);
        assert_eq!(
            h.state.results,
            vec![None, None],
            "the re-presented modal observes a fresh request, with no stale payload"
        );
        assert_eq!(h.controller.depth(), 1);
    }

    /// A payload is scoped to the exit its own request staged. A staged pop
    /// **refused** at fire time (the stack moved — see [`StagedPop`]) delivered
    /// nothing and ramps the panel back open, so the payload dies with it
    /// rather than riding whichever unrelated dismissal lands next.
    #[test]
    fn a_refused_staged_pop_drops_the_payload_it_was_carrying() {
        let mut h = NavHarness::new();
        let dismiss = ModalDismiss::new();
        let installed = dismiss.clone();
        show_overlay_modal(
            &h.controller,
            move || {
                overlay_modal(
                    Block(Size::new(200.0, 120.0)),
                    OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH),
                )
                .dismiss_handle(installed.clone())
            },
            |state: &mut NavState, result: PopResult| {
                state.results.push(result.take::<i32>());
            },
        );
        h.pass();
        h.drive(0);

        // The panel's own "Apply", carrying its value…
        dismiss.dismiss_with(PopResult::of(7));
        h.pass();
        h.paint(3000);
        // …and a page lands on top before the ramp settles, so the pop is
        // refused and the panel ramps back open.
        h.controller
            .push_transparent(|| core_any::<NavState, _>(BgPage(Size::new(400.0, 100.0))));
        h.drive(3100);
        assert_eq!(h.controller.depth(), 3, "the pushed page survives");
        assert!(h.state.results.is_empty(), "nothing was delivered");

        // Back out of the pushed page, then dismiss the modal the ordinary
        // way: the payload of the exit that never landed must not ride it.
        h.controller.request_back();
        h.drive(6000);
        assert_eq!(h.controller.depth(), 2);
        h.controller.request_back();
        h.drive(9000);
        assert_eq!(
            h.state.results,
            vec![None],
            "a later, unrelated dismissal pops with its own empty result"
        );
        assert_eq!(h.controller.depth(), 1);
    }

    /// A payload-free `dismiss()` pops empty even when an earlier
    /// `dismiss_with(..)` was never observed: the newer request supersedes the
    /// stash, so the handle cannot deliver a value the app has moved on from.
    #[test]
    fn a_plain_dismiss_after_an_unobserved_dismiss_with_pops_empty() {
        let mut h = NavHarness::new();
        let dismiss = ModalDismiss::new();
        let installed = dismiss.clone();
        show_overlay_modal(
            &h.controller,
            move || {
                overlay_modal(
                    Block(Size::new(200.0, 120.0)),
                    OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH),
                )
                .dismiss_handle(installed.clone())
            },
            |state: &mut NavState, result: PopResult| {
                state.results.push(result.take::<i32>());
            },
        );
        h.pass();
        h.drive(0);

        // Both raised before any pass observes either.
        dismiss.dismiss_with(PopResult::of(7));
        dismiss.dismiss();
        h.pass();
        h.drive(3000);
        assert_eq!(
            h.state.results,
            vec![None],
            "the plain dismissal pops with nothing, not with the stale payload"
        );
        assert_eq!(h.controller.depth(), 1);
    }

    // ---- drag-to-close and snap points --------------------------------------

    /// A bottom sheet's chrome: content-tall, draggable, handled.
    fn sheet_config() -> OverlayModalConfig {
        OverlayModalConfig::edge(OverlaySide::Bottom)
            .handle(true)
            .drag(true)
    }

    /// Build an entered, draggable bottom panel plus its close counter.
    fn dragged() -> (OverlayModalWidget, Rc<Cell<u32>>) {
        let (view, closed) = staged(sheet_config());
        let mut w = build(&view);
        layout(&mut w);
        run_ramp(&mut w, 0.0);
        (w, closed)
    }

    #[test]
    fn a_drag_past_the_midpoint_closes_and_a_shorter_one_springs_back() {
        for (travel, closes) in [(100.0, true), (30.0, false)] {
            let (mut w, closed) = dragged();
            let extent = w.panel_rect().height();
            let start = w.handle_rect().unwrap().center();
            let mut state = Flags::default();
            dispatch(
                &mut w,
                &mut state,
                &pointer(PointerPhase::Down, start.x, start.y),
            );
            dispatch(
                &mut w,
                &mut state,
                &pointer(PointerPhase::Move, start.x, start.y + travel),
            );
            // The panel tracks the pointer: progress falls by the fraction of
            // its own extent the drag covered.
            let expected = 1.0 - travel / extent;
            assert!(
                (w.progress() - expected).abs() < 1e-9,
                "{travel} → {}",
                w.progress()
            );
            assert!(
                w.panel_rect().y0 > 0.0 && w.panel_rect().y1 > WINDOW.height,
                "the panel followed it down"
            );
            dispatch(
                &mut w,
                &mut state,
                &pointer(PointerPhase::Up, start.x, start.y + travel),
            );
            run_ramp(&mut w, 3000.0);
            if closes {
                assert_eq!(closed.get(), 1, "past the midpoint it commits");
                assert_eq!(w.progress(), 0.0);
            } else {
                assert_eq!(closed.get(), 0, "short of it, it settles back open");
                assert!((w.progress() - 1.0).abs() < 1e-9);
            }
        }
    }

    #[test]
    fn a_non_dismissable_sheet_springs_back_from_a_drag_past_the_midpoint() {
        // Neither `on_dismiss` nor `on_close` wired: `overlay_modal` alone, not
        // the `view`/`staged` helpers above (both wire `on_dismiss`) — the shape
        // a `Stack`-mounted sheet with no dismiss hook is left in.
        let mut w = build(&overlay_modal(
            Block(Size::new(200.0, 120.0)),
            sheet_config(),
        ));
        layout(&mut w);
        run_ramp(&mut w, 0.0);
        let extent = w.panel_rect().height();
        let start = w.handle_rect().unwrap().center();
        let mut state = Flags::default();
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Down, start.x, start.y),
        );
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Move, start.x, start.y + extent * 0.9),
        );
        assert!(
            w.progress() < 0.2,
            "the panel still tracks the pointer while dragging: {}",
            w.progress()
        );
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Up, start.x, start.y + extent * 0.9),
        );
        run_ramp(&mut w, 3000.0);
        assert!(
            (w.progress() - 1.0).abs() < 1e-9,
            "no dismiss hook: springs back to open_progress() instead of \
             sticking near zero as an invisible full-window barrier — {}",
            w.progress()
        );
        // The panel is unambiguously open and hittable where it rests, not a
        // residual off-screen sliver.
        assert!(w.panel_rect().contains(w.panel_rect().center()));
        assert!(w.panel_rect().y0 < WINDOW.height && w.panel_rect().y1 == WINDOW.height);
        assert_eq!(state.dismissed, 0, "no dismiss hook ever fired");
    }

    #[test]
    fn snap_points_zero_is_treated_as_absent_and_opens_fully() {
        let (view, _closed) = staged(sheet_config());
        let mut w = build(&view.snap_points(&[0.0]));
        assert!(
            w.open_progress() > PROGRESS_EPSILON,
            "a first point of 0.0 is treated as absent: {}",
            w.open_progress()
        );
        assert_eq!(w.open_progress(), 1.0, "falls back to fully open");

        layout(&mut w);
        run_ramp(&mut w, 0.0);
        assert!(
            (w.progress() - 1.0).abs() < 1e-9,
            "the sheet opens fully rather than opening already closed: {}",
            w.progress()
        );
    }

    #[test]
    fn a_flick_toward_the_edge_closes_from_anywhere() {
        // A tall panel, so the flick's own travel stays a small fraction of the
        // extent and the *speed* is what decides.
        let closed = Rc::new(Cell::new(0u32));
        let hook = closed.clone();
        let mut w = build(
            &overlay_modal(Block(Size::new(200.0, 400.0)), sheet_config())
                .on_close(move || hook.set(hook.get() + 1)),
        );
        layout(&mut w);
        run_ramp(&mut w, 0.0);
        let start = w.handle_rect().unwrap().center();
        let mut state = Flags::default();
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Down, start.x, start.y),
        );
        // A short, fast flick: 40px between two frames 16ms apart is 2500 px/s,
        // well past `OVERLAY_FLING_VELOCITY`, while the panel is still nearly
        // open.
        frame(&mut w, 3000.0);
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Move, start.x, start.y + 40.0),
        );
        frame(&mut w, 3016.0);
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Move, start.x, start.y + 80.0),
        );
        assert!(w.progress() > 0.5, "still mostly open: {}", w.progress());
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Up, start.x, start.y + 80.0),
        );
        run_ramp(&mut w, 4000.0);
        assert_eq!(closed.get(), 1, "the flick committed to the close");
    }

    #[test]
    fn catching_a_closing_sheet_cancels_its_dismissal() {
        let (mut w, closed) = dragged();
        let mut state = Flags::default();
        let handle = w.handle_rect().unwrap().center();
        dispatch(&mut w, &mut state, &escape());
        frame(&mut w, 3000.0);
        frame(
            &mut w,
            3000.0 + MaterialMotion::LONG_2.as_millis() as f64 / 4.0,
        );
        assert!(w.is_exiting() && w.progress() < 1.0);

        // Grabbing the panel mid-exit and pulling it back open wins.
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Down, handle.x, handle.y),
        );
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Move, handle.x, handle.y - 60.0),
        );
        assert!(!w.is_exiting(), "the drag owns the panel now");
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Up, handle.x, handle.y - 60.0),
        );
        run_ramp(&mut w, 4000.0);
        assert_eq!(closed.get(), 0, "nothing closed");
        assert!((w.progress() - 1.0).abs() < 1e-9, "back open");
    }

    #[test]
    fn a_cancelled_drag_returns_to_where_it_started() {
        let (mut w, closed) = dragged();
        let start = w.handle_rect().unwrap().center();
        let mut state = Flags::default();
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Down, start.x, start.y),
        );
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Move, start.x, start.y + 90.0),
        );
        assert!(w.progress() < 1.0);
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Cancel, start.x, start.y + 90.0),
        );
        run_ramp(&mut w, 3000.0);
        assert!((w.progress() - 1.0).abs() < 1e-9, "restored");
        assert_eq!(closed.get(), 0);
    }

    #[test]
    fn a_tap_on_a_draggable_handle_still_dismisses_but_one_on_the_panel_does_not() {
        let (mut w, closed) = dragged();
        let mut state = Flags::default();
        let handle = w.handle_rect().unwrap().center();
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Down, handle.x, handle.y),
        );
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Up, handle.x, handle.y),
        );
        run_ramp(&mut w, 3000.0);
        assert_eq!(closed.get(), 1);

        let (mut w, closed) = dragged();
        let body = w.panel_rect().center();
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Down, body.x, body.y),
        );
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Up, body.x, body.y),
        );
        run_ramp(&mut w, 3000.0);
        assert_eq!(
            closed.get(),
            0,
            "the panel surface is a barrier, not a button"
        );
        assert!((w.progress() - 1.0).abs() < 1e-9);
    }

    #[test]
    fn snap_points_open_at_the_first_and_the_release_takes_the_nearest() {
        let (view, closed) = staged(sheet_config());
        let mut w = build(&view.snap_points(&[0.5, 1.0]));
        layout(&mut w);
        run_ramp(&mut w, 0.0);
        assert!(
            (w.progress() - 0.5).abs() < 1e-9,
            "opens at the first point: {}",
            w.progress()
        );
        let extent = w.panel_rect().height();
        assert!(
            (w.panel_rect().y0 - (WINDOW.height - extent * 0.5)).abs() < 1e-9,
            "and shows exactly that fraction of itself"
        );

        // Dragged up most of the way: the release snaps to the point above.
        let start = w.handle_rect().unwrap().center();
        let mut state = Flags::default();
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Down, start.x, start.y),
        );
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Move, start.x, start.y - extent * 0.4),
        );
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Up, start.x, start.y - extent * 0.4),
        );
        run_ramp(&mut w, 3000.0);
        assert!((w.progress() - 1.0).abs() < 1e-9, "{}", w.progress());
        assert_eq!(closed.get(), 0);

        // Below the lowest point, `0.0` is the nearest: it closes.
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Down, start.x, start.y),
        );
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Move, start.x, start.y + extent * 0.85),
        );
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Up, start.x, start.y + extent * 0.85),
        );
        run_ramp(&mut w, 6000.0);
        assert_eq!(closed.get(), 1);
    }

    #[test]
    fn a_snap_point_above_one_is_logical_px_against_the_extent() {
        let (view, _closed) = staged(sheet_config());
        let mut w = build(&view.snap_points(&[60.0]));
        layout(&mut w);
        run_ramp(&mut w, 0.0);
        let extent = w.panel_rect().height();
        assert!(
            (w.progress() - 60.0 / extent).abs() < 1e-9,
            "{}",
            w.progress()
        );
        assert!(
            (w.panel_rect().y0 - (WINDOW.height - 60.0)).abs() < 1e-9,
            "60 logical px of the sheet are on screen"
        );
    }

    #[test]
    fn snap_points_drops_non_finite_values_at_the_boundary() {
        let (view, _closed) = staged(sheet_config());
        let view = view.snap_points(&[f64::NAN, f64::INFINITY]);
        assert!(
            view.snap_points.is_empty(),
            "NaN and infinity are both non-finite: dropped by the builder, \
             never stored"
        );
    }

    #[test]
    fn non_finite_snap_points_behave_as_absent_through_a_drag_and_never_panic() {
        // Same shape as `a_drag_past_the_midpoint_closes_and_a_shorter_one_
        // springs_back`, but with degenerate snap points: NaN/∞ are dropped
        // at the boundary (`OverlayModalView::snap_points`), so
        // `snap_targets()` is exactly the no-snap-points default `{0.0, 1.0}`
        // and the drag clamp's `open` bound is never NaN — the crash this
        // guards against is `f64::clamp`'s internal `assert!(min <= max)`
        // panicking on a NaN bound, an abort under `panic = "abort"`.
        let (view, closed) = staged(sheet_config());
        let mut w = build(&view.snap_points(&[f64::NAN, f64::INFINITY]));
        layout(&mut w);
        run_ramp(&mut w, 0.0);
        assert!(
            (w.progress() - 1.0).abs() < 1e-9,
            "opens fully, same as no snap points at all: {}",
            w.progress()
        );

        let extent = w.panel_rect().height();
        let start = w.handle_rect().unwrap().center();
        let mut state = Flags::default();
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Down, start.x, start.y),
        );
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Move, start.x, start.y + extent * 0.9),
        );
        assert!(
            w.progress().is_finite(),
            "no NaN reached progress mid-drag: {}",
            w.progress()
        );
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Up, start.x, start.y + extent * 0.9),
        );
        run_ramp(&mut w, 3000.0);
        assert!(w.progress().is_finite());
        assert_eq!(
            closed.get(),
            1,
            "past the midpoint it commits, same as the no-snap-points default"
        );
    }

    #[test]
    fn degenerate_snap_points_dont_strand_the_barrier_on_a_tap_dismiss() {
        // A handle tap (not a drag) still routes through the same exit-ramp
        // settle check (`settled_exit`'s `progress <= PROGRESS_EPSILON`).
        // Degenerate snap points must not leave a NaN in `progress` that
        // would never satisfy that comparison and strand the barrier open
        // forever.
        let (view, closed) = staged(sheet_config());
        let mut w = build(&view.snap_points(&[f64::NAN, f64::INFINITY]));
        layout(&mut w);
        run_ramp(&mut w, 0.0);
        let handle = w.handle_rect().unwrap().center();
        let mut state = Flags::default();
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Down, handle.x, handle.y),
        );
        dispatch(
            &mut w,
            &mut state,
            &pointer(PointerPhase::Up, handle.x, handle.y),
        );
        run_ramp(&mut w, 3000.0);
        assert!(
            w.progress().is_finite(),
            "no NaN reached progress: {}",
            w.progress()
        );
        assert_eq!(w.progress(), 0.0, "settled fully closed, not stranded");
        assert_eq!(
            closed.get(),
            1,
            "the barrier settled and fired on_close, not left stuck open"
        );
    }

    // ---- semantics ----------------------------------------------------------

    #[test]
    fn semantics_is_a_modal_node_labelled_by_its_title() {
        fn logic(_s: &mut Flags) -> OverlayModalView<Flags> {
            overlay_modal(
                Block(Size::new(100.0, 50.0)),
                settled(OverlayModalConfig::centered(OVERLAY_DIALOG_MAX_WIDTH))
                    .role(OverlayRole::AlertDialog),
            )
            .label("Are you sure?")
        }
        let mut root: RenderRoot<Flags, OverlayModalView<Flags>> = RenderRoot::new();
        let mut state = Flags::default();
        root.rebuild(&mut logic, &mut state);
        let mut tcx = TextContext::new();
        root.layout_with_text(WINDOW, &mut tcx as &mut dyn Any);
        let update = root.semantics();
        let (_, node) = update
            .nodes
            .iter()
            .find(|(_, n)| n.role() == Role::AlertDialog)
            .expect("an AlertDialog node");
        assert!(node.is_modal());
        assert_eq!(node.label(), Some("Are you sure?"));
    }

    #[test]
    fn visit_children_publishes_the_content() {
        let w = build(&view(settled(OverlayModalConfig::centered(
            OVERLAY_DIALOG_MAX_WIDTH,
        ))));
        let mut seen = 0usize;
        Widget::visit_children(&w, &mut |_pod| seen += 1);
        assert_eq!(seen, 1);
    }
}