aetna-web 0.3.6

Aetna browser host for wasm apps
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
//! Browser host for Aetna wasm apps.
//!
//! Write normal UI code against `aetna_core::prelude::*`, then call
//! [`start_with`] from your wasm crate's `#[wasm_bindgen(start)]`
//! entry point. The host opens a wgpu surface against a canvas in the
//! page and drives the app through winit's browser event loop.
//!
//! The default configuration expects a `<canvas id="aetna_canvas">`.
//! Use [`start_with_config`] when embedding into a page with a different
//! canvas id.
//!
//! `aetna-winit-wgpu` is the equivalent reusable native host.

use aetna_core::Rect;

/// Default canvas element id used by [`WebHostConfig::default`].
pub const DEFAULT_CANVAS_ID: &str = "aetna_canvas";

/// Default logical viewport. Sized to feel reasonable both as a winit
/// window and as a browser canvas. Browsers can override this by
/// resizing the canvas; the runner reacts to `winit::Resized`.
pub const VIEWPORT: Rect = Rect {
    x: 0.0,
    y: 0.0,
    w: 900.0,
    h: 640.0,
};

/// Browser host configuration.
#[derive(Clone, Debug)]
pub struct WebHostConfig {
    /// Fallback logical viewport used when the canvas has no CSS size
    /// yet. Once the page lays the canvas out, the host tracks its CSS
    /// box through `ResizeObserver`.
    pub viewport: Rect,
    /// Id of the canvas element the host should attach to.
    pub canvas_id: String,
}

impl WebHostConfig {
    pub fn new(viewport: Rect) -> Self {
        Self {
            viewport,
            canvas_id: DEFAULT_CANVAS_ID.to_string(),
        }
    }

    pub fn with_canvas_id(mut self, canvas_id: impl Into<String>) -> Self {
        self.canvas_id = canvas_id.into();
        self
    }
}

impl Default for WebHostConfig {
    fn default() -> Self {
        Self::new(VIEWPORT)
    }
}

#[cfg(target_arch = "wasm32")]
pub use web_entry::{WebHandle, start_with, start_with_config};

#[cfg(not(target_arch = "wasm32"))]
pub use native_stub::{WebHandle, start_with, start_with_config};

#[cfg(not(target_arch = "wasm32"))]
mod native_stub {
    use aetna_core::{App, Rect};

    use super::WebHostConfig;

    /// Browser redraw handle.
    ///
    /// On non-wasm targets this is a no-op placeholder so host crates
    /// can type-check shared code. It is only functional on
    /// `wasm32-unknown-unknown`.
    #[derive(Clone, Debug, Default)]
    pub struct WebHandle {
        _private: (),
    }

    impl WebHandle {
        pub fn request_redraw(&self) {}
    }

    pub fn start_with<A: App + 'static>(_viewport: Rect, _app: A) -> WebHandle {
        panic!("aetna-web can only start apps on wasm32-unknown-unknown")
    }

    pub fn start_with_config<A: App + 'static>(_config: WebHostConfig, _app: A) -> WebHandle {
        panic!("aetna-web can only start apps on wasm32-unknown-unknown")
    }
}

// ---- Wasm host ----
//
// Lives in its own module so it can pull in wasm-only deps without
// polluting native builds.

#[cfg(target_arch = "wasm32")]
mod web_entry {
    use std::cell::{Cell, RefCell};
    use std::collections::VecDeque;
    use std::rc::Rc;
    use std::sync::Arc;

    use aetna_core::{
        App, BuildCx, Cursor, FrameTrigger, HostDiagnostics, KeyModifiers, Palette, Pointer,
        PointerButton, PointerId, PointerKind, Rect, UiEvent, UiEventKind, UiKey, clipboard,
        widgets::text_input::{self, ClipboardKind},
    };
    use aetna_wgpu::{PrepareTimings, Runner};

    // MSAA is off on the browser. The WebGL2 path doesn't advertise
    // `MULTISAMPLED_SHADING`, so MSAA gives nothing to the SDF stock
    // surfaces (they do their own analytic AA in the fragment shader);
    // it would only have improved vector-icon polygon-edge AA. With it
    // on, Firefox + Mesa's implicit MSAA resolve was mis-syncing
    // partial regions of the swapchain — the sidebar would freeze at
    // its previous pixels until something forced a tree reshape. WebGPU
    // (Chromium) was unaffected but we use the same value for both
    // browser backends to keep one code path. Revisit once the WebGL2
    // resolve issue is understood (or once WebGPU is the only target).
    const SAMPLE_COUNT: u32 = 1;
    use wasm_bindgen::JsCast;
    use wasm_bindgen::prelude::Closure;
    use web_time::{Duration, Instant};
    use winit::application::ApplicationHandler;
    use winit::event::{ElementState, MouseScrollDelta, WindowEvent};
    use winit::event_loop::{ActiveEventLoop, EventLoop};
    use winit::keyboard::{Key, NamedKey};
    use winit::platform::web::{EventLoopExtWebSys, WindowAttributesExtWebSys};
    use winit::window::{CursorIcon, Window, WindowId};

    use super::WebHostConfig;

    /// Number of redraws to accumulate before logging an averaged
    /// frame-timing line. 60 → roughly once per second at 60fps when
    /// animations are in flight; for idle UI (no redraws) the log
    /// just stops, which is the right behavior.
    const FRAME_LOG_INTERVAL: u32 = 60;

    /// Pointer event captured by a DOM listener and queued for the
    /// next frame's dispatch pass. We can't dispatch directly inside
    /// the closure because the app handle and the renderer live on
    /// `Host`, which is owned by winit's event loop and only reachable
    /// through `&mut self` in `window_event`. The queue lets the
    /// closures stay simple (push + request_redraw) while the
    /// dispatch path runs with full host state.
    enum QueuedPointer {
        Move(Pointer),
        Down(Pointer),
        Up(Pointer),
        Cancel(Pointer),
        Leave,
    }

    /// Map `PointerEvent.pointerType` → [`PointerKind`].
    fn pointer_kind_from_type(s: &str) -> PointerKind {
        match s {
            "touch" => PointerKind::Touch,
            "pen" => PointerKind::Pen,
            // "mouse", "" or any future / unknown value falls back to
            // mouse semantics — that's the conservative default for
            // hover-driven affordances.
            _ => PointerKind::Mouse,
        }
    }

    /// Map `PointerEvent.button` → [`PointerButton`]. `None` for
    /// buttons Aetna does not route (back, forward, pen eraser).
    fn pointer_button_from_event(b: i16) -> Option<PointerButton> {
        match b {
            0 => Some(PointerButton::Primary),
            1 => Some(PointerButton::Middle),
            2 => Some(PointerButton::Secondary),
            _ => None,
        }
    }

    /// Translate a DOM `PointerEvent` to an Aetna [`Pointer`]. Uses
    /// `offset_x`/`offset_y` because they are already canvas-local
    /// CSS pixels — the runtime expects logical-pixel coordinates,
    /// so no DPI division is needed (in contrast to winit's
    /// physical-pixel `CursorMoved`).
    fn pointer_from_event(event: &web_sys::PointerEvent, button: PointerButton) -> Pointer {
        let pressure = event.pressure();
        Pointer {
            x: event.offset_x() as f32,
            y: event.offset_y() as f32,
            button,
            kind: pointer_kind_from_type(&event.pointer_type()),
            id: PointerId(event.pointer_id() as u32),
            // PointerEvent always returns a value for `pressure`, but
            // it's `0.0` for non-pressure-sensitive devices (mouse).
            // `Some(0.0)` would be misleading, so we filter that case.
            pressure: if pressure > 0.0 { Some(pressure) } else { None },
        }
    }

    /// Rolling per-frame timing bucket. Three top-level CPU stages
    /// (`build`, `prepare`, `submit`) plus a per-stage breakdown of
    /// what's inside `prepare` (layout / draw_ops / paint / gpu_upload
    /// / snapshot — see [`PrepareTimings`]). `inter` is the wall-clock
    /// interval between consecutive RedrawRequested calls; comparing
    /// `build + prepare + submit` against `inter` shows how much frame
    /// budget the CPU is burning vs. how much the browser's rAF throttle
    /// gives us.
    #[derive(Default)]
    struct FrameStats {
        build_us: u64,
        prepare_us: u64,
        submit_us: u64,
        inter_us: u64,
        // Sub-buckets inside prepare. Sum is ~prepare_us minus a few
        // microseconds of Instant::now() overhead.
        layout_us: u64,
        draw_ops_us: u64,
        paint_us: u64,
        gpu_upload_us: u64,
        snapshot_us: u64,
        samples: u32,
        last_frame_start: Option<Instant>,
    }

    impl FrameStats {
        fn record(
            &mut self,
            frame_start: Instant,
            t1: Instant,
            t2: Instant,
            t3: Instant,
            prep: PrepareTimings,
        ) {
            self.build_us += (t1 - frame_start).as_micros() as u64;
            self.prepare_us += (t2 - t1).as_micros() as u64;
            self.submit_us += (t3 - t2).as_micros() as u64;
            self.layout_us += prep.layout.as_micros() as u64;
            self.draw_ops_us += prep.draw_ops.as_micros() as u64;
            self.paint_us += prep.paint.as_micros() as u64;
            self.gpu_upload_us += prep.gpu_upload.as_micros() as u64;
            self.snapshot_us += prep.snapshot.as_micros() as u64;
            if let Some(prev) = self.last_frame_start {
                self.inter_us += (frame_start - prev).as_micros() as u64;
            }
            self.last_frame_start = Some(frame_start);
            self.samples += 1;
            if self.samples >= FRAME_LOG_INTERVAL {
                self.flush();
            }
        }

        fn flush(&mut self) {
            // `inter` averages over `samples - 1` because the first
            // frame in each window has no prior frame to diff against.
            let n = self.samples as u64;
            let inter_n = (self.samples.saturating_sub(1)) as u64;
            let build = self.build_us / n;
            let prepare = self.prepare_us / n;
            let submit = self.submit_us / n;
            let layout = self.layout_us / n;
            let draw_ops = self.draw_ops_us / n;
            let paint = self.paint_us / n;
            let gpu_upload = self.gpu_upload_us / n;
            let snapshot = self.snapshot_us / n;
            let cpu = build + prepare + submit;
            let inter = self.inter_us.checked_div(inter_n).unwrap_or(0);
            let util = (cpu * 100).checked_div(inter).unwrap_or(0);
            log::info!(
                "frame[{n}] inter={:.2}ms cpu={:.2}ms util={util}% | build={:.2} prepare={:.2} (layout={:.2} draw_ops={:.2} paint={:.2} gpu={:.2} snapshot={:.2}) submit={:.2}",
                inter as f64 / 1000.0,
                cpu as f64 / 1000.0,
                build as f64 / 1000.0,
                prepare as f64 / 1000.0,
                layout as f64 / 1000.0,
                draw_ops as f64 / 1000.0,
                paint as f64 / 1000.0,
                gpu_upload as f64 / 1000.0,
                snapshot as f64 / 1000.0,
                submit as f64 / 1000.0,
            );
            self.build_us = 0;
            self.prepare_us = 0;
            self.submit_us = 0;
            self.inter_us = 0;
            self.layout_us = 0;
            self.draw_ops_us = 0;
            self.paint_us = 0;
            self.gpu_upload_us = 0;
            self.snapshot_us = 0;
            self.samples = 0;
            // Keep last_frame_start so `inter` in the next window
            // includes the gap from the last logged frame to the
            // first frame of the new window.
        }
    }

    /// Wire the global `tracing` subscriber to `tracing-wasm`, which
    /// emits `performance.mark` / `performance.measure` calls for every
    /// span. Open DevTools → Performance, hit Record, exercise the UI;
    /// each span shows up as a labeled User Timing measure in the
    /// flamegraph (`prepare::layout`, `paint::text::shape_runs`, etc).
    /// Defaults are fine — span events go to console.log, measures get
    /// written, and the subscriber only sees enabled spans (no extra
    /// filter wiring needed on top of the `profiling` feature).
    #[cfg(feature = "profiling")]
    fn install_profiling_subscriber() {
        tracing_wasm::set_as_global_default();
    }

    /// Handle returned by [`start_with`] so embedding code can wake the
    /// host after external browser events enqueue app work.
    #[derive(Clone)]
    pub struct WebHandle {
        inner: Rc<WebHandleInner>,
    }

    struct WebHandleInner {
        window: RefCell<Option<Arc<Window>>>,
        ready: Cell<bool>,
        pending_redraw: Cell<bool>,
    }

    impl WebHandle {
        fn new() -> Self {
            Self {
                inner: Rc::new(WebHandleInner {
                    window: RefCell::new(None),
                    ready: Cell::new(false),
                    pending_redraw: Cell::new(false),
                }),
            }
        }

        /// Request a redraw from external browser integration code.
        ///
        /// If the browser window or GPU setup is not ready yet, the
        /// request is remembered and flushed once setup completes.
        pub fn request_redraw(&self) {
            if self.inner.ready.get()
                && let Some(window) = self.inner.window.borrow().as_ref()
            {
                window.request_redraw();
                return;
            }
            self.inner.pending_redraw.set(true);
        }

        fn set_window(&self, window: Arc<Window>) {
            *self.inner.window.borrow_mut() = Some(window);
        }

        fn mark_ready(&self) -> bool {
            self.inner.ready.set(true);
            self.inner.pending_redraw.replace(false)
        }
    }

    /// Start an Aetna app in the browser using the default canvas id.
    ///
    /// Call this from the downstream crate's own
    /// `#[wasm_bindgen(start)]` function.
    pub fn start_with<A: App + 'static>(viewport: Rect, app: A) -> WebHandle {
        start_with_config(WebHostConfig::new(viewport), app)
    }

    /// Start an Aetna app in the browser with explicit host config.
    ///
    /// The function spawns winit's web event loop and returns
    /// immediately. Keep the returned [`WebHandle`] anywhere external
    /// JS callbacks need to wake Aetna after pushing work into
    /// app-owned shared state.
    pub fn start_with_config<A: App + 'static>(config: WebHostConfig, app: A) -> WebHandle {
        // Surface panics in the browser console with a stack trace —
        // without this hook a wasm panic dies silently as `unreachable`.
        console_error_panic_hook::set_once();
        let _ = console_log::init_with_level(log::Level::Info);
        // When built with `--features profiling`, route every
        // `profile_span!` call to the browser's User Timing API so spans
        // show up as named measures in DevTools → Performance alongside
        // the page's own frame/script work. Off-builds compile this away.
        #[cfg(feature = "profiling")]
        install_profiling_subscriber();

        let event_loop = EventLoop::new().expect("EventLoop::new");
        let handle = WebHandle::new();
        let host = Host::new(config, app, handle.clone());
        // spawn_app hands control to the browser. Native uses
        // run_app(...) which blocks; on wasm32 the event loop is
        // driven by the browser's animation-frame callbacks.
        event_loop.spawn_app(host);
        handle
    }

    /// Open a URL surfaced by `App::drain_link_opens` in a new tab.
    /// `_blank` matches what users expect for a click on an external
    /// link in app UI; `noopener` severs the `window.opener` reference
    /// so the opened page can't reverse-control this one. Failures are
    /// logged rather than panicking — popup blockers and CSP rules can
    /// reject the open and the showcase shouldn't crash because the
    /// browser said no.
    fn open_link(url: &str) {
        let Some(window) = web_sys::window() else {
            log::warn!("aetna-web: no window; dropping link open for {url}");
            return;
        };
        if let Err(err) = window.open_with_url_and_target_and_features(url, "_blank", "noopener") {
            log::warn!("aetna-web: window.open({url}) failed: {err:?}");
        }
    }

    /// Locate the configured canvas element in the host page.
    fn locate_canvas(canvas_id: &str) -> web_sys::HtmlCanvasElement {
        let window = web_sys::window().expect("no window");
        let document = window.document().expect("no document");
        document
            .get_element_by_id(canvas_id)
            .unwrap_or_else(|| panic!("missing #{canvas_id} canvas element"))
            .dyn_into::<web_sys::HtmlCanvasElement>()
            .unwrap_or_else(|_| panic!("#{canvas_id} is not a canvas"))
    }

    /// Read the canvas's CSS-laid-out box at the device pixel ratio.
    /// Returned size is what the swapchain backing buffer should match;
    /// callers pass it to `apply_canvas_size` to actually reconfigure
    /// the surface.
    fn measure_canvas(canvas: &web_sys::HtmlCanvasElement, fallback: Rect) -> (u32, u32) {
        let dpr = web_sys::window()
            .map(|w| w.device_pixel_ratio())
            .unwrap_or(1.0)
            .max(1.0);
        let css_w = if canvas.client_width() > 0 {
            canvas.client_width() as f64
        } else {
            fallback.w.max(1.0) as f64
        };
        let css_h = if canvas.client_height() > 0 {
            canvas.client_height() as f64
        } else {
            fallback.h.max(1.0) as f64
        };
        let phys_w = (css_w * dpr).round() as u32;
        let phys_h = (css_h * dpr).round() as u32;
        (phys_w, phys_h)
    }

    /// Set the canvas's drawing buffer to `(phys_w, phys_h)` and
    /// reconfigure the surface + MSAA target to match. Called once at
    /// initial setup and on every ResizeObserver fire afterward.
    ///
    /// We bypass winit's `request_inner_size` round-trip — the web
    /// backend doesn't reliably translate it into a `Resized` event, so
    /// canvas resizes mid-session were leaving the swapchain stretched
    /// at the original size until the page reloaded. Doing the
    /// reconfigure inline keeps the surface in lockstep with the
    /// canvas.
    fn apply_canvas_size(
        canvas: &web_sys::HtmlCanvasElement,
        gfx: &mut Gfx,
        phys_w: u32,
        phys_h: u32,
    ) {
        canvas.set_width(phys_w);
        canvas.set_height(phys_h);
        if gfx.config.width == phys_w && gfx.config.height == phys_h {
            return;
        }
        gfx.config.width = phys_w;
        gfx.config.height = phys_h;
        gfx.surface.configure(&gfx.device, &gfx.config);
        gfx.renderer.set_surface_size(phys_w, phys_h);
        if let Some(msaa) = gfx.msaa.as_mut() {
            let extent = surface_extent(&gfx.config);
            if !msaa.matches(extent) {
                *msaa = aetna_wgpu::MsaaTarget::new(
                    &gfx.device,
                    gfx.render_format,
                    extent,
                    SAMPLE_COUNT,
                );
            }
        }
    }

    /// Install `pointermove` / `pointerdown` / `pointerup` /
    /// `pointercancel` / `pointerleave` listeners on `canvas` and
    /// stash the closures in `out` for the host's lifetime.
    ///
    /// Each listener pushes onto the shared queue and requests a
    /// redraw; the host's `window_event` drains the queue at the top
    /// of every call. `pointerdown` also calls `setPointerCapture` so
    /// the pointer keeps reporting to the canvas during a drag even
    /// when the contact slides off — without this, slider scrubbing
    /// and text-selection drag stop the moment the finger leaves the
    /// element.
    fn install_pointer_listeners(
        canvas: &web_sys::HtmlCanvasElement,
        window: &Arc<Window>,
        pending: &Rc<RefCell<VecDeque<QueuedPointer>>>,
        gfx: &Rc<RefCell<Option<Gfx>>>,
        soft_keyboard: Option<&Rc<SoftKeyboard>>,
        out: &mut Vec<Closure<dyn FnMut(web_sys::PointerEvent)>>,
    ) {
        // pointermove
        {
            let pending = pending.clone();
            let window = window.clone();
            let closure: Closure<dyn FnMut(web_sys::PointerEvent)> =
                Closure::new(move |event: web_sys::PointerEvent| {
                    let p = pointer_from_event(&event, PointerButton::Primary);
                    pending.borrow_mut().push_back(QueuedPointer::Move(p));
                    window.request_redraw();
                });
            canvas
                .add_event_listener_with_callback("pointermove", closure.as_ref().unchecked_ref())
                .expect("add pointermove listener");
            out.push(closure);
        }

        // pointerdown
        {
            let pending = pending.clone();
            let window = window.clone();
            let canvas_for_capture = canvas.clone();
            let gfx_for_hit = gfx.clone();
            let soft_keyboard = soft_keyboard.cloned();
            let closure: Closure<dyn FnMut(web_sys::PointerEvent)> =
                Closure::new(move |event: web_sys::PointerEvent| {
                    let Some(button) = pointer_button_from_event(event.button()) else {
                        return;
                    };
                    let p = pointer_from_event(&event, button);
                    // Soft-keyboard summon must happen synchronously
                    // inside this user-gesture handler — iOS rejects
                    // programmatic `.focus()` from any later context.
                    // Hit-test against the runner's last laid-out
                    // tree (read-only borrow) to decide whether the
                    // press would land on a text-input widget; if
                    // so, focus the hidden textarea now. The runner-
                    // side dispatch follows on the next frame via
                    // the queue/drain path.
                    let mut focused_textarea = false;
                    if matches!(p.kind, PointerKind::Touch | PointerKind::Pen)
                        && let Some(sk) = soft_keyboard.as_ref()
                    {
                        let want_keyboard = gfx_for_hit
                            .borrow()
                            .as_ref()
                            .map(|g| g.renderer.would_press_focus_text_input(p.x, p.y))
                            .unwrap_or(false);
                        if want_keyboard {
                            sk.focus_if_needed();
                            focused_textarea = true;
                        }
                    }
                    // Take focus on tap-down so subsequent keydown
                    // events (soft keyboard, hardware keyboard on
                    // tablets) reach the canvas. winit's web backend
                    // would normally do this for compat-mouse events,
                    // but we no longer route through there.
                    //
                    // Skip when the textarea was just focused — the
                    // canvas is fighting for the same DOM focus, and
                    // taking it back here was preventing Android (and
                    // iOS) from ever seeing a focused textarea long
                    // enough to summon the on-screen keyboard.
                    // Hardware-keyboard input into a text input still
                    // works because keystrokes reach the textarea's
                    // own listeners and route through `text_input` /
                    // `key_down` the same way they would via the
                    // canvas's keydown handler.
                    if !focused_textarea {
                        let _ = canvas_for_capture
                            .dyn_ref::<web_sys::HtmlElement>()
                            .and_then(|el| el.focus().ok());
                    }
                    // Keep this pointer captured so a drag that
                    // slides off the canvas still produces events to
                    // the runner (essential for touch sliders,
                    // drag-select, and text-input scrubbing).
                    let _ = canvas_for_capture.set_pointer_capture(event.pointer_id());
                    // When the press just summoned the on-screen
                    // keyboard, suppress the browser's default
                    // pointerdown action so it doesn't shift DOM
                    // focus to the canvas (a tabindex=0 element)
                    // after our listener returns. Android Chrome
                    // does that focus shift as part of touch
                    // pointerdown handling on focusable elements,
                    // and the resulting blur on our hidden input
                    // dismisses the keyboard one frame after it
                    // appears. We also stopPropagation so any
                    // document-level listener the host page wires
                    // doesn't get a second crack at shifting focus.
                    if focused_textarea {
                        event.prevent_default();
                        event.stop_propagation();
                    }
                    pending.borrow_mut().push_back(QueuedPointer::Down(p));
                    window.request_redraw();
                });
            canvas
                .add_event_listener_with_callback("pointerdown", closure.as_ref().unchecked_ref())
                .expect("add pointerdown listener");
            out.push(closure);
        }

        // pointerup
        {
            let pending = pending.clone();
            let window = window.clone();
            let closure: Closure<dyn FnMut(web_sys::PointerEvent)> =
                Closure::new(move |event: web_sys::PointerEvent| {
                    let Some(button) = pointer_button_from_event(event.button()) else {
                        return;
                    };
                    let p = pointer_from_event(&event, button);
                    pending.borrow_mut().push_back(QueuedPointer::Up(p));
                    window.request_redraw();
                });
            canvas
                .add_event_listener_with_callback("pointerup", closure.as_ref().unchecked_ref())
                .expect("add pointerup listener");
            out.push(closure);
        }

        // pointercancel — fired when the OS / browser steals the
        // pointer (e.g., a system gesture interrupts a touch). Treat
        // it like an up so any in-flight press / drag state clears.
        {
            let pending = pending.clone();
            let window = window.clone();
            let closure: Closure<dyn FnMut(web_sys::PointerEvent)> =
                Closure::new(move |event: web_sys::PointerEvent| {
                    let p = pointer_from_event(&event, PointerButton::Primary);
                    pending.borrow_mut().push_back(QueuedPointer::Cancel(p));
                    window.request_redraw();
                });
            canvas
                .add_event_listener_with_callback("pointercancel", closure.as_ref().unchecked_ref())
                .expect("add pointercancel listener");
            out.push(closure);
        }

        // pointerleave — pointer left the canvas. Mirrors winit's
        // CursorLeft on native; clears hover state.
        {
            let pending = pending.clone();
            let window = window.clone();
            let closure: Closure<dyn FnMut(web_sys::PointerEvent)> =
                Closure::new(move |_event: web_sys::PointerEvent| {
                    pending.borrow_mut().push_back(QueuedPointer::Leave);
                    window.request_redraw();
                });
            canvas
                .add_event_listener_with_callback("pointerleave", closure.as_ref().unchecked_ref())
                .expect("add pointerleave listener");
            out.push(closure);
        }
    }

    // ===================================================================
    // Soft keyboard
    //
    // A `<canvas>` cannot summon the on-screen keyboard on touch
    // platforms — only focusable text-input DOM elements can, and only
    // when the focus comes from a user-gesture event handler. This
    // module overlays a hidden `<textarea>` and synchronously focuses
    // it from the pointerdown DOM listener when the press would land
    // on an Aetna text-input widget. Once focused, the textarea
    // receives `input` events for typed characters (routed to the
    // runtime as `text_input(...)`) and `keydown` events for editing
    // keys (routed as synthetic `key_down(Backspace, ...)`).
    //
    // The native host (aetna-winit-wgpu) routes hardware keyboards
    // through winit and is unaffected by any of this. Soft keyboards
    // on a future Android winit host would use winit's own IME path.
    // ===================================================================

    /// One discrete edit produced by the soft keyboard. Drained by
    /// the host once per `window_event` and dispatched through the
    /// runtime's existing keyboard / text-input entry points so the
    /// focused widget sees the same shape it would for a hardware
    /// keystroke.
    enum TextEdit {
        /// User typed text — route as `runner.text_input(s)`.
        Insert(String),
        /// User pressed backspace — route as
        /// `runner.key_down(UiKey::Backspace, ...)`.
        Backspace,
    }

    /// The hidden `<input>` that summons the soft keyboard plus its
    /// DOM listeners and the pending-edit queue. Held by [`Host`]
    /// for the lifetime of the page; the closures inside borrow
    /// the queue via clones of its `Rc`.
    ///
    /// Modeled on egui's `text_agent.rs` after observing that
    /// Android's keyboard refused to stay open against an
    /// `opacity:0; pointer-events:none` element. Egui keeps the
    /// element technically interactive (no pointer-events: none),
    /// uses `<input type="text">` rather than `<textarea>`, and
    /// hides it via `caret-color: transparent` +
    /// `background-color: transparent` instead of opacity. Android
    /// then treats it as a real focusable input and the keyboard
    /// stays up.
    struct SoftKeyboard {
        input: web_sys::HtmlInputElement,
        /// Whether we believe the input currently holds DOM focus.
        /// Tracked here (rather than read via `document.activeElement`
        /// every time) so `focus_if_needed` can no-op for repeated
        /// taps that don't actually need to refocus. `Rc<Cell<_>>`
        /// because the `blur` closure also writes to it when the OS
        /// dismisses the keyboard outside our control.
        focused: Rc<Cell<bool>>,
        /// Queue of edits captured by the DOM listeners since the
        /// last drain. Drained by [`Host`] inside `window_event`.
        pending: Rc<RefCell<VecDeque<TextEdit>>>,
        /// Held for drop side-effects: the `input` event closure.
        _input_closure: Closure<dyn FnMut(web_sys::InputEvent)>,
        /// Held for drop side-effects: the `keydown` closure that
        /// catches editing keys (Backspace, Enter, arrow keys) the
        /// soft keyboard fires as `keydown` rather than `input`.
        _keydown_closure: Closure<dyn FnMut(web_sys::KeyboardEvent)>,
        /// Held for drop side-effects: the `blur` closure that
        /// resets `focused` when the OS / user dismisses the
        /// keyboard outside of our control.
        _blur_closure: Closure<dyn FnMut(web_sys::Event)>,
    }

    impl SoftKeyboard {
        /// Create the hidden input, attach it to the document, and
        /// wire up the listeners. Returns `None` if any DOM
        /// operation fails (no body, etc.) — the host then runs
        /// without soft-keyboard support, which is the correct
        /// degradation for environments where it can't work.
        fn install(canvas: &web_sys::HtmlCanvasElement, window: &Arc<Window>) -> Option<Self> {
            let document = canvas.owner_document()?;
            let input = document
                .create_element("input")
                .ok()?
                .dyn_into::<web_sys::HtmlInputElement>()
                .ok()?;
            input.set_type("text");
            // Visible-for-focus, invisible-for-the-eye. The element
            // has to remain *technically* focusable for Android's
            // keyboard to stay up — `pointer-events: none`,
            // `opacity: 0`, and `display: none` all disqualify. We
            // mirror egui's working configuration: a 1×1
            // transparent-background element with the caret hidden,
            // pinned to `(0, 0)` of the document. The canvas paints
            // on top of everything else and absorbs every visible
            // tap; the input is just a DOM focus target.
            if let Some(style) = input.dyn_ref::<web_sys::HtmlElement>().map(|e| e.style()) {
                let _ = style.set_property("position", "absolute");
                let _ = style.set_property("top", "0");
                let _ = style.set_property("left", "0");
                let _ = style.set_property("width", "1px");
                let _ = style.set_property("height", "1px");
                let _ = style.set_property("background-color", "transparent");
                let _ = style.set_property("border", "none");
                let _ = style.set_property("outline", "none");
                let _ = style.set_property("caret-color", "transparent");
            }
            // Attribute hygiene: prevent the on-screen keyboard from
            // showing autocorrect suggestions / capitalization /
            // browser autofill, which would interfere with character-
            // by-character routing into the runtime.
            let _ = input.set_attribute("autocapitalize", "off");
            let _ = input.set_attribute("autocomplete", "off");
            let _ = input.set_attribute("autocorrect", "off");
            let _ = input.set_attribute("spellcheck", "false");
            document.body()?.append_child(&input).ok()?;

            let pending: Rc<RefCell<VecDeque<TextEdit>>> = Rc::new(RefCell::new(VecDeque::new()));

            // input: fires on every character insertion and on
            // deletes. Read inputType to discriminate; route to the
            // pending queue and clear the input so the next event
            // sees only the new edit (we don't keep the input's
            // value as the source of truth — the focused Aetna
            // widget owns the actual string).
            //
            // Android Gboard workaround (from egui): after a
            // non-composition `input`, blur and refocus the element
            // so the predictive-text suggestion bar doesn't latch
            // invisible characters that have to be deleted before
            // real ones. Skip during composition (IME) since blur
            // would cancel the in-progress glyph.
            let input_pending = pending.clone();
            let input_window = window.clone();
            let input_el_for_input = input.clone();
            let input_closure: Closure<dyn FnMut(web_sys::InputEvent)> =
                Closure::new(move |event: web_sys::InputEvent| {
                    let composing = event.is_composing();
                    let input_type = event.input_type();
                    let edit = match input_type.as_str() {
                        "deleteContentBackward"
                        | "deleteWordBackward"
                        | "deleteSoftLineBackward"
                        | "deleteHardLineBackward" => Some(TextEdit::Backspace),
                        _ => {
                            let value = input_el_for_input.value();
                            if value.is_empty() || composing {
                                None
                            } else {
                                Some(TextEdit::Insert(value))
                            }
                        }
                    };
                    if !composing {
                        input_el_for_input.set_value("");
                        // Gboard reset.
                        let _ = input_el_for_input.blur();
                        let _ = input_el_for_input.focus();
                    }
                    if let Some(edit) = edit {
                        input_pending.borrow_mut().push_back(edit);
                        input_window.request_redraw();
                    }
                });
            input
                .add_event_listener_with_callback("input", input_closure.as_ref().unchecked_ref())
                .ok()?;

            // keydown: when our hidden input has focus, the canvas
            // never sees keystrokes — so we have to forward editing
            // keys (Backspace, Enter, arrows) through here. The
            // `input` handler above also covers Backspace via
            // inputType for the typical Android case; this catches
            // the iPad-with-hardware-keyboard variant where
            // Backspace fires as `keydown` only.
            let keydown_pending = pending.clone();
            let keydown_window = window.clone();
            let keydown_closure: Closure<dyn FnMut(web_sys::KeyboardEvent)> =
                Closure::new(move |event: web_sys::KeyboardEvent| {
                    if event.key() == "Backspace" {
                        keydown_pending.borrow_mut().push_back(TextEdit::Backspace);
                        keydown_window.request_redraw();
                        event.prevent_default();
                    }
                });
            input
                .add_event_listener_with_callback(
                    "keydown",
                    keydown_closure.as_ref().unchecked_ref(),
                )
                .ok()?;

            // blur: keep our `focused` mirror in sync when the
            // input loses focus outside our control (user dismissed
            // the keyboard via the OS dismiss button, tab key,
            // etc.). Without this, `focus_if_needed` would no-op
            // on the next text-input tap.
            let focused: Rc<Cell<bool>> = Rc::new(Cell::new(false));
            let blur_focused = focused.clone();
            let blur_closure: Closure<dyn FnMut(web_sys::Event)> =
                Closure::new(move |_event: web_sys::Event| {
                    blur_focused.set(false);
                });
            input
                .add_event_listener_with_callback("blur", blur_closure.as_ref().unchecked_ref())
                .ok()?;

            Some(Self {
                input,
                focused,
                pending,
                _input_closure: input_closure,
                _keydown_closure: keydown_closure,
                _blur_closure: blur_closure,
            })
        }

        /// Focus the input so the soft keyboard opens. **Must be
        /// called inside a user-gesture event handler** (e.g., the
        /// pointerdown DOM closure) — iOS suppresses programmatic
        /// focus from any other context. No-op if we believe the
        /// input already has focus.
        fn focus_if_needed(&self) {
            if !self.focused.get() {
                let _ = self.input.focus();
                self.focused.set(true);
            }
        }

        /// Blur the input so the soft keyboard dismisses. Safe to
        /// call from any context. No-op when the input isn't
        /// believed to be focused.
        fn dismiss(&self) {
            if self.focused.get() {
                let _ = self.input.blur();
                self.focused.set(false);
            }
        }

        /// Drain pending edits captured by the listeners since the
        /// last drain. Called by the host inside `window_event`.
        fn drain(&self) -> Vec<TextEdit> {
            self.pending.borrow_mut().drain(..).collect()
        }
    }

    /// Mirrors the native winit + wgpu host shape, but with browser
    /// surface init (async via wasm-bindgen-futures rather than
    /// pollster). Kept inline here so `aetna-winit-wgpu` stays free of
    /// wasm-only deps.
    struct Host<A: App> {
        config: WebHostConfig,
        app: A,
        handle: WebHandle,
        gfx: Rc<RefCell<Option<Gfx>>>,
        last_pointer: Option<(f32, f32)>,
        modifiers: KeyModifiers,
        stats: FrameStats,
        /// Last cursor pushed to `Window::set_cursor`. winit-web maps
        /// the icon to `canvas.style.cursor` so this drives the
        /// browser's CSS cursor; we cache to avoid resetting the same
        /// string each frame.
        last_cursor: Cursor,
        /// Reason the next redraw is being requested. Each event handler
        /// that calls `request_redraw` sets this beforehand; the
        /// RedrawRequested arm consumes it once and snapshots it into
        /// [`HostDiagnostics::trigger`]. Defaults back to `Other` after
        /// each consume — safe fallback for redraws the host can't
        /// attribute (e.g. the post-async-setup `request_redraw`).
        next_trigger: FrameTrigger,
        /// Wall clock at the start of the previous redraw; diff with
        /// the next frame's start gives `last_frame_dt`.
        last_frame_at: Option<Instant>,
        /// Counts redraws actually rendered.
        frame_index: u64,
        /// Timing breakdown from the last completed rendered frame.
        last_build: Duration,
        last_prepare: Duration,
        last_layout: Duration,
        last_layout_intrinsic_cache_hits: u64,
        last_layout_intrinsic_cache_misses: u64,
        last_layout_pruned_subtrees: u64,
        last_layout_pruned_nodes: u64,
        last_draw_ops: Duration,
        last_draw_ops_culled_text_ops: u64,
        last_paint: Duration,
        last_paint_culled_ops: u64,
        last_gpu_upload: Duration,
        last_snapshot: Duration,
        last_submit: Duration,
        last_text_layout_cache_hits: u64,
        last_text_layout_cache_misses: u64,
        last_text_layout_cache_evictions: u64,
        last_text_layout_shaped_bytes: u64,
        /// Physical canvas size used by the most recent full
        /// [`Runner::prepare`] call. The repaint dispatcher requires
        /// this to match the current `gfx.config` size before taking
        /// the paint-only path: the cached `DrawOp` list was laid out
        /// against this size, so a `ResizeObserver` fire that updated
        /// `gfx.config` since must force a fresh layout rather than
        /// painting stale geometry to the new viewport.
        last_prepared_size: Option<(u32, u32)>,
        /// Adapter backend tag, captured at adapter selection time.
        /// `Rc<RefCell>` because the surface is created in an async
        /// task that finishes after `Host::new`; the cell is read
        /// each frame in the RedrawRequested arm.
        backend: Rc<RefCell<&'static str>>,
        /// Browser `paste` events carry trusted clipboard text without
        /// the Firefox permission menu used by `navigator.clipboard.readText`.
        /// The callback enqueues text here, then requests a redraw; the
        /// RedrawRequested arm converts it into a focused Aetna `TextInput`.
        pending_clipboard_text: Rc<RefCell<VecDeque<String>>>,
        /// Web browsers do not expose the X11/Wayland primary-selection
        /// clipboard. Keep an app-local approximation so Aetna selection
        /// highlight can still feed middle-click paste inside the canvas.
        primary_selection: String,
        /// Held for its drop side-effects: the JS paste callback object.
        _paste_closure: Option<Closure<dyn FnMut(web_sys::ClipboardEvent)>>,
        /// Held for its drop side-effects: the JS keydown callback object.
        _keydown_closure: Option<Closure<dyn FnMut(web_sys::KeyboardEvent)>>,
        /// Held for its drop side-effects: the JS callback object
        /// that ResizeObserver fires. Dropping this disconnects the
        /// observer.
        _resize_closure: Option<Closure<dyn FnMut()>>,
        /// The observer itself; held alongside the closure so its
        /// JS-side observation outlives this frame.
        _resize_observer: Option<web_sys::ResizeObserver>,
        /// DOM pointer events captured by the listeners installed in
        /// `resumed()`. Drained at the top of every `window_event`
        /// call so dispatch into the runner and app uses the same
        /// `&mut self` path the rest of the host does.
        pending_pointer: Rc<RefCell<VecDeque<QueuedPointer>>>,
        /// Held for drop side-effects: the JS callbacks for each of
        /// pointermove / pointerdown / pointerup / pointercancel /
        /// pointerleave on the canvas.
        _pointer_closures: Vec<Closure<dyn FnMut(web_sys::PointerEvent)>>,
        /// Held for drop side-effects: the JS callback that calls
        /// `preventDefault` on `contextmenu` so the browser's native
        /// menu doesn't pop over the canvas. Right-click already
        /// emits `PointerButton::Secondary` through the pointer
        /// listeners; this just suppresses the platform menu so apps
        /// can render their own.
        _contextmenu_closure: Option<Closure<dyn FnMut(web_sys::MouseEvent)>>,
        /// Bottom safe-area inset in logical pixels, set by the
        /// VisualViewport `resize` listener whenever the keyboard
        /// (or any other platform chrome that shrinks the visual
        /// viewport) appears or disappears. The cell is shared with
        /// the JS callback via `Rc<Cell<f32>>`; the host reads it
        /// each frame and feeds it into `BuildCx::with_safe_area`.
        keyboard_inset_bottom: Rc<Cell<f32>>,
        /// Held for drop side-effects: the JS callback that updates
        /// `keyboard_inset_bottom` on visualViewport resize. None on
        /// browsers that don't expose `window.visualViewport` (older
        /// engines / jsdom-style test contexts).
        _viewport_closure: Option<Closure<dyn FnMut(web_sys::Event)>>,
        /// Hidden `<textarea>` that summons the on-screen keyboard
        /// when a touch press lands on an Aetna text-input widget.
        /// `None` when soft-keyboard install failed (no body, etc.)
        /// — the host still runs, just without on-screen-keyboard
        /// support. Shared with the pointerdown closure via `Rc`
        /// clone so focus-on-press can fire in the user-gesture
        /// context.
        soft_keyboard: Option<Rc<SoftKeyboard>>,
    }

    struct Gfx {
        window: Arc<Window>,
        surface: wgpu::Surface<'static>,
        device: wgpu::Device,
        queue: wgpu::Queue,
        config: wgpu::SurfaceConfiguration,
        renderer: Runner,
        /// `None` when [`SAMPLE_COUNT`] is 1 — the renderer draws
        /// straight into the swapchain texture and there's no resolve
        /// pass. `Some` when MSAA is enabled, holding the
        /// multisampled colour attachment that the swapchain texture
        /// is the resolve target for.
        msaa: Option<aetna_wgpu::MsaaTarget>,
        /// Format used for render-target views and pipelines. May
        /// differ from `config.format` when we re-view a linear
        /// swapchain texture as sRGB (Chromium WebGPU path) — the
        /// swapchain stores `Rgba8Unorm`, but every view is
        /// `Rgba8UnormSrgb` so the hardware encodes on write.
        render_format: wgpu::TextureFormat,
    }

    fn surface_extent(config: &wgpu::SurfaceConfiguration) -> wgpu::Extent3d {
        wgpu::Extent3d {
            width: config.width,
            height: config.height,
            depth_or_array_layers: 1,
        }
    }

    impl<A: App> Host<A> {
        fn new(config: WebHostConfig, app: A, handle: WebHandle) -> Self {
            Self {
                config,
                app,
                handle,
                gfx: Rc::new(RefCell::new(None)),
                last_pointer: None,
                modifiers: KeyModifiers::default(),
                stats: FrameStats::default(),
                last_cursor: Cursor::Default,
                next_trigger: FrameTrigger::Initial,
                last_frame_at: None,
                frame_index: 0,
                last_build: Duration::ZERO,
                last_prepare: Duration::ZERO,
                last_layout: Duration::ZERO,
                last_layout_intrinsic_cache_hits: 0,
                last_layout_intrinsic_cache_misses: 0,
                last_layout_pruned_subtrees: 0,
                last_layout_pruned_nodes: 0,
                last_draw_ops: Duration::ZERO,
                last_draw_ops_culled_text_ops: 0,
                last_paint: Duration::ZERO,
                last_paint_culled_ops: 0,
                last_gpu_upload: Duration::ZERO,
                last_snapshot: Duration::ZERO,
                last_submit: Duration::ZERO,
                last_text_layout_cache_hits: 0,
                last_text_layout_cache_misses: 0,
                last_text_layout_cache_evictions: 0,
                last_text_layout_shaped_bytes: 0,
                last_prepared_size: None,
                backend: Rc::new(RefCell::new("?")),
                pending_clipboard_text: Rc::new(RefCell::new(VecDeque::new())),
                primary_selection: String::new(),
                _paste_closure: None,
                _keydown_closure: None,
                _resize_closure: None,
                _resize_observer: None,
                pending_pointer: Rc::new(RefCell::new(VecDeque::new())),
                _pointer_closures: Vec::new(),
                _contextmenu_closure: None,
                keyboard_inset_bottom: Rc::new(Cell::new(0.0)),
                _viewport_closure: None,
                soft_keyboard: None,
            }
        }

        /// Drain DOM PointerEvents captured by the listeners since the
        /// last `window_event` call and dispatch them through the
        /// runner + app the same way native winit pointer events do.
        ///
        /// Returns `true` when at least one event triggered a redraw
        /// — the host uses this to set `next_trigger` for the next
        /// frame's diagnostics.
        fn drain_pending_pointer(&mut self, gfx: &mut Gfx) -> bool {
            // Drain time-driven events (touch long-press) before any
            // queued DOM input. Even on frames where no DOM event
            // arrived (the user held still through the long-press
            // deadline), this still needs to fire — `next_redraw_in`
            // schedules the wakeup that brings us here.
            let mut redraw = false;
            let polled = gfx.renderer.poll_input(Instant::now());
            if !polled.is_empty() {
                redraw = true;
                for event in polled {
                    dispatch_app_event(
                        &mut self.app,
                        event,
                        &gfx.renderer,
                        &mut self.primary_selection,
                    );
                }
            }
            let queue: Vec<QueuedPointer> = self.pending_pointer.borrow_mut().drain(..).collect();
            if queue.is_empty() {
                return redraw;
            }
            for queued in queue {
                match queued {
                    QueuedPointer::Move(p) => {
                        self.last_pointer = Some((p.x, p.y));
                        let moved = gfx.renderer.pointer_moved(p);
                        for event in moved.events {
                            dispatch_app_event(
                                &mut self.app,
                                event,
                                &gfx.renderer,
                                &mut self.primary_selection,
                            );
                        }
                        if moved.needs_redraw {
                            redraw = true;
                        }
                    }
                    QueuedPointer::Down(p) => {
                        self.last_pointer = Some((p.x, p.y));
                        for event in gfx.renderer.pointer_down(p) {
                            dispatch_app_event(
                                &mut self.app,
                                event,
                                &gfx.renderer,
                                &mut self.primary_selection,
                            );
                        }
                        redraw = true;
                    }
                    QueuedPointer::Up(p) | QueuedPointer::Cancel(p) => {
                        self.last_pointer = Some((p.x, p.y));
                        for event in gfx.renderer.pointer_up(p) {
                            let event =
                                attach_primary_selection_text(event, &self.primary_selection);
                            dispatch_app_event(
                                &mut self.app,
                                event,
                                &gfx.renderer,
                                &mut self.primary_selection,
                            );
                        }
                        redraw = true;
                    }
                    QueuedPointer::Leave => {
                        self.last_pointer = None;
                        for event in gfx.renderer.pointer_left() {
                            dispatch_app_event(
                                &mut self.app,
                                event,
                                &gfx.renderer,
                                &mut self.primary_selection,
                            );
                        }
                        redraw = true;
                    }
                }
            }
            redraw
        }

        /// Drain edits captured by the soft-keyboard textarea since
        /// the last `window_event` and route them through the
        /// runner's existing keyboard / text-input entry points so
        /// the focused widget sees the same shape it would for a
        /// hardware keystroke. Returns `true` when at least one edit
        /// was dispatched so the caller can mark the next-frame
        /// trigger.
        fn drain_soft_keyboard(&mut self, gfx: &mut Gfx) -> bool {
            let Some(sk) = self.soft_keyboard.as_ref() else {
                return false;
            };
            let edits = sk.drain();
            if edits.is_empty() {
                return false;
            }
            for edit in edits {
                match edit {
                    TextEdit::Insert(text) => {
                        if let Some(event) = gfx.renderer.text_input(text) {
                            dispatch_app_event(
                                &mut self.app,
                                event,
                                &gfx.renderer,
                                &mut self.primary_selection,
                            );
                        }
                    }
                    TextEdit::Backspace => {
                        for event in gfx
                            .renderer
                            .key_down(UiKey::Backspace, self.modifiers, false)
                        {
                            dispatch_app_event(
                                &mut self.app,
                                event,
                                &gfx.renderer,
                                &mut self.primary_selection,
                            );
                        }
                    }
                }
            }
            true
        }

        /// Sync the soft keyboard's open/closed state with the
        /// runner's current focus. Called once per `window_event`
        /// after pointer / soft-keyboard drain so a press that
        /// shifted focus away from a text input can dismiss the
        /// on-screen keyboard within the same frame.
        ///
        /// We never *open* the keyboard from here — that has to
        /// happen synchronously inside the pointerdown closure for
        /// iOS to honor it. Closing has no such restriction.
        fn sync_soft_keyboard_focus(&self, gfx: &Gfx) {
            let Some(sk) = self.soft_keyboard.as_ref() else {
                return;
            };
            // Only dismiss when our state says the keyboard should
            // be down AND the DOM input still believes it's focused.
            // Skipping the .blur() when DOM focus is already gone
            // avoids redundant blur events; more importantly, it
            // means a stray sync that races a still-resolving focus
            // doesn't tear the keyboard down out from under itself.
            if !gfx.renderer.focused_captures_keys() && sk.focused.get() {
                sk.dismiss();
            }
        }
    }

    fn backend_label(backend: wgpu::Backend) -> &'static str {
        match backend {
            wgpu::Backend::Vulkan => "Vulkan",
            wgpu::Backend::Metal => "Metal",
            wgpu::Backend::Dx12 => "DX12",
            wgpu::Backend::Gl => "WebGL2",
            wgpu::Backend::BrowserWebGpu => "WebGPU",
            wgpu::Backend::Noop => "noop",
        }
    }

    /// sRGB-tagged view-format sibling for a linear `*8Unorm` swapchain
    /// format. Used to recover gamma-correct output on Chromium's WebGPU
    /// surface: the swapchain offers only linear formats there, so we
    /// declare the sRGB form as a view format and render through that —
    /// hardware applies the sRGB encode on store and the compositor
    /// reads gamma-correct pixels. Returns `None` for formats that have
    /// no sRGB sibling (e.g. `Rgba16Float`, where the float storage is
    /// already linear-precision-correct), in which case the caller
    /// keeps the chosen format unchanged.
    fn srgb_view_of(format: wgpu::TextureFormat) -> Option<wgpu::TextureFormat> {
        use wgpu::TextureFormat as F;
        match format {
            F::Rgba8Unorm => Some(F::Rgba8UnormSrgb),
            F::Bgra8Unorm => Some(F::Bgra8UnormSrgb),
            _ => None,
        }
    }

    impl<A: App + 'static> ApplicationHandler for Host<A> {
        fn resumed(&mut self, event_loop: &ActiveEventLoop) {
            if self.gfx.borrow().is_some() {
                return;
            }
            let canvas = locate_canvas(&self.config.canvas_id);

            // Build the window bound to the existing canvas. We do
            // *not* call `with_inner_size` — on the web backend that
            // forces canvas.width/height to the requested physical
            // pixels, which then disagrees with the surface size if
            // we read it from CSS. Letting winit pick from the canvas
            // attributes (default 300×150 if unset, otherwise whatever
            // the host page declared) keeps inner_size() and the
            // canvas backing buffer in lockstep. The ResizeObserver
            // installed below carries the canvas through later layout
            // changes; we don't depend on winit dispatching `Resized`.
            let attrs = Window::default_attributes()
                .with_canvas(Some(canvas.clone()))
                // Browser paste, including Linux middle-click primary
                // paste, is delivered as a DOM ClipboardEvent. winit's
                // default web preventDefault path suppresses those
                // browser-side events, so Aetna handles clipboard
                // suppression at the document paste listener instead.
                .with_prevent_default(false);
            let window = Arc::new(event_loop.create_window(attrs).expect("create window"));
            self.handle.set_window(window.clone());

            // Force the canvas backing buffer to match the canvas's
            // CSS-laid-out size at the device pixel ratio. Without
            // this the canvas defaults to 300×150 device pixels, the
            // swapchain ends up tiny and stretched, and Firefox's
            // WebGPU backend fails the first present with "not enough
            // memory left" because the surface texture and the canvas
            // drawing buffer disagree. winit's `Window::inner_size()`
            // reads canvas.width/canvas.height on the web backend, so
            // setting them here is what the async surface setup picks
            // up for the initial swap-chain dimensions.
            let viewport = self.config.viewport;
            let (initial_w, initial_h) = measure_canvas(&canvas, viewport);
            canvas.set_width(initial_w);
            canvas.set_height(initial_h);

            // Keep the canvas backing buffer tracking its CSS box
            // size for the lifetime of the page. ResizeObserver fires
            // once on observe() with the initial size, then again
            // every time the canvas's content rect changes. We bypass
            // winit's `request_inner_size` round-trip — its web
            // backend doesn't reliably translate that into a
            // `Resized` event, which left the swapchain stretched
            // mid-session — and reconfigure the surface directly via
            // `apply_canvas_size`. Until the async surface setup
            // completes we just keep canvas.width/height in sync so
            // the eventual `inner_size()` read picks up the latest.
            let canvas_for_observer = canvas.clone();
            let window_for_observer = window.clone();
            let gfx_for_observer = self.gfx.clone();
            let resize_closure: Closure<dyn FnMut()> = Closure::new(move || {
                let (phys_w, phys_h) = measure_canvas(&canvas_for_observer, viewport);
                let mut gfx_borrow = gfx_for_observer.borrow_mut();
                if let Some(gfx) = gfx_borrow.as_mut() {
                    apply_canvas_size(&canvas_for_observer, gfx, phys_w, phys_h);
                } else {
                    canvas_for_observer.set_width(phys_w);
                    canvas_for_observer.set_height(phys_h);
                }
                drop(gfx_borrow);
                window_for_observer.request_redraw();
            });
            let observer = web_sys::ResizeObserver::new(resize_closure.as_ref().unchecked_ref())
                .expect("ResizeObserver::new failed");
            observer.observe(&canvas);
            self._resize_closure = Some(resize_closure);
            self._resize_observer = Some(observer);

            let pending_clipboard_text = self.pending_clipboard_text.clone();
            let window_for_paste = window.clone();
            let paste_closure: Closure<dyn FnMut(web_sys::ClipboardEvent)> =
                Closure::new(move |event: web_sys::ClipboardEvent| {
                    let Some(data) = event.clipboard_data() else {
                        log::warn!("aetna-web: paste event had no clipboardData");
                        return;
                    };
                    let Ok(text) = data.get_data("text/plain") else {
                        log::warn!("aetna-web: paste event could not read text/plain");
                        return;
                    };
                    if text.is_empty() {
                        return;
                    }
                    event.prevent_default();
                    event.stop_propagation();
                    pending_clipboard_text.borrow_mut().push_back(text);
                    window_for_paste.request_redraw();
                });
            canvas
                .owner_document()
                .expect("canvas has no owner document")
                .add_event_listener_with_callback("paste", paste_closure.as_ref().unchecked_ref())
                .expect("add paste listener");
            self._paste_closure = Some(paste_closure);

            let keydown_closure: Closure<dyn FnMut(web_sys::KeyboardEvent)> =
                Closure::new(move |event: web_sys::KeyboardEvent| {
                    if should_prevent_browser_key_default(&event) {
                        event.prevent_default();
                    }
                });
            canvas
                .add_event_listener_with_callback(
                    "keydown",
                    keydown_closure.as_ref().unchecked_ref(),
                )
                .expect("add keydown listener");
            self._keydown_closure = Some(keydown_closure);

            // Tell the browser the canvas owns all touch input —
            // without this, `touch-action: auto` (the default) makes
            // touch-drag pan/zoom the page before any PointerEvent
            // ever fires, so the runtime sees nothing. Setting it on
            // the element matches what touch-first canvas apps
            // (drawing tools, games) ship.
            if let Some(style) = canvas.dyn_ref::<web_sys::HtmlElement>().map(|e| e.style()) {
                let _ = style.set_property("touch-action", "none");
            }

            // Soft-keyboard plumbing. Install before the pointer
            // listeners so the pointerdown closure can call into it
            // synchronously from the user-gesture context. Failure
            // to install (no body, etc.) leaves the host running
            // without on-screen-keyboard support, which is the
            // correct degradation for environments where it can't
            // work.
            self.soft_keyboard = SoftKeyboard::install(&canvas, &window).map(Rc::new);
            if self.soft_keyboard.is_none() {
                log::warn!(
                    "aetna-web: soft keyboard install failed; text input will not summon \
                     the on-screen keyboard"
                );
            }

            // Bind DOM PointerEvent directly. winit on the browser
            // collapses touch and pen to mouse before forwarding, so
            // routing through `WindowEvent::MouseInput` would lose
            // the modality, the per-pointer ID, and pressure — the
            // exact information the runtime needs to specialize for
            // touch. Each listener pushes onto `pending_pointer` and
            // requests a redraw; the next `window_event` call drains
            // the queue and dispatches into the runner + app with
            // full host state. The compatibility mouse events winit
            // would otherwise translate are ignored further down by
            // this file deliberately not handling
            // `WindowEvent::MouseInput` / `CursorMoved` /
            // `CursorLeft` on web.
            install_pointer_listeners(
                &canvas,
                &window,
                &self.pending_pointer,
                &self.gfx,
                self.soft_keyboard.as_ref(),
                &mut self._pointer_closures,
            );

            // Suppress the browser's native context menu on the
            // canvas. Right-click already routes to the runtime as
            // `PointerButton::Secondary` via the pointerdown listener
            // above; without this the platform menu pops on top of
            // the app and intercepts subsequent input. Apps that want
            // an Aetna-rendered menu wire it through the Secondary
            // press path as they would on native.
            let contextmenu_closure: Closure<dyn FnMut(web_sys::MouseEvent)> =
                Closure::new(move |event: web_sys::MouseEvent| {
                    event.prevent_default();
                });
            canvas
                .add_event_listener_with_callback(
                    "contextmenu",
                    contextmenu_closure.as_ref().unchecked_ref(),
                )
                .expect("add contextmenu listener");
            self._contextmenu_closure = Some(contextmenu_closure);

            // VisualViewport reports the visible region of the page
            // minus platform chrome. When the on-screen keyboard
            // appears, `visualViewport.height` shrinks while
            // `window.innerHeight` (the layout viewport) doesn't —
            // the difference is the keyboard inset, which apps read
            // through `BuildCx::safe_area_bottom` and use to inset
            // their interactive content. Skip silently on browsers
            // without VisualViewport (older engines, jsdom).
            if let Some(window_obj) = web_sys::window()
                && let Some(vv) = window_obj.visual_viewport()
            {
                let cell = self.keyboard_inset_bottom.clone();
                let layout_window = window_obj.clone();
                // Seed the cell with the current value so the first
                // frame after install has the right inset (handles
                // the case of resuming a tab where the keyboard is
                // already up). Clamp small differences (URL-bar
                // hide/show varies inner_height vs visualViewport by
                // ~5px on iOS Safari) so the seed reads as zero.
                let initial_inset = ((layout_window
                    .inner_height()
                    .ok()
                    .and_then(|v| v.as_f64())
                    .unwrap_or(0.0)
                    - vv.height())
                .max(0.0) as f32)
                    .max(0.0);
                let initial_inset = if initial_inset < 16.0 {
                    0.0
                } else {
                    initial_inset
                };
                cell.set(initial_inset);
                // Note: this listener intentionally does *not* call
                // `request_redraw`. The keyboard appearing already
                // chains through the focus that summoned it
                // (animation deadlines drive the next few frames),
                // and inserting an extra redraw here on Android
                // raced with the just-summoned soft keyboard's
                // focus and dismissed it almost immediately. The
                // cell is read by `BuildCx::with_safe_area` each
                // frame; whichever frame fires next picks up the
                // new value.
                let viewport_closure: Closure<dyn FnMut(web_sys::Event)> =
                    Closure::new(move |_event: web_sys::Event| {
                        let Some(window_obj) = web_sys::window() else {
                            return;
                        };
                        let Some(vv) = window_obj.visual_viewport() else {
                            return;
                        };
                        let layout_h = window_obj
                            .inner_height()
                            .ok()
                            .and_then(|v| v.as_f64())
                            .unwrap_or(0.0);
                        let visible_h = vv.height();
                        let raw = (layout_h - visible_h).max(0.0) as f32;
                        // Same small-difference clamp as the seed —
                        // keeps URL-bar jitter from looking like a
                        // tiny keyboard.
                        let inset = if raw < 16.0 { 0.0 } else { raw };
                        cell.set(inset);
                    });
                vv.add_event_listener_with_callback(
                    "resize",
                    viewport_closure.as_ref().unchecked_ref(),
                )
                .expect("add visualViewport resize listener");
                self._viewport_closure = Some(viewport_closure);
            }

            // Allow both browser backends. wgpu's synchronous
            // Instance::new() can't safely decide this: if
            // `navigator.gpu` exists, it routes the whole instance
            // through WebGPU, even on browsers/GPUs where
            // requestAdapter() later returns null. The async helper
            // probes adapter creation first and removes WebGPU from the
            // descriptor when it is not really usable, letting WebGL2
            // handle Chrome/Linux-style partial support instead of
            // panicking during adapter selection.
            //
            // WebGPU is required for backdrop-sampling shaders
            // (`liquid_glass`) because WebGL2 surfaces don't advertise
            // `COPY_SRC` on the swapchain texture, so the snapshot copy
            // can't run — we register backdrop shaders only when the
            // chosen adapter's surface supports COPY_SRC, which in
            // practice means "WebGPU was selected."
            //
            // Firefox: as of 2026-05, Firefox's WebGPU implementation
            // still wedges its compositor on pointer events with our
            // atlas-uploading path (whole canvas goes black until the
            // cursor leaves). The workaround on the user side is to
            // disable WebGPU in `about:config` (`dom.webgpu.enabled =
            // false`); wgpu then transparently picks WebGL2 here and
            // backdrop shaders are skipped via the COPY_SRC check
            // below. Revisit when Firefox WebGPU stabilises.
            // Adapter + device requests are async on wasm; spawn the
            // setup as a future and stash the result in self.gfx so
            // subsequent resumed/window_event calls find it ready.
            //
            // `App::shaders()` is captured here (before the move into
            // the async block) so the runner can register custom
            // shaders the App declares — including backdrop-sampling
            // ones like `liquid_glass`. Without this the showcase's
            // glass card draws are silently dropped because the
            // pipeline doesn't exist.
            let shaders = self.app.shaders();
            let theme = self.app.theme();
            let gfx_slot = self.gfx.clone();
            let backend_slot = self.backend.clone();
            let window_for_async = window.clone();
            let handle_for_async = self.handle.clone();
            wasm_bindgen_futures::spawn_local(async move {
                let mut instance_desc = wgpu::InstanceDescriptor::new_without_display_handle();
                instance_desc.backends = wgpu::Backends::BROWSER_WEBGPU | wgpu::Backends::GL;
                let instance = wgpu::util::new_instance_with_webgpu_detection(instance_desc).await;
                let surface = instance
                    .create_surface(window_for_async.clone())
                    .expect("create surface");

                let adapter = instance
                    .request_adapter(&wgpu::RequestAdapterOptions {
                        power_preference: wgpu::PowerPreference::default(),
                        compatible_surface: Some(&surface),
                        force_fallback_adapter: false,
                    })
                    .await
                    .expect("no compatible adapter");

                // Log the adapter we actually got. `Backends::BROWSER_WEBGPU
                // | Backends::GL` silently falls back to WebGL2 if the
                // browser's WebGPU init fails, and WebGL2 frames cost
                // an order of magnitude more GPU time than WebGPU on
                // the same scene — so this is the first thing to check
                // when investigating "why is it slow on the web".
                let info = adapter.get_info();
                log::info!(
                    "aetna-web: adapter selected — backend={:?} name={:?} driver={:?} device_type={:?}",
                    info.backend,
                    info.name,
                    info.driver,
                    info.device_type,
                );
                *backend_slot.borrow_mut() = backend_label(info.backend);

                // Per-sample MSAA shading is a downlevel cap. WebGL2
                // (GLES 3.0) and most browser WebGPU adapters don't
                // support it, and naga rejects shaders that use
                // `@interpolate(perspective, sample)` at module
                // creation when the cap is missing. Read the flag here
                // and pass it to `Runner::with_caps` so stock + custom
                // shaders downlevel cleanly on those backends.
                //
                // Chrome's SwiftShader WebGL2 fallback currently reports
                // `MULTISAMPLED_SHADING` through wgpu, but the GLSL ES
                // target still rejects the sample interpolation qualifier.
                // Treat WebGL2 as unsupported regardless of the reported
                // flag; WebGPU/native can keep trusting the adapter cap.
                let downlevel = adapter.get_downlevel_capabilities();
                let per_sample_shading = info.backend != wgpu::Backend::Gl
                    && downlevel
                        .flags
                        .contains(wgpu::DownlevelFlags::MULTISAMPLED_SHADING);
                if !per_sample_shading {
                    log::info!(
                        "aetna-web: per-sample shading unavailable on selected backend; \
                         shaders will downlevel `@interpolate(perspective, sample)` to per-pixel-centre interpolation"
                    );
                }

                // WebGL2 has a tighter feature/limit envelope than
                // native; downlevel_webgl2_defaults is the matching
                // baseline. Cap at the adapter's actual limits so
                // device creation succeeds on every integrated GPU.
                let limits =
                    wgpu::Limits::downlevel_webgl2_defaults().using_resolution(adapter.limits());

                let (device, queue) = adapter
                    .request_device(&wgpu::DeviceDescriptor {
                        label: Some("aetna_web::device"),
                        required_features: wgpu::Features::empty(),
                        required_limits: limits,
                        experimental_features: wgpu::ExperimentalFeatures::default(),
                        memory_hints: wgpu::MemoryHints::Performance,
                        trace: wgpu::Trace::Off,
                    })
                    .await
                    .expect("request_device");

                let surface_caps = surface.get_capabilities(&adapter);
                let format = surface_caps
                    .formats
                    .iter()
                    .copied()
                    .find(|f| f.is_srgb())
                    .unwrap_or(surface_caps.formats[0]);
                // Decide the render-target view format. If the chosen
                // swapchain format is already sRGB-tagged (native, most
                // browsers' WebGL2 surfaces), this collapses to the
                // same format. Chromium's WebGPU surface offers only
                // linear formats — `Rgba8Unorm`, `Bgra8Unorm`,
                // `Rgba16Float` — so without this fix-up our shaders'
                // linear writes hit the compositor uncorrected and the
                // page renders 2.2-gamma's worth darker than native.
                // The trick: keep the swapchain format as `Rgba8Unorm`
                // (storage), declare `Rgba8UnormSrgb` as a view format,
                // and create every render-target view through that. The
                // hardware applies the sRGB encode on store. WebGPU
                // explicitly permits this view-format reinterpretation
                // because the two formats differ only in the sRGB flag.
                let render_format = srgb_view_of(format).unwrap_or(format);
                let view_formats = if render_format != format {
                    vec![render_format]
                } else {
                    Vec::new()
                };
                log::info!(
                    "aetna-web: surface format {:?} (sRGB? {}) → render view {:?}; offered {:?}",
                    format,
                    format.is_srgb(),
                    render_format,
                    surface_caps.formats,
                );
                // Single source of truth for the swapchain size:
                // winit's inner_size() in physical pixels. Same value
                // that the native winit + wgpu host uses; matches what
                // sync_canvas_to_css() set the canvas backing buffer to.
                let inner = window_for_async.inner_size();
                // COPY_SRC is required so backdrop-sampling shaders can
                // copy the post-Pass-A surface into the runner's
                // snapshot texture mid-frame. WebGL2 surfaces typically
                // advertise it; if the adapter ever doesn't, we fall
                // back to RENDER_ATTACHMENT-only and any backdrop
                // shaders the App declared simply won't paint a glass
                // surface (the rest of the UI is unaffected).
                let want_copy_src = surface_caps.usages.contains(wgpu::TextureUsages::COPY_SRC);
                let usage = if want_copy_src {
                    wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC
                } else {
                    log::warn!(
                        "aetna-web: surface does not advertise COPY_SRC; backdrop-sampling \
                         shaders will paint nothing on this backend"
                    );
                    wgpu::TextureUsages::RENDER_ATTACHMENT
                };
                // Prefer Fifo (vsync) so redraws can't outrun the
                // browser's compositor — same rationale as
                // aetna-winit-wgpu.
                let present_mode = if surface_caps
                    .present_modes
                    .contains(&wgpu::PresentMode::Fifo)
                {
                    wgpu::PresentMode::Fifo
                } else {
                    surface_caps.present_modes[0]
                };
                let config = wgpu::SurfaceConfiguration {
                    usage,
                    format,
                    width: inner.width.max(1),
                    height: inner.height.max(1),
                    present_mode,
                    alpha_mode: surface_caps.alpha_modes[0],
                    view_formats,
                    desired_maximum_frame_latency: 2,
                };
                surface.configure(&device, &config);

                let mut renderer = Runner::with_caps(
                    &device,
                    &queue,
                    render_format,
                    SAMPLE_COUNT,
                    per_sample_shading,
                );
                renderer.set_theme(theme);
                renderer.set_surface_size(config.width, config.height);
                // Register every shader the App declared. If the
                // surface doesn't support COPY_SRC (so multi-pass
                // backdrop sampling is impossible), skip the backdrop
                // shaders rather than registering them and rendering
                // garbage.
                for s in shaders {
                    if s.samples_backdrop && !want_copy_src {
                        continue;
                    }
                    renderer.register_shader_with(
                        &device,
                        s.name,
                        s.wgsl,
                        s.samples_backdrop,
                        s.samples_time,
                    );
                }

                // MSAA target only when SAMPLE_COUNT > 1; the
                // single-sample path renders straight into the
                // swapchain texture.
                let msaa = if SAMPLE_COUNT > 1 {
                    Some(aetna_wgpu::MsaaTarget::new(
                        &device,
                        render_format,
                        surface_extent(&config),
                        SAMPLE_COUNT,
                    ))
                } else {
                    None
                };
                *gfx_slot.borrow_mut() = Some(Gfx {
                    window: window_for_async.clone(),
                    surface,
                    device,
                    queue,
                    config,
                    renderer,
                    msaa,
                    render_format,
                });
                if handle_for_async.mark_ready() {
                    log::debug!("aetna-web: flushing pending external redraw request");
                }
                window_for_async.request_redraw();
            });
        }

        fn window_event(
            &mut self,
            event_loop: &ActiveEventLoop,
            _id: WindowId,
            event: WindowEvent,
        ) {
            // Clone the `Rc` first so the `RefMut` we get from
            // `borrow_mut` is tied to the cloned cell rather than
            // through `&self.gfx` — that lets `drain_pending_pointer`
            // re-borrow `self` mutably while `gfx_borrow` is still
            // live.
            let gfx_cell = self.gfx.clone();
            let mut gfx_borrow = gfx_cell.borrow_mut();
            let Some(gfx) = gfx_borrow.as_mut() else {
                // Async setup hasn't finished; drop the event. The
                // post-setup `request_redraw` will trigger a fresh
                // RedrawRequested once we're ready.
                return;
            };
            // Drain DOM PointerEvent listeners before processing the
            // winit event. The closures pushed onto
            // `pending_pointer` and called `request_redraw`, which
            // is what brought us here — handle the captured input
            // first so RedrawRequested sees the post-event state.
            if self.drain_pending_pointer(gfx) {
                self.next_trigger = FrameTrigger::Pointer;
            }
            // Drain soft-keyboard edits next — order matters because
            // a pointer event may have shifted focus to a text
            // input, after which keystrokes captured this frame
            // should reach the new target.
            if self.drain_soft_keyboard(gfx) {
                self.next_trigger = FrameTrigger::Keyboard;
            }
            // If focus moved off a text input this frame, dismiss
            // the on-screen keyboard now (done after both drains so
            // the focus state reflects everything that just
            // happened).
            self.sync_soft_keyboard_focus(gfx);
            let scale = gfx.window.scale_factor() as f32;

            match event {
                WindowEvent::CloseRequested => event_loop.exit(),

                WindowEvent::Resized(size) => {
                    gfx.config.width = size.width.max(1);
                    gfx.config.height = size.height.max(1);
                    gfx.surface.configure(&gfx.device, &gfx.config);
                    gfx.renderer
                        .set_surface_size(gfx.config.width, gfx.config.height);
                    if let Some(msaa) = gfx.msaa.as_mut() {
                        let extent = surface_extent(&gfx.config);
                        if !msaa.matches(extent) {
                            *msaa = aetna_wgpu::MsaaTarget::new(
                                &gfx.device,
                                gfx.render_format,
                                extent,
                                SAMPLE_COUNT,
                            );
                        }
                    }
                    self.next_trigger = FrameTrigger::Resize;
                    gfx.window.request_redraw();
                }

                // Pointer input on web flows through DOM PointerEvent
                // listeners installed in `resumed()`. winit's
                // CursorMoved / CursorLeft / MouseInput on the web
                // backend collapse touch and pen to mouse before
                // forwarding, so handling them here would either
                // double-route (the DOM listener already saw them)
                // or strip the modality. They're intentionally
                // ignored — the drain at the top of window_event
                // dispatches everything the closures captured.

                // Browser drag/drop and clipboard-image plumbing rides
                // the HTML File API rather than winit (which doesn't
                // surface DroppedFile on wasm32). Web hosts that need
                // file-drop support listen for `dragenter` / `drop` on
                // the canvas via wasm-bindgen and route the resulting
                // bytes through their own paths. The winit event arms
                // exist for source-parity with the native hosts; on
                // web they currently won't fire.
                WindowEvent::HoveredFile(path) => {
                    let (lx, ly) = self.last_pointer.unwrap_or((0.0, 0.0));
                    for event in gfx.renderer.file_hovered(path, lx, ly) {
                        dispatch_app_event(
                            &mut self.app,
                            event,
                            &gfx.renderer,
                            &mut self.primary_selection,
                        );
                    }
                    self.next_trigger = FrameTrigger::Pointer;
                    gfx.window.request_redraw();
                }

                WindowEvent::HoveredFileCancelled => {
                    for event in gfx.renderer.file_hover_cancelled() {
                        dispatch_app_event(
                            &mut self.app,
                            event,
                            &gfx.renderer,
                            &mut self.primary_selection,
                        );
                    }
                    self.next_trigger = FrameTrigger::Pointer;
                    gfx.window.request_redraw();
                }

                WindowEvent::DroppedFile(path) => {
                    let (lx, ly) = self.last_pointer.unwrap_or((0.0, 0.0));
                    for event in gfx.renderer.file_dropped(path, lx, ly) {
                        dispatch_app_event(
                            &mut self.app,
                            event,
                            &gfx.renderer,
                            &mut self.primary_selection,
                        );
                    }
                    self.next_trigger = FrameTrigger::Pointer;
                    gfx.window.request_redraw();
                }

                WindowEvent::MouseWheel { delta, .. } => {
                    let Some((lx, ly)) = self.last_pointer else {
                        return;
                    };
                    let dy = match delta {
                        MouseScrollDelta::LineDelta(_, y) => -y * 50.0,
                        MouseScrollDelta::PixelDelta(p) => -(p.y as f32) / scale,
                    };
                    if gfx.renderer.pointer_wheel(lx, ly, dy) {
                        self.next_trigger = FrameTrigger::Pointer;
                        gfx.window.request_redraw();
                    }
                }

                WindowEvent::ModifiersChanged(modifiers) => {
                    self.modifiers = key_modifiers(modifiers.state());
                    gfx.renderer.set_modifiers(self.modifiers);
                }

                WindowEvent::KeyboardInput {
                    event:
                        key_event @ winit::event::KeyEvent {
                            state: ElementState::Pressed,
                            ..
                        },
                    is_synthetic: false,
                    ..
                } => {
                    if let Some(key) = map_key(&key_event.logical_key) {
                        for event in gfx.renderer.key_down(key, self.modifiers, key_event.repeat) {
                            match text_input::clipboard_request(&event) {
                                Some(ClipboardKind::Copy) => {
                                    copy_current_selection(&gfx.renderer, write_clipboard_text);
                                    dispatch_app_event(
                                        &mut self.app,
                                        event,
                                        &gfx.renderer,
                                        &mut self.primary_selection,
                                    );
                                }
                                Some(ClipboardKind::Cut) => {
                                    copy_current_selection(&gfx.renderer, write_clipboard_text);
                                    dispatch_app_event(
                                        &mut self.app,
                                        clipboard::delete_selection_event(event),
                                        &gfx.renderer,
                                        &mut self.primary_selection,
                                    );
                                }
                                Some(ClipboardKind::Paste) => {}
                                None => dispatch_app_event(
                                    &mut self.app,
                                    event,
                                    &gfx.renderer,
                                    &mut self.primary_selection,
                                ),
                            }
                        }
                    }
                    if let Some(text) = &key_event.text
                        && let Some(event) = gfx.renderer.text_input(text.to_string())
                    {
                        dispatch_app_event(
                            &mut self.app,
                            event,
                            &gfx.renderer,
                            &mut self.primary_selection,
                        );
                    }
                    self.next_trigger = FrameTrigger::Keyboard;
                    gfx.window.request_redraw();
                }
                WindowEvent::Ime(winit::event::Ime::Commit(text)) => {
                    if let Some(event) = gfx.renderer.text_input(text) {
                        dispatch_app_event(
                            &mut self.app,
                            event,
                            &gfx.renderer,
                            &mut self.primary_selection,
                        );
                    }
                    self.next_trigger = FrameTrigger::Keyboard;
                    gfx.window.request_redraw();
                }

                WindowEvent::RedrawRequested => {
                    let frame_start = Instant::now();
                    let clipboard_drained = drain_pending_clipboard_text(
                        &mut self.app,
                        &mut gfx.renderer,
                        &self.pending_clipboard_text,
                        &mut self.primary_selection,
                    );
                    if clipboard_drained {
                        self.next_trigger = FrameTrigger::Keyboard;
                    }
                    let frame = match gfx.surface.get_current_texture() {
                        wgpu::CurrentSurfaceTexture::Success(frame)
                        | wgpu::CurrentSurfaceTexture::Suboptimal(frame) => frame,
                        wgpu::CurrentSurfaceTexture::Lost
                        | wgpu::CurrentSurfaceTexture::Outdated => {
                            gfx.surface.configure(&gfx.device, &gfx.config);
                            return;
                        }
                        other => {
                            log::error!("surface unavailable: {other:?}");
                            return;
                        }
                    };
                    // Render through the sRGB view format (see
                    // `srgb_view_of` and the surface configuration step
                    // for why). When the swapchain is already sRGB this
                    // collapses to the storage format and the view is
                    // identical to `..Default::default()`.
                    let view = frame.texture.create_view(&wgpu::TextureViewDescriptor {
                        format: Some(gfx.render_format),
                        ..Default::default()
                    });

                    let last_frame_dt = self
                        .last_frame_at
                        .map(|t| frame_start.duration_since(t))
                        .unwrap_or(std::time::Duration::ZERO);
                    self.last_frame_at = Some(frame_start);
                    let trigger = std::mem::take(&mut self.next_trigger);
                    let scale_factor = gfx.window.scale_factor() as f32;
                    let viewport_rect = Rect::new(
                        0.0,
                        0.0,
                        gfx.config.width as f32 / scale_factor,
                        gfx.config.height as f32 / scale_factor,
                    );
                    let current_size = (gfx.config.width, gfx.config.height);
                    // Paint-only path: a time-driven shader's deadline
                    // fired and nothing else has changed since the last
                    // full prepare — skip rebuild + layout and reuse the
                    // cached ops via `repaint`. The size guard catches
                    // ResizeObserver fires that updated `gfx.config`
                    // since the last prepare without setting a trigger.
                    let paint_only = trigger == FrameTrigger::ShaderPaint
                        && Some(current_size) == self.last_prepared_size;

                    let (prepare, palette, t_after_build, t_after_prepare) = if paint_only {
                        // No build pass: reuse the renderer's already-set
                        // theme palette and skip diagnostics / frame_index
                        // bump. Apps reading `cx.diagnostics()` see the
                        // overlay update only on layout frames, which is
                        // the documented contract for paint-only.
                        let palette = gfx.renderer.theme().palette().clone();
                        let t_after_build = Instant::now();
                        let prepare = gfx.renderer.repaint(
                            &gfx.device,
                            &gfx.queue,
                            viewport_rect,
                            scale_factor,
                        );
                        let t_after_prepare = Instant::now();
                        (prepare, palette, t_after_build, t_after_prepare)
                    } else {
                        self.frame_index = self.frame_index.wrapping_add(1);
                        let diagnostics = HostDiagnostics {
                            backend: *self.backend.borrow(),
                            surface_size: (gfx.config.width, gfx.config.height),
                            scale_factor,
                            msaa_samples: SAMPLE_COUNT,
                            frame_index: self.frame_index,
                            last_frame_dt,
                            last_build: self.last_build,
                            last_prepare: self.last_prepare,
                            last_layout: self.last_layout,
                            last_layout_intrinsic_cache_hits: self.last_layout_intrinsic_cache_hits,
                            last_layout_intrinsic_cache_misses: self
                                .last_layout_intrinsic_cache_misses,
                            last_layout_pruned_subtrees: self.last_layout_pruned_subtrees,
                            last_layout_pruned_nodes: self.last_layout_pruned_nodes,
                            last_draw_ops: self.last_draw_ops,
                            last_draw_ops_culled_text_ops: self.last_draw_ops_culled_text_ops,
                            last_paint: self.last_paint,
                            last_paint_culled_ops: self.last_paint_culled_ops,
                            last_gpu_upload: self.last_gpu_upload,
                            last_snapshot: self.last_snapshot,
                            last_submit: self.last_submit,
                            last_text_layout_cache_hits: self.last_text_layout_cache_hits,
                            last_text_layout_cache_misses: self.last_text_layout_cache_misses,
                            last_text_layout_cache_evictions: self.last_text_layout_cache_evictions,
                            last_text_layout_shaped_bytes: self.last_text_layout_shaped_bytes,
                            trigger,
                        };
                        self.app.before_build();
                        let theme = self.app.theme();
                        let safe_area = aetna_core::Sides {
                            left: 0.0,
                            right: 0.0,
                            top: 0.0,
                            bottom: self.keyboard_inset_bottom.get(),
                        };
                        let cx = BuildCx::new(&theme)
                            .with_ui_state(gfx.renderer.ui_state())
                            .with_diagnostics(&diagnostics)
                            .with_viewport(viewport_rect.w, viewport_rect.h)
                            .with_safe_area(safe_area);
                        let mut tree = self.app.build(&cx);
                        let palette = theme.palette().clone();
                        gfx.renderer.set_theme(theme);
                        gfx.renderer.set_hotkeys(self.app.hotkeys());
                        gfx.renderer.set_selection(self.app.selection());
                        gfx.renderer.push_toasts(self.app.drain_toasts());
                        gfx.renderer
                            .push_focus_requests(self.app.drain_focus_requests());
                        gfx.renderer
                            .push_scroll_requests(self.app.drain_scroll_requests());
                        for url in self.app.drain_link_opens() {
                            open_link(&url);
                        }
                        let t_after_build = Instant::now();
                        let prepare = gfx.renderer.prepare(
                            &gfx.device,
                            &gfx.queue,
                            &mut tree,
                            viewport_rect,
                            scale_factor,
                        );
                        let t_after_prepare = Instant::now();

                        // Cursor resolution depends on the laid-out tree
                        // and the hovered key derived from layout ids,
                        // so it only updates on the full-prepare path.
                        // Paint-only frames inherit the previous cursor.
                        let cursor = gfx.renderer.ui_state().cursor(&tree);
                        if cursor != self.last_cursor {
                            gfx.window.set_cursor(winit_cursor(cursor));
                            self.last_cursor = cursor;
                        }
                        self.last_prepared_size = Some(current_size);
                        (prepare, palette, t_after_build, t_after_prepare)
                    };

                    let mut encoder =
                        gfx.device
                            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                                label: Some("aetna_web::encoder"),
                            });
                    // `render()` owns pass lifetimes itself so it can
                    // split around `BackdropSnapshot` boundaries when
                    // the App uses backdrop-sampling shaders. With no
                    // boundary it collapses to a single Clear pass —
                    // same behaviour as the old `begin_render_pass +
                    // draw + end_render_pass` path.
                    gfx.renderer.render(
                        &gfx.device,
                        &mut encoder,
                        &frame.texture,
                        &view,
                        gfx.msaa.as_ref().map(|m| &m.view),
                        wgpu::LoadOp::Clear(bg_color(&palette)),
                    );
                    gfx.queue.submit(Some(encoder.finish()));
                    frame.present();
                    let t_after_submit = Instant::now();

                    self.stats.record(
                        frame_start,
                        t_after_build,
                        t_after_prepare,
                        t_after_submit,
                        prepare.timings,
                    );
                    self.last_build = t_after_build - frame_start;
                    self.last_prepare = t_after_prepare - t_after_build;
                    self.last_submit = t_after_submit - t_after_prepare;
                    self.last_layout = prepare.timings.layout;
                    self.last_layout_intrinsic_cache_hits =
                        prepare.timings.layout_intrinsic_cache.hits;
                    self.last_layout_intrinsic_cache_misses =
                        prepare.timings.layout_intrinsic_cache.misses;
                    self.last_layout_pruned_subtrees = prepare.timings.layout_prune.subtrees;
                    self.last_layout_pruned_nodes = prepare.timings.layout_prune.nodes;
                    self.last_draw_ops = prepare.timings.draw_ops;
                    self.last_draw_ops_culled_text_ops = prepare.timings.draw_ops_culled_text_ops;
                    self.last_paint = prepare.timings.paint;
                    self.last_paint_culled_ops = prepare.timings.paint_culled_ops;
                    self.last_gpu_upload = prepare.timings.gpu_upload;
                    self.last_snapshot = prepare.timings.snapshot;
                    self.last_text_layout_cache_hits = prepare.timings.text_layout_cache.hits;
                    self.last_text_layout_cache_misses = prepare.timings.text_layout_cache.misses;
                    self.last_text_layout_cache_evictions =
                        prepare.timings.text_layout_cache.evictions;
                    self.last_text_layout_shaped_bytes =
                        prepare.timings.text_layout_cache.shaped_bytes;

                    // Two-lane scheduling: a layout-driven signal
                    // (animation settling, widget redraw_within,
                    // tooltip / toast pending) takes precedence over a
                    // paint-only signal — both arrive immediately
                    // because the browser raf loop has no deadline
                    // parking, but the trigger encodes which path the
                    // next frame should take. On a paint-only frame
                    // `repaint` reports `next_layout_redraw_in = None`
                    // (it didn't re-evaluate), so the layout deadline
                    // can only fall through if the prior full prepare
                    // already cleared it.
                    if prepare.next_layout_redraw_in.is_some() {
                        self.next_trigger = FrameTrigger::Animation;
                        gfx.window.request_redraw();
                    } else if prepare.next_paint_redraw_in.is_some() {
                        self.next_trigger = FrameTrigger::ShaderPaint;
                        gfx.window.request_redraw();
                    }
                    let _ = self.config.viewport;
                }
                _ => {}
            }
        }
    }

    fn map_key(key: &Key) -> Option<UiKey> {
        match key {
            Key::Named(NamedKey::Enter) => Some(UiKey::Enter),
            Key::Named(NamedKey::Escape) => Some(UiKey::Escape),
            Key::Named(NamedKey::Tab) => Some(UiKey::Tab),
            Key::Named(NamedKey::Space) => Some(UiKey::Space),
            Key::Named(NamedKey::ArrowUp) => Some(UiKey::ArrowUp),
            Key::Named(NamedKey::ArrowDown) => Some(UiKey::ArrowDown),
            Key::Named(NamedKey::ArrowLeft) => Some(UiKey::ArrowLeft),
            Key::Named(NamedKey::ArrowRight) => Some(UiKey::ArrowRight),
            Key::Named(NamedKey::Backspace) => Some(UiKey::Backspace),
            Key::Named(NamedKey::Delete) => Some(UiKey::Delete),
            Key::Named(NamedKey::Home) => Some(UiKey::Home),
            Key::Named(NamedKey::End) => Some(UiKey::End),
            Key::Named(NamedKey::PageUp) => Some(UiKey::PageUp),
            Key::Named(NamedKey::PageDown) => Some(UiKey::PageDown),
            Key::Character(s) => Some(UiKey::Character(s.to_string())),
            Key::Named(named) => Some(UiKey::Other(format!("{named:?}"))),
            _ => None,
        }
    }

    fn key_modifiers(mods: winit::keyboard::ModifiersState) -> KeyModifiers {
        KeyModifiers {
            shift: mods.shift_key(),
            ctrl: mods.control_key(),
            alt: mods.alt_key(),
            logo: mods.super_key(),
        }
    }

    fn should_prevent_browser_key_default(event: &web_sys::KeyboardEvent) -> bool {
        // Keep browser/system shortcuts alive, especially Ctrl/Cmd+V:
        // preventing that keydown suppresses the trusted DOM `paste`
        // event that carries clipboard text in Firefox.
        if event.ctrl_key() || event.meta_key() || event.alt_key() {
            return false;
        }

        let key = event.key();
        if key.chars().count() == 1 {
            return true;
        }

        matches!(
            key.as_str(),
            "ArrowUp"
                | "ArrowDown"
                | "ArrowLeft"
                | "ArrowRight"
                | "Backspace"
                | "Delete"
                | "Home"
                | "End"
                | "PageUp"
                | "PageDown"
                | "Tab"
                | "Enter"
                | "Escape"
        )
    }

    /// Translate an Aetna [`Cursor`] to winit's [`CursorIcon`]. winit's
    /// web backend then maps that to a CSS `cursor:` string and writes
    /// it to the canvas's inline style — so this is the only piece of
    /// platform-specific cursor wiring the browser host needs.
    /// `Cursor` is `non_exhaustive`; new variants land in `aetna-core`
    /// and a parallel arm here, with the wildcard as a forward-compat
    /// fallback.
    fn winit_cursor(cursor: Cursor) -> CursorIcon {
        match cursor {
            Cursor::Default => CursorIcon::Default,
            Cursor::Pointer => CursorIcon::Pointer,
            Cursor::Text => CursorIcon::Text,
            Cursor::NotAllowed => CursorIcon::NotAllowed,
            Cursor::Grab => CursorIcon::Grab,
            Cursor::Grabbing => CursorIcon::Grabbing,
            Cursor::Move => CursorIcon::Move,
            Cursor::EwResize => CursorIcon::EwResize,
            Cursor::NsResize => CursorIcon::NsResize,
            Cursor::NwseResize => CursorIcon::NwseResize,
            Cursor::NeswResize => CursorIcon::NeswResize,
            Cursor::ColResize => CursorIcon::ColResize,
            Cursor::RowResize => CursorIcon::RowResize,
            Cursor::Crosshair => CursorIcon::Crosshair,
            _ => CursorIcon::Default,
        }
    }

    fn bg_color(palette: &Palette) -> wgpu::Color {
        let c = palette.background;
        wgpu::Color {
            r: srgb_to_linear(c.r as f64 / 255.0),
            g: srgb_to_linear(c.g as f64 / 255.0),
            b: srgb_to_linear(c.b as f64 / 255.0),
            a: c.a as f64 / 255.0,
        }
    }

    fn srgb_to_linear(c: f64) -> f64 {
        if c <= 0.04045 {
            c / 12.92
        } else {
            ((c + 0.055) / 1.055).powf(2.4)
        }
    }

    fn copy_current_selection(renderer: &Runner, write_text: impl FnOnce(String)) {
        // Read the selection out of `last_tree` (via the runtime
        // helper) — see `RunnerCore::selected_text` for why a
        // build-only path would miss selections inside a virtual
        // list.
        let Some(text) = renderer.selected_text() else {
            return;
        };
        write_text(text);
    }

    fn write_clipboard_text(text: String) {
        let Some(window) = web_sys::window() else {
            log::warn!("aetna-web: no window; clipboard write dropped");
            return;
        };
        let promise = window.navigator().clipboard().write_text(&text);
        wasm_bindgen_futures::spawn_local(async move {
            if let Err(err) = wasm_bindgen_futures::JsFuture::from(promise).await {
                log::warn!("aetna-web: clipboard writeText failed: {err:?}");
            }
        });
    }

    fn attach_primary_selection_text(mut event: UiEvent, primary_selection: &str) -> UiEvent {
        if event.kind == UiEventKind::MiddleClick && !primary_selection.is_empty() {
            event.text = Some(primary_selection.to_string());
        }
        event
    }

    fn dispatch_app_event<A: App>(
        app: &mut A,
        event: UiEvent,
        renderer: &Runner,
        primary_selection: &mut String,
    ) {
        let before = app.selection();
        app.on_event(event);
        if app.selection() != before {
            // Resolve the post-event selection against `last_tree`.
            // The new selection's keys are typically the row the user
            // just clicked, which is present in the previous frame's
            // snapshot.
            *primary_selection = renderer
                .selected_text_for(&app.selection())
                .filter(|text| !text.is_empty())
                .unwrap_or_default();
        }
    }

    fn drain_pending_clipboard_text<A: App>(
        app: &mut A,
        renderer: &mut Runner,
        pending_text: &Rc<RefCell<VecDeque<String>>>,
        primary_selection: &mut String,
    ) -> bool {
        let mut drained = false;
        while let Some(text) = pending_text.borrow_mut().pop_front() {
            let Some(event) = renderer.text_input(text.clone()) else {
                continue;
            };
            drained = true;
            let event = clipboard::paste_text_event(event, text);
            dispatch_app_event(app, event, renderer, primary_selection);
        }
        drained
    }
}