bevy-react 0.1.2

Drive bevy_ui from a React app over an embedded V8 runtime.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
//! The two Bevy systems that drive the boundary each frame:
//! - [`apply_js_ops`] drains reconciler op batches and mutates the UI tree.
//! - [`collect_ui_events`] reports interactions back to the JS thread.

use crate::animations::AnimatedNode;
use crate::canvas::{CanvasSurface, blank_canvas_image, clamp_physical_size};
use crate::portal::{RPortal, blank_portal_image};
use crate::surface::{RSurface, SurfaceVirtualPointer};
use accesskit::Role;
use bevy::a11y::AccessibilityNode;
use bevy::ecs::system::SystemParam;
use bevy::image::Image;
use bevy::input_focus::tab_navigation::TabIndex;
use bevy::input_focus::{AutoFocus, FocusGained, FocusLost};
use bevy::picking::events::{Click, Drag, Enter, Leave, Pointer, Press, Release};
use bevy::picking::pointer::{PointerButton, PointerId};
use bevy::platform::collections::HashSet;
use bevy::prelude::*;
use bevy::text::{EditableText, FontCx, LayoutCx, TextCursorStyle, TextEdit, TextEditChange};
use bevy::ui::FocusPolicy;
use bevy::ui::RelativeCursorPosition;
use bevy::ui::widget::NodeImageMode;
use bevy::ui::{ComputedNode, ScrollPosition, UiGlobalTransform};

use crate::anchor::{AnchorScaling, Anchored};
use crate::bridge::{
    CanvasSizeTracker, FocusState, HoverState, JsBridge, PointerHandlers, RNode, ScrollListener,
    ScrollStep, SpanKind, StyleVariants, WheelListener,
};
use crate::filter::{FilterAssets, FilterMaterial, FilterMaterialCache, filter_material};
use crate::plugin::Fonts;
use crate::protocol::{NodeId, Op, Outbound, Props, ROOT_ID, Style, UiEvent};
use crate::transition::{ScrollTransitionState, apply_scroll_transition};
use crate::ui_map::{
    AtlasLayoutCache, apply_atlas, apply_opacity, apply_style, apply_style_masked,
    apply_text_style, image_node, overlay_style, parse_color, resolved_text_style, text_layout,
};

/// Live instrumentation of the [`apply_js_ops`] hot path. Updated once per frame
/// that applies at least one reconciler op (empty frames leave it untouched), so
/// a benchmark driver — or any consumer — can poll `applied_count` to detect
/// "my flushed batch has landed" and read the timing of the most recent batch.
///
/// Note `last_translate` measures only the op→command *queuing* in
/// [`apply_js_ops`]; the queued `Commands` (entity spawn / component insert /
/// hierarchy) execute later at a sync point, and `bevy_ui` layout later still —
/// neither is included here. `last_apply_end` is exposed so a downstream timer
/// can bracket those phases (e.g. up to `UiSystems::Layout`).
///
/// Timings are wall-clock, measured on native only; on web they stay zero/`None`
/// (`std::time::Instant` is unavailable on wasm).
#[derive(Resource, Default, Debug, Clone, Copy)]
pub struct OpApplyStats {
    /// Count of non-empty op batches applied since startup (one increment per
    /// frame that applied at least one op).
    pub applied_count: u64,
    /// Number of ops in the most recently applied batch.
    pub last_ops: usize,
    /// Time spent translating the most recent batch into ECS commands — the
    /// [`apply_js_ops`] body only. Excludes command execution and layout.
    pub last_translate: std::time::Duration,
    /// The instant [`apply_js_ops`] finished queuing the most recent batch
    /// (native only). A later system can subtract this from a post-layout instant
    /// to time command execution + layout.
    pub last_apply_end: Option<std::time::Instant>,
}

/// The asset stores + caches the op-apply path builds components from: the
/// `<image atlas>` `TextureAtlasLayout`s and the `filter` style's
/// [`FilterMaterial`]s (plus the shared white pixel). Bundled as one `SystemParam`
/// so [`apply_js_ops`] stays under Bevy's per-system parameter limit.
#[derive(SystemParam)]
pub struct UiAssets<'w> {
    layouts: ResMut<'w, Assets<TextureAtlasLayout>>,
    atlas_cache: ResMut<'w, AtlasLayoutCache>,
    filter_materials: ResMut<'w, Assets<FilterMaterial>>,
    filter_cache: ResMut<'w, FilterMaterialCache>,
    filter_assets: Res<'w, FilterAssets>,
}

/// Apply every queued reconciler op to the ECS. Runs in `Update`; ops simply
/// queue in the channel until this drains them, so startup ordering is a
/// non-issue.
#[allow(clippy::too_many_arguments)]
pub fn apply_js_ops(
    mut commands: Commands,
    mut bridge: ResMut<JsBridge>,
    assets: Res<AssetServer>,
    fonts: Res<Fonts>,
    mut images: ResMut<Assets<Image>>,
    // Sprite-sheet grids for `<image atlas>`, plus the cache that keeps repeated
    // commits from leaking a `TextureAtlasLayout` per frame (see `AtlasLayoutCache`).
    // Asset stores + caches for `<image atlas>` and the `filter` material, bundled
    // into one `SystemParam` so `apply_js_ops` stays within Bevy's 16-param limit.
    mut ui_assets: UiAssets,
    children: Query<&Children>,
    rnodes: Query<&RNode>,
    // On re-render the entity's kind isn't on the op, so we detect a `<button>` by
    // its marker to keep re-asserting its `FocusPolicy::Block` default (see
    // `apply_button_focus_default`) that the per-commit `apply_style` resets to `Pass`.
    buttons: Query<(), With<Button>>,
    // The persistent world-anchor overlay layer (a child of the root). It is
    // infrastructure, not a reconciler node, so `Op::Reset` must preserve it and
    // the end-of-batch hierarchy rebuild must keep it in the root's children.
    anchor_layer: Query<Entity, With<crate::anchor::AnchorLayer>>,
    mut editables: Query<&mut EditableText>,
    // Controlled `scrollTop`/`scrollLeft`: every `Node` has a `ScrollPosition`
    // (it's a required component), so `get_mut(e)` succeeds for any node — we only
    // write the axis React controls, and only when it diverges from the live value.
    // `ComputedNode` lets us clamp the write to the scrollable range, like the
    // wheel handler does, so a controlled offset can't overscroll. With a scroll
    // transition the offset is eased: the controlled value sets the target rather
    // than `ScrollPosition` directly.
    mut scroll_query: Query<(
        &mut ScrollPosition,
        &ComputedNode,
        Option<&mut ScrollTransitionState>,
    )>,
    mut a11y_nodes: Query<&mut AccessibilityNode>,
    // A `<text>` *root* carries a layout `Node`; a span (nested `<text>` or a
    // bare string) does not. Used on update to re-apply layout/visual/transform
    // style to roots only — spans must never get a `Node`.
    text_roots: Query<(), With<Node>>,
    mut stats: ResMut<OpApplyStats>,
) {
    // Drain all pending batches first so we don't hold an immutable borrow of
    // `bridge` while mutating `bridge.nodes` below.
    let mut ops: Vec<Op> = Vec::new();
    while let Ok(batch) = bridge.ops_rx.try_recv() {
        ops.extend(batch);
    }
    if ops.is_empty() {
        return;
    }
    let op_count = ops.len();
    #[cfg(not(target_arch = "wasm32"))]
    let started = std::time::Instant::now();
    debug!("applying {op_count} reconciler op(s)");

    // Parents whose child ORDER diverged from the ECS this batch (same-parent
    // re-appends and every `Insert`); they get one `replace_children` after the
    // loop instead of a per-op O(siblings) splice — mass reorders are O(ops) +
    // one O(children) rebuild, not quadratic. First-time attaches still queue an
    // O(1) `add_child` per op (a same-batch ancestor removal must reach the child
    // recursively), and removals don't dirty their parent at all: despawn's
    // relationship cleanup drops the child from `Children` preserving the order
    // of the rest.
    let mut dirty: HashSet<NodeId> = HashSet::new();

    for op in ops {
        match op {
            Op::Reset => {
                // Despawn the whole tree under the root (recursive), then reset
                // the id map to just the root. Stale ops referencing despawned
                // ids resolve to None afterwards and are skipped harmlessly.
                if let Some(&root) = bridge.nodes.get(&ROOT_ID)
                    && let Ok(kids) = children.get(root)
                {
                    for child in kids.iter() {
                        // The anchor layer is persistent infrastructure: keep it,
                        // but despawn the reconciler overlays reparented under it
                        // so a reload doesn't leave stale duplicate overlays.
                        if anchor_layer.contains(child) {
                            if let Ok(overlays) = children.get(child) {
                                for overlay in overlays.iter() {
                                    commands.entity(overlay).despawn();
                                }
                            }
                        } else {
                            commands.entity(child).despawn();
                        }
                    }
                }
                // Detached `<surface>` roots aren't under `root`, so the child-despawn
                // above misses them. On a cold reload the old React tree is discarded
                // without unmount lifecycle (no `detachDeletedInstance`), so despawn
                // them here too — otherwise stale surface subtrees keep rendering into
                // their texture.
                for id in bridge.surfaces.iter() {
                    if let Some(&e) = bridge.nodes.get(id) {
                        commands.entity(e).despawn();
                    }
                }
                bridge.nodes.retain(|&id, _| id == ROOT_ID);
                bridge.props_cache.clear();
                bridge.text_styles.clear();
                bridge.spans.clear();
                bridge.editable_inputs.clear();
                bridge.surfaces.clear();
                bridge.editable_values.clear();
                bridge.editable_selections.clear();
                bridge.editable_select_handlers.clear();
                bridge.editable_focus_handlers.clear();
                bridge.editable_pending_selection.clear();
                bridge.scroll_positions.clear();
                // The root persists but its children were just despawned; the shadow
                // tree is fully rebuilt by the ops that follow. Drop any pre-reset
                // dirty parents too — the reloaded app re-uses node ids, and its own
                // ops re-dirty whatever it rebuilds.
                bridge.siblings.clear();
                bridge.child_list.clear();
                bridge.parent_of.clear();
                bridge.surface_parent.clear();
                bridge.child_surfaces.clear();
                dirty.clear();
            }
            Op::Create {
                id,
                kind,
                props,
                text,
            } => {
                let entity = match kind.as_str() {
                    // A `<text>` root: a UI node carrying the text block + style.
                    // A single-string child rides inline as `text` (no child span).
                    "text" => {
                        let mut ec = commands.spawn(RNode(id));
                        apply_style(&mut ec, &props.style);
                        ec.insert(Text::new(text.clone().unwrap_or_default()));
                        apply_text_style(&mut ec, &props.style, &fonts);
                        if let Some(layout) = text_layout(&props.style) {
                            ec.insert(layout);
                        }
                        apply_anchor(&mut ec, &props);
                        ec.id()
                    }
                    // A nested `<text>`: a styled span (no layout box of its own).
                    // A single-string child rides inline as `text`.
                    "textSpan" => {
                        let mut ec =
                            commands.spawn((RNode(id), TextSpan(text.clone().unwrap_or_default())));
                        apply_text_style(&mut ec, &props.style, &fonts);
                        ec.id()
                    }
                    // A `<canvas>`: a styled node carrying an `ImageNode` whose
                    // texture the canvas system paints from the display list. The
                    // image stretches to fill the node's laid-out box.
                    "canvas" => {
                        let handle = images.add(blank_canvas_image());
                        let mut node_img = ImageNode::new(handle);
                        node_img.image_mode = NodeImageMode::Stretch;
                        let mut ec = commands.spawn(RNode(id));
                        apply_style(&mut ec, &props.style);
                        ec.insert((
                            node_img,
                            CanvasSurface::new(props.draw.clone().unwrap_or_default()),
                            CanvasSizeTracker::default(),
                        ));
                        apply_style_variants(&mut ec, &props);
                        apply_pointer_handlers(&mut ec, &props);
                        apply_animated(&mut ec, &props);
                        apply_anchor(&mut ec, &props);
                        ec.id()
                    }
                    // A `<portal>`: a styled node carrying an `ImageNode` whose
                    // texture is an offscreen render target the [`crate::portal`]
                    // registry owns. Starts on a blank placeholder; `bind_portals`
                    // swaps in the real target texture for `target` once it exists.
                    "portal" => {
                        let handle = images.add(blank_portal_image());
                        let mut node_img = ImageNode::new(handle);
                        node_img.image_mode = NodeImageMode::Stretch;
                        let mut ec = commands.spawn(RNode(id));
                        apply_style(&mut ec, &props.style);
                        ec.insert((node_img, RPortal(props.target.clone().unwrap_or_default())));
                        apply_style_variants(&mut ec, &props);
                        apply_pointer_handlers(&mut ec, &props);
                        apply_animated(&mut ec, &props);
                        apply_anchor(&mut ec, &props);
                        ec.id()
                    }
                    // A `<surface>`: a styled container whose subtree renders into
                    // an offscreen image instead of the on-screen UI. It is a
                    // **detached UI root** — `crate::surface::bind_surfaces`
                    // points its `UiTargetCamera` at the surface's offscreen UI
                    // camera, and the child-attach ops below keep it out of the
                    // on-screen Bevy hierarchy. The root fills the texture by
                    // default (user `style` overrides). Pointer/click events on it
                    // arrive via the surface picking path (`collect_surface_events`),
                    // not the legacy `Interaction` focus path.
                    "surface" => {
                        let style = overlay_style(&surface_root_base(), &props.style);
                        let mut ec = commands.spawn(RNode(id));
                        apply_style(&mut ec, &style);
                        ec.insert(RSurface(props.target.clone().unwrap_or_default()));
                        apply_anchor(&mut ec, &props);
                        ec.id()
                    }
                    // An `<editableText>`: a focusable native text input. Bevy's
                    // `EditableTextInputPlugin` (registered by `DefaultPlugins`)
                    // drives keyboard/focus/cursor/selection/clipboard; we just
                    // spawn the widget and observe `TextEditChange` for `onChange`.
                    "editableText" => {
                        let mut ec = commands.spawn(RNode(id));
                        apply_style(&mut ec, &props.style);
                        let mut editable =
                            EditableText::new(props.value.as_deref().unwrap_or_default());
                        editable.max_characters = props.max_length;
                        editable.allow_newlines = props.multiline;
                        let (text_color, font, line_height, letter_spacing) =
                            resolved_text_style(&props.style, &fonts);
                        ec.insert((
                            editable,
                            text_color,
                            font,
                            line_height,
                            letter_spacing,
                            TextLayout {
                                linebreak: if props.multiline {
                                    LineBreak::WordBoundary
                                } else {
                                    LineBreak::NoWrap
                                },
                                ..default()
                            },
                            // Caret follows the text color so it stays visible on
                            // any themed background (the default is a dark slate).
                            TextCursorStyle {
                                color: text_color.0,
                                ..default()
                            },
                            // Focusable via click (the widget's picking observers)
                            // and Tab navigation.
                            TabIndex(0),
                            // Announce as a text field to assistive tech; the live
                            // value is kept in sync by `sync_editable_a11y`.
                            AccessibilityNode(editable_a11y_node(&props)),
                        ));
                        // `AutoFocus`'s `on_add` hook focuses the entity once mounted.
                        if props.autofocus {
                            ec.insert(AutoFocus);
                        }
                        // `focusStyle` (and any hover/press) — applied Bevy-side as
                        // the field's focus/interaction state changes.
                        apply_style_variants(&mut ec, &props);
                        apply_anchor(&mut ec, &props);
                        ec.id()
                    }
                    _ => spawn_element(
                        &mut commands,
                        id,
                        &kind,
                        &props,
                        &assets,
                        &mut ui_assets.layouts,
                        &mut ui_assets.atlas_cache,
                        &mut FilterCtx {
                            materials: &mut ui_assets.filter_materials,
                            cache: &mut ui_assets.filter_cache,
                            white: &ui_assets.filter_assets.white,
                        },
                    ),
                };
                if matches!(kind.as_str(), "text" | "textSpan") {
                    bridge
                        .text_styles
                        .insert(id, resolved_text_style(&props.style, &fonts));
                }
                // A `textSpan` carries its text in a `TextSpan` component, so a later
                // `Op::UpdateText` must update that (not insert a stray `Text`). It is
                // `InlineStyled`: nested `<text>` spans keep their own style.
                if kind == "textSpan" {
                    bridge.spans.insert(id, SpanKind::InlineStyled);
                }
                if kind == "editableText" {
                    bridge.editable_inputs.insert(id);
                    bridge
                        .editable_values
                        .insert(id, props.value.clone().unwrap_or_default());
                    register_editable_handlers(&mut bridge, id, &props);
                    queue_pending_selection(
                        &mut bridge,
                        id,
                        props.selection_start,
                        props.selection_end,
                    );
                }
                if kind == "surface" {
                    bridge.surfaces.insert(id);
                }
                // Controlled scroll + the `onScroll` listener apply to any node
                // (anything with `overflow: scroll`). A `textSpan` has no `Node`
                // and so never matches the read-back query — harmless there.
                {
                    let mut ec = commands.entity(entity);
                    apply_scroll_listener(&mut ec, &props);
                    apply_wheel_listener(&mut ec, &props);
                    apply_scroll_step(&mut ec, &props);
                    apply_scroll_transition(&mut ec, &props.style);
                    create_controlled_scroll(&mut bridge, &mut ec, id, &props);
                }
                bridge.nodes.insert(id, entity);
                // Seed the retained props a later update's delta merges into.
                // Event-like fields were consumed by the create itself and are
                // never part of the retained state.
                let (state, _) = props.split_events();
                bridge.props_cache.insert(id, Box::new(state));
            }
            Op::CreateText { id, text } => {
                let entity = commands
                    .spawn((Text::new(text), TextColor(Color::WHITE), RNode(id)))
                    .id();
                bridge.nodes.insert(id, entity);
            }
            Op::CreateTextSpan { id, text } => {
                // A bare-string run inside a `<text>`. Style is inherited from its
                // parent on append (see below); until then it keeps span defaults.
                let entity = commands.spawn((TextSpan(text), RNode(id))).id();
                bridge.nodes.insert(id, entity);
                bridge.spans.insert(id, SpanKind::RawInherited);
            }
            Op::Append { parent, child } => {
                // A `<surface>` is a detached UI root: never parent it into the
                // on-screen hierarchy (it renders to its own offscreen camera). Its
                // own children attach to it normally via their own Append ops. Record
                // its React parent so removing an ancestor can despawn this detached
                // root (Bevy's recursive despawn never reaches it).
                if bridge.surfaces.contains(&child) {
                    bridge.attach_surface(child, parent);
                    continue;
                }
                if let (Some(p), Some(c)) = (resolve(&bridge, parent), resolve(&bridge, child)) {
                    let same_parent = bridge.parent_of.get(&child) == Some(&parent);
                    bridge.append_child(parent, child);
                    if same_parent {
                        // Re-append = move to the end: an O(1) shadow reorder, synced
                        // to the ECS by the end-of-batch rebuild.
                        dirty.insert(parent);
                    } else {
                        // Fresh node (or cross-parent move): attach in the ECS NOW —
                        // a same-batch removal of an ancestor must be able to despawn
                        // it recursively; deferring the attach would leak it as an
                        // orphaned window-UI root. `add_child` appends, matching the
                        // shadow tail (so no rebuild is needed), and a cross-parent
                        // `add_child` also detaches from the old ECS parent via the
                        // relationship hooks.
                        commands.entity(p).add_child(c);
                    }
                    inherit_text_style(&mut commands, &bridge, parent, child, c);
                }
            }
            Op::Insert {
                parent,
                child,
                before,
            } => {
                // A detached `<surface>` root is never parented (see `Op::Append`), but
                // still record its React parent for ancestor-removal cleanup.
                if bridge.surfaces.contains(&child) {
                    bridge.attach_surface(child, parent);
                    continue;
                }
                // Ordered insertion: place `child` at `before`'s position. The live
                // `Children` can't be read here (commands queued earlier in this same
                // batch haven't applied), so the shadow tree is the ordering truth and
                // the ECS position is fixed up by the end-of-batch rebuild of the
                // (always dirty) parent. A missing `before` falls back to appending.
                if let (Some(p), Some(c)) = (resolve(&bridge, parent), resolve(&bridge, child)) {
                    let same_parent = bridge.parent_of.get(&child) == Some(&parent);
                    bridge.insert_before(parent, child, before);
                    if !same_parent {
                        // Fresh/cross-parent: attach NOW (at the end — the rebuild
                        // moves it into place); see `Op::Append` for why deferring
                        // the attach itself would leak on same-batch removal.
                        commands.entity(p).add_child(c);
                    }
                    dirty.insert(parent);
                    inherit_text_style(&mut commands, &bridge, parent, child, c);
                }
            }
            Op::Remove { parent: _, child } => {
                // React emits `Remove` only for the subtree's top node, and Bevy
                // despawns that node recursively — but a `<surface>` nested under it is a
                // detached root (no `ChildOf`), so neither reaches it. Despawn every
                // detached surface at/under `child` (incl. `child` itself if it is one)
                // before the recursive despawn below; otherwise the orphaned surface
                // keeps rendering its stale subtree into its (often shared) texture.
                let mut surfaces = bridge.surfaces_under(child);
                if bridge.surfaces.contains(&child) {
                    bridge.detach_surface(child);
                    surfaces.push(child);
                }
                for s in surfaces {
                    if let Some(se) = resolve(&bridge, s) {
                        commands.entity(se).despawn();
                    }
                    // `forget_subtree` prunes `s` *and* the content rendered inside it
                    // (its `child_order` subtree) from every per-node side-table.
                    bridge.detach(s);
                    bridge.forget_subtree(s);
                }

                if let Some(c) = resolve(&bridge, child) {
                    commands.entity(c).despawn();
                    // Unlink from the parent's ordered list, then drop the whole subtree
                    // from the shadow tree — `forget_subtree` prunes `child` and every
                    // despawned descendant from all per-node side-tables, so no stale
                    // `NodeId → Entity` handles linger until the next `Reset`.
                    bridge.detach(child);
                    bridge.forget_subtree(child);
                }
            }
            Op::Update {
                id,
                props,
                unset,
                style_unset,
            } => {
                let Some(e) = resolve(&bridge, id) else {
                    continue;
                };
                // Merge the delta into the retained per-node props, yielding the
                // merged full props, what the delta touched, and the event-like
                // fields to act on.
                //
                // The cache entry is taken OUT of the map for the duration of the
                // arm and re-inserted at the end — the branches below borrow it
                // as `props` while also borrowing `bridge` mutably, and this way
                // no per-update `Props` clone is needed (it measurably showed up
                // in the update benchmarks).
                let mut cached = bridge.props_cache.remove(&id).unwrap_or_else(|| {
                    // Only reachable through a bug (create always seeds the
                    // cache); merging onto defaults degrades to "delta = the
                    // whole truth" rather than crashing.
                    warn!("delta update for uncached node {id}; merging onto defaults");
                    Box::default()
                });
                let (dirty, ev) = cached.merge_delta(props, &unset, &style_unset);
                let props = cached;
                use crate::protocol::style_groups as g;
                if bridge.text_styles.contains_key(&id) {
                    // A `<text>` element: refresh its resolved style — but only
                    // when a text-style field actually changed (resolution does
                    // color parsing + a font lookup, and the raw-span
                    // re-propagation below is O(children)).
                    let resolved = dirty.style.intersects(g::TEXT).then(|| {
                        let style = resolved_text_style(&props.style, &fonts);
                        bridge.text_styles.insert(id, style.clone());
                        style
                    });
                    let mut ec = commands.entity(e);
                    if let Some(style) = &resolved {
                        ec.insert(style.clone());
                    }
                    // A text *root* (has a `Node`) also gets the layout/visual/
                    // transform style + transition, mirroring its create path —
                    // otherwise a `transform`/`transition` on a `<text>` would only
                    // apply on mount and never animate. Spans have no `Node` and are
                    // skipped so they never gain a layout box.
                    if text_roots.contains(e) {
                        apply_style_masked(&mut ec, &props.style, dirty.style);
                    }
                    // Parity quirk preserved: a stale `TextLayout` is never removed
                    // when both its fields go absent, only overwritten.
                    if dirty.style.intersects(g::TEXT_LAYOUT)
                        && let Some(layout) = text_layout(&props.style)
                    {
                        ec.insert(layout);
                    }
                    if dirty.anchor {
                        apply_anchor(&mut ec, &props);
                    }
                    // Re-propagate the resolved style to any bare-string children
                    // that inherit it (after the last `ec` use — the loop needs
                    // `commands` back).
                    if let Some(style) = resolved
                        && let Ok(kids) = children.get(e)
                    {
                        for child in kids.iter() {
                            if let Ok(rnode) = rnodes.get(child)
                                && bridge.spans.get(&rnode.0) == Some(&SpanKind::RawInherited)
                            {
                                commands.entity(child).insert(style.clone());
                            }
                        }
                    }
                } else if bridge.editable_inputs.contains(&id) {
                    // Controlled `editableText`: push `value` into the live buffer
                    // only when it diverges from what the widget already holds, so
                    // a re-render echoing the user's own keystrokes is a no-op and
                    // never resets the cursor. Re-applying baseline keeps the
                    // `onChange` dedup from echoing this programmatic set back.
                    if let Some(new_val) = &ev.value {
                        if let Ok(mut editable) = editables.get_mut(e)
                            && editable.value().to_string() != *new_val
                        {
                            editable.editor_mut().set_text(new_val);
                            editable.queue_edit(TextEdit::TextEnd(false));
                        }
                        bridge.editable_values.insert(id, new_val.clone());
                    }
                    // Handler presence and the controlled selection can change on a
                    // re-render; refresh them. The accessible label is kept live too.
                    if dirty.editable_handlers {
                        register_editable_handlers(&mut bridge, id, &props);
                    }
                    queue_pending_selection(&mut bridge, id, ev.selection_start, ev.selection_end);
                    if dirty.aria_label
                        && let Ok(mut node) = a11y_nodes.get_mut(e)
                    {
                        match &props.aria_label {
                            Some(label) => node.set_label(label.clone()),
                            None => node.clear_label(),
                        }
                    }
                    let mut ec = commands.entity(e);
                    apply_style_masked(&mut ec, &props.style, dirty.style);
                    if dirty.any_style_variant() {
                        apply_style_variants(&mut ec, &props);
                    }
                } else if bridge.surfaces.contains(&id) {
                    // A `<surface>` re-render: re-apply the (full-size-defaulted)
                    // style and rebind its name. It shares the `target` wire field
                    // with `<portal>`, so it must branch before the general path
                    // below (which would wrongly stamp an `RPortal`).
                    let mut ec = commands.entity(e);
                    if dirty.style.any() {
                        let style = overlay_style(&surface_root_base(), &props.style);
                        apply_style_masked(&mut ec, &style, dirty.style);
                    }
                    if dirty.target
                        && let Some(name) = &props.target
                    {
                        ec.insert(RSurface(name.clone()));
                    }
                    if dirty.anchor {
                        apply_anchor(&mut ec, &props);
                    }
                } else {
                    let mut ec = commands.entity(e);
                    apply_style_masked(&mut ec, &props.style, dirty.style);
                    // Image attributes only ever appear on `image` elements, so
                    // their presence is enough to re-apply the texture/tint. A
                    // removed `filter` also lands here: its material made the
                    // `ImageNode` transparent, so the normal image must be rebuilt.
                    if (dirty.image || dirty.style.intersects(g::FILTER)) && is_image(&props) {
                        let mut img = image_node(&props, &assets);
                        apply_atlas(
                            &mut img,
                            &props,
                            &mut ui_assets.layouts,
                            &mut ui_assets.atlas_cache,
                        );
                        ec.insert(img);
                    }
                    // A `filter` swaps the node's draw for a `MaterialNode`; run
                    // after the style/image above so it can drop the components it
                    // replaces. Absent → it removes any prior filter material. Its
                    // material bakes tint/src (image attrs) plus filter, opacity and
                    // background color, so any of those dirties re-runs it.
                    if dirty.image || dirty.style.intersects(g::FILTER | g::BACKGROUND) {
                        apply_filter(
                            &mut ec,
                            &props,
                            &assets,
                            &mut FilterCtx {
                                materials: &mut ui_assets.filter_materials,
                                cache: &mut ui_assets.filter_cache,
                                white: &ui_assets.filter_assets.white,
                            },
                        );
                    }
                    // A `<canvas>`'s new declarative display list: clear + replay
                    // on the retained surface. Queued (not re-inserted) so the
                    // surface's retained pixmap and pending imperative commands
                    // aren't thrown away with the component.
                    if let Some(cmds) = ev.draw {
                        ec.queue(move |mut entity: EntityWorldMut| {
                            if let Some(mut surface) = entity.get_mut::<CanvasSurface>() {
                                surface.set_display_list(cmds);
                            }
                        });
                    }
                    // A `<portal>`'s new target name: rebind it (the binding system
                    // points its `ImageNode` at the new target next frame).
                    if dirty.target
                        && let Some(target) = &props.target
                    {
                        ec.insert(RPortal(target.clone()));
                    }
                    // When `apply_style_masked` reset this entity's `FocusPolicy` to
                    // the `Pass` default, re-assert a button's `Block` (no-op /
                    // `Pass` for plain nodes). Skipped when the mask skipped the
                    // `FocusPolicy` insert — nothing reset it.
                    if dirty.style.intersects(g::FOCUS_POLICY) && buttons.get(e).is_ok() {
                        apply_button_focus_default(&mut ec, &props.style);
                    }
                    // `StyleVariants.base` mirrors the (merged) base style, so any
                    // style change rebuilds it. Skipping when untouched also avoids
                    // a spurious `Changed<StyleVariants>` → full restyle merge from
                    // `apply_interaction_styles` on every unrelated update.
                    if dirty.any_style_variant() {
                        apply_style_variants(&mut ec, &props);
                    }
                    if dirty.pointer {
                        apply_pointer_handlers(&mut ec, &props);
                    }
                    if dirty.scroll_listener {
                        apply_scroll_listener(&mut ec, &props);
                    }
                    if dirty.wheel {
                        apply_wheel_listener(&mut ec, &props);
                    }
                    if dirty.scroll_step {
                        apply_scroll_step(&mut ec, &props);
                    }
                    if dirty.style.intersects(g::SCROLL_TRANSITION) {
                        apply_scroll_transition(&mut ec, &props.style);
                    }
                    if dirty.animated {
                        apply_animated(&mut ec, &props);
                    }
                    if dirty.anchor {
                        apply_anchor(&mut ec, &props);
                    }
                    update_controlled_scroll(
                        &mut bridge,
                        &mut scroll_query,
                        e,
                        id,
                        ev.scroll_left,
                        ev.scroll_top,
                    );
                }
                // Retain the merged props for the next delta (see above).
                bridge.props_cache.insert(id, props);
            }
            Op::UpdateText { id, text } => {
                if let Some(e) = resolve(&bridge, id) {
                    // A run is either a standalone `Text` or, inside a `<text>`, a
                    // `TextSpan` — update whichever this entity is.
                    if bridge.spans.contains_key(&id) {
                        commands.entity(e).insert(TextSpan(text));
                    } else {
                        commands.entity(e).insert(Text::new(text));
                    }
                }
            }
            Op::Draw { id, cmds } => {
                // Imperative canvas drawing (a handle's microtask flush) or the
                // runtime's declarative replay after a resize: append to the
                // retained surface. A missing node (already unmounted, stale
                // handle) is skipped silently, like every other op. Queued so a
                // same-batch `Create`'s deferred `CanvasSurface` insert lands
                // first.
                if let Some(e) = resolve(&bridge, id) {
                    commands.entity(e).queue(move |mut entity: EntityWorldMut| {
                        if let Some(mut surface) = entity.get_mut::<CanvasSurface>() {
                            surface.enqueue(cmds);
                        }
                    });
                }
            }
        }
    }

    // Sync the ECS hierarchy: one `replace_children` per parent whose child list
    // changed this batch (Bevy diffs — kept children get no `ChildOf` rewrite, the
    // order becomes exactly the slice's). Skipping unresolvable parents guards the
    // despawned-entity panic: anything removed (or wiped by `Reset`) mid-batch was
    // pruned from `bridge.nodes` by `forget_subtree`.
    for parent in dirty {
        let Some(p) = resolve(&bridge, parent) else {
            continue;
        };
        let mut list: Vec<Entity> = Vec::new();
        // The AnchorLayer is a Rust-side child of the root, invisible to the shadow
        // tree — keep it as the first child (its spawn-time position; overlays are
        // lifted by `GlobalZIndex`, not sibling order). Without this, the root's
        // rebuild would strip its `ChildOf`.
        if parent == ROOT_ID
            && let Ok(layer) = anchor_layer.single()
        {
            list.push(layer);
        }
        list.extend(
            bridge
                .children_of(parent)
                .filter_map(|id| resolve(&bridge, id)),
        );
        // Note: an anchored overlay under `parent` gets `ChildOf(parent)` re-asserted
        // here (its live parent is the AnchorLayer) — same as the old per-op
        // `insert_child` path; the anchor system self-heals it next frame.
        commands.entity(p).replace_children(&list);
    }

    // Record this batch for live instrumentation (see [`OpApplyStats`]).
    stats.applied_count = stats.applied_count.wrapping_add(1);
    stats.last_ops = op_count;
    #[cfg(not(target_arch = "wasm32"))]
    {
        let end = std::time::Instant::now();
        stats.last_translate = end.duration_since(started);
        stats.last_apply_end = Some(end);
    }
}

/// When a bare-string run is appended into a `<text>`, copy the parent's text
/// style onto it (Bevy has no text-style inheritance, and the parent's freshly
/// queued components aren't yet visible to an ECS query this frame).
// TODO(review): this hand-rolled CSS-style text inheritance (here + the O(children)
// re-propagation loop in the `<text>` `Op::Update` branch) is a complexity hotspot. It's
// likely unavoidable until Bevy grows real text-style inheritance, but worth watching as the
// text model grows.
fn inherit_text_style(
    commands: &mut Commands,
    bridge: &JsBridge,
    parent: NodeId,
    child: NodeId,
    child_entity: Entity,
) {
    if bridge.spans.get(&child) != Some(&SpanKind::RawInherited) {
        return;
    }
    if let Some(style) = bridge.text_styles.get(&parent).cloned() {
        commands.entity(child_entity).insert(style);
    }
}

/// The default style a `<surface>` root gets before the user's `style` is overlaid:
/// it fills the offscreen texture (the camera's logical viewport) so the subtree
/// has a definite box to lay out in. The user can override `width`/`height` (or any
/// other field) via the element's `style` prop.
fn surface_root_base() -> Option<Style> {
    Some(Style {
        width: Some(crate::protocol::Length::Percent(100.0)),
        height: Some(crate::protocol::Length::Percent(100.0)),
        ..Default::default()
    })
}

/// The resources [`apply_filter`] needs to build/cache a `FilterMaterial` and bind
/// the shared white pixel — bundled so the call sites don't thread three params.
struct FilterCtx<'a> {
    materials: &'a mut Assets<FilterMaterial>,
    cache: &'a mut FilterMaterialCache,
    white: &'a Handle<Image>,
}

/// Apply (or clear) a `filter` style on an element. Present → build a
/// [`FilterMaterial`] (source = the `<image>`'s texture, else the shared white
/// pixel tinted by `base_color`) and insert a `MaterialNode<FilterMaterial>`,
/// dropping the standard `ImageNode` / `BackgroundColor` so the node isn't drawn
/// twice. Absent → remove any prior filter material so the node reverts to its
/// normal draw. Must run *after* `apply_style` / the image insert (it removes the
/// components those add). See [`crate::filter`] for the scope (own surface only).
fn apply_filter(ec: &mut EntityCommands, props: &Props, assets: &AssetServer, ctx: &mut FilterCtx) {
    let Some(spec) = props.style.as_ref().and_then(|s| s.filter.as_ref()) else {
        ec.remove::<MaterialNode<FilterMaterial>>();
        return;
    };
    // Base color: the image tint, else the background color, else white. Opacity is
    // folded into alpha just like the standard background/image paths.
    let opacity = props.style.as_ref().and_then(|s| s.opacity);
    let base = props
        .tint
        .as_deref()
        .or_else(|| {
            props
                .style
                .as_ref()
                .and_then(|s| s.background_color.as_deref())
        })
        .map(parse_color)
        .unwrap_or(Color::WHITE);
    let texture = match &props.src {
        Some(path) => assets.load(path),
        None => ctx.white.clone(),
    };
    let mat = filter_material(spec, texture, apply_opacity(base, opacity));
    let handle = ctx.cache.handle(ctx.materials, mat);

    // The material replaces the node's own draw (so a filtered node never carries a
    // visible `BackgroundColor` — that's already dropped in `apply_style`).
    if props.src.is_some() {
        // A `MaterialNode` has no content measure, so a filtered `<image>` with only
        // a `width` would collapse to zero height. Keep the `ImageNode` (it measures
        // the texture's intrinsic size) but make it transparent so only the filter
        // material paints — no double draw.
        let mut img = image_node(props, assets);
        img.color = img.color.with_alpha(0.0);
        ec.insert(img);
    } else {
        // A solid-colored node: the material paints the (filtered) color; drop any
        // `ImageNode` a prior render left behind.
        ec.remove::<ImageNode>();
    }
    ec.remove::<BackgroundColor>();
    ec.insert(MaterialNode(handle));
}

/// Spawn a `node`, `button`, or `image` host element with its style.
#[allow(clippy::too_many_arguments)]
fn spawn_element(
    commands: &mut Commands,
    id: NodeId,
    kind: &str,
    props: &Props,
    assets: &AssetServer,
    layouts: &mut Assets<TextureAtlasLayout>,
    atlas_cache: &mut AtlasLayoutCache,
    filter: &mut FilterCtx,
) -> Entity {
    let mut ec = commands.spawn(RNode(id));
    apply_style(&mut ec, &props.style);
    match kind {
        // `Button` requires `Interaction`, which is added automatically.
        "button" => {
            ec.insert(Button);
            // Buttons capture the pointer by default; `apply_style` already
            // defaulted this entity to `Pass`, so override unless the prop is set.
            apply_button_focus_default(&mut ec, &props.style);
        }
        "image" => {
            let mut img = image_node(props, assets);
            apply_atlas(&mut img, props, layouts, atlas_cache);
            ec.insert(img);
        }
        _ => {}
    }
    // A `filter` swaps the node's image/background draw for a filter material.
    apply_filter(&mut ec, props, assets, filter);
    apply_style_variants(&mut ec, props);
    apply_pointer_handlers(&mut ec, props);
    apply_animated(&mut ec, props);
    apply_anchor(&mut ec, props);
    ec.id()
}

/// Stamp (or clear) the [`AnimatedNode`] bindings on a host element. Present →
/// the animations plugin drives the listed props each frame (no-op if animations
/// are disabled — nothing reads the component).
fn apply_animated(ec: &mut EntityCommands, props: &Props) {
    match &props.animated {
        Some(bindings) => {
            ec.insert(AnimatedNode(bindings.clone()));
        }
        None => {
            ec.remove::<AnimatedNode>();
        }
    }
}

/// Stamp (or clear) the [`Anchored`] binding on a host element. Present → the
/// positioning system projects the target entity's world position to the screen
/// each frame and writes this node's `left`/`top`. A malformed/dead entity id is
/// ignored (the binding is simply not applied).
fn apply_anchor(ec: &mut EntityCommands, props: &Props) {
    match &props.anchor {
        Some(anchor) => match Entity::try_from_bits(anchor.entity as u64) {
            Some(target) => {
                let offset = anchor.offset.map(Vec3::from).unwrap_or(Vec3::ZERO);
                ec.insert(Anchored {
                    target,
                    offset,
                    // Sanitized once here so the per-frame scale math can't panic
                    // on JS-supplied NaN/reversed bounds.
                    scale: anchor.scale.and_then(AnchorScaling::sanitized),
                });
            }
            None => {
                ec.remove::<Anchored>();
            }
        },
        None => {
            ec.remove::<Anchored>();
        }
    }
}

/// Stamp (or clear) the hover/press [`StyleVariants`] on a host element. When
/// either variant is present the element also gets an `Interaction` so the focus
/// system tracks hover/press for it; `insert_if_new` leaves any existing
/// `Interaction` untouched (a `button`'s, or a node already mid-hover) so we
/// never reset its state on a re-render.
fn apply_style_variants(ec: &mut EntityCommands, props: &Props) {
    if props.hover_style.is_some() || props.press_style.is_some() || props.focus_style.is_some() {
        ec.insert(StyleVariants {
            base: props.style.clone(),
            hover: props.hover_style.clone(),
            press: props.press_style.clone(),
            focus: props.focus_style.clone(),
        });
        // Hover/press are driven by `Interaction`; focus by `FocusState` (toggled
        // by the focus observers). Add each only for the variants present.
        if props.hover_style.is_some() || props.press_style.is_some() {
            ec.insert_if_new(Interaction::default());
        }
        if props.focus_style.is_some() {
            ec.insert_if_new(FocusState::default());
        } else {
            ec.remove::<FocusState>();
        }
    } else {
        ec.remove::<StyleVariants>();
        ec.remove::<FocusState>();
    }
}

/// Stamp (or clear) the [`PointerHandlers`] marker plus the components the
/// drag-capture system needs. When any `onPointer*` handler is declared the
/// element also gets a [`RelativeCursorPosition`] (so we can read the cursor's
/// normalized position within it).
///
/// Both `onClick` and the `onPointer*` handlers need an `Interaction`: it is the
/// click-*ownership* marker ([`collect_ui_events`] climbs a picked leaf to the
/// nearest `Interaction`-bearing node), the drag begin/over test in
/// [`collect_pointer_events`], and the hover/press-style + [`crate::PointerCapture`]
/// source. Without it a plain `<node onClick>` — no hover/press style, not a
/// `<button>` — would never be reported as clicked. `insert_if_new` leaves an
/// existing `Interaction` (a `button`'s, or a hover/press variant's) untouched.
fn apply_pointer_handlers(ec: &mut EntityCommands, props: &Props) {
    let any_pointer = props.on_pointer_down
        || props.on_pointer_move
        || props.on_pointer_up
        || props.on_pointer_enter
        || props.on_pointer_leave;
    if any_pointer {
        ec.insert(PointerHandlers {
            down: props.on_pointer_down,
            moved: props.on_pointer_move,
            up: props.on_pointer_up,
            enter: props.on_pointer_enter,
            leave: props.on_pointer_leave,
        });
        // `RelativeCursorPosition` supplies the `x`/`y` carried by drag and hover
        // events; the drag-capture and hover systems both read it.
        ec.insert_if_new(RelativeCursorPosition::default());
    } else {
        ec.remove::<PointerHandlers>();
        ec.remove::<RelativeCursorPosition>();
    }
    // `pointerEnter`/`pointerLeave` are derived from `Interaction` transitions, so
    // the node tracks its "inside" state in `HoverState`; add/remove it in step.
    if props.on_pointer_enter || props.on_pointer_leave {
        ec.insert_if_new(HoverState::default());
    } else {
        ec.remove::<HoverState>();
    }
    if props.on_click || any_pointer {
        ec.insert_if_new(Interaction::default());
    }
}

/// Toggle the [`ScrollListener`] marker so [`collect_scroll_events`] reports this
/// node's `ScrollPosition` changes only while an `onScroll` handler is declared.
fn apply_scroll_listener(ec: &mut EntityCommands, props: &Props) {
    if props.on_scroll {
        ec.insert_if_new(ScrollListener);
    } else {
        ec.remove::<ScrollListener>();
    }
}

/// Toggle the [`WheelListener`] marker so [`crate::scroll::collect_wheel_events`]
/// reports raw wheel deltas over this node only while an `onWheel` handler is
/// declared. Independent of `overflow: scroll` — any node can receive the wheel.
fn apply_wheel_listener(ec: &mut EntityCommands, props: &Props) {
    if props.on_wheel {
        ec.insert_if_new(WheelListener);
    } else {
        ec.remove::<WheelListener>();
    }
}

/// Stamp (or clear) the per-node [`ScrollStep`] wheel step from `scrollStep`.
fn apply_scroll_step(ec: &mut EntityCommands, props: &Props) {
    match props.scroll_step {
        Some(step) => {
            ec.insert(ScrollStep(step));
        }
        None => {
            ec.remove::<ScrollStep>();
        }
    }
}

/// Apply a controlled `scrollTop`/`scrollLeft` on **create**: insert the offset
/// (defaulting the uncontrolled axis to 0) and seed [`JsBridge::scroll_positions`]
/// so neither the programmatic write nor the node's mount-frame
/// `Changed<ScrollPosition>` echoes back as an `onScroll`. A listener with no
/// controlled offset is seeded at the default `ZERO` for the same reason.
fn create_controlled_scroll(
    bridge: &mut JsBridge,
    ec: &mut EntityCommands,
    id: NodeId,
    props: &Props,
) {
    if props.scroll_top.is_some() || props.scroll_left.is_some() {
        let pos = Vec2::new(
            props.scroll_left.unwrap_or(0.0),
            props.scroll_top.unwrap_or(0.0),
        );
        // Overrides the `ZERO` that `Node`'s required `ScrollPosition` defaults to.
        ec.insert(ScrollPosition(pos));
        bridge.scroll_positions.insert(id, pos);
    } else if props.on_scroll {
        bridge.scroll_positions.insert(id, Vec2::ZERO);
    }
}

/// Push a controlled `scrollTop`/`scrollLeft` into a live node on **update**:
/// write only the axis React controls, clamped to the scrollable range, and only
/// when it diverges from the live offset (so a re-render echoing the user's own
/// wheel scroll is a no-op and never snaps the view). Mirrors the controlled
/// `value` diff for `editableText`.
///
/// Records the **requested** (pre-clamp) value in [`JsBridge::scroll_positions`].
/// When the request was in range this equals the written offset, so the read-back
/// dedups it (no echo). When the request overshot, the clamped component value
/// diverges from the recorded request, so the read-back fires one `"scroll"` with
/// the real offset — letting a controlled `scrollTop={BIG}` settle to the true max.
///
/// With a scroll transition ([`ScrollTransitionState`] present) the clamped value
/// becomes the eased **target** instead of being written to `ScrollPosition` — the
/// `drive_scroll_transition` system moves the offset toward it. The uncontrolled
/// axis keeps the current target (not the mid-ease position) so it doesn't snap.
fn update_controlled_scroll(
    bridge: &mut JsBridge,
    scroll_query: &mut Query<(
        &mut ScrollPosition,
        &ComputedNode,
        Option<&mut ScrollTransitionState>,
    )>,
    e: Entity,
    id: NodeId,
    scroll_left: Option<f32>,
    scroll_top: Option<f32>,
) {
    if scroll_top.is_none() && scroll_left.is_none() {
        return;
    }
    if let Ok((mut pos, computed, scroll_state)) = scroll_query.get_mut(e) {
        // Base on the eased target if a transition owns the offset, else the live one.
        let mut requested = scroll_state.as_ref().map_or(pos.0, |s| s.target);
        if let Some(x) = scroll_left {
            requested.x = x;
        }
        if let Some(y) = scroll_top {
            requested.y = y;
        }
        // Same range as the wheel handler (`scroll::apply_scroll`): `ComputedNode`
        // sizes are physical, the component is logical, so scale with `inverse_scale_factor`.
        let max = (computed.content_size - computed.size + computed.scrollbar_size).max(Vec2::ZERO)
            * computed.inverse_scale_factor;
        let clamped = requested.clamp(Vec2::ZERO, max);
        match scroll_state {
            // Eased: set the target; `drive_scroll_transition` moves `ScrollPosition`.
            Some(mut state) => state.target = clamped,
            // Snap: write the offset directly, only when it diverges.
            None => {
                if pos.0 != clamped {
                    pos.0 = clamped;
                }
            }
        }
        bridge.scroll_positions.insert(id, requested);
    }
}

/// `<button>` captures the pointer by default — bevy_ui's native `Button` sets
/// `FocusPolicy::Block`, and we mirror that so a button doesn't leak its click to a
/// sibling, an ancestor, or the 3D scene/portal behind it. [`apply_style`] defaults
/// every element to `Pass`, so for a button with no explicit `focusPolicy` we
/// re-assert `Block` here. A bare `<node>` keeps `Pass`, so containers/labels stay
/// click-through and don't swallow clicks meant for what's behind or around them.
/// An explicit `focusPolicy` prop (handled in `apply_style`) always wins.
fn apply_button_focus_default(ec: &mut EntityCommands, style: &Option<Style>) {
    let has_explicit = style.as_ref().is_some_and(|s| s.focus_policy.is_some());
    if !has_explicit {
        ec.insert(FocusPolicy::Block);
        // Mirror into the picking backend's blocking flag, exactly as
        // `apply_style` does for the `Pass` default (see its `FOCUS_POLICY` doc).
        ec.insert(bevy::picking::Pickable {
            should_block_lower: true,
            is_hoverable: true,
        });
    }
}

/// Whether these props carry any `image` element attribute.
fn is_image(props: &Props) -> bool {
    props.src.is_some()
        || props.tint.is_some()
        || props.image_mode.is_some()
        || props.flip_x
        || props.flip_y
        || props.source_rect.is_some()
        || props.atlas.is_some()
        || props.visual_box.is_some()
}

fn resolve(bridge: &JsBridge, id: NodeId) -> Option<Entity> {
    bridge.nodes.get(&id).copied()
}

/// Report clicks on reconciler-owned nodes to the JS thread. Rides bevy_picking's
/// `Pointer<Click>`, which fires on *release over the same node the press landed
/// on* — DOM click semantics, so press → drag off → release never clicks. Like
/// DOM `click`, only the primary (left) button clicks; right/middle interactions
/// are the `onPointer*` events' job (which carry the button). The surface
/// virtual pointer is excluded: its clicks are [`collect_surface_clicks`]' job.
pub fn collect_ui_events(
    bridge: Res<JsBridge>,
    surface_pointer: Option<Res<SurfaceVirtualPointer>>,
    mut clicks: MessageReader<Pointer<Click>>,
    // Only `Interaction`-bearing nodes own a click (a `<button>` gets one via
    // `Button`; a `<text>` child does not) — the same attribution rule as the
    // legacy `ui_focus_system` path and `collect_surface_clicks`.
    targets: Query<&RNode, With<Interaction>>,
    child_of: Query<&ChildOf>,
) {
    // One gesture fans out to every entity in the pointer's hover map (a button
    // AND its pass-through label); climbing resolves them to the same owner, so
    // dedupe per (pointer, owner) within the frame.
    let mut seen: HashSet<(PointerId, Entity)> = HashSet::new();
    for ev in clicks.read() {
        if ev.button != PointerButton::Primary {
            continue;
        }
        if surface_pointer
            .as_ref()
            .is_some_and(|p| ev.pointer_id == p.id)
        {
            continue;
        }
        // Resolve the picked leaf (often a text span) to the nearest interactive
        // ancestor, so a click on a button's label still fires the button.
        if let Some(target) = climb(ev.entity, &child_of, |e| targets.contains(e))
            && seen.insert((ev.pointer_id, target))
            && let Ok(rnode) = targets.get(target)
        {
            debug!("click -> reconciler node {}", rnode.0);
            send_ui_event(&bridge, rnode.0, "click", None, None, None);
        }
    }
}

/// Report `ScrollPosition` changes back to JS as `"scroll"` events. Scoped to
/// nodes carrying a [`ScrollListener`] (i.e. those with an `onScroll` handler) so
/// the `Changed<ScrollPosition>` query stays cheap — `ScrollPosition` is a
/// required component of every `Node`, so an unscoped query would fire for every
/// node on its mount frame. A controlled write-back is deduped against
/// [`JsBridge::scroll_positions`], breaking the controlled-component echo loop.
#[allow(clippy::type_complexity)]
pub fn collect_scroll_events(
    mut bridge: ResMut<JsBridge>,
    query: Query<(&ScrollPosition, &RNode), (With<ScrollListener>, Changed<ScrollPosition>)>,
) {
    for (scroll, rnode) in &query {
        let id = rnode.0;
        if bridge.scroll_positions.get(&id) == Some(&scroll.0) {
            // Our own controlled write (or an unchanged value) — don't echo it.
            continue;
        }
        bridge.scroll_positions.insert(id, scroll.0);
        debug!("scroll -> reconciler node {id}");
        let _ = bridge.outbound_tx.send(Outbound::UiEvent {
            event: UiEvent {
                id,
                kind: "scroll".to_string(),
                scroll_top: Some(scroll.0.y),
                scroll_left: Some(scroll.0.x),
                ..default()
            },
        });
    }
}

/// Emit a `"resize"` UI event (new logical size) for every `<canvas>` whose
/// laid-out **physical** size changed — including its first layout (0 → W×H)
/// and a DPR change at constant logical size, both of which cleared the
/// retained surface. Not gated on a handler flag: the JS runtime consumes
/// resizes unconditionally (to replay a declarative painter and keep the
/// canvas handle's size fresh); a user `onResize` is dispatched if registered.
/// The per-entity [`CanvasSizeTracker`] filters the non-size `ComputedNode`
/// rewrites layout does every pass. Sizes clamp exactly like the rasterizer's,
/// so the reported size always matches the actual buffer.
#[allow(clippy::type_complexity)]
pub fn collect_canvas_resize_events(
    bridge: Res<JsBridge>,
    mut query: Query<
        (&RNode, &ComputedNode, &mut CanvasSizeTracker),
        (With<CanvasSurface>, Changed<ComputedNode>),
    >,
) {
    for (rnode, node, mut tracker) in &mut query {
        let (w, h) = clamp_physical_size(node.size);
        if w == 0 || h == 0 || tracker.0 == (w, h) {
            continue;
        }
        tracker.0 = (w, h);
        let scale = if node.inverse_scale_factor > 0.0 {
            node.inverse_scale_factor
        } else {
            1.0
        };
        debug!("canvas resize -> reconciler node {}", rnode.0);
        let _ = bridge.outbound_tx.send(Outbound::UiEvent {
            event: UiEvent {
                id: rnode.0,
                kind: "resize".to_string(),
                width: Some(w as f32 * scale),
                height: Some(h as f32 * scale),
                ..default()
            },
        });
    }
}

/// Build the accesskit node for an `editableText` from its props (role + label +
/// initial value). The live value is kept current by [`sync_editable_a11y`].
fn editable_a11y_node(props: &Props) -> accesskit::Node {
    let role = if props.multiline {
        Role::MultilineTextInput
    } else {
        Role::TextInput
    };
    let mut node = accesskit::Node::new(role);
    if let Some(label) = &props.aria_label {
        node.set_label(label.clone());
    }
    node.set_value(props.value.clone().unwrap_or_default());
    node
}

/// Add or remove `id` from `set` to mirror a boolean prop.
fn set_membership(set: &mut HashSet<NodeId>, id: NodeId, present: bool) {
    if present {
        set.insert(id);
    } else {
        set.remove(&id);
    }
}

/// Record which optional `editableText` handlers are registered in JS, so the
/// high-frequency `"select"`/`"focus"`/`"blur"` events are only emitted when
/// something is listening. Called on create and on every controlled update.
fn register_editable_handlers(bridge: &mut JsBridge, id: NodeId, props: &Props) {
    set_membership(&mut bridge.editable_select_handlers, id, props.on_select);
    set_membership(
        &mut bridge.editable_focus_handlers,
        id,
        props.on_focus || props.on_blur,
    );
}

/// Queue a controlled selection (byte offsets) for [`apply_pending_selections`],
/// when both `selectionStart` and `selectionEnd` are supplied. (The JS delta
/// builder keeps the pair coupled: when either changes, both current values are
/// sent, so a delta update never sees half a selection.)
fn queue_pending_selection(
    bridge: &mut JsBridge,
    id: NodeId,
    start: Option<usize>,
    end: Option<usize>,
) {
    if let (Some(start), Some(end)) = (start, end) {
        bridge.editable_pending_selection.insert(id, (start, end));
    }
}

/// Report `editableText` edits back to JS. Bevy triggers [`TextEditChange`] after
/// applying edits — but also on cursor/selection moves — so this single observer
/// emits a `"change"` (deduped against the last value) when the text changed, and
/// a `"select"` (deduped against the last selection, and only for nodes with an
/// `onSelect` handler, since caret moves are frequent) when the selection moved.
/// Each is routed by node id + kind in the JS event-loop router.
pub fn on_text_edit_change(
    change: On<TextEditChange>,
    mut bridge: ResMut<JsBridge>,
    editables: Query<(&EditableText, &RNode)>,
) {
    let Ok((editable, rnode)) = editables.get(change.event_target()) else {
        return;
    };
    let id = rnode.0;
    let composing = editable.is_composing();

    let value = editable.value().to_string();
    if bridge.editable_values.get(&id) != Some(&value) {
        bridge.editable_values.insert(id, value.clone());
        debug!("change -> reconciler node {id}");
        let _ = bridge.outbound_tx.send(Outbound::UiEvent {
            event: UiEvent {
                id,
                kind: "change".to_string(),
                value: Some(value),
                composing: Some(composing),
                ..default()
            },
        });
    }

    if bridge.editable_select_handlers.contains(&id) {
        let sel = editable.editor().raw_selection();
        let anchor = sel.anchor().index();
        let focus = sel.focus().index();
        if bridge.editable_selections.get(&id) != Some(&(anchor, focus)) {
            // Pre-seeded by a programmatic select; this dedup suppresses that echo.
            bridge.editable_selections.insert(id, (anchor, focus));
            let direction = if anchor == focus {
                "none"
            } else if anchor < focus {
                "forward"
            } else {
                "backward"
            };
            let _ = bridge.outbound_tx.send(Outbound::UiEvent {
                event: UiEvent {
                    id,
                    kind: "select".to_string(),
                    selection_start: Some(anchor.min(focus)),
                    selection_end: Some(anchor.max(focus)),
                    selection_direction: Some(direction.to_string()),
                    composing: Some(composing),
                    ..default()
                },
            });
        }
    }
}

/// Emit an `editableText`'s `"focus"` / `"blur"` events, and toggle the node's
/// [`FocusState`] so a `focusStyle` is (un)applied by [`apply_interaction_styles`].
/// `FocusGained`/`FocusLost` are `auto_propagate` (they bubble to parents), so we
/// act on the originally focused entity (`ev.entity`). Event emission is gated to
/// editables with an `onFocus`/`onBlur` handler; `FocusState` is general (no-op for
/// nodes without it).
pub fn on_focus_gained(
    ev: On<FocusGained>,
    bridge: ResMut<JsBridge>,
    editables: Query<&RNode, With<EditableText>>,
    mut focus_states: Query<&mut FocusState>,
) {
    set_focus_state(&mut focus_states, ev.entity, true);
    emit_focus_event(&bridge, &editables, ev.entity, "focus");
}

/// See [`on_focus_gained`]; the blur counterpart.
pub fn on_focus_lost(
    ev: On<FocusLost>,
    bridge: ResMut<JsBridge>,
    editables: Query<&RNode, With<EditableText>>,
    mut focus_states: Query<&mut FocusState>,
) {
    set_focus_state(&mut focus_states, ev.entity, false);
    emit_focus_event(&bridge, &editables, ev.entity, "blur");
}

/// Set a node's [`FocusState`] (if it has one), nudging change-detection only when
/// the value actually flips so `apply_interaction_styles` re-merges just on change.
fn set_focus_state(focus_states: &mut Query<&mut FocusState>, entity: Entity, focused: bool) {
    if let Ok(mut state) = focus_states.get_mut(entity)
        && state.0 != focused
    {
        state.0 = focused;
    }
}

fn emit_focus_event(
    bridge: &JsBridge,
    editables: &Query<&RNode, With<EditableText>>,
    entity: Entity,
    kind: &str,
) {
    let Ok(rnode) = editables.get(entity) else {
        return;
    };
    if !bridge.editable_focus_handlers.contains(&rnode.0) {
        return;
    }
    let _ = bridge.outbound_tx.send(Outbound::UiEvent {
        event: UiEvent {
            id: rnode.0,
            kind: kind.to_string(),
            ..default()
        },
    });
}

/// Apply controlled selections queued by [`queue_pending_selection`] to the live
/// `EditableText`. Runs after Bevy's text-edit pass so offsets resolve against the
/// text applied this frame. Pre-writes the last-emitted selection so the
/// `TextEditChange` this triggers doesn't echo back to JS as a `"select"`.
pub fn apply_pending_selections(
    mut bridge: ResMut<JsBridge>,
    mut editables: Query<&mut EditableText>,
    mut font_cx: ResMut<FontCx>,
    mut layout_cx: ResMut<LayoutCx>,
) {
    if bridge.editable_pending_selection.is_empty() {
        return;
    }
    let pending: Vec<(NodeId, (usize, usize))> =
        bridge.editable_pending_selection.drain().collect();
    for (id, (start, end)) in pending {
        let Some(&entity) = bridge.nodes.get(&id) else {
            continue;
        };
        let Ok(mut editable) = editables.get_mut(entity) else {
            continue;
        };
        // Suppress the echoed `"select"` (anchor=start, focus=end after the write).
        bridge.editable_selections.insert(id, (start, end));
        editable
            .editor_mut()
            .driver(&mut font_cx.context, &mut layout_cx.0)
            .select_byte_range(start, end);
    }
}

/// Keep each `editableText`'s accessibility node's value in step with its text, so
/// screen readers announce the current content. Label/role are set on spawn (and
/// the label refreshed on update) in [`apply_js_ops`].
pub fn sync_editable_a11y(
    mut q: Query<(&EditableText, &mut AccessibilityNode), Changed<EditableText>>,
) {
    for (editable, mut node) in &mut q {
        node.set_value(editable.value().to_string());
    }
}

/// The mouse buttons the pointer pipeline reports, paired with their DOM
/// `MouseEvent.button` numbers (`0`/`1`/`2` = left/middle/right — the same set
/// bevy_picking forwards; Back/Forward/Other stay ignored).
const POINTER_BUTTONS: [(MouseButton, u8); 3] = [
    (MouseButton::Left, 0),
    (MouseButton::Middle, 1),
    (MouseButton::Right, 2),
];

/// The node currently being dragged (an `onPointer*` element pressed with any
/// mouse button), plus the last cursor positions we read for it — used as a
/// fallback when the cursor leaves the window mid-drag. `button`/`dom_button`
/// are the button that began the drag: move/up track and report it, and any
/// other button pressed mid-drag is ignored (one active drag at a time).
/// `last_pos` is the node-relative `0..1` position; `last_abs` is the absolute
/// window position.
pub struct ActiveDrag {
    entity: Option<Entity>,
    button: MouseButton,
    dom_button: u8,
    last_pos: Vec2,
    last_abs: Vec2,
}

impl Default for ActiveDrag {
    fn default() -> Self {
        Self {
            entity: None,
            button: MouseButton::Left,
            dom_button: 0,
            last_pos: Vec2::ZERO,
            last_abs: Vec2::ZERO,
        }
    }
}

/// Drive native pointer/drag events for elements that declared `onPointer*`
/// handlers. Unlike the discrete click path, this follows the cursor across
/// frames so a dragged control (e.g. a slider) keeps updating even when the
/// pointer leaves its bounds — `RelativeCursorPosition` keeps reporting while the
/// cursor is anywhere in the window, and we clamp to `0..1`. Any mouse button
/// starts a drag and is reported on its events ([`ActiveDrag::button`] — one
/// drag at a time, keyed to the button that began it).
///
/// `RelativeCursorPosition::normalized` is centered (`-0.5` = left/top edge,
/// `0.5` = right/bottom); we shift it to a `0..1` top-left origin to match the
/// CSS-like coordinates the JS handlers expect.
pub fn collect_pointer_events(
    bridge: Res<JsBridge>,
    buttons: Res<ButtonInput<MouseButton>>,
    windows: Query<&Window>,
    nodes: Query<(
        Entity,
        &RNode,
        &Interaction,
        &RelativeCursorPosition,
        &PointerHandlers,
    )>,
    interactions: Query<&Interaction>,
    mut capture: ResMut<crate::PointerCapture>,
    mut drag: Local<ActiveDrag>,
) {
    let emit = |rnode: &RNode, kind: &str, pos: Vec2, abs: Vec2, button: u8| {
        let _ = bridge.outbound_tx.send(Outbound::UiEvent {
            event: UiEvent {
                id: rnode.0,
                kind: kind.to_string(),
                x: Some(pos.x),
                y: Some(pos.y),
                client_x: Some(abs.x),
                client_y: Some(abs.y),
                button: Some(button),
                ..default()
            },
        });
    };

    // Absolute cursor position in window logical pixels; `None` when the cursor
    // is outside the window (mid-drag), where we fall back to the last reading.
    let cursor_abs = windows.iter().next().and_then(|w| w.cursor_position());

    // Begin a drag on the frame any button goes down over a handler node.
    if drag.entity.is_none() {
        'begin: for (mb, dom) in POINTER_BUTTONS {
            if !buttons.just_pressed(mb) {
                continue;
            }
            for (entity, rnode, interaction, rel, handlers) in &nodes {
                let over = if mb == MouseButton::Left {
                    // `ui_focus_system` attributes left presses for us (it
                    // honors `FocusPolicy` blocking).
                    *interaction == Interaction::Pressed
                } else {
                    // Other buttons never set `Pressed`: use this frame's hover
                    // attribution (same blocking rules) plus the geometric
                    // over-test, which rejects a stale sticky `Pressed` left
                    // behind by a left-drag that exited the node.
                    *interaction != Interaction::None && rel.cursor_over()
                };
                if over {
                    let pos = normalized_01(rel).unwrap_or(drag.last_pos);
                    let abs = cursor_abs.unwrap_or(drag.last_abs);
                    drag.entity = Some(entity);
                    drag.button = mb;
                    drag.dom_button = dom;
                    drag.last_pos = pos;
                    drag.last_abs = abs;
                    if handlers.down {
                        emit(rnode, "pointerDown", pos, abs, dom);
                    }
                    break 'begin;
                }
            }
        }
    }

    // While the initiating button is held, follow the cursor and emit move
    // events (a drag).
    if buttons.pressed(drag.button)
        && let Some(entity) = drag.entity
        && let Ok((_, rnode, _, rel, handlers)) = nodes.get(entity)
    {
        let pos = normalized_01(rel).unwrap_or(drag.last_pos);
        let abs = cursor_abs.unwrap_or(drag.last_abs);
        drag.last_pos = pos;
        drag.last_abs = abs;
        if handlers.moved {
            emit(rnode, "pointerMove", pos, abs, drag.dom_button);
        }
    }

    // End the drag when the initiating button is released.
    if buttons.just_released(drag.button)
        && let Some(entity) = drag.entity.take()
        && let Ok((_, rnode, _, rel, handlers)) = nodes.get(entity)
    {
        let pos = normalized_01(rel).unwrap_or(drag.last_pos);
        let abs = cursor_abs.unwrap_or(drag.last_abs);
        if handlers.up {
            emit(rnode, "pointerUp", pos, abs, drag.dom_button);
        }
    }

    // Publish whether the UI owns the pointer so world systems (e.g. a camera
    // controller) can ignore the mouse. `dragging` spans the whole gesture even
    // once the cursor leaves the element; `over_ui` covers hover/press on any
    // interactive node (so e.g. wheel-zoom over UI can be trapped too).
    capture.dragging = drag.entity.is_some();
    capture.over_ui = interactions.iter().any(|i| *i != Interaction::None);
}

/// Emit `pointerEnter` / `pointerLeave` for main-window nodes that declared those
/// handlers. Hover in/out is the `Interaction` `None`↔(`Hovered`|`Pressed`) boundary
/// — the same signal that drives hover *styling* ([`apply_interaction_styles`]) — so
/// this lands on the right node via `FocusPolicy` (a `<button>`, not its child text)
/// with no ancestor climbing. Per-node [`HoverState`] remembers whether the pointer
/// was inside, so a click's `Hovered`↔`Pressed` transition never re-fires enter/leave.
#[allow(clippy::type_complexity)]
pub fn collect_hover_events(
    bridge: Res<JsBridge>,
    windows: Query<&Window>,
    mut nodes: Query<
        (
            &Interaction,
            &mut HoverState,
            &PointerHandlers,
            &RNode,
            Option<&RelativeCursorPosition>,
        ),
        Changed<Interaction>,
    >,
) {
    let cursor_abs = windows.iter().next().and_then(|w| w.cursor_position());
    for (interaction, mut hover, handlers, rnode, rel) in &mut nodes {
        let inside = *interaction != Interaction::None;
        if inside == hover.0 {
            continue; // A `Hovered`↔`Pressed` change, not a boundary crossing.
        }
        hover.0 = inside;
        let kind = if inside {
            "pointerEnter"
        } else {
            "pointerLeave"
        };
        if (inside && handlers.enter) || (!inside && handlers.leave) {
            let pos = rel.and_then(normalized_01).unwrap_or(Vec2::ZERO);
            let abs = cursor_abs.unwrap_or(Vec2::ZERO);
            send_ui_event(&bridge, rnode.0, kind, Some(pos), Some(abs), None);
        }
    }
}

/// Shift `RelativeCursorPosition`'s centered, unclamped position to a clamped
/// `0..1` top-left-origin coordinate. `None` when the cursor position is unknown.
fn normalized_01(rel: &RelativeCursorPosition) -> Option<Vec2> {
    rel.normalized
        .map(|n| Vec2::new((n.x + 0.5).clamp(0.0, 1.0), (n.y + 0.5).clamp(0.0, 1.0)))
}

/// Re-apply the merged style for any element with [`StyleVariants`] whose
/// `Interaction` or `FocusState` changed (hover/press/focus in or out) — or whose
/// variants changed from a React re-render. The interaction axis: `None` → base,
/// `Hovered` → base+hover, `Pressed` → base+hover+press; then `focus` overlays last
/// (so an explicit `focusStyle` wins on conflicting fields). Both `Interaction` and
/// `FocusState` are optional — a focus-only `editableText` has no `Interaction`, and
/// a hover-only node has no `FocusState`. Runs entirely on the Bevy side: no
/// round-trip to JS, no React re-render on mouse move or focus change.
#[allow(clippy::type_complexity)]
pub fn apply_interaction_styles(
    mut commands: Commands,
    query: Query<
        (
            Entity,
            Option<&Interaction>,
            Option<&FocusState>,
            &StyleVariants,
        ),
        Or<(
            Changed<Interaction>,
            Changed<FocusState>,
            Changed<StyleVariants>,
        )>,
    >,
) {
    for (entity, interaction, focus, variants) in &query {
        let mut style = match interaction {
            Some(Interaction::Pressed) => overlay_style(
                &overlay_style(&variants.base, &variants.hover),
                &variants.press,
            ),
            Some(Interaction::Hovered) => overlay_style(&variants.base, &variants.hover),
            _ => variants.base.clone(),
        };
        if focus.is_some_and(|f| f.0) {
            style = overlay_style(&style, &variants.focus);
        }
        apply_style(&mut commands.entity(entity), &style);
    }
}

/// Send one [`Outbound::UiEvent`] to the JS thread for a reconciler node.
fn send_ui_event(
    bridge: &JsBridge,
    id: NodeId,
    kind: &str,
    pos: Option<Vec2>,
    abs: Option<Vec2>,
    button: Option<u8>,
) {
    let _ = bridge.outbound_tx.send(Outbound::UiEvent {
        event: UiEvent {
            id,
            kind: kind.to_string(),
            x: pos.map(|p| p.x),
            y: pos.map(|p| p.y),
            client_x: abs.map(|a| a.x),
            client_y: abs.map(|a| a.y),
            button,
            ..default()
        },
    });
}

/// DOM `MouseEvent.button` number for a picking button (`0`/`1`/`2` =
/// left/middle/right — bevy_picking never forwards Back/Forward/Other).
fn dom_button(button: PointerButton) -> u8 {
    match button {
        PointerButton::Primary => 0,
        PointerButton::Middle => 1,
        PointerButton::Secondary => 2,
    }
}

/// Node-relative `0..1` position (top-left origin) of a surface-space pixel
/// `position` within a node, plus that absolute surface pixel as the client coord.
/// `None` when the point can't be normalized (degenerate node).
fn surface_relative(
    node: &ComputedNode,
    transform: &UiGlobalTransform,
    position: Vec2,
) -> Option<(Vec2, Vec2)> {
    node.normalize_point(*transform, position).map(|n| {
        (
            Vec2::new((n.x + 0.5).clamp(0.0, 1.0), (n.y + 0.5).clamp(0.0, 1.0)),
            position,
        )
    })
}

/// Walk up the `ChildOf` chain from `entity` (inclusive) to the nearest entity that
/// satisfies `is_target`. Surface picking hits the topmost leaf node (e.g. a `<text>`
/// inside a `<button>`); this resolves it to the node that actually owns the
/// interaction — mirroring how the legacy focus system attributes to the nearest
/// `Interaction` node. Stops at the (detached) surface root when nothing matches.
pub(crate) fn climb(
    mut entity: Entity,
    child_of: &Query<&ChildOf>,
    is_target: impl Fn(Entity) -> bool,
) -> Option<Entity> {
    loop {
        if is_target(entity) {
            return Some(entity);
        }
        entity = child_of.get(entity).ok()?.parent();
    }
}

/// Report `<surface>` clicks to JS. The in-world picking path drives a virtual
/// pointer ([`SurfaceVirtualPointer`]) over the offscreen subtree, so a click on a
/// surface node arrives as a `Pointer<Click>` for that pointer — the analogue of
/// [`collect_ui_events`] for surfaces (whose nodes never get a legacy `Interaction`
/// press, since they don't render to a window), primary-button-only like it too.
/// Scoped to the surface pointer id so it never double-fires for main-window UI.
pub fn collect_surface_clicks(
    bridge: Res<JsBridge>,
    pointer: Option<Res<SurfaceVirtualPointer>>,
    mut clicks: MessageReader<Pointer<Click>>,
    // Only `Interaction`-bearing nodes own a click (a `<button>` gets one via `Button`;
    // a `<text>` child does not) — matching the legacy `collect_ui_events` attribution.
    targets: Query<&RNode, With<Interaction>>,
    child_of: Query<&ChildOf>,
) {
    let Some(pointer) = pointer else { return };
    // A pass-through node stacked over the target makes one gesture fan out to
    // every entity in the hover map; climbing can resolve them to the same
    // owner, so dedupe per owner within the frame.
    let mut seen: HashSet<Entity> = HashSet::new();
    for ev in clicks.read() {
        // Like DOM `click` (and `collect_ui_events`), only the primary button
        // clicks; right/middle ride the `onPointer*` events.
        if ev.pointer_id != pointer.id || ev.button != PointerButton::Primary {
            continue;
        }
        // Resolve the picked leaf to the nearest interactive ancestor (the button),
        // so a click on its label text still fires the button's handler.
        if let Some(target) = climb(ev.entity, &child_of, |e| targets.contains(e))
            && seen.insert(target)
            && let Ok(rnode) = targets.get(target)
        {
            debug!("surface click -> reconciler node {}", rnode.0);
            send_ui_event(&bridge, rnode.0, "click", None, None, None);
        }
    }
}

/// Report `onPointer*` drag events for `<surface>` nodes, mirroring
/// [`collect_pointer_events`] for the in-world picking path. Press → `pointerDown`,
/// drag → `pointerMove`, release → `pointerUp`, each gated on the node's declared
/// [`PointerHandlers`], carrying the cursor's node-relative `0..1` position
/// (the surface-space pixel as `client_x/y`) and the mouse button (a `Drag`'s
/// button is the one doing the dragging).
#[allow(clippy::too_many_arguments)]
pub fn collect_surface_pointer_events(
    bridge: Res<JsBridge>,
    pointer: Option<Res<SurfaceVirtualPointer>>,
    mut presses: MessageReader<Pointer<Press>>,
    mut releases: MessageReader<Pointer<Release>>,
    mut drags: MessageReader<Pointer<Drag>>,
    nodes: Query<(&RNode, &PointerHandlers, &ComputedNode, &UiGlobalTransform)>,
    child_of: Query<&ChildOf>,
) {
    let Some(pointer) = pointer else { return };
    // Per-kind (owner, button) dedupe: a pass-through node stacked over the
    // target fans each gesture out to every hovered entity, and climbing can
    // resolve them to the same owner. (Moves see at most one `Drag` per button
    // per frame — `drive_surface_pointer` emits one `Move` per frame — so the
    // set never suppresses a genuine repeat.)
    let mut seen: HashSet<(Entity, PointerButton)> = HashSet::new();
    let emit = |entity: Entity,
                want: fn(&PointerHandlers) -> bool,
                kind: &str,
                at: Vec2,
                button: PointerButton,
                seen: &mut HashSet<(Entity, PointerButton)>| {
        // Resolve the picked leaf to the nearest ancestor that declared `onPointer*`.
        if let Some(target) = climb(entity, &child_of, |e| nodes.contains(e))
            && seen.insert((target, button))
            && let Ok((rnode, handlers, node, transform)) = nodes.get(target)
            && want(handlers)
            && let Some((pos, abs)) = surface_relative(node, transform, at)
        {
            send_ui_event(
                &bridge,
                rnode.0,
                kind,
                Some(pos),
                Some(abs),
                Some(dom_button(button)),
            );
        }
    };
    for ev in presses.read() {
        if ev.pointer_id == pointer.id {
            emit(
                ev.entity,
                |h| h.down,
                "pointerDown",
                ev.pointer_location.position,
                ev.button,
                &mut seen,
            );
        }
    }
    seen.clear();
    for ev in drags.read() {
        if ev.pointer_id == pointer.id {
            emit(
                ev.entity,
                |h| h.moved,
                "pointerMove",
                ev.pointer_location.position,
                ev.button,
                &mut seen,
            );
        }
    }
    seen.clear();
    for ev in releases.read() {
        if ev.pointer_id == pointer.id {
            emit(
                ev.entity,
                |h| h.up,
                "pointerUp",
                ev.pointer_location.position,
                ev.button,
                &mut seen,
            );
        }
    }
}

/// Report `pointerEnter` / `pointerLeave` for `<surface>` nodes, mirroring
/// [`collect_surface_pointer_events`] for the hover boundary. Surface nodes get no
/// legacy `Interaction`, so this reads the virtual pointer's `Pointer<Enter>` /
/// `Pointer<Leave>` picking events. Those already implement DOM
/// `mouseenter`/`mouseleave` semantics — they fire for the hovered entity *and*
/// its ancestors, only on true boundary crossings — so no climb (and no dedupe)
/// is needed, and crossing between a button's label and its padding never
/// re-fires the button's boundary. Hover events carry no button.
pub fn collect_surface_hover_events(
    bridge: Res<JsBridge>,
    pointer: Option<Res<SurfaceVirtualPointer>>,
    mut enters: MessageReader<Pointer<Enter>>,
    mut leaves: MessageReader<Pointer<Leave>>,
    nodes: Query<(&RNode, &PointerHandlers, &ComputedNode, &UiGlobalTransform)>,
) {
    let Some(pointer) = pointer else { return };
    let emit = |entity: Entity, want: fn(&PointerHandlers) -> bool, kind: &str, at: Vec2| {
        if let Ok((rnode, handlers, node, transform)) = nodes.get(entity)
            && want(handlers)
            && let Some((pos, abs)) = surface_relative(node, transform, at)
        {
            send_ui_event(&bridge, rnode.0, kind, Some(pos), Some(abs), None);
        }
    };
    for ev in enters.read() {
        if ev.pointer_id == pointer.id {
            emit(
                ev.entity,
                |h| h.enter,
                "pointerEnter",
                ev.pointer_location.position,
            );
        }
    }
    for ev in leaves.read() {
        if ev.pointer_id == pointer.id {
            emit(
                ev.entity,
                |h| h.leave,
                "pointerLeave",
                ev.pointer_location.position,
            );
        }
    }
}

/// Apply hover/press [`StyleVariants`] to `<surface>` nodes from the in-world
/// picking path — the surface-side analogue of [`apply_interaction_styles`], which
/// can't help here because surface nodes never receive a legacy `Interaction`
/// (their offscreen camera makes `ui_focus_system` skip them). Enter →
/// base+hover, press → base+hover+press, leave/release → base/hover. The hover
/// axis rides `Pointer<Enter>`/`Pointer<Leave>` (boundary-only, ancestor-aware —
/// see [`collect_surface_hover_events`]); the press axis keeps `Press`/`Release`
/// with the climb, filtered to the primary button so a right/middle press
/// doesn't trigger `pressStyle` (DOM `:active` parity with the main window's
/// `Interaction::Pressed`).
#[allow(clippy::too_many_arguments)]
pub fn apply_surface_interaction_styles(
    mut commands: Commands,
    pointer: Option<Res<SurfaceVirtualPointer>>,
    mut enters: MessageReader<Pointer<Enter>>,
    mut leaves: MessageReader<Pointer<Leave>>,
    mut presses: MessageReader<Pointer<Press>>,
    mut releases: MessageReader<Pointer<Release>>,
    variants: Query<&StyleVariants>,
    child_of: Query<&ChildOf>,
) {
    let Some(pointer) = pointer else { return };
    let mut restyle = |entity: Entity, style: Option<Style>| {
        apply_style(&mut commands.entity(entity), &style);
    };
    // Resolve a picked leaf to the nearest ancestor with hover/press variants (the
    // button), so its label text highlights the button rather than nothing.
    let target = |entity: Entity| climb(entity, &child_of, |e| variants.contains(e));
    for ev in leaves.read() {
        if ev.pointer_id == pointer.id
            && let Ok(v) = variants.get(ev.entity)
        {
            restyle(ev.entity, v.base.clone());
        }
    }
    for ev in enters.read() {
        if ev.pointer_id == pointer.id
            && let Ok(v) = variants.get(ev.entity)
        {
            restyle(ev.entity, overlay_style(&v.base, &v.hover));
        }
    }
    for ev in releases.read() {
        if ev.pointer_id == pointer.id
            && ev.button == PointerButton::Primary
            && let Some(t) = target(ev.entity)
            && let Ok(v) = variants.get(t)
        {
            restyle(t, overlay_style(&v.base, &v.hover));
        }
    }
    for ev in presses.read() {
        if ev.pointer_id == pointer.id
            && ev.button == PointerButton::Primary
            && let Some(t) = target(ev.entity)
            && let Ok(v) = variants.get(t)
        {
            let pressed = overlay_style(&overlay_style(&v.base, &v.hover), &v.press);
            restyle(t, pressed);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bridge::JsBridge;
    use crate::transition::TransitionInput;
    use std::f32::consts::PI;

    // Pass rotate as an explicit `rad` string so the asserted radian value is
    // carried verbatim (a bare number would be read as degrees).
    fn text_props(rotate: f32) -> Props {
        serde_json::from_value(serde_json::json!({
            "style": {
                "transform": { "rotate": format!("{rotate}rad") },
                "transition": { "transform": { "duration": 0.3 } },
            }
        }))
        .expect("valid text props")
    }

    /// A delta update: only the supplied fields are touched.
    fn update_delta(id: NodeId, props: Props, unset: &[&str], style_unset: &[&str]) -> Op {
        Op::Update {
            id,
            props,
            unset: unset.iter().map(|s| s.to_string()).collect(),
            style_unset: style_unset.iter().map(|s| s.to_string()).collect(),
        }
    }

    /// Spin up a minimal app wired to `apply_js_ops`, returning the app and the
    /// op sender (the outbound receiver is leaked to keep the sender open).
    fn op_app() -> (App, crossbeam_channel::Sender<Vec<Op>>) {
        let mut app = App::new();
        app.add_plugins((MinimalPlugins, AssetPlugin::default()));
        app.init_asset::<Image>();
        app.init_asset::<TextureAtlasLayout>();
        app.init_resource::<Fonts>();
        app.init_resource::<OpApplyStats>();
        app.init_resource::<AtlasLayoutCache>();
        // `apply_js_ops` reads the `filter` material assets/cache + white pixel.
        app.init_asset::<FilterMaterial>();
        app.init_resource::<FilterMaterialCache>();
        app.add_systems(Startup, crate::filter::init_filter_assets);

        let (ops_tx, ops_rx) = crossbeam_channel::unbounded::<Vec<Op>>();
        let (out_tx, out_rx) = tokio::sync::mpsc::unbounded_channel::<Outbound>();
        std::mem::forget(out_rx); // keep the channel open for the test's lifetime
        let root = app.world_mut().spawn_empty().id();
        app.insert_resource(JsBridge::new(ops_rx, out_tx, root));
        app.add_systems(Update, apply_js_ops);
        (app, ops_tx)
    }

    /// A plain `<node onClick>` — no hover/press style, not a `<button>` — must get
    /// an `Interaction` so [`collect_ui_events`] can report its clicks. Regression:
    /// `onClick` crossed the wire as a bool but nothing attached an `Interaction`,
    /// so such a node was silently unclickable (only a `<button>`, or a node that
    /// also had a hover/press style or an `onPointer*` handler, worked).
    #[test]
    fn node_onclick_attaches_interaction() {
        let (mut app, ops_tx) = op_app();

        ops_tx
            .send(vec![
                // 1: a bare onClick node — the case that was broken.
                Op::Create {
                    id: 1,
                    kind: "node".into(),
                    props: serde_json::from_value(serde_json::json!({ "onClick": true })).unwrap(),
                    text: None,
                },
                // 2: a node with no interaction props at all — must stay inert.
                Op::Create {
                    id: 2,
                    kind: "node".into(),
                    props: Props::default(),
                    text: None,
                },
            ])
            .unwrap();
        app.update();

        let nodes = &app.world().resource::<JsBridge>().nodes;
        let (clickable, inert) = (nodes[&1], nodes[&2]);
        assert!(
            app.world().entity(clickable).get::<Interaction>().is_some(),
            "`onClick` alone must make a <node> clickable"
        );
        assert!(
            app.world().entity(inert).get::<Interaction>().is_none(),
            "a node with no handlers/hover/press must not gain an Interaction"
        );
    }

    /// A node with `onPointerEnter`/`onPointerLeave` gets an `Interaction` + a
    /// [`HoverState`], and the reconciler stamps the handler flags.
    #[test]
    fn pointer_enter_leave_stamps_hover_state() {
        let (mut app, ops_tx) = op_app();
        ops_tx
            .send(vec![Op::Create {
                id: 1,
                kind: "node".into(),
                props: serde_json::from_value(
                    serde_json::json!({ "onPointerEnter": true, "onPointerLeave": true }),
                )
                .unwrap(),
                text: None,
            }])
            .unwrap();
        app.update();

        let e = app.world().resource::<JsBridge>().nodes[&1];
        let entity = app.world().entity(e);
        assert!(
            entity.get::<Interaction>().is_some(),
            "hover handlers must make the node interactive"
        );
        assert!(
            entity.get::<HoverState>().is_some(),
            "hover handlers must stamp a HoverState"
        );
        let handlers = entity.get::<PointerHandlers>().expect("PointerHandlers");
        assert!(handlers.enter && handlers.leave);
    }

    /// [`collect_hover_events`] emits `pointerEnter` on the first non-`None`
    /// interaction and `pointerLeave` on the return to `None`, and must NOT re-fire
    /// on the `Hovered`↔`Pressed` transition of a click (guarded by [`HoverState`]).
    #[test]
    fn hover_events_fire_on_boundary_only() {
        let mut app = App::new();
        app.add_plugins(MinimalPlugins);
        let (out_tx, mut out_rx) = tokio::sync::mpsc::unbounded_channel::<Outbound>();
        let (_ops_tx, ops_rx) = crossbeam_channel::unbounded::<Vec<Op>>();
        let root = app.world_mut().spawn_empty().id();
        app.insert_resource(JsBridge::new(ops_rx, out_tx, root));
        app.add_systems(Update, collect_hover_events);

        let e = app
            .world_mut()
            .spawn((
                Interaction::None,
                HoverState(false),
                PointerHandlers {
                    enter: true,
                    leave: true,
                    ..default()
                },
                RNode(1),
            ))
            .id();

        let set = |app: &mut App, i: Interaction| {
            *app.world_mut()
                .entity_mut(e)
                .get_mut::<Interaction>()
                .unwrap() = i;
            app.update();
        };

        app.update(); // Mount frame: still "outside" (None) → no event.
        set(&mut app, Interaction::Hovered); // None → Hovered: enter.
        set(&mut app, Interaction::Pressed); // Hovered → Pressed: no re-enter.
        set(&mut app, Interaction::None); // Pressed → None: leave.

        let kinds: Vec<String> = std::iter::from_fn(|| out_rx.try_recv().ok())
            .map(|o| match o {
                Outbound::UiEvent { event } => {
                    assert_eq!(event.id, 1);
                    event.kind
                }
                other => panic!("expected a UiEvent, got {other:?}"),
            })
            .collect();
        assert_eq!(kinds, vec!["pointerEnter", "pointerLeave"]);
    }

    /// `FocusPolicy` defaults differ by element kind: a `<button>` captures the
    /// pointer (`Block`, mirroring bevy_ui's native `Button`), while a `<node>`
    /// passes it through (`Pass`), so a container/label never swallows clicks meant
    /// for what's behind it. An explicit `focusPolicy` prop overrides either, and
    /// re-rendering a button keeps its `Block` (the per-commit `apply_style` resets
    /// it to `Pass` first).
    #[test]
    fn focus_policy_defaults_block_button_pass_node() {
        let (mut app, ops_tx) = op_app();

        let node_props =
            |json: serde_json::Value| -> Props { serde_json::from_value(json).unwrap() };
        ops_tx
            .send(vec![
                // 1: bare button → Block default.
                Op::Create {
                    id: 1,
                    kind: "button".into(),
                    props: Props::default(),
                    text: None,
                },
                // 2: bare node → Pass default.
                Op::Create {
                    id: 2,
                    kind: "node".into(),
                    props: Props::default(),
                    text: None,
                },
                // 3: button with explicit focusPolicy "pass" → overrides the default.
                Op::Create {
                    id: 3,
                    kind: "button".into(),
                    props: node_props(serde_json::json!({ "style": { "focusPolicy": "pass" } })),
                    text: None,
                },
            ])
            .unwrap();
        app.update();

        let fp = |app: &App, id: u32| -> Option<FocusPolicy> {
            let e = app.world().resource::<JsBridge>().nodes[&id];
            app.world().entity(e).get::<FocusPolicy>().copied()
        };
        // The picking mirror: `Pickable.should_block_lower` must track the policy,
        // because the picking backend (which clicks and all `<surface>` interaction
        // ride) ignores `FocusPolicy` and blocks when `Pickable` is absent.
        let blocks = |app: &App, id: u32| -> Option<bool> {
            let e = app.world().resource::<JsBridge>().nodes[&id];
            app.world()
                .entity(e)
                .get::<bevy::picking::Pickable>()
                .map(|p| p.should_block_lower)
        };
        assert_eq!(
            fp(&app, 1),
            Some(FocusPolicy::Block),
            "button defaults to Block"
        );
        assert_eq!(blocks(&app, 1), Some(true), "button blocks picking too");
        assert_eq!(
            fp(&app, 2),
            Some(FocusPolicy::Pass),
            "node defaults to Pass"
        );
        assert_eq!(blocks(&app, 2), Some(false), "node passes picking too");
        assert_eq!(
            fp(&app, 3),
            Some(FocusPolicy::Pass),
            "explicit focusPolicy overrides the button default"
        );
        assert_eq!(
            blocks(&app, 3),
            Some(false),
            "explicit pass unblocks picking on a button"
        );

        // A delta that dirties the FOCUS_POLICY group (unsetting the — already
        // absent — `focusPolicy` field) makes `apply_style` reset the bare
        // button to `Pass`; the button default must be re-asserted so it stays
        // `Block`. (A delta touching nothing wouldn't run the group at all.)
        ops_tx
            .send(vec![update_delta(
                1,
                Props::default(),
                &[],
                &["focusPolicy"],
            )])
            .unwrap();
        app.update();
        assert_eq!(
            fp(&app, 1),
            Some(FocusPolicy::Block),
            "a re-rendered button keeps its Block default"
        );
        assert_eq!(
            blocks(&app, 1),
            Some(true),
            "a re-rendered button keeps blocking picking"
        );
    }

    /// A synthetic picking `Pointer<Click>` location: the render target is
    /// irrelevant to the collectors, so a default image handle stands in.
    fn click_location() -> bevy::picking::pointer::Location {
        bevy::picking::pointer::Location {
            target: bevy::camera::NormalizedRenderTarget::Image(Handle::<Image>::default().into()),
            position: Vec2::ZERO,
        }
    }

    /// A minimal app wired for the picking-based click collectors: a `JsBridge`
    /// (with its outbound receiver kept alive) + `Pointer<Click>` messages.
    fn click_app() -> (App, tokio::sync::mpsc::UnboundedReceiver<Outbound>) {
        let mut app = App::new();
        app.add_plugins(MinimalPlugins);
        let (out_tx, out_rx) = tokio::sync::mpsc::unbounded_channel::<Outbound>();
        let (_ops_tx, ops_rx) = crossbeam_channel::unbounded::<Vec<Op>>();
        std::mem::forget(_ops_tx); // Keep the ops channel open for the app's lifetime.
        let root = app.world_mut().spawn_empty().id();
        app.insert_resource(JsBridge::new(ops_rx, out_tx, root));
        app.add_message::<Pointer<Click>>();
        (app, out_rx)
    }

    fn drain_clicks(out_rx: &mut tokio::sync::mpsc::UnboundedReceiver<Outbound>) -> Vec<UiEvent> {
        std::iter::from_fn(|| out_rx.try_recv().ok())
            .map(|o| match o {
                Outbound::UiEvent { event } => event,
                other => panic!("expected a UiEvent, got {other:?}"),
            })
            .collect()
    }

    /// [`collect_ui_events`] rides `Pointer<Click>`: only the primary button
    /// clicks (right/middle are the `onPointer*` events' job), a click on a
    /// node's leaf (label) climbs to the `Interaction`-bearing owner, and the
    /// multi-pick fan-out (leaf + owner both hovered) dedupes to ONE event.
    #[test]
    fn picking_click_fires_once_primary_only() {
        let (mut app, mut out_rx) = click_app();
        app.add_systems(Update, collect_ui_events);

        let owner = app.world_mut().spawn((RNode(1), Interaction::None)).id();
        let leaf = app.world_mut().spawn(ChildOf(owner)).id();

        let click = |entity, button| {
            Pointer::new(
                PointerId::Mouse,
                click_location(),
                Click {
                    button,
                    hit: bevy::picking::backend::HitData::new(Entity::PLACEHOLDER, 0.0, None, None),
                    duration: std::time::Duration::ZERO,
                    count: 1,
                },
                entity,
            )
        };
        // A right click must be ignored entirely…
        app.world_mut()
            .write_message(click(leaf, PointerButton::Secondary));
        // …while a primary gesture fans out to every hovered entity (leaf +
        // owner) and must dedupe to one click.
        app.world_mut()
            .write_message(click(leaf, PointerButton::Primary));
        app.world_mut()
            .write_message(click(owner, PointerButton::Primary));
        app.update();

        let events = drain_clicks(&mut out_rx);
        assert_eq!(
            events.len(),
            1,
            "secondary filtered out; leaf + owner primary picks dedupe to one click"
        );
        assert_eq!(events[0].id, 1);
        assert_eq!(events[0].kind, "click");
        assert_eq!(
            events[0].button, None,
            "clicks carry no button (primary implied)"
        );
    }

    /// The surface virtual pointer's clicks belong to [`collect_surface_clicks`]
    /// alone: [`collect_ui_events`] must skip them (no double-fire), and the
    /// surface collector reports exactly one click.
    #[test]
    fn surface_pointer_clicks_are_not_main_clicks() {
        let (mut app, mut out_rx) = click_app();
        app.add_systems(Startup, crate::surface::init_surface_pointer);
        app.add_systems(Update, (collect_ui_events, collect_surface_clicks));
        app.update(); // Run Startup so the pointer resource exists.

        let owner = app.world_mut().spawn((RNode(7), Interaction::None)).id();
        let surface_id = app.world().resource::<SurfaceVirtualPointer>().id;
        app.world_mut().write_message(Pointer::new(
            surface_id,
            click_location(),
            Click {
                button: PointerButton::Primary,
                hit: bevy::picking::backend::HitData::new(Entity::PLACEHOLDER, 0.0, None, None),
                duration: std::time::Duration::ZERO,
                count: 1,
            },
            owner,
        ));
        app.update();

        let events = drain_clicks(&mut out_rx);
        assert_eq!(
            events.len(),
            1,
            "exactly one click: surface-collected, not double-fired by collect_ui_events"
        );
        assert_eq!(events[0].id, 7);
        assert_eq!(events[0].button, None, "clicks carry no button");
    }

    /// A `<text>` root's `transform`/`transition` must update on re-render — not
    /// just at mount. Regression: the text-update branch skipped `apply_style`, so
    /// a rotating chevron's target never changed and the animation never ran.
    #[test]
    fn text_update_reapplies_transform_target() {
        let mut app = App::new();
        app.add_plugins((MinimalPlugins, AssetPlugin::default()));
        app.init_asset::<Image>();
        app.init_asset::<TextureAtlasLayout>();
        app.init_resource::<Fonts>();
        app.init_resource::<OpApplyStats>();
        app.init_resource::<AtlasLayoutCache>();
        // `apply_js_ops` reads the `filter` material assets/cache + white pixel.
        app.init_asset::<FilterMaterial>();
        app.init_resource::<FilterMaterialCache>();
        app.add_systems(Startup, crate::filter::init_filter_assets);

        let (ops_tx, ops_rx) = crossbeam_channel::unbounded::<Vec<Op>>();
        // Keep the outbound receiver alive so the sender stays open.
        let (out_tx, _out_rx) = tokio::sync::mpsc::unbounded_channel::<Outbound>();
        let root = app.world_mut().spawn_empty().id();
        app.insert_resource(JsBridge::new(ops_rx, out_tx, root));
        app.add_systems(Update, apply_js_ops);

        // Mount a `<text>` with rotate 0.
        ops_tx
            .send(vec![Op::Create {
                id: 1,
                kind: "text".into(),
                props: text_props(0.0),
                text: None,
            }])
            .unwrap();
        app.update();
        let e = app.world().resource::<JsBridge>().nodes[&1];
        assert_eq!(
            app.world()
                .entity(e)
                .get::<TransitionInput>()
                .unwrap()
                .rotate,
            Some(0.0),
            "create stamps the initial transform target"
        );

        // Re-render with rotate π — the transition target must follow.
        ops_tx
            .send(vec![update_delta(1, text_props(PI), &[], &[])])
            .unwrap();
        app.update();
        assert_eq!(
            app.world()
                .entity(e)
                .get::<TransitionInput>()
                .unwrap()
                .rotate,
            Some(PI),
            "a text re-render must refresh the transform target so it animates"
        );
    }

    /// Regression: an inline-text nested `<text>` (a `textSpan` carrying its text
    /// on the create op) must keep updating its `TextSpan` on `Op::UpdateText` — it
    /// must never gain a stray `Text` component (which renders a duplicate, leaving
    /// the old value visible alongside the new one).
    #[test]
    fn update_text_on_inline_span_keeps_textspan() {
        let (mut app, ops_tx, _root) = ordering_app();

        ops_tx
            .send(vec![
                // A `<text>` root with a nested inline `<text>{0}</text>` span.
                Op::Create {
                    id: 1,
                    kind: "text".into(),
                    props: Props::default(),
                    text: None,
                },
                Op::Create {
                    id: 2,
                    kind: "textSpan".into(),
                    props: Props::default(),
                    text: Some("0".into()),
                },
                Op::Append {
                    parent: 1,
                    child: 2,
                },
            ])
            .unwrap();
        app.update();

        ops_tx
            .send(vec![Op::UpdateText {
                id: 2,
                text: "1".into(),
            }])
            .unwrap();
        app.update();

        let span = ent(&app, 2);
        assert_eq!(
            app.world().entity(span).get::<TextSpan>().map(|s| &*s.0),
            Some("1"),
            "the span's TextSpan must hold the updated text"
        );
        assert!(
            app.world().entity(span).get::<Text>().is_none(),
            "a span must never gain a Text component (that renders a duplicate)"
        );
    }

    // --- ordered insertion (`Op::Insert` honoring `before`) --------------------

    /// Build a minimal app with `apply_js_ops` wired up and a spawned UI root, plus
    /// the ops sender. Mirrors `text_update_reapplies_transform_target`'s harness.
    fn ordering_app() -> (App, crossbeam_channel::Sender<Vec<Op>>, Entity) {
        let mut app = App::new();
        app.add_plugins((MinimalPlugins, AssetPlugin::default()));
        app.init_asset::<Image>();
        app.init_asset::<TextureAtlasLayout>();
        app.init_resource::<Fonts>();
        app.init_resource::<OpApplyStats>();
        app.init_resource::<AtlasLayoutCache>();
        // `apply_js_ops` reads the `filter` material assets/cache + white pixel.
        app.init_asset::<FilterMaterial>();
        app.init_resource::<FilterMaterialCache>();
        app.add_systems(Startup, crate::filter::init_filter_assets);
        let (ops_tx, ops_rx) = crossbeam_channel::unbounded::<Vec<Op>>();
        let (out_tx, _out_rx) = tokio::sync::mpsc::unbounded_channel::<Outbound>();
        let root = app.world_mut().spawn_empty().id();
        app.insert_resource(JsBridge::new(ops_rx, out_tx, root));
        app.add_systems(Update, apply_js_ops);
        (app, ops_tx, root)
    }

    fn create_node(id: NodeId) -> Op {
        Op::Create {
            id,
            kind: "node".into(),
            props: Props::default(),
            text: None,
        }
    }

    /// The entity a node id resolved to.
    fn ent(app: &App, id: NodeId) -> Entity {
        app.world().resource::<JsBridge>().nodes[&id]
    }

    /// The parent's children, in order.
    fn children_of(app: &App, parent: Entity) -> Vec<Entity> {
        app.world()
            .entity(parent)
            .get::<Children>()
            .map(|c| c.iter().collect())
            .unwrap_or_default()
    }

    /// Append-only construction yields the appended order — and does so within a
    /// single batch, where the live `Children` is not yet readable.
    #[test]
    fn append_builds_child_order() {
        let (mut app, tx, _root) = ordering_app();
        tx.send(vec![
            create_node(1), // parent
            create_node(2),
            create_node(3),
            create_node(4),
            Op::Append {
                parent: ROOT_ID,
                child: 1,
            },
            Op::Append {
                parent: 1,
                child: 2,
            },
            Op::Append {
                parent: 1,
                child: 3,
            },
            Op::Append {
                parent: 1,
                child: 4,
            },
        ])
        .unwrap();
        app.update();

        let parent = ent(&app, 1);
        assert_eq!(
            children_of(&app, parent),
            vec![ent(&app, 2), ent(&app, 3), ent(&app, 4)],
        );
    }

    /// Moving an existing child with `Insert` reorders it (React emits `insertBefore`
    /// with the same id, no preceding remove): `[A,B,C]` + move C before A → `[C,A,B]`.
    #[test]
    fn insert_reorders_existing_child() {
        let (mut app, tx, _root) = ordering_app();
        tx.send(vec![
            create_node(1),
            create_node(2),
            create_node(3),
            create_node(4),
            Op::Append {
                parent: ROOT_ID,
                child: 1,
            },
            Op::Append {
                parent: 1,
                child: 2,
            },
            Op::Append {
                parent: 1,
                child: 3,
            },
            Op::Append {
                parent: 1,
                child: 4,
            },
        ])
        .unwrap();
        app.update();

        // Move C (4) before A (2).
        tx.send(vec![Op::Insert {
            parent: 1,
            child: 4,
            before: 2,
        }])
        .unwrap();
        app.update();

        let parent = ent(&app, 1);
        assert_eq!(
            children_of(&app, parent),
            vec![ent(&app, 4), ent(&app, 2), ent(&app, 3)],
            "C should move to the front: [C, A, B]"
        );
    }

    /// Inserting a brand-new child mid-list lands it at `before`'s position:
    /// `[A,B,C]` + insert D before B → `[A,D,B,C]`.
    #[test]
    fn insert_new_child_in_the_middle() {
        let (mut app, tx, _root) = ordering_app();
        tx.send(vec![
            create_node(1),
            create_node(2),
            create_node(3),
            create_node(4),
            Op::Append {
                parent: ROOT_ID,
                child: 1,
            },
            Op::Append {
                parent: 1,
                child: 2,
            },
            Op::Append {
                parent: 1,
                child: 3,
            },
            Op::Append {
                parent: 1,
                child: 4,
            },
        ])
        .unwrap();
        app.update();

        // New node D (5) inserted before B (3).
        tx.send(vec![
            create_node(5),
            Op::Insert {
                parent: 1,
                child: 5,
                before: 3,
            },
        ])
        .unwrap();
        app.update();

        let parent = ent(&app, 1);
        assert_eq!(
            children_of(&app, parent),
            vec![ent(&app, 2), ent(&app, 5), ent(&app, 3), ent(&app, 4)],
            "D should land before B: [A, D, B, C]"
        );
    }

    /// The regression that motivates the shadow tree: an `Insert` whose `before` was
    /// appended earlier in the SAME batch. The live `Children` can't be read mid-batch
    /// (deferred commands), so the index must come from the shadow order — `[X, Y]`.
    #[test]
    fn insert_orders_within_a_single_batch() {
        let (mut app, tx, _root) = ordering_app();
        tx.send(vec![
            create_node(10), // parent
            create_node(11), // X
            create_node(12), // Y
            Op::Append {
                parent: ROOT_ID,
                child: 10,
            },
            Op::Append {
                parent: 10,
                child: 12,
            }, // Y appended first
            Op::Insert {
                parent: 10,
                child: 11,
                before: 12,
            }, // X inserted before Y, same batch
        ])
        .unwrap();
        app.update();

        let parent = ent(&app, 10);
        assert_eq!(
            children_of(&app, parent),
            vec![ent(&app, 11), ent(&app, 12)],
            "X must precede Y even though Children was unreadable mid-batch"
        );
    }

    /// One batch mixing all three structural ops on the same parent: append a new
    /// child, move an existing one, remove another. The end-of-batch rebuild must
    /// produce the final order in one `replace_children`, with the removed child's
    /// despawn applied first.
    #[test]
    fn mixed_batch_orders_correctly() {
        let (mut app, tx, _root) = ordering_app();
        tx.send(vec![
            create_node(1),
            create_node(2),
            create_node(3),
            create_node(4),
            Op::Append {
                parent: ROOT_ID,
                child: 1,
            },
            Op::Append {
                parent: 1,
                child: 2,
            },
            Op::Append {
                parent: 1,
                child: 3,
            },
            Op::Append {
                parent: 1,
                child: 4,
            },
        ])
        .unwrap();
        app.update();

        // [2,3,4] → append 5 → move 4 before 2 → remove 3 ⇒ [4,2,5].
        tx.send(vec![
            create_node(5),
            Op::Append {
                parent: 1,
                child: 5,
            },
            Op::Insert {
                parent: 1,
                child: 4,
                before: 2,
            },
            Op::Remove {
                parent: 1,
                child: 3,
            },
        ])
        .unwrap();
        app.update();

        let parent = ent(&app, 1);
        assert_eq!(
            children_of(&app, parent),
            vec![ent(&app, 4), ent(&app, 2), ent(&app, 5)],
            "append + move + remove in one batch must land as [4, 2, 5]"
        );
    }

    /// Moving a child to a DIFFERENT parent in one batch: the old `ChildOf` must be
    /// dropped eagerly (the rebuild's `replace_children` skips relationship hooks for
    /// the entities it adds), or the child would linger in the old parent's
    /// `Children`.
    #[test]
    fn move_between_parents_in_one_batch() {
        let (mut app, tx, _root) = ordering_app();
        tx.send(vec![
            create_node(1), // parent A
            create_node(2), // parent B
            create_node(3),
            create_node(4),
            create_node(5),
            Op::Append {
                parent: ROOT_ID,
                child: 1,
            },
            Op::Append {
                parent: ROOT_ID,
                child: 2,
            },
            Op::Append {
                parent: 1,
                child: 3,
            },
            Op::Append {
                parent: 1,
                child: 4,
            },
            Op::Append {
                parent: 2,
                child: 5,
            },
        ])
        .unwrap();
        app.update();

        // Move 3 from A to B (append at B's end).
        tx.send(vec![Op::Append {
            parent: 2,
            child: 3,
        }])
        .unwrap();
        app.update();

        let (a, b) = (ent(&app, 1), ent(&app, 2));
        assert_eq!(
            children_of(&app, a),
            vec![ent(&app, 4)],
            "the moved child must leave the old parent's Children"
        );
        assert_eq!(children_of(&app, b), vec![ent(&app, 5), ent(&app, 3)]);
        assert_eq!(
            app.world()
                .entity(ent(&app, 3))
                .get::<ChildOf>()
                .map(|c| c.parent()),
            Some(b),
            "the moved child's ChildOf must point at the new parent"
        );
    }

    /// The `AnchorLayer` is a Rust-side child of the root, invisible to the shadow
    /// tree — a root rebuild must keep it as the first child instead of stripping
    /// its `ChildOf`.
    #[test]
    fn root_rebuild_preserves_anchor_layer() {
        let (mut app, tx, root) = ordering_app();
        let layer = app
            .world_mut()
            .spawn((crate::anchor::AnchorLayer, ChildOf(root)))
            .id();

        tx.send(vec![
            create_node(1),
            create_node(2),
            Op::Append {
                parent: ROOT_ID,
                child: 1,
            },
            Op::Append {
                parent: ROOT_ID,
                child: 2,
            },
        ])
        .unwrap();
        app.update();
        assert_eq!(
            children_of(&app, root),
            vec![layer, ent(&app, 1), ent(&app, 2)]
        );

        // Reorder the root's reconciler children; the layer must stay first.
        tx.send(vec![Op::Insert {
            parent: ROOT_ID,
            child: 2,
            before: 1,
        }])
        .unwrap();
        app.update();
        assert_eq!(
            children_of(&app, root),
            vec![layer, ent(&app, 2), ent(&app, 1)],
            "the AnchorLayer must survive root rebuilds as the first child"
        );
    }

    /// The leak regression the demos app exposed: a child created and appended in
    /// the SAME batch that removes its (pre-existing) parent. The attach must be
    /// queued per op — if it were deferred to the end-of-batch rebuild (which skips
    /// removed parents), the recursive despawn couldn't reach the child and it would
    /// survive as an orphaned window-UI root.
    #[test]
    fn same_batch_create_under_removed_parent_despawns() {
        let (mut app, tx, _root) = ordering_app();
        tx.send(vec![
            create_node(1),
            Op::Append {
                parent: ROOT_ID,
                child: 1,
            },
        ])
        .unwrap();
        app.update();

        // One batch: grow the subtree, then remove its root.
        tx.send(vec![
            create_node(2),
            Op::Append {
                parent: 1,
                child: 2,
            },
            Op::Remove {
                parent: ROOT_ID,
                child: 1,
            },
        ])
        .unwrap();
        app.update();

        let survivors = app.world_mut().query::<&RNode>().iter(app.world()).count();
        assert_eq!(
            survivors, 0,
            "the same-batch child must be despawned with its removed parent, not \
             leaked as an orphaned root"
        );
    }

    /// Remove + reorder on the same parent in one batch: the dirty rebuild runs with
    /// a despawned ex-child mid-queue and must not resurrect or panic on it.
    #[test]
    fn remove_then_reorder_same_parent() {
        let (mut app, tx, _root) = ordering_app();
        tx.send(vec![
            create_node(1),
            create_node(2),
            create_node(3),
            create_node(4),
            Op::Append {
                parent: ROOT_ID,
                child: 1,
            },
            Op::Append {
                parent: 1,
                child: 2,
            },
            Op::Append {
                parent: 1,
                child: 3,
            },
            Op::Append {
                parent: 1,
                child: 4,
            },
        ])
        .unwrap();
        app.update();

        // [2,3,4] → remove 3, then move 4 before 2 ⇒ [4,2].
        tx.send(vec![
            Op::Remove {
                parent: 1,
                child: 3,
            },
            Op::Insert {
                parent: 1,
                child: 4,
                before: 2,
            },
        ])
        .unwrap();
        app.update();

        let parent = ent(&app, 1);
        assert_eq!(children_of(&app, parent), vec![ent(&app, 4), ent(&app, 2)]);
    }

    /// A `<portal>` mounts to an `ImageNode` carrying an `RPortal` with its target
    /// name; an update rebinds the name.
    #[test]
    fn portal_mounts_with_target_and_rebinds() {
        use crate::portal::RPortal;
        use bevy::ui::widget::ImageNode;
        let (mut app, tx, _root) = ordering_app();
        tx.send(vec![Op::Create {
            id: 1,
            kind: "portal".into(),
            props: serde_json::from_value(serde_json::json!({ "target": "follow" }))
                .expect("valid portal props"),
            text: None,
        }])
        .unwrap();
        app.update();

        let e = ent(&app, 1);
        assert_eq!(
            app.world().entity(e).get::<RPortal>().map(|p| p.0.clone()),
            Some("follow".to_string()),
            "a portal carries its target name"
        );
        assert!(
            app.world().entity(e).get::<ImageNode>().is_some(),
            "a portal is backed by an ImageNode"
        );

        tx.send(vec![update_delta(
            1,
            serde_json::from_value(serde_json::json!({ "target": "minimap" }))
                .expect("valid portal props"),
            &[],
            &[],
        )])
        .unwrap();
        app.update();
        assert_eq!(
            app.world().entity(e).get::<RPortal>().map(|p| p.0.clone()),
            Some("minimap".to_string()),
            "an update rebinds the portal's target name"
        );
    }

    /// A `<surface>` mounts carrying its name in an `RSurface`, and stays a detached
    /// UI root: appending it under a parent must NOT add it to that parent's Bevy
    /// `Children` (it renders to its own offscreen camera instead).
    #[test]
    fn surface_mounts_detached_with_name() {
        use crate::surface::RSurface;
        let (mut app, tx, _root) = ordering_app();
        tx.send(vec![
            create_node(1), // a normal parent under the root
            Op::Create {
                id: 2,
                kind: "surface".into(),
                props: serde_json::from_value(serde_json::json!({ "target": "monitor" }))
                    .expect("valid surface props"),
                text: None,
            },
            Op::Append {
                parent: ROOT_ID,
                child: 1,
            },
            // React appends the surface under node 1; the reconciler must keep it
            // detached (no Bevy parent) so it is an independent layout root.
            Op::Append {
                parent: 1,
                child: 2,
            },
        ])
        .unwrap();
        app.update();

        let surface = ent(&app, 2);
        assert_eq!(
            app.world()
                .entity(surface)
                .get::<RSurface>()
                .map(|s| s.0.clone()),
            Some("monitor".to_string()),
            "a surface carries its name in RSurface"
        );
        assert!(
            app.world().entity(surface).get::<ChildOf>().is_none(),
            "a surface is a detached root — never parented into the on-screen tree"
        );
        assert!(
            children_of(&app, ent(&app, 1)).is_empty(),
            "the surface's React parent has no Bevy children"
        );

        // An update rebinds the surface name (and never stamps an RPortal).
        tx.send(vec![update_delta(
            2,
            serde_json::from_value(serde_json::json!({ "target": "panel" }))
                .expect("valid surface props"),
            &[],
            &[],
        )])
        .unwrap();
        app.update();
        assert_eq!(
            app.world()
                .entity(surface)
                .get::<RSurface>()
                .map(|s| s.0.clone()),
            Some("panel".to_string()),
            "an update rebinds the surface name"
        );
        assert!(
            app.world()
                .entity(surface)
                .get::<crate::portal::RPortal>()
                .is_none(),
            "a surface update must not stamp an RPortal (shared `target` field)"
        );
    }

    /// `Op::Reset` must keep the persistent anchor layer alive (it is spawned once at
    /// startup) while still clearing the reconciler overlays reparented under it.
    #[test]
    fn reset_preserves_anchor_layer_but_clears_its_overlays() {
        use crate::anchor::AnchorLayer;
        let (mut app, tx, root) = ordering_app();

        // The anchor layer is a child of the root; an overlay (a reconciler node) has
        // been reparented under it, exactly as `position_anchored_nodes` would do.
        let layer = app.world_mut().spawn((AnchorLayer, ChildOf(root))).id();
        let overlay = app.world_mut().spawn((RNode(99), ChildOf(layer))).id();

        tx.send(vec![Op::Reset]).unwrap();
        app.update();

        assert!(
            app.world().entities().contains(layer),
            "Op::Reset must preserve the persistent anchor layer"
        );
        assert!(
            !app.world().entities().contains(overlay),
            "Op::Reset must despawn overlays reparented under the anchor layer"
        );
    }

    /// `Op::Reset` must despawn detached `<surface>` roots. They aren't children of the
    /// UI root (a surface renders to its own offscreen camera), so the root-children
    /// despawn misses them; a cold reload would otherwise leak a stale surface subtree
    /// that keeps rendering into the texture.
    #[test]
    fn reset_despawns_detached_surfaces() {
        let (mut app, tx, _root) = ordering_app();

        // Mount a `<surface>` under the root (it stays a detached root in Bevy).
        tx.send(vec![
            Op::Create {
                id: 1,
                kind: "surface".into(),
                props: serde_json::from_value(serde_json::json!({ "target": "monitor" }))
                    .expect("valid surface props"),
                text: None,
            },
            Op::Append {
                parent: ROOT_ID,
                child: 1,
            },
        ])
        .unwrap();
        app.update();
        let surface = ent(&app, 1);
        assert!(app.world().entities().contains(surface));

        tx.send(vec![Op::Reset]).unwrap();
        app.update();

        assert!(
            !app.world().entities().contains(surface),
            "Op::Reset must despawn the detached surface root"
        );
        assert!(
            app.world().resource::<JsBridge>().surfaces.is_empty(),
            "Op::Reset must clear surface bookkeeping"
        );
    }

    /// Removing an ancestor whose subtree *contains* a detached `<surface>` must despawn
    /// the surface too. React emits `Remove` only for the subtree's top node, and the
    /// surface is a detached root (no `ChildOf`), so neither React's op nor Bevy's
    /// recursive despawn of the ancestor reaches it — `apply_js_ops` must find it via the
    /// tracked React parentage. Regression: navigating away from the Home demo left its
    /// `<surface name="monitor">` rendering into the shared monitor texture under the
    /// `<surface>` demo. This reproduces the exact op stream React emits (verified: only
    /// the wrapper gets a `Remove`, never the nested surface).
    #[test]
    fn remove_ancestor_despawns_nested_surface() {
        let (mut app, tx, _root) = ordering_app();
        // Mirror Home's shape: a wrapper `<node>` under the root, a `<surface>` nested
        // inside it, and a normal node rendered inside the surface.
        tx.send(vec![
            create_node(1), // wrapper (Home's container)
            Op::Create {
                id: 2,
                kind: "surface".into(),
                props: serde_json::from_value(serde_json::json!({ "target": "monitor" }))
                    .expect("valid surface props"),
                text: None,
            },
            create_node(3), // content rendered inside the surface
            Op::Append {
                parent: ROOT_ID,
                child: 1,
            },
            Op::Append {
                parent: 1,
                child: 2,
            }, // surface nested under the wrapper
            Op::Append {
                parent: 2,
                child: 3,
            }, // content inside the surface
        ])
        .unwrap();
        app.update();
        let wrapper = ent(&app, 1);
        let surface = ent(&app, 2);
        let inner = ent(&app, 3);
        assert!(app.world().entities().contains(surface));

        // React unmounts the wrapper: a single `Remove` for the top node only.
        tx.send(vec![Op::Remove {
            parent: ROOT_ID,
            child: 1,
        }])
        .unwrap();
        app.update();

        assert!(
            !app.world().entities().contains(wrapper),
            "the removed wrapper is despawned"
        );
        assert!(
            !app.world().entities().contains(surface),
            "the detached <surface> nested under the removed wrapper must be despawned"
        );
        assert!(
            !app.world().entities().contains(inner),
            "the surface's own subtree is despawned with it"
        );
        let bridge = app.world().resource::<JsBridge>();
        assert!(bridge.surfaces.is_empty(), "surface bookkeeping is cleared");
        assert!(
            !bridge.nodes.contains_key(&2),
            "the surface node id is forgotten"
        );
        assert!(
            bridge.child_surfaces.is_empty() && bridge.surface_parent.is_empty(),
            "surface parentage maps are cleared"
        );
    }

    /// Removing a subtree must forget its *descendants'* per-node bookkeeping, not just
    /// the removed root's. React emits `Remove` only for the top node, and Bevy despawns
    /// the whole subtree recursively — so the bridge's `NodeId`-keyed side-tables would
    /// otherwise keep stale entries for every descendant until the next `Op::Reset`.
    #[test]
    fn remove_subtree_forgets_descendant_node_data() {
        let (mut app, tx, _root) = ordering_app();
        // A plain nested subtree wrapper(1) → mid(2) → leaf(3); `leaf` is an
        // `editableText` so a set-typed side-table (`editable_inputs`) is exercised too.
        tx.send(vec![
            create_node(1),
            create_node(2),
            Op::Create {
                id: 3,
                kind: "editableText".into(),
                props: Props::default(),
                text: None,
            },
            Op::Append {
                parent: ROOT_ID,
                child: 1,
            },
            Op::Append {
                parent: 1,
                child: 2,
            },
            Op::Append {
                parent: 2,
                child: 3,
            },
        ])
        .unwrap();
        app.update();
        let mid = ent(&app, 2);
        let leaf = ent(&app, 3);
        assert!(
            app.world()
                .resource::<JsBridge>()
                .editable_inputs
                .contains(&3),
            "the editableText descendant is tracked before removal"
        );

        // React unmounts the wrapper: a single `Remove` for the top node only.
        tx.send(vec![Op::Remove {
            parent: ROOT_ID,
            child: 1,
        }])
        .unwrap();
        app.update();

        assert!(
            !app.world().entities().contains(mid),
            "the descendant mid node is despawned with the subtree"
        );
        assert!(
            !app.world().entities().contains(leaf),
            "the descendant leaf node is despawned with the subtree"
        );
        let bridge = app.world().resource::<JsBridge>();
        assert!(
            !bridge.nodes.contains_key(&1),
            "the removed root is forgotten"
        );
        assert!(
            !bridge.nodes.contains_key(&2),
            "the descendant mid node id is forgotten (no stale entity handle)"
        );
        assert!(
            !bridge.nodes.contains_key(&3),
            "the descendant leaf node id is forgotten (no stale entity handle)"
        );
        assert!(
            !bridge.editable_inputs.contains(&3),
            "the descendant editableText is dropped from the editable_inputs set"
        );
    }

    /// A node created with a controlled `scrollTop` gets that `ScrollPosition`; an
    /// `onScroll` node gets a `ScrollListener` and is seeded in the dedup map (at
    /// `ZERO` when uncontrolled) so its mount-frame change doesn't echo back.
    #[test]
    fn controlled_scroll_create_sets_position_and_listener() {
        let (mut app, ops_tx) = op_app();
        ops_tx
            .send(vec![
                // controlled offset + an onScroll handler.
                Op::Create {
                    id: 1,
                    kind: "node".into(),
                    props: serde_json::from_value(serde_json::json!({
                        "scrollTop": 50.0, "onScroll": true,
                        "style": { "overflowY": "scroll" }
                    }))
                    .unwrap(),
                    text: None,
                },
                // listener only (read-only scroll): seeded at ZERO.
                Op::Create {
                    id: 2,
                    kind: "node".into(),
                    props: serde_json::from_value(serde_json::json!({ "onScroll": true })).unwrap(),
                    text: None,
                },
                // controlled only, no handler → no marker.
                Op::Create {
                    id: 3,
                    kind: "node".into(),
                    props: serde_json::from_value(serde_json::json!({ "scrollTop": 30.0 }))
                        .unwrap(),
                    text: None,
                },
            ])
            .unwrap();
        app.update();

        let nodes = app.world().resource::<JsBridge>().nodes.clone();
        let (e1, e2, e3) = (nodes[&1], nodes[&2], nodes[&3]);

        assert_eq!(
            app.world().entity(e1).get::<ScrollPosition>().unwrap().0,
            Vec2::new(0.0, 50.0)
        );
        assert!(app.world().entity(e1).get::<ScrollListener>().is_some());
        assert!(app.world().entity(e2).get::<ScrollListener>().is_some());
        assert!(
            app.world().entity(e3).get::<ScrollListener>().is_none(),
            "a controlled node with no onScroll must not be marked"
        );

        let bridge = app.world().resource::<JsBridge>();
        assert_eq!(bridge.scroll_positions.get(&1), Some(&Vec2::new(0.0, 50.0)));
        assert_eq!(bridge.scroll_positions.get(&2), Some(&Vec2::ZERO));
        assert_eq!(bridge.scroll_positions.get(&3), Some(&Vec2::new(0.0, 30.0)));
    }

    /// A controlled `scrollTop` past the scrollable range clamps the written
    /// `ScrollPosition` to the max, while recording the *requested* value so the
    /// read-back can correct React's controlled state down to the real max.
    #[test]
    fn controlled_scroll_update_clamps_to_range() {
        let (mut app, ops_tx) = op_app();
        ops_tx
            .send(vec![Op::Create {
                id: 1,
                kind: "node".into(),
                props: serde_json::from_value(serde_json::json!({
                    "onScroll": true, "style": { "overflowY": "scroll" }
                }))
                .unwrap(),
                text: None,
            }])
            .unwrap();
        app.update();

        let e1 = app.world().resource::<JsBridge>().nodes[&1];
        // A laid-out size with real range: content 300, view 100 → max scroll 200.
        app.world_mut().entity_mut(e1).insert(ComputedNode {
            size: Vec2::new(200.0, 100.0),
            content_size: Vec2::new(200.0, 300.0),
            inverse_scale_factor: 1.0,
            ..default()
        });

        ops_tx
            .send(vec![update_delta(
                1,
                serde_json::from_value(serde_json::json!({
                    "onScroll": true, "scrollTop": 10000.0,
                    "style": { "overflowY": "scroll" }
                }))
                .unwrap(),
                &[],
                &[],
            )])
            .unwrap();
        app.update();

        assert_eq!(
            app.world().entity(e1).get::<ScrollPosition>().unwrap().0,
            Vec2::new(0.0, 200.0),
            "the written offset is clamped to the scrollable range"
        );
        assert_eq!(
            app.world().resource::<JsBridge>().scroll_positions.get(&1),
            Some(&Vec2::new(0.0, 10000.0)),
            "the requested (pre-clamp) value is recorded so the read-back can correct React"
        );
    }

    /// [`collect_scroll_events`] reports a `"scroll"` for a `ScrollListener` node
    /// whose offset diverges from the recorded one, ignores non-listener nodes, and
    /// records the emitted value.
    #[test]
    fn collect_scroll_events_emits_for_listener_only() {
        use bevy::ecs::system::RunSystemOnce;

        let mut world = World::new();
        let (out_tx, mut out_rx) = tokio::sync::mpsc::unbounded_channel::<Outbound>();
        let (_ops_tx, ops_rx) = crossbeam_channel::unbounded::<Vec<Op>>();
        let root = world.spawn_empty().id();
        world.insert_resource(JsBridge::new(ops_rx, out_tx, root));

        world.spawn((
            ScrollPosition(Vec2::new(0.0, 50.0)),
            RNode(1),
            ScrollListener,
        ));
        // No marker → must be ignored even though its ScrollPosition is "changed".
        world.spawn((ScrollPosition(Vec2::new(0.0, 70.0)), RNode(2)));

        world.run_system_once(collect_scroll_events).unwrap();

        match out_rx.try_recv().expect("a scroll event for the listener") {
            Outbound::UiEvent { event } => {
                assert_eq!(event.id, 1);
                assert_eq!(event.kind, "scroll");
                assert_eq!(event.scroll_top, Some(50.0));
                assert_eq!(event.scroll_left, Some(0.0));
            }
            other => panic!("expected a UiEvent, got {other:?}"),
        }
        assert!(
            out_rx.try_recv().is_err(),
            "the non-listener node must not emit"
        );
        assert_eq!(
            world.resource::<JsBridge>().scroll_positions.get(&1),
            Some(&Vec2::new(0.0, 50.0))
        );
    }

    /// A `ScrollPosition` equal to the recorded value (a controlled write-back, or
    /// an unchanged offset) is NOT echoed — this is what breaks the controlled
    /// component's feedback loop.
    #[test]
    fn collect_scroll_events_dedups_controlled_writeback() {
        use bevy::ecs::system::RunSystemOnce;

        let mut world = World::new();
        let (out_tx, mut out_rx) = tokio::sync::mpsc::unbounded_channel::<Outbound>();
        let (_ops_tx, ops_rx) = crossbeam_channel::unbounded::<Vec<Op>>();
        let root = world.spawn_empty().id();
        world.insert_resource(JsBridge::new(ops_rx, out_tx, root));

        // The controlled write already recorded this exact offset.
        world
            .resource_mut::<JsBridge>()
            .scroll_positions
            .insert(1, Vec2::new(0.0, 50.0));
        world.spawn((
            ScrollPosition(Vec2::new(0.0, 50.0)),
            RNode(1),
            ScrollListener,
        ));

        world.run_system_once(collect_scroll_events).unwrap();

        assert!(
            out_rx.try_recv().is_err(),
            "a write-back equal to the recorded value must not echo back to React"
        );
    }

    /// With a `transition: { scroll }`, a controlled `scrollTop` change sets the eased
    /// `ScrollTransitionState` target instead of snapping `ScrollPosition` — the drive
    /// system (not exercised here) moves the offset toward it.
    #[test]
    fn controlled_scroll_with_transition_sets_target_not_position() {
        let (mut app, ops_tx) = op_app();
        let style = serde_json::json!({
            "overflowY": "scroll", "transition": { "scroll": { "duration": 300 } }
        });
        ops_tx
            .send(vec![Op::Create {
                id: 1,
                kind: "node".into(),
                props: serde_json::from_value(serde_json::json!({ "style": style })).unwrap(),
                text: None,
            }])
            .unwrap();
        app.update();

        let e1 = app.world().resource::<JsBridge>().nodes[&1];
        // A real scroll range so the target isn't clamped away (content 300, view 100).
        app.world_mut().entity_mut(e1).insert(ComputedNode {
            size: Vec2::new(200.0, 100.0),
            content_size: Vec2::new(200.0, 300.0),
            inverse_scale_factor: 1.0,
            ..default()
        });

        ops_tx
            .send(vec![update_delta(
                1,
                serde_json::from_value(serde_json::json!({ "scrollTop": 80.0, "style": style }))
                    .unwrap(),
                &[],
                &[],
            )])
            .unwrap();
        app.update();

        assert_eq!(
            app.world().entity(e1).get::<ScrollPosition>().unwrap().0,
            Vec2::ZERO,
            "a controlled change with a scroll transition must not snap the offset"
        );
        assert_eq!(
            app.world()
                .entity(e1)
                .get::<ScrollTransitionState>()
                .unwrap()
                .target,
            Vec2::new(0.0, 80.0),
            "it sets the eased target instead"
        );
    }
    /// A delta update touching only `width` must leave every other derived
    /// component untouched — not merely re-inserted-equal, but with its change
    /// tick intact (re-insertion would re-extract paint and re-run the
    /// interaction restyle via `Changed<StyleVariants>`).
    #[test]
    fn delta_update_skips_untouched_groups() {
        let (mut app, ops_tx) = op_app();
        ops_tx
            .send(vec![Op::Create {
                id: 1,
                kind: "node".into(),
                props: serde_json::from_value(serde_json::json!({
                    "style": {
                        "backgroundColor": "red",
                        "width": 10,
                        "outline": { "color": "white" },
                    },
                    "hoverStyle": { "backgroundColor": "blue" },
                    "onClick": true,
                }))
                .unwrap(),
                text: None,
            }])
            .unwrap();
        app.update();

        let e = app.world().resource::<JsBridge>().nodes[&1];
        let paint_ticks = |app: &App| {
            let entity = app.world().entity(e);
            (
                entity
                    .get_change_ticks::<BackgroundColor>()
                    .unwrap()
                    .changed,
                entity.get_change_ticks::<Outline>().unwrap().changed,
            )
        };
        let variants_tick = |app: &App| {
            app.world()
                .entity(e)
                .get_change_ticks::<StyleVariants>()
                .unwrap()
                .changed
        };
        let ticks_before = paint_ticks(&app);

        ops_tx
            .send(vec![update_delta(
                1,
                serde_json::from_value(serde_json::json!({ "style": { "width": 100 } })).unwrap(),
                &[],
                &[],
            )])
            .unwrap();
        app.update();

        {
            let entity = app.world().entity(e);
            assert_eq!(
                entity.get::<Node>().unwrap().width,
                Val::Px(100.0),
                "the delta's own field must apply"
            );
            assert_eq!(
                entity.get::<BackgroundColor>().unwrap().0,
                crate::ui_map::parse_color("red"),
                "untouched background survives a width-only delta"
            );
            assert!(
                entity.get::<StyleVariants>().is_some(),
                "variants survive (base mirrors the style, so it was rebuilt)"
            );
            assert!(
                entity.get::<Interaction>().is_some(),
                "the onClick Interaction survives"
            );
        }
        assert_eq!(
            ticks_before,
            paint_ticks(&app),
            "untouched paint groups must not even be marked changed"
        );

        // A non-style delta (a handler toggle) must not touch `StyleVariants`
        // at all — re-inserting it would trigger a full interaction restyle
        // via `Changed<StyleVariants>` on every unrelated update.
        let tick_before = variants_tick(&app);
        ops_tx
            .send(vec![update_delta(
                1,
                serde_json::from_value(serde_json::json!({ "onPointerDown": true })).unwrap(),
                &[],
                &[],
            )])
            .unwrap();
        app.update();
        assert_eq!(
            tick_before,
            variants_tick(&app),
            "a handler-only delta must not re-insert StyleVariants"
        );
    }

    /// `styleUnset` removes exactly the named field's component; the rest of
    /// the merged style (and unrelated props) stay.
    #[test]
    fn delta_style_unset_removes_component() {
        let (mut app, ops_tx) = op_app();
        ops_tx
            .send(vec![Op::Create {
                id: 1,
                kind: "node".into(),
                props: serde_json::from_value(serde_json::json!({
                    "style": { "backgroundColor": "red", "width": 10 },
                }))
                .unwrap(),
                text: None,
            }])
            .unwrap();
        app.update();
        let e = app.world().resource::<JsBridge>().nodes[&1];
        assert!(app.world().entity(e).get::<BackgroundColor>().is_some());

        ops_tx
            .send(vec![update_delta(
                1,
                Props::default(),
                &[],
                &["backgroundColor"],
            )])
            .unwrap();
        app.update();

        let entity = app.world().entity(e);
        assert!(
            entity.get::<BackgroundColor>().is_none(),
            "an unset style field removes its component"
        );
        assert_eq!(
            entity.get::<Node>().unwrap().width,
            Val::Px(10.0),
            "the retained width survives the unset"
        );
    }

    /// Explicit unsets are the delta's "reset" mechanism: `styleUnset` drops
    /// the style field's component, `unset` drops a whole prop (here the last
    /// variant style, which must remove `StyleVariants` from the entity).
    #[test]
    fn delta_unsets_reset_absent_fields() {
        let (mut app, ops_tx) = op_app();
        ops_tx
            .send(vec![Op::Create {
                id: 1,
                kind: "node".into(),
                props: serde_json::from_value(serde_json::json!({
                    "style": { "backgroundColor": "red" },
                    "hoverStyle": { "backgroundColor": "blue" },
                }))
                .unwrap(),
                text: None,
            }])
            .unwrap();
        app.update();
        let e = app.world().resource::<JsBridge>().nodes[&1];
        assert!(app.world().entity(e).get::<StyleVariants>().is_some());

        ops_tx
            .send(vec![update_delta(
                1,
                serde_json::from_value(serde_json::json!({ "style": { "width": 5 } })).unwrap(),
                &["hoverStyle"],
                &["backgroundColor"],
            )])
            .unwrap();
        app.update();

        let entity = app.world().entity(e);
        assert!(
            entity.get::<BackgroundColor>().is_none(),
            "styleUnset resets the background"
        );
        assert!(
            entity.get::<StyleVariants>().is_none(),
            "unsetting the last variant style removes StyleVariants"
        );
        assert_eq!(
            entity.get::<Node>().unwrap().width,
            Val::Px(5.0),
            "the delta's own field still applies"
        );
    }

    /// An unrelated delta on a controlled-scroll node must not touch the
    /// scroll offset (event-like props are never replayed from the cache).
    #[test]
    fn delta_update_does_not_replay_controlled_scroll() {
        let (mut app, ops_tx) = op_app();
        ops_tx
            .send(vec![Op::Create {
                id: 1,
                kind: "node".into(),
                props: serde_json::from_value(serde_json::json!({
                    "scrollTop": 40.0,
                    "style": { "overflowY": "scroll" },
                }))
                .unwrap(),
                text: None,
            }])
            .unwrap();
        app.update();
        let e = app.world().resource::<JsBridge>().nodes[&1];
        // Simulate the user scrolling away from the controlled value.
        app.world_mut()
            .entity_mut(e)
            .get_mut::<ScrollPosition>()
            .unwrap()
            .0 = Vec2::new(0.0, 7.0);

        ops_tx
            .send(vec![update_delta(
                1,
                serde_json::from_value(serde_json::json!({ "style": { "width": 50 } })).unwrap(),
                &[],
                &[],
            )])
            .unwrap();
        app.update();

        assert_eq!(
            app.world().entity(e).get::<ScrollPosition>().unwrap().0,
            Vec2::new(0.0, 7.0),
            "a width-only delta must not re-push the cached scrollTop"
        );
    }

    /// On a `<text>` with inheriting bare-string spans, a transform-only delta
    /// must skip the O(children) span re-propagation (their tick stays), while
    /// a `color` delta re-propagates.
    #[test]
    fn text_delta_gates_span_repropagation() {
        let (mut app, ops_tx) = op_app();
        ops_tx
            .send(vec![
                Op::Create {
                    id: 1,
                    kind: "text".into(),
                    props: serde_json::from_value(serde_json::json!({
                        "style": { "color": "red" },
                    }))
                    .unwrap(),
                    text: None,
                },
                Op::CreateTextSpan {
                    id: 2,
                    text: "run".into(),
                },
                Op::Append {
                    parent: 1,
                    child: 2,
                },
            ])
            .unwrap();
        app.update();
        let bridge = app.world().resource::<JsBridge>();
        let (root, span) = (bridge.nodes[&1], bridge.nodes[&2]);
        let span_tick = app
            .world()
            .entity(span)
            .get_change_ticks::<TextColor>()
            .unwrap()
            .changed;

        // Transform-only delta: no text-style group dirty → span untouched.
        ops_tx
            .send(vec![update_delta(
                1,
                serde_json::from_value(
                    serde_json::json!({ "style": { "transform": { "scale": 2.0 } } }),
                )
                .unwrap(),
                &[],
                &[],
            )])
            .unwrap();
        app.update();
        assert_eq!(
            app.world()
                .entity(span)
                .get_change_ticks::<TextColor>()
                .unwrap()
                .changed,
            span_tick,
            "a transform-only text delta must not re-propagate to spans"
        );

        // Color delta: text group dirty → span restyled.
        ops_tx
            .send(vec![update_delta(
                1,
                serde_json::from_value(serde_json::json!({ "style": { "color": "blue" } }))
                    .unwrap(),
                &[],
                &[],
            )])
            .unwrap();
        app.update();
        let world = app.world();
        assert_eq!(
            world.entity(span).get::<TextColor>().unwrap().0,
            crate::ui_map::parse_color("blue"),
            "a color delta re-propagates to inheriting spans"
        );
        assert_eq!(
            world.entity(root).get::<TextColor>().unwrap().0,
            crate::ui_map::parse_color("blue")
        );
    }

    /// A handler toggled off via `unset` clears its marker; the merged (not
    /// delta-only) props drive the rebuild, so the other handler survives.
    #[test]
    fn delta_toggles_pointer_handlers() {
        let (mut app, ops_tx) = op_app();
        ops_tx
            .send(vec![Op::Create {
                id: 1,
                kind: "node".into(),
                props: serde_json::from_value(
                    serde_json::json!({ "onPointerDown": true, "onPointerUp": true }),
                )
                .unwrap(),
                text: None,
            }])
            .unwrap();
        app.update();
        let e = app.world().resource::<JsBridge>().nodes[&1];

        // Unset one of the two: the marker must keep the other (merged props).
        ops_tx
            .send(vec![update_delta(
                1,
                Props::default(),
                &["onPointerUp"],
                &[],
            )])
            .unwrap();
        app.update();
        let handlers = app
            .world()
            .entity(e)
            .get::<PointerHandlers>()
            .expect("one handler remains");
        assert!(handlers.down && !handlers.up);

        ops_tx
            .send(vec![update_delta(
                1,
                Props::default(),
                &["onPointerDown"],
                &[],
            )])
            .unwrap();
        app.update();
        assert!(
            app.world().entity(e).get::<PointerHandlers>().is_none(),
            "unsetting the last handler clears the marker"
        );
    }
}