frust-glyph 0.5.2

Glyph design-system catalog for Frust: a terminal-native, dark-first, monospace-led widget set with bundled Space Mono and IBM Plex Mono 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
//! Glyph modal dialog: a scrim + centered surface panel confirmation dialog —
//! the Glyph recipe over the existing navigator transparent-push modal plumbing.
//!
//! # Navigator-modal architecture (reuse, don't fork)
//!
//! A `GlyphDialog` is pushed as a **transparent navigator page** via
//! [`NavigatorController::push_with_options`], with a
//! [`BackPolicy`](frust::BackPolicy) and dismiss signal (below):
//! the page below stays visible under the scrim, and the navigator's modal
//! contract — input routed only to the top page, pointer capture / focus / IME
//! threaded through the page pod — is what makes it modal. [`show_glyph_dialog`]
//! wraps the push, wiring dismissal to `controller.pop()`; nav is consumed
//! read-only. Enforcing "at most one dialog/overlay at a time" stays the app's
//! (or the navigator's) concern — a second transparent page just stacks.
//!
//! # Enter/exit staging (widget-internal, not a navigator transition)
//!
//! The dialog drives its **own** enter/exit animation from
//! `PaintCtx::frame_time` because its two moving parts stage *independently*:
//! the **panel** scales `0.94 → 1.0` over the spatial `enter` duration (220ms)
//! while the **scrim** cross-fades on its own clamped progress. One navigator
//! `Layer` (a single alpha + scale over the
//! whole page) cannot express that, so the staging lives here and the dialog is
//! pushed with [`TransitionSpec::NONE`] — navigator gives the modal contract,
//! widget gives the motion.
//!
//! Exit reverses over the faster `exit` duration (150ms) — "exits always faster
//! than entrances" (the Glyph design system's rule). A dismiss gesture does
//! **not** pop immediately: it flips the widget into its exit phase, and only on
//! completion is the app-supplied close callback
//! ([`on_close`](GlyphDialogView::on_close) / [`show_glyph_dialog`]'s auto-wired
//! `controller.pop()`) fired from [`GlyphDialogWidget::advance`] — during paint,
//! which is sound because `NavigatorController::pop` merely enqueues an op
//! applied on the next rebuild.
//!
//! # Actions, and the dismiss callback is state-free
//!
//! Action buttons are app-provided [`AnyView`]s ([`frust::ButtonStyle`]: a ghost
//! cancel + a danger/primary confirm) that pop the navigator **directly** on tap
//! (e.g. `controller.pop_with_result(PopResult::of(true))`), bypassing the exit
//! animation; only the scrim-tap / `Escape` *cancel* path plays the staging.
//!
//! Firing from paint makes that close callback a plain `Fn()` — not the material
//! dialog's `Fn(&mut State)`, a deliberate divergence. App state changes ride the
//! navigator's `on_result` instead (delivered with `&mut State` after the pop,
//! carrying the dialog's [`PopResult`]): an **action** pops with a value, a
//! **cancel** pops empty.
//!
//! # Body/content slot
//!
//! [`body`](GlyphDialogView::body) (supporting text) and
//! [`content`](GlyphDialogView::content) (an arbitrary app-provided
//! [`AnyView`]) share one slot between the title and the action row —
//! **`content` wins if both are set**, silently in debug and release (no panic,
//! no assert: a `.body()` call is simply shadowed). Reach for `content` when the
//! dialog needs more than static text; a text field is the motivating case.
//!
//! **Sizing:** the slot gets `body`'s own loose-width/unbounded-height
//! constraints (`BoxConstraints::loose(Size::new(w, f64::INFINITY))`), laying
//! out at its intrinsic height while the panel grows to fit. **A documented
//! limit, not a bug:** an oversized slot is never clipped or auto-scrolled, so
//! arbitrarily tall content can push the panel off the top/bottom of the
//! viewport — wrap genuinely unbounded content in your own scroller first.
//!
//! **Focus:** the slot is routed exactly like an action button — a `Down` that
//! hits it is hit-tested and forwarded via
//! [`frust::authoring::route_event_single`], and once it holds the recorded focus
//! path, `Key`/`Ime` events (focus-routed, never hit-tested) go straight to it
//! *before* the dialog's own Escape/dismiss handling gets a look. So a focused
//! [`TextInput`](frust::TextInput) inside `.content()` receives every keystroke;
//! only a key it declines (Escape, which a text field doesn't handle) falls
//! through to the dismiss check.
//!
//! **Blur without dismiss:** a `Down` that reaches neither an action nor the
//! slot — dead panel space: the padding, the title, the gaps — while the slot
//! *did* hold the session ends that session: the dialog publishes an inactive
//! IME surface, which the root reads as a full `release_focus_session`, so the
//! field blurs and the platform keyboard retracts. The dialog itself stays open
//! and stays focused (the barrier consumes the Down, and the same dispatch's
//! focus claim re-applies after the release — `RenderRoot::event`'s documented
//! ordering), so `Escape` keeps working afterwards. Tapping dialog chrome is
//! how a user dismisses the keyboard without answering the dialog.
//!
//! # Keyboard avoidance
//!
//! The panel centers in the **keyboard-free band**, not the whole window:
//! `WindowInsets::view_insets` (the fully-obscured edges — in practice the IME;
//! system bars live in `view_padding`) is read from [`LayoutCtx`] every layout
//! pass and shrinks the band the panel centers in, so an open keyboard slides
//! the panel up and its action row stays reachable. Insets are already a layout
//! input — a shell's `set_insets` flags LAYOUT — so the retraction re-centers
//! the panel by the same path, with no widget-side state.
//!
//! The panel's *height* is deliberately not clamped to the band: a panel taller
//! than the free space pins to the top and overflows downward, exactly the
//! documented overflow degrade an oversized content slot already has (above) —
//! wrap tall content in your own scroller.
//!
//! # `dismissable(bool)` + back-dismiss
//!
//! [`GlyphDialogView::dismissable`] (default `true`) is the single barrier flag
//! gating the scrim tap, `Escape`, and an Android back press together — `false`
//! disables all three (only an action button or an app-driven
//! `controller.pop()` can still close it) and [`show_glyph_dialog`] pushes with
//! [`BackPolicy::Veto`](frust::BackPolicy::Veto), consuming a
//! back press with no visible effect. `true` pushes
//! [`BackPolicy::DismissAnimated`](frust::BackPolicy::DismissAnimated):
//! `show_glyph_dialog` hands the widget the shared dismiss-signal cell
//! [`NavigatorController::request_back`] bumps on a back press, and the widget's
//! `paint` pass (`observe_dismiss_signal`, [`BackPolicy`]'s documented
//! observation seam) compares it against the last-seen value and calls
//! [`begin_exit`](GlyphDialogWidget::begin_exit) — the same staged exit a
//! scrim/Escape cancel drives, never an immediate raw pop.
//!
//! # Typeface
//!
//! The title and body are plain `text(..)` children opted into
//! `.themed_family(..)`: the title takes the live theme's `headlineSmall`
//! family and the body its `bodyMedium` family — Space Mono and IBM Plex Mono
//! under Glyph's own scale, the faces they always painted — resolved at
//! layout, so a theme swap repaints them in the new family. With no theme
//! threaded they fall back to `Text`'s own system family.
//!
//! # Semantics
//!
//! The dialog contributes one [`Role::Dialog`] container node with the accesskit
//! **modal** flag set, labelled by the title, with title/body-or-content/actions
//! as its accesskit children (mirroring `crate::material::dialog`); the
//! body/content slot forwards through [`ChildPod::semantics_child`] whichever of
//! `body`/`content` occupies it, so a `.content()` subtree's own semantics reach
//! the accessibility tree like any other child.

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

use frust::Theme;
use frust::authoring::Role;
use frust::authoring::text::{FontWeight, LineHeight};
use frust::authoring::{
    AnyView, BoxConstraints, BuildCtx, ChangeFlags, ChildPod, EditingState, EventCtx, EventResult,
    ImeState, InputEvent, Key, LayoutCtx, NamedKey, PaintCtx, PaintScene, PointerPhase,
    SemanticsCtx, View, Widget, any,
};
use frust::{Curve, FrameTime};
use kurbo::{Affine, Point, Rect, RoundedRect, Shape, Size};
use peniko::{Brush, Color};

use frust::Timing;
use frust::authoring::{ThemeTextColor, ThemeTextType};
use frust::text;
use frust::{BackPolicy, NavigatorController, PopResult, PushOptions};
use frust::{TransitionDriver, TransitionSpec, make_driver};

use crate::press::presses;

/// Scrim opacity behind the panel at full enter (an original, hand-picked
/// value — a terminal-dark modal barrier, heavier than M3's 32% so the amber
/// panel reads against the void surface).
const SCRIM_ALPHA: f32 = 0.6;
/// Panel padding on all four edges, in logical px (an original, hand-picked
/// value — Glyph's roomy `--space-5` gutter).
const DIALOG_PADDING: f64 = 20.0;
/// Vertical spacing between the title and body, in logical px.
const TITLE_BODY_GAP: f64 = 10.0;
/// Vertical spacing between the body and the action row, in logical px.
const BODY_ACTIONS_GAP: f64 = 20.0;
/// Horizontal spacing between adjacent action buttons, in logical px.
const ACTION_GAP: f64 = 10.0;
/// Minimum dialog panel width, in logical px.
const MIN_WIDTH: f64 = 300.0;
/// Maximum dialog panel width, in logical px.
const MAX_WIDTH: f64 = 480.0;
/// Breathing margin kept between the panel and the window's horizontal edges,
/// in logical px per side (an original, hand-picked value — Glyph's roomy
/// gutter family, slightly wider than the panel's own 20px `DIALOG_PADDING`).
/// On any window narrower than `MAX_WIDTH + 2 * SCREEN_MARGIN` this margin,
/// not `MAX_WIDTH`, is what bounds the panel — every phone falls in that
/// range, so without it the panel goes full-bleed edge-to-edge.
const SCREEN_MARGIN: f64 = 24.0;

/// Unthemed-fallback panel corner radius — Glyph's `--radius-lg` (14px). A theme
/// resolves this from `shape.large`.
const RADIUS: f64 = 14.0;
/// Unthemed-fallback panel surface fill (Glyph dark `bg-raised` `#1e2430`). A
/// theme resolves this from `colors.surface_container_high`.
const CONTAINER: Color = Color::from_rgb8(0x1e, 0x24, 0x30);
/// Unthemed-fallback panel border (Glyph dark `border-bright`). A theme resolves
/// this from `colors.outline`.
const BORDER: Color = Color::from_rgb8(0x3e, 0x3f, 0x44);
/// Panel border width, in logical px (`--border` = 1px).
const BORDER_WIDTH: f64 = 1.0;
/// Corner-rounding tolerance for the border stroke (mirrors
/// `crate::alert`'s constant).
const PATH_TOLERANCE: f64 = 0.1;
/// Unthemed-fallback scrim base color (a theme resolves this from `colors.scrim`).
const SCRIM: Color = Color::from_rgb8(0x00, 0x00, 0x00);
/// Unthemed-fallback chrome-level shadow (Glyph `--shadow-chrome`: a deep
/// `0 12px 32px` drop). A theme resolves this from `elevation.level5`.
const SHADOW_Y: f64 = 12.0;
const SHADOW_BLUR: f64 = 32.0;
const SHADOW_ALPHA: f32 = 0.45;

/// Title type: 15/700. Its family is the live theme's `headlineSmall` role
/// (Glyph's `display` family, Space Mono, under Glyph's own scale).
const TITLE_SIZE: f32 = 15.0;
const TITLE_WEIGHT: FontWeight = FontWeight::BOLD;
const TITLE_LINE_HEIGHT: f32 = 20.0;
/// Body type: 12.5, `fg-muted`. Its family is the live theme's `bodyMedium`
/// role (Glyph's `body` family, IBM Plex Mono, under Glyph's own scale).
const BODY_SIZE: f32 = 12.5;
const BODY_LINE_HEIGHT: f32 = 18.0;

/// Panel enter scale start (`0.94 → 1.0` over the spatial enter).
const ENTER_SCALE_START: f64 = 0.94;
/// Enter duration fallback (`durations.base` = 220ms) when no theme is threaded.
const ENTER_DURATION: Duration = Duration::from_millis(220);
/// Enter easing fallback (Glyph `spatial` cubic — an authored overshoot).
const ENTER_CURVE: Curve = Curve::Cubic(0.34, 1.35, 0.64, 1.0);
/// Exit duration fallback (`durations.fast` = 150ms; exits faster than entrances).
const EXIT_DURATION: Duration = Duration::from_millis(150);
/// Exit easing fallback (Glyph `exit` accelerate-out cubic).
const EXIT_CURVE: Curve = Curve::Cubic(0.4, 0.0, 1.0, 1.0);
/// `reduce_motion`'s collapsed crossfade duration (mirrors
/// `nav::transition::REDUCE_MOTION_DURATION`).
const REDUCE_MOTION_DURATION: Duration = Duration::from_millis(120);

/// The cleared/inactive IME surface published when a Down on dead panel space
/// ends the body slot's session, so the platform keyboard retracts (mirrors
/// `nav::navigator`'s and `motion::switcher`'s identical local helpers).
///
/// `active: false` is what makes this a **session release** rather than a
/// surface refresh: `RenderRoot::event` reads the inactive flag as "this
/// session is over" and takes the full release (focus flag *and* stored
/// surface), before it applies the same dispatch's focus claim. The remaining
/// fields are the empty/no-selection form — no shell reads them for an inactive
/// surface — spelled out so the value is a valid, self-describing `ImeState`.
fn cleared_ime_state() -> ImeState {
    ImeState {
        active: false,
        editing: EditingState {
            text: String::new(),
            selection_base: -1,
            selection_extent: -1,
            composing_base: -1,
            composing_extent: -1,
        },
        caret: None,
        content_type: Default::default(),
        suppress_soft_keyboard: false,
    }
}

/// Replace `color`'s alpha channel with `alpha`.
fn with_alpha(color: Color, alpha: f32) -> Color {
    let c = color.components;
    Color::new([c[0], c[1], c[2], alpha])
}

/// The `(enter, exit)` [`Timing`]s for the current `reduce_motion` state: the
/// authored spatial/exit durations+curves, or both collapsed to a fast linear
/// crossfade (a hard accessibility rule).
fn resolve_timings(theme: Option<&Theme>) -> (Timing, Timing) {
    if theme.map(|t| t.motion.reduce_motion).unwrap_or(false) {
        let t = Timing::Duration(REDUCE_MOTION_DURATION, Curve::Linear);
        return (t, t);
    }
    match theme {
        Some(t) => (
            Timing::Duration(
                Duration::from_secs_f64(t.motion.durations.base / 1000.0),
                t.motion.easing.spatial,
            ),
            Timing::Duration(
                Duration::from_secs_f64(t.motion.durations.fast / 1000.0),
                t.motion.easing.exit,
            ),
        ),
        None => (
            Timing::Duration(ENTER_DURATION, ENTER_CURVE),
            Timing::Duration(EXIT_DURATION, EXIT_CURVE),
        ),
    }
}

fn resolve_container(theme: Option<&Theme>) -> Color {
    match theme {
        Some(t) => t.scheme().surface_container_high,
        None => CONTAINER,
    }
}

fn resolve_border(theme: Option<&Theme>) -> Color {
    match theme {
        Some(t) => t.scheme().outline,
        None => BORDER,
    }
}

fn resolve_radius(theme: Option<&Theme>) -> f64 {
    match theme {
        Some(t) => t.shape.large,
        None => RADIUS,
    }
}

fn resolve_scrim(theme: Option<&Theme>) -> Color {
    match theme {
        Some(t) => t.scheme().scrim,
        None => SCRIM,
    }
}

/// The `(y_offset, blur_std_dev, color)` chrome-level shadow triple: themed
/// `elevation.level5.shadow(brightness)`, or the unthemed fallback.
fn resolve_shadow(theme: Option<&Theme>) -> (f64, f64, Color) {
    match theme {
        Some(t) => {
            let s = t.elevation.level5.shadow(t.brightness);
            (
                s.y_offset,
                s.blur_std_dev,
                with_alpha(t.scheme().shadow, s.color_alpha),
            )
        }
        None => (SHADOW_Y, SHADOW_BLUR, with_alpha(SCRIM, SHADOW_ALPHA)),
    }
}

/// Coerce a possibly-infinite constraint dimension to a finite value.
fn finite_or_zero(v: f64) -> f64 {
    if v.is_finite() { v } else { 0.0 }
}

/// The title child view (15/700, `onSurface`, family from the theme's
/// `headlineSmall` role at layout — unthemed, `Text`'s own system family).
fn title_view<State: 'static>(s: &str) -> AnyView<State> {
    any::<State, _>(
        text(s.to_string())
            .size(TITLE_SIZE)
            .weight(TITLE_WEIGHT)
            .line_height(LineHeight::Absolute(TITLE_LINE_HEIGHT))
            .themed_family(ThemeTextType::HeadlineSmall),
    )
}

/// The body child view (12.5, `onSurfaceVariant`, family from the theme's
/// `bodyMedium` role at layout — unthemed, `Text`'s own system family).
fn body_view<State: 'static>(s: &str) -> AnyView<State> {
    any::<State, _>(
        text(s.to_string())
            .size(BODY_SIZE)
            .line_height(LineHeight::Absolute(BODY_LINE_HEIGHT))
            .themed_role(ThemeTextColor::OnSurfaceVariant)
            .themed_family(ThemeTextType::BodyMedium),
    )
}

/// A state-free "close this dialog" callback — see the [module docs](self)'s
/// "Actions, and the dismiss callback is state-free" note.
type OnClose = Rc<dyn Fn()>;

/// A declarative Glyph modal dialog. See the [module docs](self).
pub struct GlyphDialogView<State: 'static> {
    title: Option<String>,
    body: Option<String>,
    /// Arbitrary body/content-slot widget — see
    /// [`content`](GlyphDialogView::content) and the [module docs](self)'s
    /// "Body/content slot" section. Wins over `body` when both are set.
    content: Option<AnyView<State>>,
    actions: Vec<AnyView<State>>,
    scrim_dismissible: bool,
    on_close: Option<OnClose>,
    dismissable: bool,
    /// The shared back-press dismiss-signal cell (the `DismissAnimated`
    /// seam) — wired internally by [`show_glyph_dialog`], never part of the
    /// public builder surface (see the [module docs](self)).
    dismiss_signal: Option<Rc<Cell<u64>>>,
}

/// The resolved body/content slot for one frame — see
/// [`GlyphDialogView::body_slot`].
enum BodySlot<'a, State: 'static> {
    /// Neither `body` nor `content` is set.
    None,
    /// `body` text, rendered through [`body_view`].
    Text(&'a str),
    /// An app-provided [`content`](GlyphDialogView::content) view (wins over
    /// `body` when both are set).
    Content(&'a AnyView<State>),
}

impl<State: 'static> GlyphDialogView<State> {
    /// Resolve the body/content slot for this frame, applying the
    /// content-wins precedence documented on [`content`](Self::content): a
    /// `.body()` call is simply shadowed (never a panic, live or in a debug
    /// build) when `.content()` is also set.
    fn body_slot(&self) -> BodySlot<'_, State> {
        if let Some(c) = &self.content {
            BodySlot::Content(c)
        } else if let Some(b) = &self.body {
            BodySlot::Text(b.as_str())
        } else {
            BodySlot::None
        }
    }
}

/// Create an empty Glyph dialog. Chain [`title`](GlyphDialogView::title)/
/// [`body`](GlyphDialogView::body)/[`action`](GlyphDialogView::action) to fill
/// it, and [`on_close`](GlyphDialogView::on_close) to wire dismissal (usually
/// `controller.pop()` — [`show_glyph_dialog`] does this for you).
pub fn glyph_dialog<State: 'static>() -> GlyphDialogView<State> {
    GlyphDialogView {
        title: None,
        body: None,
        content: None,
        actions: Vec::new(),
        scrim_dismissible: true,
        on_close: None,
        dismissable: true,
        dismiss_signal: None,
    }
}

/// PascalCase alias for [`glyph_dialog`], matching the widget-fn vocabulary.
#[allow(non_snake_case)]
pub fn GlyphDialog<State: 'static>() -> GlyphDialogView<State> {
    glyph_dialog()
}

impl<State: 'static> GlyphDialogView<State> {
    /// Set the dialog title (`onSurface`; family from the theme's
    /// `headlineSmall` role — Glyph's display family, Space Mono).
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Set the dialog supporting text (`onSurfaceVariant`; family from the
    /// theme's `bodyMedium` role — Glyph's body family, IBM Plex Mono).
    ///
    /// Shares its slot with [`content`](Self::content) — **`content` wins if
    /// both are set** (see the [module docs](self)'s "Body/content slot"
    /// section); this call is otherwise unaffected by whether `content` is
    /// also set later in the chain.
    pub fn body(mut self, body: impl Into<String>) -> Self {
        self.body = Some(body.into());
        self
    }

    /// Set arbitrary widget content in the body slot — the first-class
    /// escape hatch for content `.body()`'s plain-text slot can't express
    /// (the motivating case: a text field inside the dialog).
    ///
    /// Shares its slot with [`body`](Self::body) — **`content` wins if both
    /// are set**, silently (no panic, no assert, in debug or release). See
    /// the [module docs](self)'s "Body/content slot" section for the
    /// sizing/overflow and focus contract.
    pub fn content(mut self, content: AnyView<State>) -> Self {
        self.content = Some(content);
        self
    }

    /// Replace the trailing action row (app-provided buttons, in reading order —
    /// the last sits closest to the trailing edge).
    pub fn actions(mut self, actions: Vec<AnyView<State>>) -> Self {
        self.actions = actions;
        self
    }

    /// Append one action button to the trailing action row.
    pub fn action(mut self, action: AnyView<State>) -> Self {
        self.actions.push(action);
        self
    }

    /// Whether a tap on the scrim (outside the panel) cancels the dialog
    /// (default `true`). Set `false` for a dialog the user must answer via an
    /// action.
    pub fn scrim_dismissible(mut self, dismissible: bool) -> Self {
        self.scrim_dismissible = dismissible;
        self
    }

    /// Whether this dialog can be dismissed by the user at all — the scrim
    /// tap, `Escape`, and an Android back press (default `true`, Flutter's
    /// `barrierDismissible` parity — see the [module docs](self)). `false`
    /// disables all three; only an explicit action button or an app-driven
    /// `controller.pop()` still closes it. Combines with
    /// [`scrim_dismissible`](Self::scrim_dismissible) (both must allow a scrim
    /// tap to cancel).
    pub fn dismissable(mut self, dismissable: bool) -> Self {
        self.dismissable = dismissable;
        self
    }

    /// Set the state-free close callback — invoked once, from paint, when the
    /// exit animation completes after a scrim/Escape cancel. [`show_glyph_dialog`]
    /// wires this to `controller.pop()` automatically.
    pub fn on_close<F: Fn() + 'static>(mut self, on_close: F) -> Self {
        self.on_close = Some(Rc::new(on_close));
        self
    }
}

/// Push `build`'s dialog as a transparent navigator page (the page below stays
/// visible under the scrim), and register `on_result` for the value the dialog
/// pops with. The scrim/Escape cancel is wired to `controller.pop()` (an empty
/// [`PopResult`]); an action pops with a value via
/// `controller.pop_with_result(..)`.
///
/// The dialog is pushed with [`TransitionSpec::NONE`] — the navigator supplies
/// the modal contract, the widget supplies its own enter/exit staging (see the
/// [module docs](self)).
///
/// ```ignore
/// show_glyph_dialog(
///     &state.nav,
///     || glyph_dialog().title("Delete?").body("This can't be undone.").action(confirm_button),
///     |state: &mut State, result: PopResult| {
///         state.confirmed = result.take::<bool>().unwrap_or(false);
///     },
/// );
/// ```
pub fn show_glyph_dialog<State, B, R>(
    controller: &NavigatorController<State>,
    build: B,
    on_result: R,
) where
    State: 'static,
    B: Fn() -> GlyphDialogView<State> + 'static,
    R: Fn(&mut State, PopResult) + 'static,
{
    let close_ctrl = controller.clone();
    // Peeked once, at show-time: the back policy/dismiss-signal wiring is
    // fixed for the life of this pushed page (mirrors the back-press seam's push-time
    // `PushOptions` contract), even though `build` is re-invoked on every
    // later navigator rebuild to diff the page's content.
    let dismissable = build().dismissable;
    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 = close_ctrl.clone();
            let mut view = build().on_close(move || ctrl.pop());
            view.dismiss_signal = widget_signal.clone();
            any::<State, _>(view)
        },
        options,
    );
}

/// The dialog's enter/exit lifecycle phase.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Phase {
    /// Animating in (panel `0.94 → 1.0`, scrim fading in).
    Enter,
    /// Fully shown, at rest.
    Shown,
    /// Animating out after a scrim/Escape cancel.
    Exit,
    /// Exit complete; the close callback has fired and the page will be popped.
    Dismissed,
}

/// The retained widget for a [`GlyphDialogView`]. See the [module docs](self).
pub struct GlyphDialogWidget {
    title: Option<ChildPod>,
    title_text: Option<String>,
    /// The body/content slot — either the built `body` text
    /// ([`body_view`]) or an app-provided [`GlyphDialogView::content`] view,
    /// whichever [`BodySlot`] resolved to (see the [module docs](self)'s
    /// "Body/content slot" section). Routed for events, painted, and
    /// forwarded for semantics exactly like `title`/an action — the widget
    /// never needs to know which of the two occupies it.
    body: Option<ChildPod>,
    /// `body`'s source text, `Some` only when the slot is currently holding
    /// `body_view` text (not an app [`GlyphDialogView::content`] view).
    body_text: Option<String>,
    actions: Vec<ChildPod>,
    scrim_dismissible: bool,
    on_close: Option<OnClose>,
    dismissable: bool,
    /// The shared back-press dismiss-signal cell (the `DismissAnimated`
    /// seam) — see [`observe_dismiss_signal`](Self::observe_dismiss_signal).
    dismiss_signal: Option<Rc<Cell<u64>>>,
    /// The last generation observed from `dismiss_signal` (0 with no signal
    /// wired, or a `Veto`/non-dismissable dialog).
    last_seen_dismiss: u64,
    /// The centered panel rect in the widget's own local coordinate space.
    panel: Rect,
    phase: Phase,
    /// The enter/exit progress driver — lazily built on the first paint that
    /// sees the phase (rebuild has no theme to resolve a [`Timing`] from).
    driver: Option<TransitionDriver>,
    /// A scrim/panel-background press is in flight (the modal barrier captured
    /// the pointer).
    scrim_captured: bool,
    /// Whether that press started outside the panel (only an outside press
    /// released outside cancels).
    scrim_down_outside: bool,
}

/// Reconcile one optional text child (title/body) in place.
fn reconcile_optional<State: 'static>(
    prev: Option<&String>,
    next: Option<&String>,
    pod: &mut Option<ChildPod>,
    make: impl Fn(&str) -> AnyView<State>,
    ctx: &mut BuildCtx<'_>,
) -> ChangeFlags {
    match (prev, next) {
        (None, Some(s)) => {
            *pod = Some(frust::authoring::build_child(&make(s.as_str()), ctx));
            ChangeFlags::LAYOUT | ChangeFlags::PAINT
        }
        (Some(s), None) => {
            if let Some(p) = pod.as_mut() {
                frust::authoring::teardown_child(&make(s.as_str()), p, ctx);
            }
            *pod = None;
            ChangeFlags::LAYOUT | ChangeFlags::PAINT
        }
        (Some(a), Some(b)) => match pod.as_mut() {
            Some(p) => {
                frust::authoring::rebuild_child(&make(a.as_str()), &make(b.as_str()), p, ctx)
            }
            None => ChangeFlags::NONE,
        },
        (None, None) => ChangeFlags::NONE,
    }
}

/// Reconcile the body/content slot in place, applying the content-wins
/// precedence documented on [`GlyphDialogView::content`].
///
/// Unlike [`reconcile_optional`] (a plain optional string, e.g. `title`),
/// this slot's `Some` case can be either `body` text or an app-provided
/// [`AnyView`] — a transition between any two of the three states (none,
/// text, content) is handled the same way `Some(a) -> Some(b)` handles a
/// same-string no-op or a text edit: [`frust::authoring::rebuild_child`]
/// delegates to `AnyView`'s own type-erased rebuild, which tears down and
/// rebuilds the child on a concrete-type mismatch (text ↔ content, or
/// content ↔ a *different* content view) and mutates in place otherwise —
/// this function only has to decide when the pod itself is born or dies.
fn reconcile_body_slot<State: 'static>(
    prev: &GlyphDialogView<State>,
    next: &GlyphDialogView<State>,
    pod: &mut Option<ChildPod>,
    ctx: &mut BuildCtx<'_>,
) -> ChangeFlags {
    match (prev.body_slot(), next.body_slot()) {
        (BodySlot::None, BodySlot::None) => ChangeFlags::NONE,
        (BodySlot::None, BodySlot::Text(s)) => {
            *pod = Some(frust::authoring::build_child(&body_view::<State>(s), ctx));
            ChangeFlags::LAYOUT | ChangeFlags::PAINT
        }
        (BodySlot::None, BodySlot::Content(v)) => {
            *pod = Some(frust::authoring::build_child(v, ctx));
            ChangeFlags::LAYOUT | ChangeFlags::PAINT
        }
        (BodySlot::Text(s), BodySlot::None) => {
            if let Some(p) = pod.as_mut() {
                frust::authoring::teardown_child(&body_view::<State>(s), p, ctx);
            }
            *pod = None;
            ChangeFlags::LAYOUT | ChangeFlags::PAINT
        }
        (BodySlot::Content(_), BodySlot::None) => {
            if let (Some(v), Some(p)) = (&prev.content, pod.as_mut()) {
                frust::authoring::teardown_child(v, p, ctx);
            }
            *pod = None;
            ChangeFlags::LAYOUT | ChangeFlags::PAINT
        }
        (BodySlot::Text(a), BodySlot::Text(b)) => match pod.as_mut() {
            Some(p) => frust::authoring::rebuild_child(
                &body_view::<State>(a),
                &body_view::<State>(b),
                p,
                ctx,
            ),
            None => ChangeFlags::NONE,
        },
        (BodySlot::Text(a), BodySlot::Content(v)) => match pod.as_mut() {
            Some(p) => frust::authoring::rebuild_child(&body_view::<State>(a), v, p, ctx),
            None => ChangeFlags::NONE,
        },
        (BodySlot::Content(_), BodySlot::Text(b)) => match pod.as_mut() {
            Some(p) => {
                let pv = prev
                    .content
                    .as_ref()
                    .expect("BodySlot::Content implies `content` is set");
                frust::authoring::rebuild_child(pv, &body_view::<State>(b), p, ctx)
            }
            None => ChangeFlags::NONE,
        },
        (BodySlot::Content(_), BodySlot::Content(_)) => match pod.as_mut() {
            Some(p) => {
                let pv = prev
                    .content
                    .as_ref()
                    .expect("BodySlot::Content implies `content` is set");
                let nv = next
                    .content
                    .as_ref()
                    .expect("BodySlot::Content implies `content` is set");
                frust::authoring::rebuild_child(pv, nv, p, ctx)
            }
            None => ChangeFlags::NONE,
        },
    }
}

impl<State: 'static> View<State> for GlyphDialogView<State> {
    type Element = GlyphDialogWidget;

    fn build(&self, ctx: &mut BuildCtx<'_>) -> GlyphDialogWidget {
        GlyphDialogWidget {
            title: self
                .title
                .as_ref()
                .map(|s| frust::authoring::build_child(&title_view::<State>(s), ctx)),
            title_text: self.title.clone(),
            body: match self.body_slot() {
                BodySlot::None => None,
                BodySlot::Text(s) => {
                    Some(frust::authoring::build_child(&body_view::<State>(s), ctx))
                }
                BodySlot::Content(v) => Some(frust::authoring::build_child(v, ctx)),
            },
            body_text: match self.body_slot() {
                BodySlot::Text(s) => Some(s.to_string()),
                _ => None,
            },
            actions: self
                .actions
                .iter()
                .map(|v| frust::authoring::build_child(v, ctx))
                .collect(),
            scrim_dismissible: self.scrim_dismissible,
            on_close: self.on_close.clone(),
            dismissable: self.dismissable,
            dismiss_signal: self.dismiss_signal.clone(),
            last_seen_dismiss: self.dismiss_signal.as_ref().map(|s| s.get()).unwrap_or(0),
            panel: Rect::ZERO,
            phase: Phase::Enter,
            driver: None,
            scrim_captured: false,
            scrim_down_outside: false,
        }
    }

    fn rebuild(
        &self,
        prev: &Self,
        element: &mut GlyphDialogWidget,
        ctx: &mut BuildCtx<'_>,
    ) -> ChangeFlags {
        let mut flags = ChangeFlags::NONE;
        flags |= reconcile_optional(
            prev.title.as_ref(),
            self.title.as_ref(),
            &mut element.title,
            title_view::<State>,
            ctx,
        );
        element.title_text = self.title.clone();
        flags |= reconcile_body_slot(prev, self, &mut element.body, ctx);
        element.body_text = match self.body_slot() {
            BodySlot::Text(s) => Some(s.to_string()),
            _ => None,
        };

        let prev_views: Vec<&AnyView<State>> = prev.actions.iter().collect();
        let next_views: Vec<&AnyView<State>> = self.actions.iter().collect();
        flags |= frust::authoring::rebuild_children(
            &prev_views,
            &next_views,
            &mut element.actions,
            ctx,
            |view: &&AnyView<State>| *view,
            |_| None,
        );

        element.scrim_dismissible = self.scrim_dismissible;
        // Closures aren't comparable; reinstall the close adapter unconditionally.
        element.on_close = self.on_close.clone();
        element.dismissable = self.dismissable;
        // The dismiss-signal cell's identity is fixed at push time (see
        // `show_glyph_dialog`); reinstalling it here never disturbs
        // `last_seen_dismiss`.
        element.dismiss_signal = self.dismiss_signal.clone();
        flags
    }

    fn teardown(&self, element: &mut GlyphDialogWidget, ctx: &mut BuildCtx<'_>) {
        if let (Some(s), Some(p)) = (&self.title, element.title.as_mut()) {
            frust::authoring::teardown_child(&title_view::<State>(s), p, ctx);
        }
        match (self.body_slot(), element.body.as_mut()) {
            (BodySlot::Text(s), Some(p)) => {
                frust::authoring::teardown_child(&body_view::<State>(s), p, ctx);
            }
            (BodySlot::Content(v), Some(p)) => {
                frust::authoring::teardown_child(v, p, ctx);
            }
            _ => {}
        }
        for (view, pod) in self.actions.iter().zip(element.actions.iter_mut()) {
            frust::authoring::teardown_child(view, pod, ctx);
        }
    }
}

impl GlyphDialogWidget {
    /// Begin the exit animation (a scrim/Escape cancel). Idempotent: only a
    /// `Enter`/`Shown` dialog can start exiting.
    fn begin_exit(&mut self) {
        if matches!(self.phase, Phase::Enter | Phase::Shown) {
            self.phase = Phase::Exit;
            self.driver = None;
        }
    }

    /// Observe the shared back-press dismiss-signal cell (see the
    /// `dismiss_signal` field docs) and begin the exit staging exactly once
    /// per bump — the `BackPolicy::DismissAnimated` seam's widget-side half
    /// (`nav::navigator::BackPolicy`'s documented observation seam). A back
    /// request flags `PAINT`, so this always runs before the next frame is
    /// shown.
    fn observe_dismiss_signal(&mut self) {
        if let Some(signal) = &self.dismiss_signal {
            let current = signal.get();
            if current != self.last_seen_dismiss {
                self.last_seen_dismiss = current;
                self.begin_exit();
            }
        }
    }

    /// Advance the enter/exit phase machine to frame time `now`, returning the
    /// `(panel_scale, scrim_fraction)` to paint at plus whether the widget is
    /// still animating. Factored out of `paint` so the full timeline is drivable
    /// with synthetic [`FrameTime`]s in a unit test (mirrors
    /// `crate::toast`'s `advance`).
    fn advance(&mut self, now: FrameTime, enter: Timing, exit: Timing) -> (f64, f32, bool) {
        match self.phase {
            Phase::Enter => {
                let adv = self
                    .driver
                    .get_or_insert_with(|| make_driver(enter).0)
                    .advance(now);
                if adv.done {
                    self.phase = Phase::Shown;
                    self.driver = None;
                }
                let p = adv.value;
                let scale = ENTER_SCALE_START + (1.0 - ENTER_SCALE_START) * p;
                (scale, p.clamp(0.0, 1.0) as f32, !adv.done)
            }
            Phase::Shown => (1.0, 1.0, false),
            Phase::Exit => {
                let adv = self
                    .driver
                    .get_or_insert_with(|| make_driver(exit).0)
                    .advance(now);
                let q = adv.value.clamp(0.0, 1.0);
                let scale = 1.0 - (1.0 - ENTER_SCALE_START) * q;
                if adv.done {
                    self.phase = Phase::Dismissed;
                    self.driver = None;
                    if let Some(on_close) = &self.on_close {
                        on_close();
                    }
                }
                (scale, (1.0 - q) as f32, !adv.done)
            }
            Phase::Dismissed => (ENTER_SCALE_START, 0.0, false),
        }
    }
}

impl Widget for GlyphDialogWidget {
    fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
        let area_w = finite_or_zero(bc.max().width);
        let area_h = finite_or_zero(bc.max().height);

        // The keyboard-free band the panel centers inside (see the [module
        // docs](self)'s "Keyboard avoidance" section). `view_insets` is the
        // *fully-obscured* edge set — in practice the IME, never the system
        // bars, which live in `view_padding` (`frust_core::WindowInsets`) — so
        // the vertical band shrinks exactly by the open keyboard. Read fresh
        // every layout pass, the same way `SafeArea`/`glyph::appbar` read
        // theirs: a shell's `set_insets` flags LAYOUT itself, so the panel
        // re-centers on the keyboard's way up *and* its way down with no
        // widget-side state and no animation of our own.
        let view_insets = ctx.window_insets().view_insets;
        let free_top = view_insets.top.clamp(0.0, area_h);
        let free_bottom = (area_h - view_insets.bottom).clamp(free_top, area_h);
        let free_h = free_bottom - free_top;

        let panel_max_w = (area_w - 2.0 * SCREEN_MARGIN).clamp(0.0, MAX_WIDTH);
        let content_max_w = (panel_max_w - 2.0 * DIALOG_PADDING).max(0.0);
        let child_bc = BoxConstraints::loose(Size::new(content_max_w, f64::INFINITY));

        let mut content_w: f64 = 0.0;
        let title_size = self.title.as_mut().map(|p| {
            let s = p.layout_child(ctx, &child_bc);
            content_w = content_w.max(s.width);
            s
        });
        let body_size = self.body.as_mut().map(|p| {
            let s = p.layout_child(ctx, &child_bc);
            content_w = content_w.max(s.width);
            s
        });

        let mut actions_w: f64 = 0.0;
        let mut actions_h: f64 = 0.0;
        for (i, pod) in self.actions.iter_mut().enumerate() {
            let s = pod.layout_child(ctx, &child_bc);
            if i > 0 {
                actions_w += ACTION_GAP;
            }
            actions_w += s.width;
            actions_h = actions_h.max(s.height);
        }
        if !self.actions.is_empty() {
            content_w = content_w.max(actions_w);
        }

        // The margin wins over MIN_WIDTH's own floor: on a window narrower than
        // `MIN_WIDTH + 2 * SCREEN_MARGIN`, MIN_WIDTH would sit above panel_max_w
        // and invert this clamp, so the lower bound shrinks to panel_max_w
        // instead of pushing the panel back out to full bleed.
        let lower = MIN_WIDTH.min(panel_max_w);
        let panel_w = (content_w + 2.0 * DIALOG_PADDING).clamp(lower, panel_max_w);

        let mut y = DIALOG_PADDING;
        let mut title_y = 0.0;
        let mut body_y = 0.0;
        let mut actions_y = 0.0;
        if let Some(s) = title_size {
            title_y = y;
            y += s.height;
        }
        if let Some(s) = body_size {
            if title_size.is_some() {
                y += TITLE_BODY_GAP;
            }
            body_y = y;
            y += s.height;
        }
        if !self.actions.is_empty() {
            if title_size.is_some() || body_size.is_some() {
                y += BODY_ACTIONS_GAP;
            }
            actions_y = y;
            y += actions_h;
        }
        y += DIALOG_PADDING;
        let panel_h = y;

        let panel_x = ((area_w - panel_w) / 2.0).max(0.0);
        // Centered in the keyboard-free band, not the whole window — with no
        // insets pushed the band *is* the window and this is the previous
        // `(area_h - panel_h) / 2.0` exactly. A panel taller than the band
        // pins to the top (the `max(0.0)`) and overflows downward, which is
        // the same documented overflow degrade an oversized content slot
        // already has (the [module docs](self)'s "Body/content slot"): the
        // panel is never clipped or auto-scrolled, so its own height is
        // deliberately NOT clamped to the band.
        let panel_y = (free_top + (free_h - panel_h) / 2.0).max(0.0);
        self.panel = Rect::new(panel_x, panel_y, panel_x + panel_w, panel_y + panel_h);

        if let Some(p) = self.title.as_mut() {
            p.set_origin(Point::new(panel_x + DIALOG_PADDING, panel_y + title_y));
        }
        if let Some(p) = self.body.as_mut() {
            p.set_origin(Point::new(panel_x + DIALOG_PADDING, panel_y + body_y));
        }
        let mut ax = panel_x + panel_w - DIALOG_PADDING;
        for pod in self.actions.iter_mut().rev() {
            let w = pod.size().width;
            ax -= w;
            pod.set_origin(Point::new(ax, panel_y + actions_y));
            ax -= ACTION_GAP;
        }

        bc.constrain(Size::new(area_w, area_h))
    }

    fn paint(&mut self, ctx: &mut PaintCtx, scene: &mut dyn PaintScene) {
        self.observe_dismiss_signal();
        let theme = Theme::from_paint_ctx(ctx);
        let (enter, exit) = resolve_timings(theme);
        let (scale, scrim_frac, animating) = self.advance(ctx.frame_time(), enter, exit);

        // Scrim fills the whole area (the modal barrier) — its own fade, never
        // scaled with the panel.
        let scrim = with_alpha(resolve_scrim(theme), SCRIM_ALPHA * scrim_frac);
        scene.fill_rect(ctx.origin(), ctx.size(), scrim);

        // The panel scales about its own center; the scrim above did not.
        let panel_origin = Point::new(
            ctx.origin().x + self.panel.x0,
            ctx.origin().y + self.panel.y0,
        );
        let panel_size = Size::new(self.panel.width(), self.panel.height());
        let center = Point::new(
            panel_origin.x + panel_size.width / 2.0,
            panel_origin.y + panel_size.height / 2.0,
        );
        let transform = Affine::translate((center.x, center.y))
            * Affine::scale(scale)
            * Affine::translate((-center.x, -center.y));
        scene.push_transform(transform);

        let (shadow_y, shadow_blur, shadow_color) = resolve_shadow(theme);
        let radius = resolve_radius(theme);
        scene.draw_shadow(
            Point::new(panel_origin.x, panel_origin.y + shadow_y),
            panel_size,
            radius,
            shadow_blur,
            shadow_color,
        );
        scene.fill_rounded_rect(panel_origin, panel_size, radius, resolve_container(theme));
        let rr = RoundedRect::from_rect(Rect::from_origin_size(Point::ORIGIN, panel_size), radius);
        let path = rr.to_path(PATH_TOLERANCE);
        scene.stroke_path(
            panel_origin,
            &path,
            BORDER_WIDTH,
            &Brush::Solid(resolve_border(theme)),
        );

        if let Some(p) = self.title.as_mut() {
            p.paint_child(ctx, scene);
        }
        if let Some(p) = self.body.as_mut() {
            p.paint_child(ctx, scene);
        }
        for pod in &mut self.actions {
            pod.paint_child(ctx, scene);
        }
        scene.pop_transform();

        // Keep frames coming while animating, and for one frame past Dismissed
        // so the rebuild that applies the pop actually runs.
        if animating || self.phase == Phase::Dismissed {
            ctx.request_frame();
        }
    }

    fn event(&mut self, ctx: &mut EventCtx, event: &InputEvent) -> EventResult {
        // Claim focus on every Down. Load-bearing TWICE over: the root treats a
        // Down that bubbles no claim as a blur (`release_focus_session` drops
        // focus + IME state), so the re-claim is what keeps the session alive
        // while this dialog is up; and the claim is also the dialog's *own* key
        // chain — `Key`/`Ime` are focus-routed, never hit-tested, so a dialog
        // whose pod is not focused never sees `Escape` at all. Re-claiming while
        // already focused is a change-guarded no-op (no generation bump) — do
        // not add a claim-once guard, it kills the session on the second tap.
        let pointer_down = matches!(event, InputEvent::Pointer(p) if p.phase == PointerPhase::Down);
        if pointer_down {
            ctx.request_focus();
        }
        // Whether the body/content slot owned the live focus/IME session on the
        // way *into* this Down. Snapshotted here because the routing below
        // blurs the slot's own recorded flag (`route_event_single`'s
        // blur-on-outside-tap) before the Down arm could ask. Composed with
        // `ctx.has_focus()`, never the slot flag alone, per CODE_STANDARDS'
        // focus rule: a stale flag under an already-blurred ancestor must not
        // let this dialog release somebody else's session.
        let content_held_session =
            pointer_down && ctx.has_focus() && self.body.as_ref().is_some_and(|p| p.is_focused());
        // An action already capturing (or freshly hit) consumes the event first.
        if frust::authoring::route_event(&mut self.actions, ctx, event) == EventResult::Handled {
            return EventResult::Handled;
        }
        // The body/content slot is next — this is what lets a focused
        // `TextInput` inside `.content()` receive every keystroke (focus-routed
        // `Key`/`Ime`) or a drag (an already-captured pointer), *before* the
        // Escape/scrim handling below gets a look. A key the slot declines
        // (Escape, since a text field doesn't handle it) falls through as
        // documented in the [module docs](self)'s "Body/content slot" section.
        if let Some(pod) = self.body.as_mut()
            && frust::authoring::route_event_single(pod, ctx, event) == EventResult::Handled
        {
            return EventResult::Handled;
        }
        // Escape (once focused) begins the exit/cancel — gated by `dismissable`
        // (a non-dismissable dialog ignores it, same as the scrim).
        if let InputEvent::Key(key_event) = event {
            if self.dismissable && key_event.key == Key::Named(NamedKey::Escape) {
                self.begin_exit();
                return EventResult::Handled;
            }
            return EventResult::Ignored;
        }
        // Everything else is the modal barrier.
        let InputEvent::Pointer(p) = event else {
            return EventResult::Ignored;
        };
        match p.phase {
            PointerPhase::Down => {
                let down_outside = !self.panel.contains(p.position);
                // Dead panel space (padding, the title, the gaps): this Down
                // reached neither an action nor the body/content slot, yet the
                // slot held the live session — so it is a blur *inside* the
                // dialog. End that session explicitly with an inactive publish
                // (the same primitive the navigator's post-pop
                // `cleared_ime_state` and `PatternSwitcher` use; the root reads
                // an inactive surface as a full `release_focus_session`, and
                // does so *before* it applies this dispatch's own focus claim —
                // `RenderRoot::event`'s documented ordering). Net effect: the
                // field blurs and the keyboard retracts, while the dialog keeps
                // both its focus link (so `Escape` still routes) and its panel
                // (a dead-space tap is not a dismiss — the barrier below still
                // consumes the Down, so nothing reaches the page underneath).
                //
                // The scrim is deliberately excluded (`!scrim_down_outside`):
                // outside-Down behavior is unchanged, and a scrim tap that
                // actually dismisses already ends the session through the
                // navigator's own pop path.
                if content_held_session && !down_outside {
                    ctx.publish_ime_state(cleared_ime_state());
                }
                // The barrier swallows a secondary press like every other one —
                // it blocks the page behind it whatever button pressed — but it
                // arms no scrim dismiss from it, so a right-click can never
                // close the dialog. The session bookkeeping above is deliberately
                // *not* button-gated: a `Down` is a blur at the root whatever
                // button carried it.
                if !presses(p) {
                    return EventResult::Handled;
                }
                self.scrim_captured = true;
                self.scrim_down_outside = down_outside;
                ctx.capture_pointer();
                EventResult::Handled
            }
            PointerPhase::Move => {
                if self.scrim_captured {
                    EventResult::Handled
                } else {
                    EventResult::Ignored
                }
            }
            PointerPhase::Up => {
                if !self.scrim_captured {
                    return EventResult::Ignored;
                }
                let released_outside = !self.panel.contains(p.position);
                if self.dismissable
                    && self.scrim_dismissible
                    && self.scrim_down_outside
                    && released_outside
                {
                    self.begin_exit();
                }
                self.scrim_captured = false;
                EventResult::Handled
            }
            PointerPhase::Cancel => {
                // Cancel never touches state — just clear the barrier flag.
                self.scrim_captured = false;
                EventResult::Handled
            }
        }
    }

    fn semantics(&self, ctx: &mut SemanticsCtx) {
        let label = self.title_text.clone();
        ctx.push_container(
            Role::Dialog,
            |node| {
                node.set_modal();
                if let Some(label) = &label {
                    node.set_label(label.as_str());
                }
            },
            |ctx| {
                if let Some(p) = &self.title {
                    p.semantics_child(ctx);
                }
                if let Some(p) = &self.body {
                    p.semantics_child(ctx);
                }
                for pod in &self.actions {
                    pod.semantics_child(ctx);
                }
            },
        );
    }

    frust::authoring::visit_children!(title, body, actions);
}

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

    fn ft_ms(ms: f64) -> FrameTime {
        FrameTime::from_nanos((ms * 1_000_000.0) as u64)
    }

    fn ev(phase: PointerPhase, x: f64, y: f64) -> InputEvent {
        InputEvent::Pointer(PointerEvent {
            phase,
            position: Point::new(x, y),
            button: PointerButton::Primary,
        })
    }

    /// The same event on the secondary (right) button.
    fn secondary_ev(phase: PointerPhase, x: f64, y: f64) -> InputEvent {
        InputEvent::Pointer(PointerEvent {
            phase,
            position: Point::new(x, y),
            button: PointerButton::Secondary,
        })
    }

    fn escape_event() -> InputEvent {
        InputEvent::Key(KeyEvent {
            key: Key::Named(NamedKey::Escape),
            modifiers: Modifiers::default(),
            repeat: false,
        })
    }

    fn build<S: 'static>(view: &GlyphDialogView<S>) -> GlyphDialogWidget {
        let mut counter = 0u64;
        View::<S>::build(view, &mut BuildCtx::new(&mut counter))
    }

    /// Records fills, rounded fills, shadows, strokes, and transform push/pops.
    #[derive(Default)]
    struct Recorder {
        rects: Vec<(Point, Size, Color)>,
        rrects: Vec<(Point, Size, f64, Color)>,
        shadows: usize,
        strokes: Vec<Color>,
        transforms: Vec<Affine>,
        transform_pops: u32,
    }
    impl PaintScene for Recorder {
        fn fill_rect(&mut self, o: Point, s: Size, c: Color) {
            self.rects.push((o, s, c));
        }
        fn draw_text(&mut self, _o: Point, _t: &str) {}
        fn fill_rounded_rect(&mut self, o: Point, s: Size, radius: f64, color: Color) {
            self.rrects.push((o, s, radius, color));
        }
        fn draw_shadow(&mut self, _o: Point, _s: Size, _r: f64, _b: f64, _c: Color) {
            self.shadows += 1;
        }
        fn stroke_path(&mut self, _o: Point, _p: &kurbo::BezPath, _w: f64, brush: &Brush) {
            if let Brush::Solid(c) = brush {
                self.strokes.push(*c);
            }
        }
        fn push_transform(&mut self, t: Affine) {
            self.transforms.push(t);
        }
        fn pop_transform(&mut self) {
            self.transform_pops += 1;
        }
    }

    // -- Enter/exit staging (advance table) -----------------------------

    #[test]
    fn enter_staging_scales_panel_094_to_1_and_fades_scrim_in() {
        let view: GlyphDialogView<()> = glyph_dialog().title("Hi");
        let mut w = build(&view);
        let (enter, exit) = resolve_timings(None);

        // Seed the clock: panel starts at 0.94, scrim invisible.
        let (scale0, scrim0, animating0) = w.advance(ft_ms(0.0), enter, exit);
        assert!((scale0 - ENTER_SCALE_START).abs() < 1e-6);
        assert!(scrim0.abs() < 1e-6);
        assert!(animating0);
        assert_eq!(w.phase, Phase::Enter);

        // Past the 220ms enter: settles fully shown (scale 1.0, scrim 1.0).
        let (scale1, scrim1, animating1) = w.advance(ft_ms(400.0), enter, exit);
        assert!((scale1 - 1.0).abs() < 1e-6);
        assert!((scrim1 - 1.0).abs() < 1e-6);
        assert!(!animating1);
        assert_eq!(w.phase, Phase::Shown);
    }

    #[test]
    fn exit_is_faster_than_enter_and_reverses_the_staging() {
        // The exit driver (150ms) settles well before the enter driver (220ms).
        let view: GlyphDialogView<()> = glyph_dialog().title("Hi");
        let mut w = build(&view);
        let (enter, exit) = resolve_timings(None);

        w.advance(ft_ms(0.0), enter, exit);
        w.advance(ft_ms(400.0), enter, exit); // -> Shown
        w.begin_exit();
        assert_eq!(w.phase, Phase::Exit);

        // Seed the exit clock: starts fully shown.
        let (scale_seed, scrim_seed, _) = w.advance(ft_ms(400.0), enter, exit);
        assert!((scale_seed - 1.0).abs() < 1e-6);
        assert!((scrim_seed - 1.0).abs() < 1e-6);

        // Still exiting 149ms in (would already be done at the 150ms exit, but
        // not yet at the 220ms enter — proving the exit is the faster driver).
        let (_, _, animating_mid) = w.advance(ft_ms(400.0 + 149.0), enter, exit);
        assert!(animating_mid);

        // Past the 150ms exit: collapsed and Dismissed.
        let (scale_end, scrim_end, animating_end) = w.advance(ft_ms(400.0 + 200.0), enter, exit);
        assert!((scale_end - ENTER_SCALE_START).abs() < 1e-6);
        assert!(scrim_end.abs() < 1e-6);
        assert!(!animating_end);
        assert_eq!(w.phase, Phase::Dismissed);
    }

    #[test]
    fn on_close_fires_once_when_the_exit_completes() {
        let count = Rc::new(Cell::new(0u32));
        let c = count.clone();
        let view: GlyphDialogView<()> = glyph_dialog()
            .title("Hi")
            .on_close(move || c.set(c.get() + 1));
        let mut w = build(&view);
        let (enter, exit) = resolve_timings(None);

        w.advance(ft_ms(0.0), enter, exit);
        w.advance(ft_ms(400.0), enter, exit);
        w.begin_exit();
        w.advance(ft_ms(400.0), enter, exit);
        assert_eq!(count.get(), 0, "on_close waits for the exit to finish");
        w.advance(ft_ms(700.0), enter, exit); // completes the exit
        assert_eq!(count.get(), 1);
        // Idempotent past Dismissed.
        w.advance(ft_ms(900.0), enter, exit);
        assert_eq!(count.get(), 1);
    }

    #[test]
    fn scrim_uses_own_fade_while_panel_scales_under_a_transform() {
        // Paint at enter start: the scrim fill is emitted *before* the transform
        // push (its own fade), and the panel fill/border ride inside the
        // transform — so scrim and panel stage independently.
        let view: GlyphDialogView<()> = glyph_dialog().title("Hi");
        let mut w = build(&view);
        let mut tcx = TextContext::new();
        let mut lctx = LayoutCtx::with_text_context(&mut tcx as &mut dyn Any);
        let area = Size::new(400.0, 600.0);
        w.layout(&mut lctx, &BoxConstraints::tight(area));

        let mut rec = Recorder::default();
        let mut pctx = PaintCtx::new(Point::ZERO, area);
        w.paint(&mut pctx, &mut rec);

        // A full-area scrim fill, at (near) zero alpha at the seeded start.
        assert_eq!(rec.rects[0].1, area);
        assert!(
            rec.rects[0].2.components[3] < 1e-3,
            "scrim starts transparent"
        );
        // Panel fill + border stroke + shadow emitted under one transform.
        assert_eq!(rec.transforms.len(), 1);
        assert_eq!(rec.transform_pops, 1);
        assert_eq!(rec.rrects.len(), 1, "the panel surface fill");
        assert_eq!(rec.strokes.len(), 1, "the panel border stroke");
        assert_eq!(rec.shadows, 1, "the chrome-level shadow");
        assert!(
            pctx.needs_frame(),
            "an in-flight enter requests another frame"
        );
    }

    // -- Token assertions (dark + light) --------------------------------

    #[test]
    fn glyph_dark_and_light_resolve_panel_ring_and_scrim() {
        let dark = crate::baseline();
        let light = dark.clone().with_brightness(frust::Brightness::Light);
        for theme in [&dark, &light] {
            assert_eq!(
                resolve_container(Some(theme)),
                theme.scheme().surface_container_high
            );
            assert_eq!(resolve_border(Some(theme)), theme.scheme().outline);
            assert_eq!(resolve_scrim(Some(theme)), theme.scheme().scrim);
            assert_eq!(resolve_radius(Some(theme)), theme.shape.large);
        }
        // Dark and light panels differ (not a mere value flip).
        assert_ne!(
            resolve_container(Some(&dark)),
            resolve_container(Some(&light))
        );
    }

    #[test]
    fn themed_paint_fills_panel_with_glyph_surface() {
        let theme = crate::baseline();
        let view: GlyphDialogView<()> = glyph_dialog().title("Confirm");
        let mut w = build(&view);
        let mut tcx = TextContext::new();
        let area = Size::new(400.0, 600.0);
        let mut lctx =
            LayoutCtx::with_resources(Some(&mut tcx as &mut dyn Any), Some(&theme as &dyn Any));
        w.layout(&mut lctx, &BoxConstraints::tight(area));

        let mut rec = Recorder::default();
        // Advance to Shown so the panel is at full opacity/scale.
        let mut pctx = PaintCtx::new(Point::ZERO, area).with_theme(&theme);
        w.phase = Phase::Shown;
        w.paint(&mut pctx, &mut rec);
        assert_eq!(rec.rrects[0].3, theme.scheme().surface_container_high);
        assert_eq!(rec.rrects[0].2, theme.shape.large);
        assert_eq!(rec.strokes[0], theme.scheme().outline);
    }

    // -- Navigator integration: scrim cancel pops with an empty result --

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

    fn app_page(
        controller: &NavigatorController<NavState>,
    ) -> impl FnMut(&mut NavState) -> NavigatorView<NavState> {
        let ctrl = controller.clone();
        move |_: &mut NavState| navigator(&ctrl, || core_any::<NavState, _>(sized(400.0, 600.0)))
    }

    struct Sized {
        size: Size,
    }
    struct SizedW {
        size: Size,
    }
    impl View<NavState> for Sized {
        type Element = SizedW;
        fn build(&self, _c: &mut BuildCtx<'_>) -> SizedW {
            SizedW { size: self.size }
        }
        fn rebuild(&self, _p: &Self, _e: &mut SizedW, _c: &mut BuildCtx<'_>) -> ChangeFlags {
            ChangeFlags::NONE
        }
    }
    impl Widget for SizedW {
        fn layout(&mut self, _c: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            bc.constrain(self.size)
        }
        fn paint(&mut self, ctx: &mut PaintCtx, scene: &mut dyn PaintScene) {
            scene.fill_rect(ctx.origin(), ctx.size(), Color::BLACK);
        }
    }
    fn sized(w: f64, h: f64) -> Sized {
        Sized {
            size: Size::new(w, h),
        }
    }

    #[test]
    fn scrim_cancel_animates_then_pops_dialog_with_empty_result() {
        let controller: NavigatorController<NavState> = NavigatorController::new();
        let mut root: RenderRoot<NavState, NavigatorView<NavState>> = RenderRoot::new();
        let mut app = app_page(&controller);
        let mut state = NavState::default();
        let area = Size::new(400.0, 600.0);

        root.rebuild(&mut app, &mut state);
        let mut tcx = TextContext::new();
        root.layout_with_text(area, &mut tcx as &mut dyn Any);

        show_glyph_dialog(
            &controller,
            || glyph_dialog().title("Confirm"),
            |state: &mut NavState, result: PopResult| {
                state.results.push(result.take::<bool>());
            },
        );
        root.rebuild(&mut app, &mut state);
        root.layout_with_text(area, &mut tcx as &mut dyn Any);
        // Settle the enter animation.
        root.paint(&mut Recorder::default(), ft_ms(0.0));
        root.paint(&mut Recorder::default(), ft_ms(400.0));

        // Tap the scrim (top-left, outside the centered panel).
        root.event(&mut state, &ev(PointerPhase::Down, 5.0, 5.0));
        root.event(&mut state, &ev(PointerPhase::Up, 5.0, 5.0));
        assert!(
            state.results.is_empty(),
            "the exit animation has not finished yet"
        );

        // Drive the exit to completion: on_close (controller.pop()) fires, then
        // the next rebuild applies the pop and the result callback flushes.
        root.paint(&mut Recorder::default(), ft_ms(500.0));
        root.paint(&mut Recorder::default(), ft_ms(800.0));
        root.rebuild(&mut app, &mut state);
        root.layout_with_text(area, &mut tcx as &mut dyn Any);
        root.event(&mut state, &ev(PointerPhase::Move, 5.0, 5.0));

        assert_eq!(
            state.results,
            vec![None],
            "scrim cancel pops with an empty result"
        );
    }

    #[test]
    fn non_dismissible_scrim_does_not_cancel() {
        let view: GlyphDialogView<()> = glyph_dialog().title("Hi").scrim_dismissible(false);
        let mut w = build(&view);
        let mut tcx = TextContext::new();
        let mut lctx = LayoutCtx::with_text_context(&mut tcx as &mut dyn Any);
        w.layout(&mut lctx, &BoxConstraints::tight(Size::new(400.0, 600.0)));

        let mut dummy = ();
        let dispatch = |w: &mut GlyphDialogWidget, dummy: &mut (), e: &InputEvent| {
            let s: &mut dyn Any = dummy;
            let mut ctx = EventCtx::new(s, Point::ZERO, Size::new(400.0, 600.0));
            w.event(&mut ctx, e)
        };
        dispatch(&mut w, &mut dummy, &ev(PointerPhase::Down, 5.0, 5.0));
        dispatch(&mut w, &mut dummy, &ev(PointerPhase::Up, 5.0, 5.0));
        assert_eq!(
            w.phase,
            Phase::Enter,
            "a non-dismissible scrim never begins exit"
        );
    }

    #[test]
    fn a_secondary_scrim_press_is_swallowed_but_never_dismisses() {
        let view: GlyphDialogView<()> = glyph_dialog().title("Hi");
        let mut w = build(&view);
        let mut tcx = TextContext::new();
        let mut lctx = LayoutCtx::with_text_context(&mut tcx as &mut dyn Any);
        w.layout(&mut lctx, &BoxConstraints::tight(Size::new(400.0, 600.0)));

        let mut dummy = ();
        let dispatch = |w: &mut GlyphDialogWidget, dummy: &mut (), e: &InputEvent| {
            let s: &mut dyn Any = dummy;
            let mut ctx = EventCtx::new(s, Point::ZERO, Size::new(400.0, 600.0));
            w.event(&mut ctx, e)
        };
        // The same top-left scrim point a primary tap dismisses from.
        let r = dispatch(
            &mut w,
            &mut dummy,
            &secondary_ev(PointerPhase::Down, 5.0, 5.0),
        );
        assert_eq!(
            r,
            EventResult::Handled,
            "the barrier still swallows it — the page behind stays blocked"
        );
        assert!(!w.scrim_captured, "but arms no scrim dismiss");
        dispatch(
            &mut w,
            &mut dummy,
            &secondary_ev(PointerPhase::Up, 5.0, 5.0),
        );
        assert_eq!(
            w.phase,
            Phase::Enter,
            "a right-click never begins the dialog's exit"
        );

        // The primary scrim tap still dismisses.
        dispatch(&mut w, &mut dummy, &ev(PointerPhase::Down, 5.0, 5.0));
        dispatch(&mut w, &mut dummy, &ev(PointerPhase::Up, 5.0, 5.0));
        assert_eq!(w.phase, Phase::Exit);
    }

    // -- `dismissable(bool)` gates the scrim and Escape together --

    #[test]
    fn dismissable_false_gates_scrim_tap() {
        let view: GlyphDialogView<()> = glyph_dialog().title("Hi").dismissable(false);
        let mut w = build(&view);
        let mut tcx = TextContext::new();
        let mut lctx = LayoutCtx::with_text_context(&mut tcx as &mut dyn Any);
        w.layout(&mut lctx, &BoxConstraints::tight(Size::new(400.0, 600.0)));

        let mut dummy = ();
        let dispatch = |w: &mut GlyphDialogWidget, dummy: &mut (), e: &InputEvent| {
            let s: &mut dyn Any = dummy;
            let mut ctx = EventCtx::new(s, Point::ZERO, Size::new(400.0, 600.0));
            w.event(&mut ctx, e)
        };
        dispatch(&mut w, &mut dummy, &ev(PointerPhase::Down, 5.0, 5.0));
        dispatch(&mut w, &mut dummy, &ev(PointerPhase::Up, 5.0, 5.0));
        assert_eq!(
            w.phase,
            Phase::Enter,
            "dismissable(false) gates the scrim tap too"
        );
    }

    #[test]
    fn dismissable_false_gates_escape() {
        let view: GlyphDialogView<()> = glyph_dialog().title("Hi").dismissable(false);
        let mut w = build(&view);
        let mut tcx = TextContext::new();
        let mut lctx = LayoutCtx::with_text_context(&mut tcx as &mut dyn Any);
        w.layout(&mut lctx, &BoxConstraints::tight(Size::new(400.0, 600.0)));

        let mut dummy = ();
        let dispatch = |w: &mut GlyphDialogWidget, dummy: &mut (), e: &InputEvent| {
            let s: &mut dyn Any = dummy;
            let mut ctx = EventCtx::new(s, Point::ZERO, Size::new(400.0, 600.0));
            w.event(&mut ctx, e)
        };
        // A press claims focus (as usual), but the subsequent Escape is gated.
        dispatch(&mut w, &mut dummy, &ev(PointerPhase::Down, 5.0, 5.0));
        dispatch(&mut w, &mut dummy, &ev(PointerPhase::Up, 5.0, 5.0));
        dispatch(&mut w, &mut dummy, &escape_event());
        assert_eq!(w.phase, Phase::Enter, "dismissable(false) gates Escape");
    }

    // -- back request routes through dismissable/BackPolicy --

    #[test]
    fn back_request_dismissable_true_animates_exit_then_pops() {
        let controller: NavigatorController<NavState> = NavigatorController::new();
        let mut root: RenderRoot<NavState, NavigatorView<NavState>> = RenderRoot::new();
        let mut app = app_page(&controller);
        let mut state = NavState::default();
        let area = Size::new(400.0, 600.0);

        root.rebuild(&mut app, &mut state);
        let mut tcx = TextContext::new();
        root.layout_with_text(area, &mut tcx as &mut dyn Any);

        show_glyph_dialog(
            &controller,
            || glyph_dialog().title("Confirm"),
            |state: &mut NavState, result: PopResult| state.results.push(result.take::<bool>()),
        );
        root.rebuild(&mut app, &mut state);
        root.layout_with_text(area, &mut tcx as &mut dyn Any);
        root.paint(&mut Recorder::default(), ft_ms(0.0));
        root.paint(&mut Recorder::default(), ft_ms(400.0)); // settled: Shown

        assert!(
            controller.back_interest(),
            "a dismissable dialog claims back interest"
        );

        controller.request_back();
        root.rebuild(&mut app, &mut state);
        assert_eq!(
            controller.depth(),
            2,
            "DismissAnimated: the stack is unchanged immediately"
        );

        // The next paint observes the bumped signal and begins the exit; drive
        // it to completion the same way a scrim cancel does.
        root.paint(&mut Recorder::default(), ft_ms(400.0));
        assert!(
            state.results.is_empty(),
            "the exit animation has not finished yet"
        );
        root.paint(&mut Recorder::default(), ft_ms(500.0));
        root.paint(&mut Recorder::default(), ft_ms(800.0));
        root.rebuild(&mut app, &mut state);
        root.layout_with_text(area, &mut tcx as &mut dyn Any);
        root.event(&mut state, &ev(PointerPhase::Move, 5.0, 5.0));

        assert_eq!(
            state.results,
            vec![None],
            "a back request animates the exit then pops"
        );
        assert_eq!(controller.depth(), 1);
    }

    #[test]
    fn back_request_dismissable_false_vetoes_stack_unchanged() {
        let controller: NavigatorController<NavState> = NavigatorController::new();
        let mut root: RenderRoot<NavState, NavigatorView<NavState>> = RenderRoot::new();
        let mut app = app_page(&controller);
        let mut state = NavState::default();
        let area = Size::new(400.0, 600.0);

        root.rebuild(&mut app, &mut state);
        let mut tcx = TextContext::new();
        root.layout_with_text(area, &mut tcx as &mut dyn Any);

        show_glyph_dialog(
            &controller,
            || glyph_dialog().title("Confirm").dismissable(false),
            |state: &mut NavState, result: PopResult| state.results.push(result.take::<bool>()),
        );
        root.rebuild(&mut app, &mut state);
        root.layout_with_text(area, &mut tcx as &mut dyn Any);
        root.paint(&mut Recorder::default(), ft_ms(0.0));
        root.paint(&mut Recorder::default(), ft_ms(400.0)); // settled: Shown

        assert!(
            controller.back_interest(),
            "a Veto (non-dismissable) dialog still claims back interest"
        );

        controller.request_back();
        root.rebuild(&mut app, &mut state);
        assert_eq!(controller.depth(), 2, "Veto leaves the stack unchanged");

        // No staging began: driving further frames still never pops.
        root.paint(&mut Recorder::default(), ft_ms(450.0));
        root.paint(&mut Recorder::default(), ft_ms(900.0));
        assert!(
            state.results.is_empty(),
            "a non-dismissable dialog never pops on a back request"
        );
        assert_eq!(controller.depth(), 2);
    }

    #[test]
    fn escape_begins_exit_after_a_press_claims_focus() {
        let controller: NavigatorController<NavState> = NavigatorController::new();
        let mut root: RenderRoot<NavState, NavigatorView<NavState>> = RenderRoot::new();
        let mut app = app_page(&controller);
        let mut state = NavState::default();
        let area = Size::new(400.0, 600.0);

        root.rebuild(&mut app, &mut state);
        let mut tcx = TextContext::new();
        root.layout_with_text(area, &mut tcx as &mut dyn Any);

        show_glyph_dialog(
            &controller,
            || glyph_dialog().title("Confirm"),
            |state: &mut NavState, result: PopResult| state.results.push(result.take::<bool>()),
        );
        root.rebuild(&mut app, &mut state);
        root.layout_with_text(area, &mut tcx as &mut dyn Any);
        root.paint(&mut Recorder::default(), ft_ms(0.0));
        root.paint(&mut Recorder::default(), ft_ms(400.0));

        // A press claims focus; Escape then begins the exit and eventually pops.
        let (cx, cy) = (area.width / 2.0, area.height / 2.0);
        root.event(&mut state, &ev(PointerPhase::Down, cx, cy));
        root.event(&mut state, &ev(PointerPhase::Up, cx, cy));
        root.event(&mut state, &escape_event());
        root.paint(&mut Recorder::default(), ft_ms(500.0));
        root.paint(&mut Recorder::default(), ft_ms(800.0));
        root.rebuild(&mut app, &mut state);
        root.layout_with_text(area, &mut tcx as &mut dyn Any);
        root.event(&mut state, &ev(PointerPhase::Move, 5.0, 5.0));

        assert_eq!(
            state.results,
            vec![None],
            "Escape dismisses the focused dialog"
        );
    }

    #[test]
    fn a_down_reclaims_focus_after_an_external_blur() {
        use frust::authoring::ChildPod;

        let view: GlyphDialogView<()> = glyph_dialog().title("Hi");
        let area = Size::new(400.0, 600.0);
        let w = build(&view);
        let mut pod = ChildPod::new(Box::new(w));
        let mut tcx = TextContext::new();
        let mut lctx = LayoutCtx::with_text_context(&mut tcx as &mut dyn Any);
        pod.layout_child(&mut lctx, &BoxConstraints::tight(area));

        let mut dummy = ();
        {
            let s: &mut dyn Any = &mut dummy;
            let mut ctx = EventCtx::new(s, Point::ZERO, area);
            pod.event_child(&mut ctx, &ev(PointerPhase::Down, 5.0, 5.0));
        }
        assert!(pod.is_focused(), "the first Down claims focus");
        {
            let s: &mut dyn Any = &mut dummy;
            let mut ctx = EventCtx::new(s, Point::ZERO, area);
            pod.event_child(&mut ctx, &ev(PointerPhase::Up, 5.0, 5.0));
        }

        // Simulate an external blur (mirrors the root's own `Down`-with-no-
        // claim release path) so the second Down's own re-claim is what's
        // under test, not a leftover flag.
        pod.set_focused(false);
        {
            let s: &mut dyn Any = &mut dummy;
            let mut ctx = EventCtx::new(s, Point::ZERO, area);
            pod.event_child(&mut ctx, &ev(PointerPhase::Down, 5.0, 5.0));
        }
        assert!(
            pod.is_focused(),
            "a second Down must re-claim focus after an external blur — this is what \
             keeps the root's focus/IME session alive while the dialog is up"
        );
    }

    #[test]
    fn action_pops_with_a_value_via_navigator() {
        let controller: NavigatorController<NavState> = NavigatorController::new();
        let mut root: RenderRoot<NavState, NavigatorView<NavState>> = RenderRoot::new();
        let mut app = app_page(&controller);
        let mut state = NavState::default();
        let area = Size::new(400.0, 600.0);

        root.rebuild(&mut app, &mut state);
        let mut tcx = TextContext::new();
        root.layout_with_text(area, &mut tcx as &mut dyn Any);

        let action_w = 80.0;
        let action_h = 36.0;
        {
            let confirm = controller.clone();
            controller.push_transparent_for_result(
                move || {
                    let c = confirm.clone();
                    core_any::<NavState, _>(glyph_dialog().action(tap_action(
                        action_w,
                        action_h,
                        move |_s: &mut NavState| c.pop_with_result(PopResult::of(true)),
                    )))
                },
                TransitionSpec::NONE,
                |state: &mut NavState, result: PopResult| state.results.push(result.take::<bool>()),
            );
        }
        root.rebuild(&mut app, &mut state);
        root.layout_with_text(area, &mut tcx as &mut dyn Any);
        root.paint(&mut Recorder::default(), ft_ms(0.0));
        root.paint(&mut Recorder::default(), ft_ms(400.0));

        // With no title/body the panel is MIN_WIDTH wide, centered; the action
        // hugs the trailing edge, DIALOG_PADDING from the top.
        let panel_x = (area.width - MIN_WIDTH) / 2.0;
        let panel_h = 2.0 * DIALOG_PADDING + action_h;
        let panel_y = (area.height - panel_h) / 2.0;
        let action_cx = panel_x + MIN_WIDTH - DIALOG_PADDING - action_w / 2.0;
        let action_cy = panel_y + DIALOG_PADDING + action_h / 2.0;

        root.event(&mut state, &ev(PointerPhase::Down, action_cx, action_cy));
        root.event(&mut state, &ev(PointerPhase::Up, action_cx, action_cy));
        root.rebuild(&mut app, &mut state);
        root.layout_with_text(area, &mut tcx as &mut dyn Any);
        root.event(&mut state, &ev(PointerPhase::Move, 5.0, 5.0));

        assert_eq!(state.results, vec![Some(true)], "the action pops with true");
    }

    // -- Suppressing-container contract: no dangling capture after dismiss --

    #[test]
    fn no_dangling_capture_after_dismiss() {
        let controller: NavigatorController<NavState> = NavigatorController::new();
        let mut root: RenderRoot<NavState, NavigatorView<NavState>> = RenderRoot::new();
        let mut app = app_page(&controller);
        let mut state = NavState::default();
        let area = Size::new(400.0, 600.0);

        root.rebuild(&mut app, &mut state);
        let mut tcx = TextContext::new();
        root.layout_with_text(area, &mut tcx as &mut dyn Any);

        show_glyph_dialog(
            &controller,
            || glyph_dialog().title("Confirm"),
            |state: &mut NavState, result: PopResult| state.results.push(result.take::<bool>()),
        );
        root.rebuild(&mut app, &mut state);
        root.layout_with_text(area, &mut tcx as &mut dyn Any);
        root.paint(&mut Recorder::default(), ft_ms(0.0));
        root.paint(&mut Recorder::default(), ft_ms(400.0));

        // Press+release on the scrim: the modal barrier captured the pointer and
        // begins the exit. Drive it to completion and pop.
        root.event(&mut state, &ev(PointerPhase::Down, 5.0, 5.0));
        root.event(&mut state, &ev(PointerPhase::Up, 5.0, 5.0));
        root.paint(&mut Recorder::default(), ft_ms(500.0));
        root.paint(&mut Recorder::default(), ft_ms(800.0));
        root.rebuild(&mut app, &mut state);
        root.layout_with_text(area, &mut tcx as &mut dyn Any);

        // The dialog page is gone; the underlying page now receives events. A
        // stray Up must not be routed into a torn-down dialog's captured barrier.
        assert!(
            !root.is_pointer_captured(),
            "no capture survives the dismiss"
        );
        root.event(&mut state, &ev(PointerPhase::Up, 5.0, 5.0));
        assert_eq!(state.results, vec![None]);
    }

    #[test]
    fn semantics_is_a_modal_dialog_labelled_by_title() {
        fn logic(_s: &mut ()) -> GlyphDialogView<()> {
            glyph_dialog().title("Confirm").body("Sure?")
        }
        let mut root: RenderRoot<(), GlyphDialogView<()>> = RenderRoot::new();
        let mut state = ();
        root.rebuild(&mut logic, &mut state);
        let mut tcx = TextContext::new();
        root.layout_with_text(Size::new(400.0, 600.0), &mut tcx as &mut dyn Any);
        let update = root.semantics();
        let (_, node) = update
            .nodes
            .iter()
            .find(|(_, n)| n.role() == Role::Dialog)
            .expect("a Role::Dialog node is contributed");
        assert!(node.is_modal(), "the dialog node sets the modal flag");
        assert_eq!(node.label(), Some("Confirm"));
        assert!(
            !node.children().is_empty(),
            "title/body are semantics children"
        );
    }

    // -- `.content()`: an arbitrary body/content-slot view -------------

    #[test]
    fn body_only_dialog_still_builds_a_text_child_and_records_body_text() {
        // Regression guard: with no `.content()`, `body_slot()` must still
        // resolve exactly like the pre-`.content()` `Option<String>` path.
        let view: GlyphDialogView<()> = glyph_dialog().title("Hi").body("Sure?");
        let w = build(&view);
        assert!(w.body.is_some(), "body text still builds a child pod");
        assert_eq!(w.body_text.as_deref(), Some("Sure?"));
    }

    #[test]
    fn content_wins_over_body_when_both_are_set() {
        let view: GlyphDialogView<()> = glyph_dialog()
            .title("Both")
            .body("ignored text")
            .content(tap_action(50.0, 20.0, |_s: &mut ()| {}));
        let mut w = build(&view);
        let mut tcx = TextContext::new();
        let mut lctx = LayoutCtx::with_text_context(&mut tcx as &mut dyn Any);
        w.layout(&mut lctx, &BoxConstraints::tight(Size::new(400.0, 600.0)));

        assert_eq!(
            w.body_text, None,
            "content wins: the body text is not the active slot"
        );
        let slot_size = w.body.as_ref().expect("slot built").size();
        assert_eq!(
            slot_size,
            Size::new(50.0, 20.0),
            "the slot holds the fixed-size content view, not laid-out body text"
        );
    }

    #[test]
    fn content_taller_than_viewport_is_not_clamped_or_scrolled() {
        // The documented overflow limit (see the module docs' "Body/content
        // slot" section): the slot gets loose width / unbounded height, and
        // an oversized content view is neither clipped nor auto-scrolled.
        let view: GlyphDialogView<()> =
            glyph_dialog()
                .title("Tall")
                .content(tap_action(300.0, 2000.0, |_s: &mut ()| {}));
        let mut w = build(&view);
        let mut tcx = TextContext::new();
        let mut lctx = LayoutCtx::with_text_context(&mut tcx as &mut dyn Any);
        let area = Size::new(400.0, 600.0);
        w.layout(&mut lctx, &BoxConstraints::tight(area));

        let content_size = w.body.as_ref().expect("content pod built").size();
        assert_eq!(
            content_size.height, 2000.0,
            "the content slot gets unbounded (loose) height, matching body's own sizing"
        );
        assert!(
            w.panel.height() > area.height,
            "an oversized content slot is not clipped or scrolled — the panel simply grows \
             past the viewport; wrap unbounded content in your own scroll view instead"
        );
    }

    #[test]
    fn content_text_field_takes_focus_and_accepts_typing() {
        // The motivating case: a text field inside `.content()` must actually
        // be reachable — a focused child must receive keystrokes before the
        // dialog's own Escape/dismiss handling gets a look at them.
        #[derive(Default)]
        struct FieldState {
            text: String,
        }

        let view: GlyphDialogView<FieldState> = glyph_dialog().title("Rename").content(core_any::<
            FieldState,
            _,
        >(
            text_input(String::new(), |s: &mut FieldState, v| {
                s.text = v;
            }),
        ));
        let mut w = build(&view);
        let mut tcx = TextContext::new();
        let mut lctx = LayoutCtx::with_text_context(&mut tcx as &mut dyn Any);
        let area = Size::new(400.0, 600.0);
        w.layout(&mut lctx, &BoxConstraints::tight(area));

        let content_pod = w.body.as_ref().expect("content pod is built");
        let tap = Point::new(
            content_pod.origin().x + content_pod.size().width / 2.0,
            content_pod.origin().y + content_pod.size().height / 2.0,
        );

        let mut state = FieldState::default();
        let dispatch = |w: &mut GlyphDialogWidget, state: &mut FieldState, e: &InputEvent| {
            let s: &mut dyn Any = state;
            let mut ctx = EventCtx::new(s, Point::ZERO, area);
            w.event(&mut ctx, e)
        };

        dispatch(&mut w, &mut state, &ev(PointerPhase::Down, tap.x, tap.y));
        assert!(
            w.body.as_ref().unwrap().is_focused(),
            "tapping the content field focuses it (not swallowed by the scrim barrier)"
        );
        dispatch(&mut w, &mut state, &ev(PointerPhase::Up, tap.x, tap.y));

        dispatch(
            &mut w,
            &mut state,
            &InputEvent::Key(KeyEvent {
                key: Key::Character("a".to_string()),
                modifiers: Modifiers::default(),
                repeat: false,
            }),
        );
        assert_eq!(
            state.text, "a",
            "the focused content field received the keystroke instead of it being \
             swallowed by the dialog's own Key handling"
        );
    }

    // -- Screen margin on narrow windows ---------------------------------

    #[test]
    fn narrow_window_keeps_a_screen_margin_on_both_sides_even_with_stretching_content() {
        // A `CrossAxisAlignment::Stretch`-style content view that always wants
        // the full available width — bc.constrain clamps it down to
        // content_max_w, so this exercises the same path a stretched field
        // column would.
        let view: GlyphDialogView<()> =
            glyph_dialog()
                .title("Hi")
                .content(tap_action(10_000.0, 20.0, |_s: &mut ()| {}));
        let mut w = build(&view);
        let mut tcx = TextContext::new();
        let mut lctx = LayoutCtx::with_text_context(&mut tcx as &mut dyn Any);
        let area = Size::new(393.0, 800.0);
        w.layout(&mut lctx, &BoxConstraints::tight(area));

        assert_eq!(w.panel.width(), area.width - 2.0 * SCREEN_MARGIN);
        assert_eq!(w.panel.x0, SCREEN_MARGIN, "margin on the leading edge");
        assert_eq!(
            area.width - (w.panel.x0 + w.panel.width()),
            SCREEN_MARGIN,
            "margin on the trailing edge"
        );
    }

    #[test]
    fn window_narrower_than_min_width_plus_margins_still_gets_the_margin() {
        // 320 is narrower than MIN_WIDTH (300) + 2 * SCREEN_MARGIN (48) — the
        // margin must win over MIN_WIDTH's own floor rather than inverting the
        // lower/upper clamp back out to full bleed.
        let view: GlyphDialogView<()> = glyph_dialog().title("Hi");
        let mut w = build(&view);
        let mut tcx = TextContext::new();
        let mut lctx = LayoutCtx::with_text_context(&mut tcx as &mut dyn Any);
        let area = Size::new(320.0, 600.0);
        w.layout(&mut lctx, &BoxConstraints::tight(area));

        assert_eq!(w.panel.width(), 272.0);
        assert_eq!(w.panel.x0, SCREEN_MARGIN);
    }

    #[test]
    fn pathologically_tiny_window_does_not_panic_and_stays_non_negative() {
        let view: GlyphDialogView<()> = glyph_dialog().title("Hi");
        let mut w = build(&view);
        let mut tcx = TextContext::new();
        let mut lctx = LayoutCtx::with_text_context(&mut tcx as &mut dyn Any);
        let area = Size::new(30.0, 60.0);
        w.layout(&mut lctx, &BoxConstraints::tight(area));

        assert!(w.panel.width() >= 0.0);
        assert!(w.panel.x0 >= 0.0);
    }

    #[test]
    fn wide_window_still_caps_at_max_width_unaffected_by_the_margin() {
        // area_w (600) exceeds MAX_WIDTH + 2 * SCREEN_MARGIN (528): the panel
        // caps at MAX_WIDTH exactly as it did before the margin was added.
        let view: GlyphDialogView<()> =
            glyph_dialog()
                .title("Hi")
                .content(tap_action(10_000.0, 20.0, |_s: &mut ()| {}));
        let mut w = build(&view);
        let mut tcx = TextContext::new();
        let mut lctx = LayoutCtx::with_text_context(&mut tcx as &mut dyn Any);
        let area = Size::new(600.0, 800.0);
        w.layout(&mut lctx, &BoxConstraints::tight(area));

        assert_eq!(w.panel.width(), MAX_WIDTH);
        assert_eq!(w.panel.x0, (area.width - MAX_WIDTH) / 2.0);
    }

    // -- Keyboard avoidance: the panel centers in the free band ----------

    /// The retained dialog at the root of `root`'s tree (mirrors
    /// `safe_area`'s `safe_area_widget` helper).
    fn dialog_widget<S: 'static>(root: &RenderRoot<S, GlyphDialogView<S>>) -> &GlyphDialogWidget {
        let id = root.root_id().expect("root built");
        (root.tree().pod(id).expect("root pod").widget() as &dyn Any)
            .downcast_ref::<GlyphDialogWidget>()
            .expect("the root is a GlyphDialogWidget")
    }

    /// A keyboard-only inset push: `view_insets.bottom` (never `view_padding` —
    /// system bars are not the IME, see `frust_core::WindowInsets`).
    fn ime_insets(bottom: f64) -> WindowInsets {
        WindowInsets::new(
            WindowEdgeInsets::ZERO,
            WindowEdgeInsets::new(0.0, 0.0, 0.0, bottom),
        )
    }

    /// Title + a fixed-size action: `20 + 20 (title) + 20 (gap) + 36 + 20`.
    const TITLED_ACTION_PANEL_H: f64 = 116.0;

    fn titled_action_dialog(_s: &mut ()) -> GlyphDialogView<()> {
        glyph_dialog()
            .title("Confirm")
            .action(tap_action(80.0, 36.0, |_s: &mut ()| {}))
    }

    #[test]
    fn keyboard_inset_centers_the_panel_in_the_free_area() {
        // A short display (iPhone-SE-class) with a 300px keyboard up: centering
        // in the FULL window would push the action row under the keyboard,
        // which is exactly the device report this pins.
        let area = Size::new(375.0, 667.0);
        let ime = 300.0;
        let free_bottom = area.height - ime;

        let mut root: RenderRoot<(), GlyphDialogView<()>> = RenderRoot::new();
        let mut state = ();
        let mut tcx = TextContext::new();
        root.rebuild(&mut titled_action_dialog, &mut state);
        root.set_insets(ime_insets(ime));
        root.layout_with_text(area, &mut tcx as &mut dyn Any);

        let w = dialog_widget(&root);
        assert_eq!(w.panel.height(), TITLED_ACTION_PANEL_H);
        assert_eq!(
            w.panel.y0,
            (free_bottom - TITLED_ACTION_PANEL_H) / 2.0,
            "the panel centers in the keyboard-free band, not the window"
        );
        assert!(
            w.panel.y1 <= free_bottom,
            "the whole panel clears the keyboard ({} vs {free_bottom})",
            w.panel.y1
        );
        // The action row — the button the device report could not reach — sits
        // above the keyboard line, unlike the pre-fix centered position.
        let action = w.actions.first().expect("one action");
        assert!(
            action.origin().y + action.size().height <= free_bottom,
            "the action row is visible above the keyboard"
        );
        assert!(
            (area.height - TITLED_ACTION_PANEL_H) / 2.0 + TITLED_ACTION_PANEL_H > free_bottom,
            "sanity: the old full-window centering really did overlap the keyboard"
        );
    }

    #[test]
    fn keyboard_retraction_recenters_the_panel() {
        // Same input, reverse direction: insets are a layout input, so dropping
        // them back to zero re-centers the panel with no widget-side state.
        let area = Size::new(375.0, 667.0);
        let mut root: RenderRoot<(), GlyphDialogView<()>> = RenderRoot::new();
        let mut state = ();
        let mut tcx = TextContext::new();
        root.rebuild(&mut titled_action_dialog, &mut state);

        root.set_insets(ime_insets(300.0));
        root.layout_with_text(area, &mut tcx as &mut dyn Any);
        let raised_y = dialog_widget(&root).panel.y0;

        root.set_insets(WindowInsets::default());
        root.layout_with_text(area, &mut tcx as &mut dyn Any);
        let settled_y = dialog_widget(&root).panel.y0;

        assert_eq!(
            settled_y,
            (area.height - TITLED_ACTION_PANEL_H) / 2.0,
            "with the keyboard gone the band is the window again"
        );
        assert!(settled_y > raised_y, "the panel moved back down");
    }

    #[test]
    fn panel_taller_than_the_free_area_pins_to_the_top() {
        // The documented degrade: the panel's own height is never clamped to
        // the band (no clipping, no auto-scrolling), so an oversized panel pins
        // to the top and overflows downward rather than sliding off the top.
        fn logic(_s: &mut ()) -> GlyphDialogView<()> {
            glyph_dialog()
                .title("Tall")
                .content(tap_action(200.0, 500.0, |_s: &mut ()| {}))
        }
        let mut root: RenderRoot<(), GlyphDialogView<()>> = RenderRoot::new();
        let mut state = ();
        let mut tcx = TextContext::new();
        root.rebuild(&mut logic, &mut state);
        root.set_insets(ime_insets(400.0));
        root.layout_with_text(Size::new(375.0, 667.0), &mut tcx as &mut dyn Any);

        let w = dialog_widget(&root);
        assert_eq!(w.panel.y0, 0.0, "pinned to the top, never negative");
        assert!(
            w.panel.height() > 667.0 - 400.0,
            "sanity: taller than the band"
        );
    }

    #[test]
    fn keyboard_inset_leaves_the_screen_margin_and_max_width_alone() {
        // The full-bleed fix (`SCREEN_MARGIN`) is untouched by the vertical
        // band: a narrow window with a keyboard up still gets its per-side
        // margin, and the panel width is unchanged by the inset.
        fn logic(_s: &mut ()) -> GlyphDialogView<()> {
            glyph_dialog()
                .title("Hi")
                .content(tap_action(10_000.0, 20.0, |_s: &mut ()| {}))
        }
        let area = Size::new(393.0, 800.0);
        let mut root: RenderRoot<(), GlyphDialogView<()>> = RenderRoot::new();
        let mut state = ();
        let mut tcx = TextContext::new();
        root.rebuild(&mut logic, &mut state);
        root.set_insets(ime_insets(336.0));
        root.layout_with_text(area, &mut tcx as &mut dyn Any);

        let w = dialog_widget(&root);
        assert_eq!(w.panel.width(), area.width - 2.0 * SCREEN_MARGIN);
        assert_eq!(w.panel.x0, SCREEN_MARGIN);
        assert!(
            w.panel.y1 <= area.height - 336.0,
            "still clears the keyboard"
        );
    }

    // -- Dead-space blur: the field's session ends, the dialog does not --

    #[derive(Default)]
    struct FieldState {
        text: String,
    }

    fn field_dialog(s: &mut FieldState) -> GlyphDialogView<FieldState> {
        glyph_dialog()
            .title("New token")
            .content(core_any::<FieldState, _>(text_input(
                s.text.clone(),
                |s: &mut FieldState, v| s.text = v,
            )))
            .action(tap_action(80.0, 36.0, |_s: &mut FieldState| {}))
    }

    /// A mounted dialog whose content field holds the live focus/IME session,
    /// plus the geometry the blur tests aim at.
    struct FieldFixture {
        root: RenderRoot<FieldState, GlyphDialogView<FieldState>>,
        state: FieldState,
        /// Dead panel space: inside the panel's padding, on no child.
        dead: Point,
        /// The center of the action button.
        action: Point,
    }

    fn focused_field_dialog(area: Size) -> FieldFixture {
        let mut root: RenderRoot<FieldState, GlyphDialogView<FieldState>> = RenderRoot::new();
        let mut state = FieldState::default();
        let mut tcx = TextContext::new();
        root.rebuild(&mut field_dialog, &mut state);
        root.layout_with_text(area, &mut tcx as &mut dyn Any);
        root.paint(&mut Recorder::default(), ft_ms(0.0));
        root.paint(&mut Recorder::default(), ft_ms(400.0)); // settled: Shown

        let (field, dead, action) = {
            let w = dialog_widget(&root);
            let f = w.body.as_ref().expect("the content field is built");
            let a = w.actions.first().expect("one action");
            (
                Point::new(
                    f.origin().x + f.size().width / 2.0,
                    f.origin().y + f.size().height / 2.0,
                ),
                // Inside the panel, inside DIALOG_PADDING: no child lives here.
                Point::new(w.panel.x0 + 2.0, w.panel.y0 + 2.0),
                Point::new(
                    a.origin().x + a.size().width / 2.0,
                    a.origin().y + a.size().height / 2.0,
                ),
            )
        };

        // Focus the field: a Down claims, and the field publishes its surface.
        root.event(&mut state, &ev(PointerPhase::Down, field.x, field.y));
        root.event(&mut state, &ev(PointerPhase::Up, field.x, field.y));
        assert!(
            root.ime_state().is_some(),
            "precondition: the field owns a live IME session"
        );
        assert!(root.is_focus_active());

        FieldFixture {
            root,
            state,
            dead,
            action,
        }
    }

    #[test]
    fn dead_space_down_ends_the_field_session_and_keeps_the_dialog_open() {
        let area = Size::new(375.0, 667.0);
        let mut f = focused_field_dialog(area);

        f.root
            .event(&mut f.state, &ev(PointerPhase::Down, f.dead.x, f.dead.y));

        assert!(
            f.root.ime_state().is_none(),
            "a Down on dead panel space ends the field's IME session — the keyboard retracts"
        );
        let w = dialog_widget(&f.root);
        assert!(
            !w.body.as_ref().expect("field").is_focused(),
            "the field lost the recorded focus path (it blurred)"
        );
        assert_ne!(w.phase, Phase::Exit, "the dialog is not dismissing");
        assert_ne!(w.phase, Phase::Dismissed);

        // ...and it stays cleared: the blurred field must not republish its
        // surface on the next painted frame.
        f.root
            .event(&mut f.state, &ev(PointerPhase::Up, f.dead.x, f.dead.y));
        f.root.paint(&mut Recorder::default(), ft_ms(500.0));
        assert!(
            f.root.ime_state().is_none(),
            "no resurrection on the next paint"
        );
        assert_eq!(
            dialog_widget(&f.root).phase,
            Phase::Shown,
            "the dialog is still open after the blur"
        );
    }

    #[test]
    fn escape_still_dismisses_after_a_dead_space_down() {
        // The other half of the contract: ending the field's *IME* session must
        // not sever the dialog's own key chain. `Key` events are focus-routed
        // and never hit-tested, so a dialog that stopped claiming focus on a
        // dead-space Down would silently lose Escape.
        let area = Size::new(375.0, 667.0);
        let mut f = focused_field_dialog(area);

        f.root
            .event(&mut f.state, &ev(PointerPhase::Down, f.dead.x, f.dead.y));
        f.root
            .event(&mut f.state, &ev(PointerPhase::Up, f.dead.x, f.dead.y));
        assert!(
            f.root.is_focus_active(),
            "the dialog keeps the focus link the same dispatch's claim re-applied"
        );

        f.root.event(&mut f.state, &escape_event());
        assert_eq!(
            dialog_widget(&f.root).phase,
            Phase::Exit,
            "Escape still reaches the dialog after a dead-space blur"
        );
    }

    #[test]
    fn action_down_leaves_the_field_session_intact() {
        // No pre-blur regression: tapping an action while the field is focused
        // activates it with the session untouched (the action row is an
        // interactive region, not dead space).
        let area = Size::new(375.0, 667.0);
        let mut f = focused_field_dialog(area);
        let before = f.root.focus_ime_generation();

        f.root.event(
            &mut f.state,
            &ev(PointerPhase::Down, f.action.x, f.action.y),
        );
        assert!(
            f.root.ime_state().is_some(),
            "an action Down never ends the field's session"
        );
        assert_eq!(
            f.root.focus_ime_generation(),
            before,
            "and fires no focus/IME edge at all"
        );
        f.root
            .event(&mut f.state, &ev(PointerPhase::Up, f.action.x, f.action.y));
        assert_eq!(dialog_widget(&f.root).phase, Phase::Shown);
    }

    #[test]
    fn dead_space_down_with_no_focused_content_moves_nothing() {
        // The release is gated on the slot actually holding the session: a
        // dialog whose content was never focused must not publish a clear (it
        // would release a session owned somewhere else entirely).
        let area = Size::new(375.0, 667.0);
        let mut root: RenderRoot<FieldState, GlyphDialogView<FieldState>> = RenderRoot::new();
        let mut state = FieldState::default();
        let mut tcx = TextContext::new();
        root.rebuild(&mut field_dialog, &mut state);
        root.layout_with_text(area, &mut tcx as &mut dyn Any);
        root.paint(&mut Recorder::default(), ft_ms(0.0));
        root.paint(&mut Recorder::default(), ft_ms(400.0));

        let dead = {
            let w = dialog_widget(&root);
            Point::new(w.panel.x0 + 2.0, w.panel.y0 + 2.0)
        };
        let before = root.focus_ime_generation();
        root.event(&mut state, &ev(PointerPhase::Down, dead.x, dead.y));

        assert!(root.ime_state().is_none());
        assert_eq!(
            root.focus_ime_generation(),
            before + 1,
            "exactly one edge: the dialog's own first focus claim, no spurious release"
        );
        assert!(root.is_focus_active());
    }

    #[test]
    fn dead_space_down_ends_the_session_with_the_dialog_pushed_on_a_navigator() {
        // The shipped shape: pushed through `show_glyph_dialog`, so the
        // dialog's `EventCtx::has_focus()` comes from its page pod's recorded
        // flag rather than the root's seed. Geometry is computed from the
        // constants (mirroring `action_pops_with_a_value_via_navigator`) since
        // the widget is not reachable under the navigator.
        let controller: NavigatorController<NavState> = NavigatorController::new();
        let mut root: RenderRoot<NavState, NavigatorView<NavState>> = RenderRoot::new();
        let mut app = app_page(&controller);
        let mut state = NavState::default();
        let area = Size::new(375.0, 667.0);

        root.rebuild(&mut app, &mut state);
        let mut tcx = TextContext::new();
        root.layout_with_text(area, &mut tcx as &mut dyn Any);

        let (field_w, field_h) = (200.0, 40.0);
        show_glyph_dialog(
            &controller,
            move || {
                glyph_dialog()
                    .title("Confirm")
                    .content(focus_field(field_w, field_h))
            },
            |state: &mut NavState, result: PopResult| state.results.push(result.take::<bool>()),
        );
        root.rebuild(&mut app, &mut state);
        root.layout_with_text(area, &mut tcx as &mut dyn Any);
        root.paint(&mut Recorder::default(), ft_ms(0.0));
        root.paint(&mut Recorder::default(), ft_ms(400.0)); // settled: Shown

        // Title (20) + gap + the field, inside the padding; MIN_WIDTH wide.
        let panel_h = 2.0 * DIALOG_PADDING + TITLE_LINE_HEIGHT as f64 + TITLE_BODY_GAP + field_h;
        let panel_x = (area.width - MIN_WIDTH) / 2.0;
        let panel_y = (area.height - panel_h) / 2.0;
        let field = Point::new(
            panel_x + DIALOG_PADDING + field_w / 2.0,
            panel_y + DIALOG_PADDING + TITLE_LINE_HEIGHT as f64 + TITLE_BODY_GAP + field_h / 2.0,
        );
        let dead = Point::new(panel_x + 2.0, panel_y + 2.0);

        root.event(&mut state, &ev(PointerPhase::Down, field.x, field.y));
        root.event(&mut state, &ev(PointerPhase::Up, field.x, field.y));
        assert!(
            root.ime_state().is_some(),
            "precondition: the field owns a live IME session"
        );

        root.event(&mut state, &ev(PointerPhase::Down, dead.x, dead.y));
        root.event(&mut state, &ev(PointerPhase::Up, dead.x, dead.y));
        assert!(
            root.ime_state().is_none(),
            "the dead-space Down ended the session under the navigator too"
        );
        assert_eq!(controller.depth(), 2, "the dialog page is still pushed");

        // Drive frames: nothing pops, nothing resurrects the surface.
        root.paint(&mut Recorder::default(), ft_ms(500.0));
        root.paint(&mut Recorder::default(), ft_ms(800.0));
        root.rebuild(&mut app, &mut state);
        assert_eq!(controller.depth(), 2, "a dead-space tap is not a dismiss");
        assert!(state.results.is_empty());
        assert!(root.ime_state().is_none());
    }

    #[test]
    fn semantics_forwards_the_content_subtree() {
        fn logic(_s: &mut ()) -> GlyphDialogView<()> {
            glyph_dialog()
                .title("Confirm")
                .content(any::<(), _>(text("hello".to_string())))
        }
        let mut root: RenderRoot<(), GlyphDialogView<()>> = RenderRoot::new();
        let mut state = ();
        root.rebuild(&mut logic, &mut state);
        let mut tcx = TextContext::new();
        root.layout_with_text(Size::new(400.0, 600.0), &mut tcx as &mut dyn Any);
        let update = root.semantics();

        let (_, dialog_node) = update
            .nodes
            .iter()
            .find(|(_, n)| n.role() == Role::Dialog)
            .expect("a Role::Dialog node is contributed");
        let (content_id, _) = update
            .nodes
            .iter()
            .find(|(_, n)| n.role() == Role::Label && n.value() == Some("hello"))
            .expect("the content subtree's own semantics reached the tree — it was forwarded");
        assert!(
            dialog_node.children().contains(content_id),
            "the content node is a direct semantics child of the dialog container"
        );
    }

    // A fixed-size interactive leaf firing `on_tap` on up-inside (a dialog action
    // of known geometry, no text shaping) — mirrors the material dialog fixture.
    struct TapView<State: 'static> {
        size: Size,
        on_tap: Rc<dyn Fn(&mut State)>,
    }
    struct TapWidget {
        size: Size,
        on_tap: frust::authoring::ErasedCallback,
        captured: bool,
    }
    impl<State: 'static> View<State> for TapView<State> {
        type Element = TapWidget;
        fn build(&self, _ctx: &mut BuildCtx<'_>) -> TapWidget {
            TapWidget {
                size: self.size,
                on_tap: frust::authoring::erase_callback(&self.on_tap),
                captured: false,
            }
        }
        fn rebuild(&self, _p: &Self, e: &mut TapWidget, _c: &mut BuildCtx<'_>) -> ChangeFlags {
            e.on_tap = frust::authoring::erase_callback(&self.on_tap);
            ChangeFlags::NONE
        }
    }
    impl Widget for TapWidget {
        fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            bc.constrain(self.size)
        }
        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 => {
                    self.captured = true;
                    ctx.capture_pointer();
                    EventResult::Handled
                }
                PointerPhase::Up => {
                    if self.captured
                        && p.position.x >= 0.0
                        && p.position.y >= 0.0
                        && p.position.x < self.size.width
                        && p.position.y < self.size.height
                    {
                        (self.on_tap)(ctx);
                    }
                    self.captured = false;
                    EventResult::Handled
                }
                PointerPhase::Move => EventResult::Handled,
                PointerPhase::Cancel => {
                    self.captured = false;
                    EventResult::Handled
                }
            }
        }
    }
    fn tap_action<State: 'static>(
        w: f64,
        h: f64,
        on_tap: impl Fn(&mut State) + 'static,
    ) -> AnyView<State> {
        core_any::<State, _>(TapView {
            size: Size::new(w, h),
            on_tap: Rc::new(on_tap),
        })
    }

    // A fixed-size stand-in for a focused text field: claims focus and
    // publishes an ACTIVE IME surface on `Down`, exactly like `TextInput`'s
    // focus path, but with deterministic geometry (no text shaping) so a
    // navigator-hosted panel's dead space can be computed from the constants.
    struct FocusFieldView<State: 'static> {
        size: Size,
        _state: std::marker::PhantomData<State>,
    }
    struct FocusFieldWidget {
        size: Size,
    }
    impl<State: 'static> View<State> for FocusFieldView<State> {
        type Element = FocusFieldWidget;
        fn build(&self, _ctx: &mut BuildCtx<'_>) -> FocusFieldWidget {
            FocusFieldWidget { size: self.size }
        }
        fn rebuild(
            &self,
            _p: &Self,
            _e: &mut FocusFieldWidget,
            _c: &mut BuildCtx<'_>,
        ) -> ChangeFlags {
            ChangeFlags::NONE
        }
    }
    impl Widget for FocusFieldWidget {
        fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            bc.constrain(self.size)
        }
        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;
            };
            if p.phase == PointerPhase::Down {
                ctx.request_focus();
                ctx.publish_ime_state(ImeState {
                    active: true,
                    editing: EditingState {
                        text: "hi".to_string(),
                        selection_base: 2,
                        selection_extent: 2,
                        composing_base: -1,
                        composing_extent: -1,
                    },
                    caret: Some(Rect::new(0.0, 0.0, 1.0, 12.0)),
                    content_type: Default::default(),
                    suppress_soft_keyboard: false,
                });
            }
            EventResult::Handled
        }
    }
    fn focus_field<State: 'static>(w: f64, h: f64) -> AnyView<State> {
        core_any::<State, _>(FocusFieldView {
            size: Size::new(w, h),
            _state: std::marker::PhantomData,
        })
    }

    // -- Typeface: title and body follow their type-scale roles -----------

    #[cfg(feature = "bundled-fonts")]
    fn confirm(_: &mut ()) -> GlyphDialogView<()> {
        glyph_dialog().title("Confirm").body("Sure?")
    }

    #[cfg(feature = "bundled-fonts")]
    #[test]
    fn title_and_body_paint_in_their_role_faces_under_the_glyph_theme() {
        use crate::badge::typeface_probe::{Face, painted_faces};
        let faces = painted_faces(confirm, crate::baseline(), Size::new(400.0, 600.0));
        // Title, body.
        assert_eq!(faces, [Face::SpaceMono, Face::PlexMono]);
    }

    #[cfg(feature = "bundled-fonts")]
    #[test]
    fn title_and_body_follow_a_live_theme_family_swap() {
        use crate::badge::typeface_probe::{Face, faces_across_a_live_swap};
        let (before, after) = faces_across_a_live_swap(confirm, Size::new(400.0, 600.0));
        assert_eq!(before, [Face::SpaceMono, Face::PlexMono]);
        assert_eq!(after, [Face::PlexMono, Face::SpaceMono]);
    }
}