euv-core 0.47.0

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

/// Forward iteration over a node's direct children via intrusive `next_sibling` links.
impl Iterator for SceneChildIter<'_> {
    type Item = NodeId;

    /// Advances to the next direct child in O(1) with zero heap allocation.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable child iterator.
    ///
    /// # Returns
    ///
    /// - `Option<Self::Item>` - Next child handle or `None` when exhausted.
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        let Self {
            meta,
            topology,
            head,
            tail,
            remaining,
        } = self;
        if *remaining == 0 || *head == NODE_INDEX_NONE {
            return None;
        }
        let idx: u32 = *head;
        *remaining -= 1;
        if *remaining == 0 || idx == *tail {
            *head = NODE_INDEX_NONE;
            *tail = NODE_INDEX_NONE;
        } else {
            *head = topology[idx as usize].get_next_sibling();
        }
        let generation: u32 = meta[idx as usize].get_generation();
        Some(NodeId::new(idx, generation))
    }

    /// Returns exact lower and upper bounds on remaining children.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Child iterator reference.
    ///
    /// # Returns
    ///
    /// - `(usize, Option<usize>)` - Exact remaining child count bounds.
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let Self { remaining, .. } = *self;
        (remaining, Some(remaining))
    }
}

/// Reverse iteration over a node's direct children via intrusive `prev_sibling` links.
impl DoubleEndedIterator for SceneChildIter<'_> {
    /// Advances backward from the last child in O(1) with zero heap allocation.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable child iterator.
    ///
    /// # Returns
    ///
    /// - `Option<Self::Item>` - Previous child handle from the back or `None` when exhausted.
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        let Self {
            meta,
            topology,
            head,
            tail,
            remaining,
        } = self;
        if *remaining == 0 || *tail == NODE_INDEX_NONE {
            return None;
        }
        let idx: u32 = *tail;
        *remaining -= 1;
        if *remaining == 0 || idx == *head {
            *head = NODE_INDEX_NONE;
            *tail = NODE_INDEX_NONE;
        } else {
            *tail = topology[idx as usize].get_prev_sibling();
        }
        let generation: u32 = meta[idx as usize].get_generation();
        Some(NodeId::new(idx, generation))
    }
}

/// Exact-length marker for `SceneChildIter`.
impl ExactSizeIterator for SceneChildIter<'_> {}

/// Default scene tree with a pre-created root `View` node.
impl Default for SceneTree {
    /// Allocates a new `SceneTree` containing a root container node.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized scene tree.
    fn default() -> Self {
        let root_style: Style = Style::default()
            .column()
            .width(Length::Percent(100.0))
            .height(Length::Percent(100.0));
        let root_compact: CompactPaintStyle =
            CompactPaintStyle::from_paint(root_style.paint_ref(), EFFECT_ID_NONE);
        let root_node: SceneNode = SceneNode::new(1, NodeKind::View, root_style);
        Self {
            nodes: vec![root_node],
            meta: vec![NodeMeta::new(1, NODE_FLAG_ALIVE, DIRTY_ALL)],
            topology: vec![NodeTopology::default()],
            compact_paints: vec![root_compact],
            effect_table: EffectTable::new(),
            free_list: Vec::new(),
            live_count: 1,
            live_lifecycle_count: 0,
            root: NodeId::new(0, 1),
            focus: FocusManager::default(),
            revision: 1,
            transitions: Vec::new(),
            caret_visible: true,
            portal_nodes: Vec::new(),
            scroll_nodes: Vec::new(),
            dirty_paint_nodes: Vec::new(),
            full_damage_pending: true,
            layout_damage_pending: true,
            full_damage_overflow: false,
            created_since_damage: 0,
            extra_logical_damage: Vec::new(),
            text_selection: None,
            backdrop_blur_nodes: Vec::new(),
            layout_invalidations: 1,
            last_collect_composite_only: false,
            theme_entries: HashMap::new(),
            paint_epochs: vec![0],
            has_stale_hidden_dirty: false,
        }
    }
}

/// Generation-guarded theme ownership and origin snapshot bookkeeping for in-place theme remaps.
impl SceneTree {
    /// Returns the live generation of `id`, or `None` when the handle is stale or disposed.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Target node handle.
    ///
    /// # Returns
    ///
    /// - `Option<u32>` - Live generation when `id` refers to an alive node.
    fn live_generation(&self, id: NodeId) -> Option<u32> {
        let meta: &NodeMeta = self.get_meta().get(id.as_usize())?;
        ((meta.get_flags() & NODE_FLAG_ALIVE) != 0 && meta.get_generation() == id.get_generation())
            .then_some(id.get_generation())
    }

    /// Returns the generation-validated theme entry for `id`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Target node handle.
    ///
    /// # Returns
    ///
    /// - `Option<ThemeNodeEntry>` - Entry when present and belonging to the live generation.
    fn theme_entry(&self, id: NodeId) -> Option<ThemeNodeEntry> {
        let generation: u32 = self.live_generation(id)?;
        let Self { theme_entries, .. } = self;
        theme_entries
            .get(&id.get_index())
            .copied()
            .filter(|entry: &ThemeNodeEntry| entry.get_generation() == generation)
    }

    /// Updates (or creates) the generation-validated theme entry for `id` via `apply`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Target node handle.
    /// - `F` - Mutation applied to the fresh or existing entry.
    fn update_theme_entry<F>(&mut self, id: NodeId, apply: F)
    where
        F: FnOnce(&mut ThemeNodeEntry),
    {
        let Some(generation) = self.live_generation(id) else {
            return;
        };
        let Self { theme_entries, .. } = self;
        let entry: &mut ThemeNodeEntry = theme_entries
            .entry(id.get_index())
            .or_insert_with(|| ThemeNodeEntry::new(generation, false, None));
        if entry.get_generation() != generation {
            *entry = ThemeNodeEntry::new(generation, false, None);
        }
        apply(entry);
    }

    /// Marks `id` as reactively theme-owned by its component so generic in-place theme remaps skip its paint.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Target node handle.
    /// - `bool` - Whether the component owns the node's themed paint.
    pub fn set_theme_owned(&mut self, id: NodeId, owned: bool) {
        if !owned && self.theme_entry(id).is_none() {
            return;
        }
        self.update_theme_entry(id, |entry: &mut ThemeNodeEntry| {
            entry.set_owned(owned);
        });
    }

    /// Returns whether `id` is reactively theme-owned by its component.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Target node handle.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when generic theme remaps must skip `id`.
    #[must_use]
    pub fn is_theme_owned(&self, id: NodeId) -> bool {
        self.theme_entry(id)
            .is_some_and(|entry: ThemeNodeEntry| entry.get_owned())
    }

    /// Returns the theme-origin paint snapshot recorded for `id`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Target node handle.
    ///
    /// # Returns
    ///
    /// - `Option<ThemeBaseline>` - Recorded origin snapshot, if any.
    #[must_use]
    pub fn theme_baseline(&self, id: NodeId) -> Option<ThemeBaseline> {
        self.theme_entry(id)
            .and_then(|entry: ThemeNodeEntry| entry.get_baseline())
    }

    /// Records (or clears) the theme-origin paint snapshot for `id`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Target node handle.
    /// - `Option<ThemeBaseline>` - Origin snapshot to store, or `None` to clear.
    pub fn set_theme_baseline(&mut self, id: NodeId, baseline: Option<ThemeBaseline>) {
        if baseline.is_none() && self.theme_entry(id).is_none() {
            return;
        }
        self.update_theme_entry(id, |entry: &mut ThemeNodeEntry| {
            entry.set_baseline(baseline);
        });
    }
}

/// Core retained scene graph mutation and traversal operations.
impl SceneTree {
    /// Registers or removes a backdrop-blur effect radius on `id` for effect-dependency damage propagation and paint emission.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Target scene node handle.
    /// - `f32` - Gaussian backdrop blur radius in logical pixels (`<= 0.0` removes backdrop blur).
    pub fn set_backdrop_blur(&mut self, id: NodeId, blur_radius: f32) {
        if self.get_node(id).is_none() {
            return;
        }
        let clamped: f32 = if blur_radius.is_finite() {
            blur_radius.clamp(0.0, 96.0)
        } else {
            0.0
        };
        let prev_radius: f32 = self.backdrop_blur_radius(id);
        if (prev_radius - clamped).abs() <= 0.001 {
            return;
        }
        if prev_radius > 0.0 {
            self.record_node_logical_damage(id);
        }
        let blurs: &mut Vec<(NodeId, f32)> = self.get_mut_backdrop_blur_nodes();
        if clamped <= 0.0 {
            blurs.retain(|entry: &(NodeId, f32)| entry.0 != id);
        } else if let Some(slot) = blurs
            .iter_mut()
            .find(|entry: &&mut (NodeId, f32)| entry.0 == id)
        {
            slot.1 = clamped;
        } else {
            blurs.push((id, clamped));
        }
        let paint_copy: Option<PaintStyle> =
            self.get_node(id).map(|node: &SceneNode| *node.paint_ref());
        if let Some(paint) = paint_copy {
            self.sync_node_compact_paint(id.as_usize(), &paint, clamped);
        }
        self.mark_dirty(id, DIRTY_PAINT);
    }

    /// Returns the configured backdrop-blur radius in logical pixels for `id` (`0.0` when unset).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Target scene node handle.
    ///
    /// # Returns
    ///
    /// - `f32` - Active backdrop-blur radius in logical pixels.
    #[must_use]
    pub fn backdrop_blur_radius(&self, id: NodeId) -> f32 {
        for &(nid, radius) in self.get_backdrop_blur_nodes().iter() {
            if nid == id {
                return radius;
            }
        }
        0.0
    }

    /// Returns `true` when at least one live node has an active backdrop-blur effect.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether backdrop-blur effect dependency tracking is active.
    #[must_use]
    pub fn has_backdrop_blur_nodes(&self) -> bool {
        !self.get_backdrop_blur_nodes().is_empty()
    }

    /// Expands `damage` to include every visible backdrop-blur node whose sampling region intersects any damaged rect (fixpoint propagation).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `&mut DamageRegion` - Active physical damage region to expand.
    /// - `f32` - Active display scale factor.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of backdrop-blur nodes added to `damage` due to overlapping underlying mutations.
    pub fn propagate_effect_damage(&self, damage: &mut DamageRegion, scale: f32) -> usize {
        if damage.get_full_damage() || self.get_backdrop_blur_nodes().is_empty() {
            return 0;
        }
        let clamped_scale: f32 = scale.max(0.5);
        let blur_count: usize = self.get_backdrop_blur_nodes().len();
        let mut dirtied: Vec<bool> = vec![false; blur_count];
        let mut total_added: usize = 0;
        let mut changed: bool = true;
        while changed && !damage.get_full_damage() {
            changed = false;
            if damage.bounds_rect().is_none() {
                break;
            }
            for (idx, &(nid, blur_radius)) in self.get_backdrop_blur_nodes().iter().enumerate() {
                if dirtied[idx] || blur_radius <= 0.0 || !self.is_node_visible(nid) {
                    continue;
                }
                let Some(screen_rect) = self.node_screen_bounds(nid) else {
                    continue;
                };
                if screen_rect.get_width() <= 0.0 || screen_rect.get_height() <= 0.0 {
                    continue;
                }
                let sigma: f32 = (blur_radius * 0.5).max(0.75);
                let halo: f32 = (sigma * 3.0).ceil() + 2.0;
                let sample_logical: Rect = Rect::new(
                    screen_rect.get_x() - halo,
                    screen_rect.get_y() - halo,
                    screen_rect.get_width() + halo * 2.0,
                    screen_rect.get_height() + halo * 2.0,
                );
                let sample_phys: Rect =
                    Self::scale_logical_to_phys_rect(sample_logical, clamped_scale);
                let output_phys: Rect = Self::scale_logical_to_phys_rect(
                    Rect::new(
                        screen_rect.get_x() - 2.0,
                        screen_rect.get_y() - 2.0,
                        screen_rect.get_width() + 4.0,
                        screen_rect.get_height() + 4.0,
                    ),
                    clamped_scale,
                );
                let (rects, count): ([Rect; 8], usize) =
                    damage.normalized_rects(u32::MAX, u32::MAX);
                let overlaps: bool = rects
                    .iter()
                    .take(count)
                    .any(|r: &Rect| r.intersect(sample_phys).is_some());
                if overlaps {
                    damage.add_rect(output_phys);
                    dirtied[idx] = true;
                    total_added += 1;
                    changed = true;
                }
            }
        }
        total_added
    }
    /// Returns the incrementally maintained slice of live `NodeKind::Portal` and `Position::Fixed` nodes.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    ///
    /// # Returns
    ///
    /// - `&[NodeId]` - Live top-layer portal and fixed-position node handles.
    #[must_use]
    #[inline(always)]
    pub fn portal_nodes(&self) -> &[NodeId] {
        let Self { portal_nodes, .. } = self;
        portal_nodes.as_slice()
    }

    /// Returns `true` when at least one live `NodeKind::Portal` or `Position::Fixed` node is registered.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether any top-layer portal or fixed node exists in the scene.
    #[must_use]
    #[inline(always)]
    pub fn has_portal_nodes(&self) -> bool {
        let Self { portal_nodes, .. } = self;
        !portal_nodes.is_empty()
    }

    /// Synchronizes `id` membership in `portal_nodes` and `NODE_FLAG_IS_PORTAL` whenever a top-layer node is created, mutated, or disposed.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Target node handle.
    /// - `bool` - Whether the node currently qualifies as a `Portal` or `Position::Fixed` top-layer node.
    fn sync_portal_registration(&mut self, id: NodeId, is_portal: bool) {
        if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
            let next: u16 = if is_portal {
                meta.get_flags() | NODE_FLAG_IS_PORTAL
            } else {
                meta.get_flags() & !NODE_FLAG_IS_PORTAL
            };
            let _: &mut NodeMeta = meta.set_flags(next);
        }
        let portals: &mut Vec<NodeId> = self.get_mut_portal_nodes();
        if is_portal {
            if !portals.contains(&id) {
                portals.push(id);
            }
        } else if !portals.is_empty() {
            portals.retain(|existing: &NodeId| *existing != id);
        }
    }

    /// Returns the incrementally maintained slice of live `Overflow::Scroll` container nodes.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    ///
    /// # Returns
    ///
    /// - `&[NodeId]` - Live scroll container node handles.
    #[must_use]
    #[inline(always)]
    pub fn scroll_nodes(&self) -> &[NodeId] {
        let Self { scroll_nodes, .. } = self;
        scroll_nodes.as_slice()
    }

    /// Returns `true` when at least one live `Overflow::Scroll` container is registered.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether any scroll container exists in the scene.
    #[must_use]
    #[inline(always)]
    pub fn has_scroll_nodes(&self) -> bool {
        let Self { scroll_nodes, .. } = self;
        !scroll_nodes.is_empty()
    }

    /// Synchronizes `id` membership in `scroll_nodes` and `NODE_FLAG_IS_SCROLL_CONTAINER`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Target node handle.
    /// - `bool` - Whether the node currently uses `Overflow::Scroll`.
    fn sync_scroll_registration(&mut self, id: NodeId, is_scroll: bool) {
        if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
            let next: u16 = if is_scroll {
                meta.get_flags() | NODE_FLAG_IS_SCROLL_CONTAINER
            } else {
                meta.get_flags() & !NODE_FLAG_IS_SCROLL_CONTAINER
            };
            let _: &mut NodeMeta = meta.set_flags(next);
        }
        let scrolls: &mut Vec<NodeId> = self.get_mut_scroll_nodes();
        if is_scroll {
            if !scrolls.contains(&id) {
                scrolls.push(id);
            }
        } else if !scrolls.is_empty() {
            scrolls.retain(|existing: &NodeId| *existing != id);
        }
    }

    /// Synchronizes the 32-byte `CompactPaintStyle` and sparse `EffectTable` slot for node index `idx`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `usize` - Node arena slot index.
    /// - `&PaintStyle` - Current paint style reference.
    /// - `f32` - Active backdrop blur radius in logical pixels.
    fn sync_node_compact_paint(&mut self, idx: usize, paint: &PaintStyle, blur: f32) {
        let prev_effect_id: u32 = self
            .get_compact_paints()
            .get(idx)
            .map(CompactPaintStyle::get_effect_id)
            .unwrap_or(EFFECT_ID_NONE);
        let entry: PaintEffectEntry = PaintEffectEntry::from_paint_and_blur(paint, blur);
        let next_effect_id: u32 = self.get_mut_effect_table().update(prev_effect_id, entry);
        let compact: CompactPaintStyle = CompactPaintStyle::from_paint(paint, next_effect_id);
        if let Some(slot) = self.get_mut_compact_paints().get_mut(idx) {
            *slot = compact;
        }
    }

    /// Returns the 32-byte `CompactPaintStyle` stored in dense SoA for live node `id`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Target node handle.
    ///
    /// # Returns
    ///
    /// - `Option<&CompactPaintStyle>` - Borrowed 32-byte compact paint style if live.
    #[must_use]
    #[inline(always)]
    pub fn compact_paint(&self, id: NodeId) -> Option<&CompactPaintStyle> {
        let idx: usize = id.as_usize();
        let meta: &NodeMeta = self.get_meta().get(idx)?;
        if (meta.get_flags() & NODE_FLAG_ALIVE) == 0 || meta.get_generation() != id.get_generation()
        {
            return None;
        }
        self.get_compact_paints().get(idx)
    }

    /// Returns the sparse `PaintEffectEntry` for `id` in O(1) (`None` when `effect_id == EFFECT_ID_NONE`).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Target node handle.
    ///
    /// # Returns
    ///
    /// - `Option<&PaintEffectEntry>` - Borrowed rare paint effect entry if active.
    #[must_use]
    #[inline(always)]
    pub fn paint_effect(&self, id: NodeId) -> Option<&PaintEffectEntry> {
        let effect_id: u32 = self.compact_paint(id)?.get_effect_id();
        self.get_effect_table().get(effect_id)
    }

    /// Returns a shared reference to the sparse `EffectTable` owned by this scene tree.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    ///
    /// # Returns
    ///
    /// - `&EffectTable` - Borrowed sparse effect table.
    #[must_use]
    #[inline(always)]
    pub fn effect_table(&self) -> &EffectTable {
        self.get_effect_table()
    }

    /// Returns whether live node `id` has lazily allocated cold `NodeExtras` metadata.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Target node handle.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `NODE_FLAG_HAS_EXTRAS` is set on `id`.
    #[must_use]
    #[inline(always)]
    pub fn has_extras(&self, id: NodeId) -> bool {
        let Some(node) = self.get_node(id) else {
            return false;
        };
        node.has_extras()
    }

    /// Returns whether live container `id` has at least one direct child with a non-zero `z_index` in O(1).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Parent container node handle.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `NODE_FLAG_HAS_NONZERO_Z_CHILD` is set on `id`.
    #[must_use]
    #[inline(always)]
    pub fn has_nonzero_z_child(&self, id: NodeId) -> bool {
        let idx: usize = id.as_usize();
        let Some(meta) = self.get_meta().get(idx) else {
            return false;
        };
        (meta.get_flags() & NODE_FLAG_ALIVE) != 0
            && meta.get_generation() == id.get_generation()
            && (meta.get_flags() & NODE_FLAG_HAS_NONZERO_Z_CHILD) != 0
    }

    /// Returns whether live node `id` has any attached `Lifecycle` observer in O(1).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Target node handle.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `NODE_FLAG_HAS_LIFECYCLE` is set on `id`.
    #[must_use]
    #[inline(always)]
    pub fn has_lifecycle(&self, id: NodeId) -> bool {
        let idx: usize = id.as_usize();
        let Some(meta) = self.get_meta().get(idx) else {
            return false;
        };
        (meta.get_flags() & NODE_FLAG_ALIVE) != 0
            && meta.get_generation() == id.get_generation()
            && (meta.get_flags() & NODE_FLAG_HAS_LIFECYCLE) != 0
    }

    /// Returns whether live node `id` owns a reactive `Scope` in O(1).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Target node handle.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `NODE_FLAG_HAS_SCOPE` is set on `id`.
    #[must_use]
    #[inline(always)]
    pub fn has_scope(&self, id: NodeId) -> bool {
        let idx: usize = id.as_usize();
        let Some(meta) = self.get_meta().get(idx) else {
            return false;
        };
        (meta.get_flags() & NODE_FLAG_ALIVE) != 0
            && meta.get_generation() == id.get_generation()
            && (meta.get_flags() & NODE_FLAG_HAS_SCOPE) != 0
    }

    /// Returns a zero-allocation double-ended iterator over the direct children of `parent`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Parent container node handle.
    ///
    /// # Returns
    ///
    /// - `SceneChildIter<'_>` - Zero-alloc forward/reverse iterator over direct children.
    #[must_use]
    #[inline(always)]
    pub fn children_iter(&self, parent: NodeId) -> SceneChildIter<'_> {
        let idx: usize = parent.as_usize();
        let valid: bool = self.get_meta().get(idx).is_some_and(|meta: &NodeMeta| {
            (meta.get_flags() & NODE_FLAG_ALIVE) != 0
                && meta.get_generation() == parent.get_generation()
        });
        if !valid {
            return SceneChildIter {
                meta: self.get_meta().as_slice(),
                topology: self.get_topology().as_slice(),
                head: NODE_INDEX_NONE,
                tail: NODE_INDEX_NONE,
                remaining: 0,
            };
        }
        let topo: NodeTopology = self.get_topology()[idx];
        SceneChildIter {
            meta: self.get_meta().as_slice(),
            topology: self.get_topology().as_slice(),
            head: topo.get_first_child(),
            tail: topo.get_last_child(),
            remaining: topo.get_child_count() as usize,
        }
    }

    /// Visits every direct child of `parent` in paint order with zero heap allocation.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Parent container node handle.
    /// - `F` - Visitor callback invoked with each child `NodeId`.
    #[inline]
    pub fn for_each_child<F>(&self, parent: NodeId, mut visit: F)
    where
        F: FnMut(NodeId),
    {
        for child_id in self.children_iter(parent) {
            visit(child_id);
        }
    }

    /// Visits every direct child of `parent` in reverse paint order with zero heap allocation.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Parent container node handle.
    /// - `F` - Visitor callback invoked with each child `NodeId` back-to-front.
    #[inline]
    pub fn for_each_child_rev<F>(&self, parent: NodeId, mut visit: F)
    where
        F: FnMut(NodeId),
    {
        for child_id in self.children_iter(parent).rev() {
            visit(child_id);
        }
    }

    /// Returns the number of direct children attached to `parent` in O(1).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Parent container node handle.
    ///
    /// # Returns
    ///
    /// - `usize` - Direct child count (`0` for leaves or stale handles).
    #[must_use]
    #[inline(always)]
    pub fn child_count(&self, parent: NodeId) -> usize {
        let idx: usize = parent.as_usize();
        let Some(meta) = self.get_meta().get(idx) else {
            return 0;
        };
        if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
            || meta.get_generation() != parent.get_generation()
        {
            return 0;
        }
        self.get_topology()[idx].get_child_count() as usize
    }

    /// Returns `true` when `parent` is live and has at least one direct child in O(1).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Parent container node handle.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether `parent` has any direct children.
    #[must_use]
    #[inline(always)]
    pub fn has_children(&self, parent: NodeId) -> bool {
        self.child_count(parent) > 0
    }

    /// Returns the first direct child of `parent` in O(1).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Parent container node handle.
    ///
    /// # Returns
    ///
    /// - `Option<NodeId>` - First child handle if present.
    #[must_use]
    #[inline(always)]
    pub fn first_child(&self, parent: NodeId) -> Option<NodeId> {
        let idx: usize = parent.as_usize();
        let meta: &NodeMeta = self.get_meta().get(idx)?;
        if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
            || meta.get_generation() != parent.get_generation()
        {
            return None;
        }
        let first: u32 = self.get_topology()[idx].get_first_child();
        if first == NODE_INDEX_NONE {
            None
        } else {
            Some(NodeId::new(
                first,
                self.get_meta()[first as usize].get_generation(),
            ))
        }
    }

    /// Returns the last direct child of `parent` in O(1).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Parent container node handle.
    ///
    /// # Returns
    ///
    /// - `Option<NodeId>` - Last child handle if present.
    #[must_use]
    #[inline(always)]
    pub fn last_child(&self, parent: NodeId) -> Option<NodeId> {
        let idx: usize = parent.as_usize();
        let meta: &NodeMeta = self.get_meta().get(idx)?;
        if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
            || meta.get_generation() != parent.get_generation()
        {
            return None;
        }
        let last: u32 = self.get_topology()[idx].get_last_child();
        if last == NODE_INDEX_NONE {
            None
        } else {
            Some(NodeId::new(
                last,
                self.get_meta()[last as usize].get_generation(),
            ))
        }
    }

    /// Returns the next sibling after `id` in O(1).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Child node handle.
    ///
    /// # Returns
    ///
    /// - `Option<NodeId>` - Next sibling handle if present.
    #[must_use]
    #[inline(always)]
    pub fn next_sibling(&self, id: NodeId) -> Option<NodeId> {
        let idx: usize = id.as_usize();
        let meta: &NodeMeta = self.get_meta().get(idx)?;
        if (meta.get_flags() & NODE_FLAG_ALIVE) == 0 || meta.get_generation() != id.get_generation()
        {
            return None;
        }
        let next: u32 = self.get_topology()[idx].get_next_sibling();
        if next == NODE_INDEX_NONE {
            None
        } else {
            Some(NodeId::new(
                next,
                self.get_meta()[next as usize].get_generation(),
            ))
        }
    }

    /// Returns the previous sibling before `id` in O(1).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Child node handle.
    ///
    /// # Returns
    ///
    /// - `Option<NodeId>` - Previous sibling handle if present.
    #[must_use]
    #[inline(always)]
    pub fn prev_sibling(&self, id: NodeId) -> Option<NodeId> {
        let idx: usize = id.as_usize();
        let meta: &NodeMeta = self.get_meta().get(idx)?;
        if (meta.get_flags() & NODE_FLAG_ALIVE) == 0 || meta.get_generation() != id.get_generation()
        {
            return None;
        }
        let prev: u32 = self.get_topology()[idx].get_prev_sibling();
        if prev == NODE_INDEX_NONE {
            None
        } else {
            Some(NodeId::new(
                prev,
                self.get_meta()[prev as usize].get_generation(),
            ))
        }
    }

    /// Collects the direct children of `parent` into an owned `Vec<NodeId>` snapshot for callers that must mutate outside a borrow.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Parent container node handle.
    ///
    /// # Returns
    ///
    /// - `Vec<NodeId>` - Snapshot of ordered direct children.
    #[must_use]
    pub fn children_vec(&self, parent: NodeId) -> Vec<NodeId> {
        self.children_iter(parent).collect()
    }

    /// Returns `true` when `candidate` equals `root` or descends from `root` in O(depth) with zero heap allocations.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Candidate descendant node handle.
    /// - `NodeId` - Ancestor subtree root handle.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether `candidate` lies inside the subtree rooted at `root`.
    #[must_use]
    pub fn is_in_subtree(&self, candidate: NodeId, root: NodeId) -> bool {
        if candidate == root {
            return true;
        }
        let mut cursor_idx: usize = candidate.as_usize();
        let Some(start_meta) = self.get_meta().get(cursor_idx) else {
            return false;
        };
        if (start_meta.get_flags() & NODE_FLAG_ALIVE) == 0
            || start_meta.get_generation() != candidate.get_generation()
        {
            return false;
        }
        let root_idx: u32 = root.get_index();
        let root_gen: u32 = root.get_generation();
        let max_hops: usize = self.get_topology().len();
        let mut hops: usize = 0;
        while hops < max_hops {
            let parent_idx: u32 = self.get_topology()[cursor_idx].get_parent();
            if parent_idx == NODE_INDEX_NONE {
                return false;
            }
            if parent_idx == root_idx
                && self.get_meta()[parent_idx as usize].get_generation() == root_gen
            {
                return true;
            }
            cursor_idx = parent_idx as usize;
            hops += 1;
        }
        false
    }

    /// Recomputes `NODE_FLAG_HAS_NONZERO_Z_CHILD` on `parent_idx` from its current direct children.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `usize` - Parent slot index.
    fn recompute_nonzero_z_child(&mut self, parent_idx: usize) {
        let mut any_nonzero: bool = false;
        let mut cur: u32 = self.get_topology()[parent_idx].get_first_child();
        while cur != NODE_INDEX_NONE {
            let ci: usize = cur as usize;
            if self.get_nodes()[ci].layout_ref().get_z_index() != 0 {
                any_nonzero = true;
                break;
            }
            cur = self.get_topology()[ci].get_next_sibling();
        }
        if let Some(meta) = self.get_mut_meta().get_mut(parent_idx) {
            let next: u16 = if any_nonzero {
                meta.get_flags() | NODE_FLAG_HAS_NONZERO_Z_CHILD
            } else {
                meta.get_flags() & !NODE_FLAG_HAS_NONZERO_Z_CHILD
            };
            let _: &mut NodeMeta = meta.set_flags(next);
        }
    }

    /// Updates `NODE_FLAG_HAS_NONZERO_Z_CHILD` on `parent_idx` when a child's `z_index` changes from `prev_z` to `next_z`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `usize` - Parent slot index.
    /// - `i32` - Child's previous `z_index`.
    /// - `i32` - Child's updated `z_index`.
    fn sync_parent_nonzero_z(&mut self, parent_idx: usize, prev_z: i32, next_z: i32) {
        if next_z != 0 {
            if let Some(meta) = self.get_mut_meta().get_mut(parent_idx) {
                let next: u16 = meta.get_flags() | NODE_FLAG_HAS_NONZERO_Z_CHILD;
                let _: &mut NodeMeta = meta.set_flags(next);
            }
        } else if prev_z != 0 {
            self.recompute_nonzero_z_child(parent_idx);
        }
    }

    /// Detaches `child_idx` from `parent_idx` in O(1) via intrusive doubly-linked sibling pointers.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `usize` - Parent slot index.
    /// - `usize` - Child slot index currently attached to `parent_idx`.
    fn unlink_child_at(&mut self, parent_idx: usize, child_idx: usize) {
        let child_topo: NodeTopology = self.get_topology()[child_idx];
        if child_topo.get_parent() != parent_idx as u32 {
            return;
        }
        let prev: u32 = child_topo.get_prev_sibling();
        let next: u32 = child_topo.get_next_sibling();
        let topo: &mut Vec<NodeTopology> = self.get_mut_topology();
        if prev != NODE_INDEX_NONE {
            let _: &mut NodeTopology = topo[prev as usize].set_next_sibling(next);
        } else {
            let _: &mut NodeTopology = topo[parent_idx].set_first_child(next);
        }
        if next != NODE_INDEX_NONE {
            let _: &mut NodeTopology = topo[next as usize].set_prev_sibling(prev);
        } else {
            let _: &mut NodeTopology = topo[parent_idx].set_last_child(prev);
        }
        let next_count: u32 = topo[parent_idx].get_child_count().saturating_sub(1);
        let _: &mut NodeTopology = topo[parent_idx].set_child_count(next_count);
        let _: &mut NodeTopology = topo[child_idx]
            .set_parent(NODE_INDEX_NONE)
            .set_prev_sibling(NODE_INDEX_NONE)
            .set_next_sibling(NODE_INDEX_NONE);
        let _: &mut SceneNode = self.get_mut_nodes()[child_idx].set_parent(None);
        let child_z: i32 = self.get_nodes()[child_idx].layout_ref().get_z_index();
        if child_z != 0 {
            self.recompute_nonzero_z_child(parent_idx);
        }
    }

    /// Links an unattached `child_idx` at the tail of `parent_idx` in O(1) via intrusive doubly-linked sibling pointers.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `usize` - Parent slot index.
    /// - `NodeId` - Parent node handle.
    /// - `usize` - Unattached child slot index.
    fn link_child_tail_at(&mut self, parent_idx: usize, parent_id: NodeId, child_idx: usize) {
        let child_u32: u32 = child_idx as u32;
        let topo: &mut Vec<NodeTopology> = self.get_mut_topology();
        let tail: u32 = topo[parent_idx].get_last_child();
        let _: &mut NodeTopology = topo[child_idx]
            .set_parent(parent_idx as u32)
            .set_prev_sibling(tail)
            .set_next_sibling(NODE_INDEX_NONE);
        if tail != NODE_INDEX_NONE {
            let _: &mut NodeTopology = topo[tail as usize].set_next_sibling(child_u32);
        } else {
            let _: &mut NodeTopology = topo[parent_idx].set_first_child(child_u32);
        }
        let next_count: u32 = topo[parent_idx].get_child_count().saturating_add(1);
        let _: &mut NodeTopology = topo[parent_idx]
            .set_last_child(child_u32)
            .set_child_count(next_count);
        let _: &mut SceneNode = self.get_mut_nodes()[child_idx].set_parent(Some(parent_id));
        if self.get_nodes()[child_idx].layout_ref().get_z_index() != 0 {
            let next_flags: u16 =
                self.get_meta()[parent_idx].get_flags() | NODE_FLAG_HAS_NONZERO_Z_CHILD;
            let _: &mut NodeMeta = self.get_mut_meta()[parent_idx].set_flags(next_flags);
        }
    }

    /// Detaches all direct children from `parent_idx` without disposing them, clearing `HAS_NONZERO_Z_CHILD`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `usize` - Parent slot index.
    fn unlink_all_children_at(&mut self, parent_idx: usize) {
        let mut cur: u32 = self.get_topology()[parent_idx].get_first_child();
        let _: &mut NodeTopology = self.get_mut_topology()[parent_idx]
            .set_first_child(NODE_INDEX_NONE)
            .set_last_child(NODE_INDEX_NONE)
            .set_child_count(0);
        let cleared: u16 = self.get_meta()[parent_idx].get_flags() & !NODE_FLAG_HAS_NONZERO_Z_CHILD;
        let _: &mut NodeMeta = self.get_mut_meta()[parent_idx].set_flags(cleared);
        while cur != NODE_INDEX_NONE {
            let ci: usize = cur as usize;
            let next: u32 = self.get_topology()[ci].get_next_sibling();
            let _: &mut NodeTopology = self.get_mut_topology()[ci]
                .set_parent(NODE_INDEX_NONE)
                .set_prev_sibling(NODE_INDEX_NONE)
                .set_next_sibling(NODE_INDEX_NONE);
            let _: &mut SceneNode = self.get_mut_nodes()[ci].set_parent(None);
            cur = next;
        }
    }

    /// Reorders or filters `parent`'s direct children to match `new_children` without disposing detached nodes, returning `true` if modified.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Parent container node handle.
    /// - `&[NodeId]` - Desired ordered child handles.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the parent's child sequence changed.
    pub fn set_children_detached(&mut self, parent: NodeId, new_children: &[NodeId]) -> bool {
        if self.get_node(parent).is_none() {
            return false;
        }
        if self.child_count(parent) == new_children.len()
            && self.children_iter(parent).eq(new_children.iter().copied())
        {
            return false;
        }
        let parent_idx: usize = parent.as_usize();
        self.unlink_all_children_at(parent_idx);
        for child in new_children.iter().copied() {
            if child == parent || self.get_node(child).is_none() {
                continue;
            }
            let child_idx: usize = child.as_usize();
            let prev_parent: u32 = self.get_topology()[child_idx].get_parent();
            if prev_parent != NODE_INDEX_NONE {
                self.unlink_child_at(prev_parent as usize, child_idx);
            }
            self.link_child_tail_at(parent_idx, parent, child_idx);
        }
        let dirty_lay: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
        let dirty_child: u16 = DIRTY_CHILDREN | DIRTY_PAINT;
        self.mark_dirty(parent, dirty_lay | dirty_child);
        true
    }

    /// Replaces `old_child` under `parent` with `new_child` in O(1) without shifting sibling storage.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Parent container node handle.
    /// - `NodeId` - Existing direct child handle to detach.
    /// - `NodeId` - Replacement child handle to splice in place.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `old_child` was replaced by `new_child`.
    pub fn replace_child(&mut self, parent: NodeId, old_child: NodeId, new_child: NodeId) -> bool {
        if old_child == new_child || new_child == parent {
            return false;
        }
        if self.get_node(parent).is_none()
            || self.get_node(old_child).is_none()
            || self.get_node(new_child).is_none()
        {
            return false;
        }
        let parent_idx: usize = parent.as_usize();
        let old_idx: usize = old_child.as_usize();
        let new_idx: usize = new_child.as_usize();
        if self.get_topology()[old_idx].get_parent() != parent_idx as u32 {
            return false;
        }
        let prev_parent: u32 = self.get_topology()[new_idx].get_parent();
        if prev_parent != NODE_INDEX_NONE {
            self.unlink_child_at(prev_parent as usize, new_idx);
        }
        let old_topo: NodeTopology = self.get_topology()[old_idx];
        let prev: u32 = old_topo.get_prev_sibling();
        let next: u32 = old_topo.get_next_sibling();
        let new_u32: u32 = new_idx as u32;
        let topo: &mut Vec<NodeTopology> = self.get_mut_topology();
        if prev != NODE_INDEX_NONE {
            let _: &mut NodeTopology = topo[prev as usize].set_next_sibling(new_u32);
        } else {
            let _: &mut NodeTopology = topo[parent_idx].set_first_child(new_u32);
        }
        if next != NODE_INDEX_NONE {
            let _: &mut NodeTopology = topo[next as usize].set_prev_sibling(new_u32);
        } else {
            let _: &mut NodeTopology = topo[parent_idx].set_last_child(new_u32);
        }
        let _: &mut NodeTopology = topo[new_idx]
            .set_parent(parent_idx as u32)
            .set_prev_sibling(prev)
            .set_next_sibling(next);
        let _: &mut NodeTopology = topo[old_idx]
            .set_parent(NODE_INDEX_NONE)
            .set_prev_sibling(NODE_INDEX_NONE)
            .set_next_sibling(NODE_INDEX_NONE);
        let _: &mut SceneNode = self.get_mut_nodes()[old_idx].set_parent(None);
        let _: &mut SceneNode = self.get_mut_nodes()[new_idx].set_parent(Some(parent));
        let old_z: i32 = self.get_nodes()[old_idx].layout_ref().get_z_index();
        let new_z: i32 = self.get_nodes()[new_idx].layout_ref().get_z_index();
        self.sync_parent_nonzero_z(parent_idx, old_z, new_z);
        self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
        true
    }

    /// Allocates a new node of `kind` with initial `style`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeKind` - Semantic node kind.
    /// - `Style` - Initial style.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Generation-checked node handle.
    pub fn create_node(&mut self, kind: NodeKind, style: Style) -> NodeId {
        let is_portal: bool = matches!(kind, NodeKind::Portal)
            || style.layout_ref().get_position() == Position::Fixed;
        let is_scroll: bool = matches!(kind, NodeKind::ScrollView)
            || style.layout_ref().get_overflow() == Overflow::Scroll;
        let mut init_flags: u16 = NODE_FLAG_ALIVE;
        if is_portal {
            init_flags |= NODE_FLAG_IS_PORTAL;
        }
        if is_scroll {
            init_flags |= NODE_FLAG_IS_SCROLL_CONTAINER;
        }
        let effect_entry: PaintEffectEntry =
            PaintEffectEntry::from_paint_and_blur(style.paint_ref(), 0.0);
        let effect_id: u32 = self.get_mut_effect_table().insert(effect_entry);
        let compact_paint: CompactPaintStyle =
            CompactPaintStyle::from_paint(style.paint_ref(), effect_id);
        let id: NodeId = if let Some(index) = self.get_mut_free_list().pop() {
            let slot_idx: usize = index as usize;
            let slot: &mut SceneNode = &mut self.get_mut_nodes()[slot_idx];
            let next_gen: u32 = slot.get_generation().wrapping_add(1).max(1);
            *slot = SceneNode::new(next_gen, kind, style);
            self.get_mut_meta()[slot_idx] = NodeMeta::new(next_gen, init_flags, DIRTY_ALL);
            self.get_mut_topology()[slot_idx] = NodeTopology::default();
            self.get_mut_compact_paints()[slot_idx] = compact_paint;
            if let Some(ep) = self.get_mut_paint_epochs().get_mut(slot_idx) {
                *ep = ep.wrapping_add(1);
            }
            NodeId::new(index, next_gen)
        } else {
            let index: u32 = self.get_nodes().len() as u32;
            self.get_mut_nodes().push(SceneNode::new(1, kind, style));
            self.get_mut_meta()
                .push(NodeMeta::new(1, init_flags, DIRTY_ALL));
            self.get_mut_topology().push(NodeTopology::default());
            self.get_mut_compact_paints().push(compact_paint);
            self.get_mut_paint_epochs().push(0);
            NodeId::new(index, 1)
        };
        if is_portal {
            self.get_mut_portal_nodes().push(id);
            self.set_full_damage_pending(true);
            self.clear_dirty_paint_queue();
        }
        if is_scroll {
            self.get_mut_scroll_nodes().push(id);
        }
        let next_live: usize = self.get_live_count().saturating_add(1);
        self.set_live_count(next_live);
        let next_created: usize = self.get_created_since_damage().saturating_add(1);
        self.set_created_since_damage(next_created);
        self.set_layout_damage_pending(true);
        self.set_layout_invalidations(self.get_layout_invalidations().saturating_add(1));
        if next_created > DIRTY_PAINT_FULL_THRESHOLD {
            self.set_full_damage_pending(true);
            self.set_full_damage_overflow(true);
            self.clear_dirty_paint_queue();
        } else if !self.get_full_damage_pending() {
            if self.get_dirty_paint_nodes().len() >= DIRTY_PAINT_FULL_THRESHOLD {
                self.set_full_damage_pending(true);
                self.set_full_damage_overflow(true);
                self.clear_dirty_paint_queue();
            } else {
                self.get_mut_dirty_paint_nodes().push(id);
                if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
                    let next_flags: u16 = meta.get_flags() | NODE_FLAG_IN_DIRTY_PAINT_QUEUE;
                    let _: &mut NodeMeta = meta.set_flags(next_flags);
                }
            }
        }
        let next_rev: u64 = self.get_revision().wrapping_add(1);
        self.set_revision(next_rev);
        notify_frame_needed();
        id
    }

    /// Creates a container `View` node.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `Style` - Initial box style.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Created node handle.
    pub fn create_view(&mut self, style: Style) -> NodeId {
        self.create_node(NodeKind::View, style)
    }

    /// Creates a `Text` node holding `content`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `String` - Initial UTF-8 text.
    /// - `Style` - Initial text and box style.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Created text node handle.
    pub fn create_text(&mut self, content: String, style: Style) -> NodeId {
        self.create_node(NodeKind::Text(content), style)
    }

    /// Creates an editable `Input` node.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `InputNodeState` - Initial input state.
    /// - `Style` - Initial input style.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Created input node handle.
    pub fn create_input(&mut self, state: InputNodeState, style: Style) -> NodeId {
        self.create_node(NodeKind::Input(state), style)
    }

    /// Creates an `Image` node displaying `buffer`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `ImageBuffer` - Decoded RGBA8 image buffer.
    /// - `Style` - Initial image style.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Created image node handle.
    pub fn create_image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
        self.create_node(NodeKind::Image(buffer), style)
    }

    /// Creates a `ScrollView` container with `Overflow::Scroll`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `Style` - Initial scroll container style.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Created scroll view handle.
    pub fn create_scroll_view(&mut self, style: Style) -> NodeId {
        self.create_node(NodeKind::ScrollView, style.overflow(Overflow::Scroll))
    }

    /// Creates a custom `Canvas` node bound to `painter` using `CanvasCaching::DynamicPerFrame`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `Style` - Initial canvas style.
    /// - `CanvasDrawCallback` - Draw callback invoked on each paint pass.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Created canvas node handle.
    pub fn create_canvas(&mut self, style: Style, painter: CanvasDrawCallback) -> NodeId {
        self.create_canvas_with_caching(style, CanvasCaching::DynamicPerFrame, painter)
    }

    /// Creates a custom `Canvas` node bound to `painter` with an explicit `CanvasCaching` policy.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `Style` - Initial canvas style.
    /// - `CanvasCaching` - Fragment caching strategy (`DynamicPerFrame` or `RetainedStatic`).
    /// - `CanvasDrawCallback` - Draw callback invoked on paint.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Created canvas node handle.
    pub fn create_canvas_with_caching(
        &mut self,
        style: Style,
        caching: CanvasCaching,
        painter: CanvasDrawCallback,
    ) -> NodeId {
        let id: NodeId = self.create_node(NodeKind::Canvas(caching), style);
        if let Some(node) = self.get_node_mut(id) {
            node.set_canvas_painter(Some(painter));
        }
        if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
            let next: u16 = meta.get_flags() | NODE_FLAG_HAS_EXTRAS;
            let _: &mut NodeMeta = meta.set_flags(next);
        }
        id
    }

    /// Creates an overlay `Portal` node rendered in the top stacking context.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `Style` - Initial portal style.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Created portal node handle.
    pub fn create_portal(&mut self, style: Style) -> NodeId {
        self.create_node(NodeKind::Portal, style)
    }

    /// Creates a logical `Fragment` grouping node.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Created fragment node handle.
    pub fn create_fragment(&mut self) -> NodeId {
        self.create_node(NodeKind::Fragment, Style::default())
    }

    /// Returns an immutable reference to a live node matching `id`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Node handle.
    ///
    /// # Returns
    ///
    /// - `Option<&SceneNode>` - Live node reference if valid.
    #[must_use]
    pub fn get_node(&self, id: NodeId) -> Option<&SceneNode> {
        let node: &SceneNode = self.get_nodes().get(id.as_usize())?;
        if node.get_alive() && node.get_generation() == id.get_generation() {
            Some(node)
        } else {
            None
        }
    }

    /// Returns a mutable reference to a live node matching `id`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Node handle.
    ///
    /// # Returns
    ///
    /// - `Option<&mut SceneNode>` - Mutable live node reference if valid.
    pub fn get_node_mut(&mut self, id: NodeId) -> Option<&mut SceneNode> {
        let node: &mut SceneNode = self.get_mut_nodes().get_mut(id.as_usize())?;
        if node.get_alive() && node.get_generation() == id.get_generation() {
            Some(node)
        } else {
            None
        }
    }

    /// Returns total count of live scene nodes in O(1).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of live nodes in the arena.
    #[must_use]
    #[inline(always)]
    pub fn live_node_count(&self) -> usize {
        self.get_live_count()
    }

    /// Appends `child` to `parent` in O(1) via intrusive sibling links and marks layout and paint dirty upward.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Parent container node.
    /// - `NodeId` - Child node to attach.
    pub fn append_child(&mut self, parent: NodeId, child: NodeId) {
        if parent == child || self.get_node(parent).is_none() || self.get_node(child).is_none() {
            return;
        }
        let parent_idx: usize = parent.as_usize();
        let child_idx: usize = child.as_usize();
        let prev_parent: Option<NodeId> = self.get_nodes()[child_idx].parent_id();
        if let Some(old_parent) = prev_parent {
            if old_parent != parent {
                self.record_subtree_logical_damage(child);
            }
            self.unlink_child_at(old_parent.as_usize(), child_idx);
            if old_parent != parent {
                self.mark_dirty(old_parent, DIRTY_CHILDREN_CHANGE_MASK);
            }
        }
        self.link_child_tail_at(parent_idx, parent, child_idx);
        self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
    }

    /// Appends multiple `children` to `parent` in a single dirty-marking pass with zero heap allocations.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Parent container node.
    /// - `&[NodeId]` - Ordered child nodes to append.
    pub fn append_children(&mut self, parent: NodeId, children: &[NodeId]) {
        if children.is_empty() || self.get_node(parent).is_none() {
            return;
        }
        let parent_idx: usize = parent.as_usize();
        let mut attached_any: bool = false;
        for child in children.iter().copied() {
            if child == parent || self.get_node(child).is_none() {
                continue;
            }
            let child_idx: usize = child.as_usize();
            let prev_parent: Option<NodeId> = self.get_nodes()[child_idx].parent_id();
            if let Some(old_parent) = prev_parent {
                if old_parent != parent {
                    self.record_subtree_logical_damage(child);
                }
                self.unlink_child_at(old_parent.as_usize(), child_idx);
                if old_parent != parent {
                    self.mark_dirty(old_parent, DIRTY_CHILDREN_CHANGE_MASK);
                }
            }
            self.link_child_tail_at(parent_idx, parent, child_idx);
            attached_any = true;
        }
        if attached_any {
            self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
        }
    }

    /// Replaces all children of `parent` with `new_children`, disposing previous subtrees cleanly.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Parent container node.
    /// - `Vec<NodeId>` - Replacement ordered children.
    pub fn replace_children(&mut self, parent: NodeId, new_children: Vec<NodeId>) {
        if self.get_node(parent).is_none() {
            return;
        }
        let parent_idx: usize = parent.as_usize();
        let old_children: Vec<NodeId> = self.children_vec(parent);
        self.unlink_all_children_at(parent_idx);
        if new_children.is_empty() {
            for old_child in old_children.into_iter() {
                self.dispose_subtree(old_child);
            }
        } else if old_children.len() > 16 && new_children.len() > 16 {
            let keep_set: HashSet<NodeId> = new_children.iter().copied().collect();
            for old_child in old_children.into_iter() {
                if !keep_set.contains(&old_child) {
                    self.dispose_subtree(old_child);
                }
            }
        } else {
            for old_child in old_children.into_iter() {
                if !new_children.contains(&old_child) {
                    self.dispose_subtree(old_child);
                }
            }
        }
        for child in new_children.into_iter() {
            if child == parent || self.get_node(child).is_none() {
                continue;
            }
            let child_idx: usize = child.as_usize();
            let prev_parent: u32 = self.get_topology()[child_idx].get_parent();
            if prev_parent != NODE_INDEX_NONE {
                self.unlink_child_at(prev_parent as usize, child_idx);
            }
            self.link_child_tail_at(parent_idx, parent, child_idx);
        }
        self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
    }

    /// Returns `true` when `prev` and `next` paint styles differ solely in `transform` or non-zero-crossing `opacity`.
    ///
    /// # Arguments
    ///
    /// - `&PaintStyle` - Previous paint style reference.
    /// - `&PaintStyle` - Candidate replacement paint style reference.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the change qualifies for the composite-only pass without repainting node contents.
    #[inline]
    fn is_composite_only_paint_change(prev: &PaintStyle, next: &PaintStyle) -> bool {
        let same_static: bool = prev.background_color() == next.background_color()
            && prev.background_gradient() == next.background_gradient()
            && prev.get_border() == next.get_border()
            && prev.get_radius() == next.get_radius()
            && prev.box_shadow() == next.box_shadow()
            && prev.focus_ring_border() == next.focus_ring_border()
            && prev.get_cursor() == next.get_cursor()
            && prev.get_pointer_events() == next.get_pointer_events();
        let same_vis: bool = (prev.get_opacity() > 0.0) == (next.get_opacity() > 0.0);
        let composite_changed: bool = prev.get_transform() != next.get_transform()
            || (prev.get_opacity() - next.get_opacity()).abs() > 0.0001;
        same_static && same_vis && composite_changed
    }

    /// Computes the minimal dirty bitmask and optional portal update comparing `prev` and `next` styles by reference.
    ///
    /// # Arguments
    ///
    /// - `&Style` - Previous compiled style reference.
    /// - `&Style` - Candidate replacement style reference.
    /// - `bool` - Whether the target node is already `NodeKind::Portal`.
    ///
    /// # Returns
    ///
    /// - `(u16, Option<bool>)` - Tuple `(dirty_mask, portal_update)`; `dirty_mask == DIRTY_NONE` on no-op writes.
    #[inline]
    fn diff_style_change(prev: &Style, next: &Style, is_portal_kind: bool) -> (u16, Option<bool>) {
        let layout_changed: bool = prev.layout_ref() != next.layout_ref();
        let text_metrics_changed: bool = !prev.text_ref().same_layout_metrics(next.text_ref());
        if layout_changed || text_metrics_changed {
            let prev_fixed: bool = prev.layout_ref().get_position() == Position::Fixed;
            let next_fixed: bool = next.layout_ref().get_position() == Position::Fixed;
            let portal_update: Option<bool> = if !is_portal_kind && prev_fixed != next_fixed {
                Some(next_fixed)
            } else {
                None
            };
            let layout_bits: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
            let visual_bits: u16 = DIRTY_TEXT | DIRTY_PAINT;
            let mask: u16 = layout_bits | visual_bits;
            return (mask, portal_update);
        }
        let paint_changed: bool = prev.paint_ref() != next.paint_ref();
        let text_visual_changed: bool = prev.text_ref() != next.text_ref();
        if paint_changed && !text_visual_changed {
            if Self::is_composite_only_paint_change(prev.paint_ref(), next.paint_ref()) {
                return (DIRTY_COMPOSITE, None);
            }
            return (DIRTY_PAINT, None);
        }
        if paint_changed || text_visual_changed {
            (DIRTY_PAINT, None)
        } else {
            (DIRTY_NONE, None)
        }
    }

    /// Returns `true` when transitioning from `prev` to `next` paint style can shrink shadows, borders, transforms, or hide children.
    ///
    /// # Arguments
    ///
    /// - `&PaintStyle` - Previous paint style reference.
    /// - `&PaintStyle` - Replacement paint style reference.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether the node's pre-mutation conservative bounds must be snapshotted before overwriting style.
    #[inline]
    fn needs_pre_paint_damage(prev: &PaintStyle, next: &PaintStyle) -> bool {
        let shadow_changed: bool = prev.box_shadow() != next.box_shadow();
        let transform_changed: bool = prev.get_transform() != next.get_transform();
        let border_shrank: bool = prev.get_border().get_width() > next.get_border().get_width();
        let focus_removed: bool =
            prev.focus_ring_border().is_some() && next.focus_ring_border().is_none();
        let opacity_toggled_zero: bool = (prev.get_opacity() > 0.0) != (next.get_opacity() > 0.0);
        let a: bool = shadow_changed || transform_changed;
        let b: bool = border_shrank || focus_removed;
        let ab: bool = a || b;
        ab || opacity_toggled_zero
    }

    /// Surgically updates a node's `Style`, marking only `DIRTY_PAINT` for pure paint changes and skipping no-op writes.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Target node handle.
    /// - `Style` - Replacement compiled style.
    pub fn set_style(&mut self, id: NodeId, style: Style) {
        let has_children: bool = self.has_children(id);
        let Some(node) = self.get_node(id) else {
            return;
        };
        let is_portal_kind: bool = matches!(node.get_kind(), NodeKind::Portal);
        let is_scroll_kind: bool = matches!(node.get_kind(), NodeKind::ScrollView);
        let prev: &Style = node.style_ref();
        let (dirty_mask, portal_update): (u16, Option<bool>) =
            Self::diff_style_change(prev, &style, is_portal_kind);
        if dirty_mask == DIRTY_NONE {
            return;
        }
        let prev_scroll: bool =
            is_scroll_kind || prev.layout_ref().get_overflow() == Overflow::Scroll;
        let next_scroll: bool =
            is_scroll_kind || style.layout_ref().get_overflow() == Overflow::Scroll;
        let scroll_update: Option<bool> = if prev_scroll != next_scroll {
            Some(next_scroll)
        } else {
            None
        };
        let pre_paint: bool = Self::needs_pre_paint_damage(prev.paint_ref(), style.paint_ref());
        let subtree_hidden: bool = pre_paint
            && (prev.paint_ref().get_opacity() > 0.0) != (style.paint_ref().get_opacity() > 0.0)
            && has_children;
        let prev_z: i32 = prev.layout_ref().get_z_index();
        let parent_idx: u32 = self.get_topology()[id.as_usize()].get_parent();
        if subtree_hidden {
            self.record_subtree_logical_damage(id);
        } else if pre_paint {
            self.record_node_logical_damage(id);
        }
        let hiding_now: bool = style.layout_ref().get_display() == Display::None
            || style.paint_ref().get_opacity() <= 0.001
            || style.paint_ref().get_pointer_events() == PointerEvents::None;
        let next_z: i32 = style.layout_ref().get_z_index();
        let next_paint: PaintStyle = *style.paint_ref();
        if let Some(node) = self.get_node_mut(id) {
            node.set_style(style);
        }
        let blur: f32 = self.backdrop_blur_radius(id);
        self.sync_node_compact_paint(id.as_usize(), &next_paint, blur);
        if prev_z != next_z && parent_idx != NODE_INDEX_NONE {
            self.sync_parent_nonzero_z(parent_idx as usize, prev_z, next_z);
        }
        if hiding_now {
            self.clear_subtree_hover(id);
        }
        if let Some(is_portal) = portal_update {
            self.sync_portal_registration(id, is_portal);
        }
        if let Some(is_scroll) = scroll_update {
            self.sync_scroll_registration(id, is_scroll);
        }
        self.mark_dirty(id, dirty_mask);
    }

    /// Mutates a node's `Style` in place and marks the minimal dirty mask (`DIRTY_PAINT` vs layout) only if changed.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Target node handle.
    /// - `F` - In-place style mutator closure receiving `&mut Style`.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the node existed and its style changed.
    pub fn mutate_style<F>(&mut self, id: NodeId, mutator: F) -> bool
    where
        F: FnOnce(&mut Style),
    {
        let has_children: bool = self.has_children(id);
        let prev_opt: Option<(Style, bool, bool, u32)> =
            self.get_node(id).map(|node: &SceneNode| {
                (
                    *node.style_ref(),
                    matches!(node.get_kind(), NodeKind::Portal),
                    matches!(node.get_kind(), NodeKind::ScrollView),
                    self.get_topology()[id.as_usize()].get_parent(),
                )
            });
        let Some((prev, is_portal_kind, is_scroll_kind, parent_idx)) = prev_opt else {
            return false;
        };
        let mut next: Style = prev;
        mutator(&mut next);
        let (dirty_mask, portal_update): (u16, Option<bool>) =
            Self::diff_style_change(&prev, &next, is_portal_kind);
        if dirty_mask == DIRTY_NONE {
            return false;
        }
        let prev_scroll: bool =
            is_scroll_kind || prev.layout_ref().get_overflow() == Overflow::Scroll;
        let next_scroll: bool =
            is_scroll_kind || next.layout_ref().get_overflow() == Overflow::Scroll;
        let scroll_update: Option<bool> = if prev_scroll != next_scroll {
            Some(next_scroll)
        } else {
            None
        };
        let pre_paint: bool = Self::needs_pre_paint_damage(prev.paint_ref(), next.paint_ref());
        if pre_paint {
            let opacity_toggled_zero: bool =
                (prev.paint_ref().get_opacity() > 0.0) != (next.paint_ref().get_opacity() > 0.0);
            if opacity_toggled_zero && has_children {
                self.record_subtree_logical_damage(id);
            } else {
                self.record_node_logical_damage(id);
            }
        }
        let hiding_now: bool = next.layout_ref().get_display() == Display::None
            || next.paint_ref().get_opacity() <= 0.001
            || next.paint_ref().get_pointer_events() == PointerEvents::None;
        let prev_z: i32 = prev.layout_ref().get_z_index();
        let next_z: i32 = next.layout_ref().get_z_index();
        let next_paint: PaintStyle = *next.paint_ref();
        if let Some(node) = self.get_node_mut(id) {
            node.set_style(next);
        }
        let blur: f32 = self.backdrop_blur_radius(id);
        self.sync_node_compact_paint(id.as_usize(), &next_paint, blur);
        if prev_z != next_z && parent_idx != NODE_INDEX_NONE {
            self.sync_parent_nonzero_z(parent_idx as usize, prev_z, next_z);
        }
        if hiding_now {
            self.clear_subtree_hover(id);
        }
        if let Some(is_portal) = portal_update {
            self.sync_portal_registration(id, is_portal);
        }
        if let Some(is_scroll) = scroll_update {
            self.sync_scroll_registration(id, is_scroll);
        }
        self.mark_dirty(id, dirty_mask);
        true
    }

    /// Surgically updates the UTF-8 string of a `NodeKind::Text` node.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Target text node handle.
    /// - `String` - Replacement text string.
    pub fn set_text(&mut self, id: NodeId, text: String) {
        let (changed, fixed_size): (bool, bool) = match self.get_node_mut(id) {
            Some(node) => {
                let layout: &LayoutStyle = node.style_ref().layout_ref();
                let has_fixed: bool = matches!(layout.get_width(), Length::Px(_))
                    && matches!(layout.get_height(), Length::Px(_));
                match node.get_mut_kind() {
                    NodeKind::Text(current) => {
                        if *current == text {
                            (false, has_fixed)
                        } else {
                            *current = text;
                            (true, has_fixed)
                        }
                    }
                    _ => (false, false),
                }
            }
            None => (false, false),
        };
        if changed {
            let mask: u16 = if fixed_size {
                DIRTY_PAINT
            } else {
                DIRTY_TEXT_CHANGE_MASK
            };
            self.mark_dirty(id, mask);
        }
    }

    /// Replaces the UTF-8 contents of a `NodeKind::Text` node in place from a borrowed `&str`, reusing existing `String` capacity with zero allocation.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Target text node handle.
    /// - `&str` - Replacement text slice.
    pub fn set_text_str(&mut self, id: NodeId, text: &str) {
        let (changed, fixed_size): (bool, bool) = match self.get_node_mut(id) {
            Some(node) => {
                let layout: &LayoutStyle = node.style_ref().layout_ref();
                let has_fixed: bool = matches!(layout.get_width(), Length::Px(_))
                    && matches!(layout.get_height(), Length::Px(_));
                match node.get_mut_kind() {
                    NodeKind::Text(current) => {
                        if current.as_str() == text {
                            (false, has_fixed)
                        } else {
                            current.clear();
                            current.push_str(text);
                            (true, has_fixed)
                        }
                    }
                    _ => (false, false),
                }
            }
            None => (false, false),
        };
        if changed {
            let mask: u16 = if fixed_size {
                DIRTY_PAINT
            } else {
                DIRTY_TEXT_CHANGE_MASK
            };
            self.mark_dirty(id, mask);
        }
    }

    /// Mutates a `NodeKind::Text` node's backing `String` buffer directly in place via `mutate` with zero heap allocations.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Target text node handle.
    /// - `F` - Closure writing the updated text into the existing `&mut String` buffer.
    pub fn mutate_text<F>(&mut self, id: NodeId, mutate: F)
    where
        F: FnOnce(&mut String),
    {
        let (updated, fixed_size): (bool, bool) = match self.get_node_mut(id) {
            Some(node) => {
                let layout: &LayoutStyle = node.style_ref().layout_ref();
                let has_fixed: bool = matches!(layout.get_width(), Length::Px(_))
                    && matches!(layout.get_height(), Length::Px(_));
                match node.get_mut_kind() {
                    NodeKind::Text(current) => {
                        mutate(current);
                        (true, has_fixed)
                    }
                    _ => (false, false),
                }
            }
            None => (false, false),
        };
        if updated {
            let mask: u16 = if fixed_size {
                DIRTY_PAINT
            } else {
                DIRTY_TEXT_CHANGE_MASK
            };
            self.mark_dirty(id, mask);
        }
    }

    /// Updates scroll offset on a scroll container without triggering full subtree re-layout.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Target scroll container handle.
    /// - `Point` - New scroll offset clamped to content bounds.
    pub fn set_scroll_offset(&mut self, id: NodeId, offset: Point) {
        let changed: bool = match self.get_node_mut(id) {
            Some(node) => {
                let layout_box: LayoutBox = node.get_layout_box();
                let unlaid_out: bool = layout_box.get_content_size().get_width() <= 0.0
                    && layout_box.get_content_size().get_height() <= 0.0
                    && layout_box.get_content_bounds().get_width() <= 0.0
                    && layout_box.get_content_bounds().get_height() <= 0.0;
                let clamped: Point = if unlaid_out || node.virtual_scroll_metrics().is_some() {
                    Point::new(offset.get_x().max(0.0), offset.get_y().max(0.0))
                } else {
                    let max_x: f32 = (layout_box.get_content_size().get_width()
                        - layout_box.get_content_bounds().get_width())
                    .max(0.0);
                    let max_y: f32 = (layout_box.get_content_size().get_height()
                        - layout_box.get_content_bounds().get_height())
                    .max(0.0);
                    Point::new(
                        offset.get_x().clamp(0.0, max_x),
                        offset.get_y().clamp(0.0, max_y),
                    )
                };
                if layout_box.get_scroll_offset() == clamped {
                    false
                } else {
                    node.get_mut_layout_box().set_scroll_offset(clamped);
                    true
                }
            }
            None => false,
        };
        if changed {
            self.mark_dirty(id, DIRTY_SCROLL | DIRTY_COMPOSITE);
        }
    }

    /// Records virtualized scroll progress `(scroll_y, content_height)` on `id` for overlay scrollbar rendering.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Target virtualized scroll container.
    /// - `f32` - Active virtual vertical scroll offset in logical pixels.
    /// - `f32` - Full virtualized content height in logical pixels.
    pub fn set_virtual_scroll(&mut self, id: NodeId, scroll_y: f32, content_height: f32) {
        let mut changed: bool = false;
        let mut prev_metrics: Option<(f32, f32)> = None;
        let next_metrics: (f32, f32) = (scroll_y.max(0.0), content_height.max(1.0));
        let mut scrollbar_bounds: Option<(Rect, f32, f32)> = None;
        if let Some(node) = self.get_node_mut(id) {
            let prev: Option<(f32, f32)> = node.virtual_scroll_metrics();
            prev_metrics = prev;
            let next: Option<(f32, f32)> = Some(next_metrics);
            if prev != next {
                changed = true;
                node.set_virtual_scroll(next);
                let raw_b: Rect = node.get_layout_box().get_bounds();
                let bw: f32 = node.style_ref().paint_ref().get_border().get_width();
                let view_h: f32 = node
                    .get_layout_box()
                    .get_content_bounds()
                    .get_height()
                    .max(1.0);
                if raw_b.get_width() > 0.0 && raw_b.get_height() > 0.0 {
                    scrollbar_bounds = Some((raw_b, bw, view_h));
                }
            }
        }
        if changed {
            if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
                let next_flags: u16 = meta.get_flags() | NODE_FLAG_HAS_EXTRAS;
                let _: &mut NodeMeta = meta.set_flags(next_flags);
            }
            let show_scrollbar: bool = self
                .get_node(self.get_root())
                .map(|r: &SceneNode| {
                    let rb: Rect = r.get_layout_box().get_bounds();
                    rb.get_width().min(rb.get_height()) >= 540.0
                })
                .unwrap_or(true);
            if !show_scrollbar {
                let next_rev: u64 = self.get_revision().wrapping_add(1);
                self.set_revision(next_rev);
            } else if let Some((raw_b, bw, view_h)) = scrollbar_bounds
                && let Some(screen_b) = self.node_screen_bounds(id)
                && screen_b.get_width() > 0.0
                && screen_b.get_height() > 0.0
            {
                let inner_y: f32 = screen_b.get_y() + bw;
                let inner_h: f32 = (raw_b.get_height() - bw * 2.0).max(1.0);
                let track_y: f32 = inner_y + 3.0;
                let track_h: f32 = (inner_h - 6.0).max(16.0);
                let n_max_sy: f32 = (next_metrics.1 - view_h).max(0.0);
                let n_ratio: f32 = (view_h / next_metrics.1.max(view_h)).clamp(0.0, 1.0);
                let n_thumb_h: f32 = (track_h * n_ratio).clamp(20.0_f32.min(track_h), track_h);
                let n_frac: f32 = if n_max_sy > 1.0 {
                    (next_metrics.0 / n_max_sy).clamp(0.0, 1.0)
                } else {
                    0.0
                };
                let ny0: f32 = track_y + (track_h - n_thumb_h) * n_frac;
                let ny1: f32 = ny0 + n_thumb_h;
                let (y0, y1): (f32, f32) = match prev_metrics {
                    Some((py, ph)) => {
                        let p_max_sy: f32 = (ph - view_h).max(0.0);
                        let p_ratio: f32 = (view_h / ph.max(view_h)).clamp(0.0, 1.0);
                        let p_thumb_h: f32 =
                            (track_h * p_ratio).clamp(20.0_f32.min(track_h), track_h);
                        let p_frac: f32 = if p_max_sy > 1.0 {
                            (py / p_max_sy).clamp(0.0, 1.0)
                        } else {
                            0.0
                        };
                        let py0: f32 = track_y + (track_h - p_thumb_h) * p_frac;
                        let py1: f32 = py0 + p_thumb_h;
                        (py0.min(ny0) - 4.0, py1.max(ny1) + 4.0)
                    }
                    None => (screen_b.get_y(), screen_b.bottom()),
                };
                let clamped_y0: f32 = y0.max(screen_b.get_y());
                let clamped_y1: f32 = y1.min(screen_b.bottom());
                let strip_x: f32 = (screen_b.right() - bw - 12.0).max(screen_b.get_x());
                let strip_w: f32 = (screen_b.right() - strip_x + 2.0).max(1.0);
                let strip_rect: Rect = Rect::new(
                    strip_x,
                    clamped_y0,
                    strip_w,
                    (clamped_y1 - clamped_y0).max(1.0),
                );
                if !self.get_full_damage_pending() {
                    if self.get_extra_logical_damage().len() >= DIRTY_PAINT_FULL_THRESHOLD {
                        self.set_full_damage_pending(true);
                        self.set_full_damage_overflow(true);
                        self.get_mut_extra_logical_damage().clear();
                    } else {
                        self.get_mut_extra_logical_damage().push(strip_rect);
                    }
                }
                let next_rev: u64 = self.get_revision().wrapping_add(1);
                self.set_revision(next_rev);
            } else {
                self.mark_dirty(id, DIRTY_SCROLL | DIRTY_COMPOSITE);
            }
        }
    }

    /// Computes screen-space logical bounds for `id` after applying ancestor scroll offsets and transforms.
    ///
    /// Returns `Some(Rect::default())` when `id` or any ancestor has `Display::None`, preserving zero-area semantics even when descendants retain warm layout caches.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Target node handle.
    ///
    /// # Returns
    ///
    /// - `Option<Rect>` - Screen-space rectangle if the node is alive.
    #[must_use]
    pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
        let node: &SceneNode = self.get_node(id)?;
        let (off, tx, ty, sx, sy): (Point, f32, f32, f32, f32) =
            match self.node_scroll_and_transform(node) {
                Some(vals) => vals,
                None => return Some(Rect::default()),
            };
        let raw: Rect = node.get_layout_box().get_bounds();
        Some(Rect::new(
            raw.get_x() - off.get_x() + tx,
            raw.get_y() - off.get_y() + ty,
            raw.get_width() * sx,
            raw.get_height() * sy,
        ))
    }

    /// Computes accumulated ancestor scroll offset and combined 2D transform for `node` in a single ancestor walk.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `&SceneNode` - Borrowed target scene node.
    ///
    /// # Returns
    ///
    /// - `Option<(Point, f32, f32, f32, f32)>` - Tuple `(scroll_offset, tx, ty, scale_x, scale_y)`, or `None` when `node` or any ancestor has `Display::None`.
    #[inline]
    fn node_scroll_and_transform(&self, node: &SceneNode) -> Option<(Point, f32, f32, f32, f32)> {
        let style: &Style = node.style_ref();
        if style.layout_ref().get_display() == Display::None {
            return None;
        }
        let tr: Transform2D = style.paint_ref().get_transform();
        let mut tx: f32 = tr.get_translate_x();
        let mut ty: f32 = tr.get_translate_y();
        let sx_scale: f32 = tr.get_scale_x();
        let sy_scale: f32 = tr.get_scale_y();
        let start_top_layer: bool = matches!(node.get_kind(), NodeKind::Portal)
            || style.layout_ref().get_position() == Position::Fixed;
        let mut stop_transform: bool = false;
        let mut scroll_x: f32 = 0.0;
        let mut scroll_y: f32 = 0.0;
        let mut cursor: Option<NodeId> = node.parent_id();
        while let Some(pid) = cursor {
            if let Some(pnode) = self.get_node(pid) {
                let pstyle: &Style = pnode.style_ref();
                if pstyle.layout_ref().get_display() == Display::None {
                    return None;
                }
                if !stop_transform {
                    let ptr: Transform2D = pstyle.paint_ref().get_transform();
                    tx += ptr.get_translate_x();
                    ty += ptr.get_translate_y();
                    if !start_top_layer {
                        let off: Point = pnode.get_layout_box().get_scroll_offset();
                        scroll_x += off.get_x();
                        scroll_y += off.get_y();
                    }
                    let parent_top_layer: bool = matches!(pnode.get_kind(), NodeKind::Portal)
                        || pstyle.layout_ref().get_position() == Position::Fixed;
                    if parent_top_layer {
                        stop_transform = true;
                    }
                }
                cursor = pnode.parent_id();
            } else {
                break;
            }
        }
        Some((Point::new(scroll_x, scroll_y), tx, ty, sx_scale, sy_scale))
    }

    /// Computes a conservative logical screen-space paint rectangle for `id` including ancestor scroll, transform, border, focus ring, and `3 * sigma` shadow halo.
    ///
    /// Returns `None` when a non-axis-aligned rotation or ancestor scale requires a safe full-viewport fallback.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Target scene node handle.
    ///
    /// # Returns
    ///
    /// - `Option<Rect>` - Conservative logical screen bounds, `Some(Rect::default())` when unmeasured, or `None` for unsafe fallback.
    #[must_use]
    pub(crate) fn node_conservative_logical_rect(&self, id: NodeId) -> Option<Rect> {
        let node: &SceneNode = self.get_node(id)?;
        let raw_bounds: Rect = node.get_layout_box().get_bounds();
        if raw_bounds.get_width() <= 0.0 || raw_bounds.get_height() <= 0.0 {
            return Some(Rect::default());
        }
        let style: &Style = node.style_ref();
        let paint: &PaintStyle = style.paint_ref();
        let tr: Transform2D = paint.get_transform();
        if tr.get_rotation_rad().abs() > 0.0001
            || tr.get_scale_x() <= 0.0
            || tr.get_scale_y() <= 0.0
        {
            return None;
        }
        let border_w: f32 = paint.get_border().get_width();
        let focus_pad: f32 = if paint.focus_ring_border().is_some() {
            12.0
        } else {
            0.0
        };
        let mut margin: f32 = if border_w > 0.0 {
            10.0_f32.max(border_w + 6.0).max(focus_pad)
        } else {
            4.0_f32.max(focus_pad)
        };
        if let Some(shadow) = paint.box_shadow() {
            let blur_sigma: f32 = (shadow.get_blur_radius().max(0.5) * 0.5).clamp(0.75, 48.0);
            let blur_pad: f32 = (blur_sigma * 3.0).ceil() + 4.0;
            let spread: f32 = shadow.get_spread_radius().max(0.0);
            let off_max: f32 = shadow.get_offset_x().abs().max(shadow.get_offset_y().abs());
            margin = margin.max(blur_pad + spread + off_max + 4.0);
        }
        let backdrop_blur: f32 = self.backdrop_blur_radius(id);
        if backdrop_blur > 0.0 {
            let sigma: f32 = (backdrop_blur * 0.5).max(0.75);
            let blur_halo: f32 = (sigma * 3.0).ceil() + 4.0;
            margin = margin.max(blur_halo);
        }
        let tx: f32 = tr.get_translate_x();
        let ty: f32 = tr.get_translate_y();
        let sx: f32 = tr.get_scale_x();
        let sy: f32 = tr.get_scale_y();
        let base_rect: Rect = Rect::new(
            raw_bounds.get_x() - margin,
            raw_bounds.get_y() - margin,
            raw_bounds.get_width() + margin * 2.0,
            raw_bounds.get_height() + margin * 2.0,
        );
        let shifted_x: bool = tx != 0.0 || sx != 1.0;
        let shifted_y: bool = ty != 0.0 || sy != 1.0;
        let mut cur_rect: Rect = if shifted_x || shifted_y {
            let scale_pad_x: f32 = ((sx - 1.0).abs() * raw_bounds.get_width()).max(0.0);
            let scale_pad_y: f32 = ((sy - 1.0).abs() * raw_bounds.get_height()).max(0.0);
            let shifted_rect: Rect = Rect::new(
                raw_bounds.get_x() + tx - margin - scale_pad_x,
                raw_bounds.get_y() + ty - margin - scale_pad_y,
                raw_bounds.get_width() * sx + (margin + scale_pad_x) * 2.0,
                raw_bounds.get_height() * sy + (margin + scale_pad_y) * 2.0,
            );
            base_rect.union(shifted_rect)
        } else {
            base_rect
        };
        let start_top_layer: bool = matches!(node.get_kind(), NodeKind::Portal)
            || style.layout_ref().get_position() == Position::Fixed;
        let mut cursor: Option<NodeId> = node.parent_id();
        while let Some(pid) = cursor {
            let Some(pnode) = self.get_node(pid) else {
                break;
            };
            let pstyle: &Style = pnode.style_ref();
            let ptr: Transform2D = pstyle.paint_ref().get_transform();
            if ptr.get_rotation_rad().abs() > 0.0001
                || (ptr.get_scale_x() - 1.0).abs() > 0.001
                || (ptr.get_scale_y() - 1.0).abs() > 0.001
            {
                return None;
            }
            if !start_top_layer {
                let off: Point = pnode.get_layout_box().get_scroll_offset();
                cur_rect = Rect::new(
                    cur_rect.get_x() - off.get_x(),
                    cur_rect.get_y() - off.get_y(),
                    cur_rect.get_width(),
                    cur_rect.get_height(),
                );
                let p_ov: Overflow = pstyle.layout_ref().get_overflow();
                if matches!(p_ov, Overflow::Hidden | Overflow::Scroll) {
                    let pb: Rect = pnode.get_layout_box().get_bounds();
                    if pb.get_width() > 0.0 && pb.get_height() > 0.0 {
                        let clip_box: Rect = Rect::new(
                            pb.get_x() - 1.0,
                            pb.get_y() - 1.0,
                            pb.get_width() + 2.0,
                            pb.get_height() + 2.0,
                        );
                        match cur_rect.intersect(clip_box) {
                            Some(clipped) => cur_rect = clipped,
                            None => return Some(Rect::default()),
                        }
                    }
                }
            }
            let ptx: f32 = ptr.get_translate_x();
            let pty: f32 = ptr.get_translate_y();
            if ptx != 0.0 || pty != 0.0 {
                cur_rect = Rect::new(
                    cur_rect.get_x() + ptx,
                    cur_rect.get_y() + pty,
                    cur_rect.get_width(),
                    cur_rect.get_height(),
                );
            }
            let parent_top_layer: bool = matches!(pnode.get_kind(), NodeKind::Portal)
                || pstyle.layout_ref().get_position() == Position::Fixed;
            if parent_top_layer {
                break;
            }
            cursor = pnode.parent_id();
        }
        Some(cur_rect)
    }

    /// Converts a conservative logical screen rectangle into an exact outward-rounded physical pixel rectangle.
    ///
    /// # Arguments
    ///
    /// - `Rect` - Conservative logical screen rectangle.
    /// - `f32` - Active display scale factor.
    ///
    /// # Returns
    ///
    /// - `Rect` - Physical pixel rectangle guaranteed to enclose all covered pixels.
    #[must_use]
    pub(crate) fn scale_logical_to_phys_rect(logical: Rect, scale: f32) -> Rect {
        let x0: f32 = (logical.get_x() * scale).floor();
        let y0: f32 = (logical.get_y() * scale).floor();
        let x1: f32 = (logical.right() * scale).ceil();
        let y1: f32 = (logical.bottom() * scale).ceil();
        Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
    }

    /// Records the current conservative logical bounds of `id` into `extra_logical_damage` prior to destructive mutation.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Target scene node handle.
    fn record_node_logical_damage(&mut self, id: NodeId) {
        if self.get_full_damage_pending() {
            return;
        }
        let rect_opt: Option<Rect> = self.node_conservative_logical_rect(id);
        match rect_opt {
            Some(rect) => {
                if rect.get_width() <= 0.0 || rect.get_height() <= 0.0 {
                    return;
                }
                if self.get_extra_logical_damage().len() >= DIRTY_PAINT_FULL_THRESHOLD {
                    self.set_full_damage_pending(true);
                    self.set_full_damage_overflow(true);
                    self.get_mut_extra_logical_damage().clear();
                } else {
                    self.get_mut_extra_logical_damage().push(rect);
                }
            }
            None => {
                self.set_full_damage_pending(true);
            }
        }
    }

    /// Records pre-mutation conservative logical bounds for every live laid-out node in the subtree rooted at `root`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Subtree root handle.
    fn record_subtree_logical_damage(&mut self, root: NodeId) {
        if self.get_full_damage_pending() {
            return;
        }
        let mut stack: Vec<NodeId> = vec![root];
        let mut visited: usize = 0;
        while let Some(current) = stack.pop() {
            let Some(raw_bounds) = self
                .get_node(current)
                .map(|node: &SceneNode| node.layout_box_ref().get_bounds())
            else {
                continue;
            };
            visited += 1;
            if visited > DIRTY_PAINT_FULL_THRESHOLD {
                self.set_full_damage_pending(true);
                self.set_full_damage_overflow(true);
                self.get_mut_extra_logical_damage().clear();
                return;
            }
            for child in self.children_iter(current) {
                stack.push(child);
            }
            if raw_bounds.get_width() > 0.0 && raw_bounds.get_height() > 0.0 {
                self.record_node_logical_damage(current);
                if self.get_full_damage_pending() {
                    return;
                }
            }
        }
    }

    /// Starts or smoothly retargets a paint/transform transition on `transition.get_node()`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeTransition` - Transition specification to run.
    pub fn start_transition(&mut self, mut transition: NodeTransition) {
        let target: NodeId = transition.get_node();
        let had_active: bool = self
            .get_transitions()
            .iter()
            .any(|tr: &NodeTransition| tr.get_node() == target);
        self.get_mut_transitions()
            .retain(|tr: &NodeTransition| tr.get_node() != target);
        if had_active && let Some(node) = self.get_node(target) {
            let paint: PaintStyle = node.get_style().get_paint();
            let tr: Transform2D = paint.get_transform();
            let cur_op: f32 = paint.get_opacity();
            let cur_tx: f32 = tr.get_translate_x();
            let cur_ty: f32 = tr.get_translate_y();
            let cur_sc: f32 = tr.get_scale_x();
            let full_dist: f32 = (transition.get_to_tx() - transition.get_from_tx())
                .hypot(transition.get_to_ty() - transition.get_from_ty())
                .max((transition.get_to_opacity() - transition.get_from_opacity()).abs() * 100.0);
            let rem_dist: f32 = (transition.get_to_tx() - cur_tx)
                .hypot(transition.get_to_ty() - cur_ty)
                .max((transition.get_to_opacity() - cur_op).abs() * 100.0);
            if full_dist > 0.01 {
                let ratio: f32 = (rem_dist / full_dist).clamp(0.20, 1.0);
                transition.set_duration((transition.get_duration() * ratio).max(0.05));
            }
            transition.set_from_opacity(cur_op);
            transition.set_from_tx(cur_tx);
            transition.set_from_ty(cur_ty);
            transition.set_from_scale(cur_sc);
        }
        self.record_node_logical_damage(target);
        let (opacity, transform): (f32, Transform2D) = transition.sample();
        let mut unhidden: bool = false;
        if let Some(node) = self.get_node_mut(target) {
            let style: &mut Style = node.get_mut_style();
            if !transition.get_hide_on_complete()
                && style.layout_ref().get_display() == Display::None
            {
                style.get_mut_layout().set_display(Display::Flex);
                unhidden = true;
            }
            style.get_mut_paint().set_opacity(opacity);
            style.get_mut_paint().set_transform(transform);
        }
        if unhidden {
            let layout_dirty: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
            self.mark_dirty(target, layout_dirty | DIRTY_PAINT);
        } else {
            self.mark_dirty(target, DIRTY_COMPOSITE);
        }
        self.get_mut_transitions().push(transition);
    }

    /// Advances all active transitions by `dt_secs` and returns `true` if any node updated.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `f32` - Elapsed frame time in seconds.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether at least one transition ticked on this frame.
    pub fn tick_transitions(&mut self, dt_secs: f32) -> bool {
        let len: usize = self.get_transitions().len();
        if len == 0 {
            return false;
        }
        let step: f32 = dt_secs.clamp(0.001, 0.05);
        let mut any_updated: bool = false;
        let mut write_idx: usize = 0;
        for read_idx in 0..len {
            let target: NodeId = self.get_transitions()[read_idx].get_node();
            if self.get_node(target).is_none() {
                continue;
            }
            let (done, sample_opt, hide): (bool, Option<(f32, Transform2D)>, bool) = {
                let tr: &mut NodeTransition = &mut self.get_mut_transitions()[read_idx];
                let total_span: f32 = tr.get_delay() + tr.get_duration();
                let prev_elapsed: f32 = tr.get_elapsed();
                let next_elapsed: f32 = (prev_elapsed + step).min(total_span);
                tr.set_elapsed(next_elapsed);
                let is_done: bool = tr.is_complete();
                let in_hold: bool =
                    prev_elapsed > 0.0 && next_elapsed <= tr.get_delay() && !is_done;
                if in_hold {
                    (is_done, None, false)
                } else {
                    let sampled: (f32, Transform2D) = tr.sample();
                    let should_hide: bool = is_done && tr.get_hide_on_complete();
                    (is_done, Some(sampled), should_hide)
                }
            };
            if let Some((opacity, transform)) = sample_opt {
                self.record_node_logical_damage(target);
                if let Some(node) = self.get_node_mut(target) {
                    let style: &mut Style = node.get_mut_style();
                    style.get_mut_paint().set_opacity(opacity);
                    style.get_mut_paint().set_transform(transform);
                    if hide {
                        style.get_mut_layout().set_display(Display::None);
                    }
                }
                if hide {
                    self.clear_subtree_hover(target);
                    let layout_dirty: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
                    self.mark_dirty(target, layout_dirty | DIRTY_PAINT);
                } else {
                    self.mark_dirty(target, DIRTY_COMPOSITE);
                }
                any_updated = true;
            }
            if !done {
                if write_idx != read_idx {
                    self.get_mut_transitions().swap(write_idx, read_idx);
                }
                write_idx += 1;
            }
        }
        self.get_mut_transitions().truncate(write_idx);
        any_updated
    }

    /// Clears transient hover, pressed, and focus flags within `root`'s subtree in O(depth) using `FocusManager` ancestor checks.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Root node being hidden.
    pub(crate) fn clear_subtree_hover(&mut self, root: NodeId) {
        let hovered_opt: Option<NodeId> = self.get_focus().hovered_node();
        if let Some(hovered_id) = hovered_opt
            && self.is_in_subtree(hovered_id, root)
        {
            self.get_mut_focus().set_hovered(None);
            if let Some(node) = self.get_node_mut(hovered_id) {
                node.get_mut_interaction().set_hovered(false);
            }
        }
        let pressed_opt: Option<NodeId> = self.get_focus().pressed_node();
        if let Some(pressed_id) = pressed_opt
            && self.is_in_subtree(pressed_id, root)
        {
            self.get_mut_focus().set_pressed(None);
            if let Some(node) = self.get_node_mut(pressed_id) {
                node.get_mut_interaction().set_pressed(false);
            }
        }
        let focused_opt: Option<NodeId> = self.get_focus().focused_node();
        if let Some(focused_id) = focused_opt
            && self.is_in_subtree(focused_id, root)
        {
            self.get_mut_focus().set_focused(None);
            if let Some(node) = self.get_node_mut(focused_id) {
                node.get_mut_interaction().set_focused(false);
            }
        }
    }

    /// Returns `true` while one or more node transitions are still running.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether animations are active.
    #[must_use]
    pub fn has_active_transitions(&self) -> bool {
        !self.get_transitions().is_empty()
    }

    /// Attaches a `Lifecycle` hook observer onto `id` for mount, activate, freeze, resume, unmount, and destroy dispatch.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Target scene node handle.
    /// - `Rc<dyn Lifecycle>` - Shared lifecycle hook observer.
    pub fn attach_lifecycle(&mut self, id: NodeId, hook: Rc<dyn Lifecycle>) {
        let attached: bool = if let Some(node) = self.get_node_mut(id) {
            node.add_lifecycle(hook);
            true
        } else {
            false
        };
        if attached {
            if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
                let add_flags: u16 = NODE_FLAG_HAS_EXTRAS + NODE_FLAG_HAS_LIFECYCLE;
                let next_flags: u16 = meta.get_flags() | add_flags;
                let _: &mut NodeMeta = meta.set_flags(next_flags);
            }
            let next_lc: usize = self.get_live_lifecycle_count().saturating_add(1);
            self.set_live_lifecycle_count(next_lc);
        }
    }

    /// Collects all `(NodeId, Rc<dyn Lifecycle>)` observers in the subtree rooted at `root`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Subtree root handle.
    ///
    /// # Returns
    ///
    /// - `Vec<(NodeId, Rc<dyn Lifecycle>)>` - Ordered observers in pre-order traversal.
    #[must_use]
    pub fn collect_subtree_lifecycles(&self, root: NodeId) -> Vec<(NodeId, Rc<dyn Lifecycle>)> {
        if self.get_live_lifecycle_count() == 0 {
            return Vec::new();
        }
        let mut out: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
        let mut stack: Vec<NodeId> = vec![root];
        while let Some(current) = stack.pop() {
            let idx: usize = current.as_usize();
            let Some(meta) = self.get_meta().get(idx) else {
                continue;
            };
            if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
                || meta.get_generation() != current.get_generation()
            {
                continue;
            }
            if (meta.get_flags() & NODE_FLAG_HAS_LIFECYCLE) != 0 {
                for hook in self.get_nodes()[idx].lifecycle_observers().into_iter() {
                    out.push((current, hook));
                }
            }
            for child in self.children_iter(current).rev() {
                stack.push(child);
            }
        }
        out
    }

    /// Collects all `Lifecycle` observers attached to visible (`Display != None`) nodes across the entire tree.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    ///
    /// # Returns
    ///
    /// - `Vec<(NodeId, Rc<dyn Lifecycle>)>` - Visible `(node, lifecycle)` observer pairs in pre-order.
    #[must_use]
    pub fn collect_visible_lifecycles(&self) -> Vec<(NodeId, Rc<dyn Lifecycle>)> {
        if self.get_live_lifecycle_count() == 0 {
            return Vec::new();
        }
        let mut out: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
        let mut stack: Vec<NodeId> = vec![self.get_root()];
        while let Some(current) = stack.pop() {
            if let Some(node) = self.get_node(current) {
                if node.layout_ref().get_display() == Display::None {
                    continue;
                }
                if (self.get_meta()[current.as_usize()].get_flags() & NODE_FLAG_HAS_LIFECYCLE) != 0
                {
                    for hook in node.lifecycle_observers().into_iter() {
                        out.push((current, hook));
                    }
                }
                for child in self.children_iter(current).rev() {
                    stack.push(child);
                }
            }
        }
        out
    }

    /// Collects all reactive `ScopeId`s attached to nodes within the subtree rooted at `root`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Subtree root handle.
    ///
    /// # Returns
    ///
    /// - `Vec<ScopeId>` - Owned scope identifiers discovered within `root`.
    #[must_use]
    pub fn collect_subtree_scope_ids(&self, root: NodeId) -> Vec<ScopeId> {
        let mut out: Vec<ScopeId> = Vec::new();
        let mut stack: Vec<NodeId> = vec![root];
        while let Some(current) = stack.pop() {
            let idx: usize = current.as_usize();
            let Some(meta) = self.get_meta().get(idx) else {
                continue;
            };
            if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
                || meta.get_generation() != current.get_generation()
            {
                continue;
            }
            if (meta.get_flags() & NODE_FLAG_HAS_SCOPE) != 0
                && let Some(scope) = self.get_nodes()[idx].owned_scope()
            {
                out.push(scope.id());
            }
            for child in self.children_iter(current).rev() {
                stack.push(child);
            }
        }
        out
    }

    /// Cancels any active paint/transform transitions targeting nodes within the subtree rooted at `root`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Subtree root handle.
    pub fn cancel_subtree_transitions(&mut self, root: NodeId) {
        if self.get_transitions().is_empty() {
            return;
        }
        let mut ids: HashSet<NodeId> = HashSet::new();
        let mut stack: Vec<NodeId> = vec![root];
        while let Some(current) = stack.pop() {
            if ids.insert(current) && self.get_node(current).is_some() {
                for child in self.children_iter(current) {
                    stack.push(child);
                }
            }
        }
        self.get_mut_transitions()
            .retain(|tr: &NodeTransition| !ids.contains(&tr.get_node()));
    }

    /// Attaches a reactive `Scope` to `id` so it automatically disposes when the node unmounts.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Target node handle.
    /// - `Scope` - Reactive ownership scope.
    pub fn attach_scope(&mut self, id: NodeId, scope: Scope) {
        let attached: bool = if let Some(node) = self.get_node_mut(id) {
            if let Some(existing) = node.owned_scope() {
                existing.enter(|| {
                    on_cleanup(move || {
                        scope.dispose();
                    });
                });
            } else {
                node.set_scope(Some(scope));
            }
            true
        } else {
            false
        };
        if attached && let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
            let add_flags: u16 = NODE_FLAG_HAS_EXTRAS + NODE_FLAG_HAS_SCOPE;
            let next_flags: u16 = meta.get_flags() | add_flags;
            let _: &mut NodeMeta = meta.set_flags(next_flags);
        }
    }

    /// Returns the monotonic per-node paint invalidation epoch for `id` in O(1).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Target node handle.
    ///
    /// # Returns
    ///
    /// - `u32` - Wrapping monotonic paint epoch incremented on every paint/layout/content invalidation.
    #[must_use]
    #[inline(always)]
    pub(crate) fn node_paint_epoch(&self, id: NodeId) -> u32 {
        self.get_paint_epochs()
            .get(id.as_usize())
            .copied()
            .unwrap_or(0)
    }

    /// Returns `true` when the root node currently carries any layout-pass dirty flag.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether the root node requires a layout pass.
    #[must_use]
    #[inline(always)]
    pub(crate) fn root_has_layout_dirty(&self) -> bool {
        let root_id: NodeId = self.get_root();
        self.get_node(root_id).is_some_and(|root_node: &SceneNode| {
            root_node.get_dirty().intersects(DIRTY_LAYOUT_PASS_MASK)
        })
    }

    /// Clears `dirty_paint_nodes` while resetting `NODE_FLAG_IN_DIRTY_PAINT_QUEUE` on every queued slot.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    fn clear_dirty_paint_queue(&mut self) {
        let Self {
            dirty_paint_nodes,
            meta,
            ..
        } = self;
        for nid in dirty_paint_nodes.drain(..) {
            if let Some(slot_meta) = meta.get_mut(nid.as_usize()) {
                let next_flags: u16 = slot_meta.get_flags() & !NODE_FLAG_IN_DIRTY_PAINT_QUEUE;
                let _: &mut NodeMeta = slot_meta.set_flags(next_flags);
            }
        }
    }

    /// Marks `id` dirty with `mask` and propagates subtree dirty bits to ancestors in O(depth).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Mutated node handle.
    /// - `u16` - Dirty flag bits to set.
    pub fn mark_dirty(&mut self, id: NodeId, mask: u16) {
        let check_layout_registries: bool = (mask & DIRTY_LAYOUT) != 0;
        let (mut parent_opt, portal_state, scroll_state, nonzero_z_state): (
            Option<NodeId>,
            Option<bool>,
            Option<bool>,
            Option<bool>,
        ) = match self.get_node_mut(id) {
            Some(node) => {
                node.get_mut_dirty().insert(mask);
                let (portal_opt, scroll_opt, nz_z_opt): (Option<bool>, Option<bool>, Option<bool>) =
                    if check_layout_registries {
                        let is_portal: bool = matches!(node.get_kind(), NodeKind::Portal)
                            || node.layout_ref().get_position() == Position::Fixed;
                        let is_scroll: bool = matches!(node.get_kind(), NodeKind::ScrollView)
                            || node.layout_ref().get_overflow() == Overflow::Scroll;
                        let has_nz_z: bool = node.layout_ref().get_z_index() != 0;
                        (Some(is_portal), Some(is_scroll), Some(has_nz_z))
                    } else {
                        (None, None, None)
                    };
                (node.parent_id(), portal_opt, scroll_opt, nz_z_opt)
            }
            None => return,
        };
        let node_idx: usize = id.as_usize();
        if (mask & (DIRTY_PAINT | DIRTY_FULL_DAMAGE_MASK)) != 0
            && let Some(epoch) = self.get_mut_paint_epochs().get_mut(node_idx)
        {
            *epoch = epoch.wrapping_add(1);
        }
        let prev_meta_flags: u16 = if let Some(meta) = self.get_mut_meta().get_mut(node_idx) {
            let next_dirty: u16 = meta.get_dirty() | mask;
            let _: &mut NodeMeta = meta.set_dirty(next_dirty);
            meta.get_flags()
        } else {
            0
        };
        if let Some(is_portal) = portal_state {
            let was_portal: bool = (prev_meta_flags & NODE_FLAG_IS_PORTAL) != 0;
            if is_portal != was_portal {
                self.sync_portal_registration(id, is_portal);
            }
        }
        if let Some(is_scroll) = scroll_state {
            let was_scroll: bool = (prev_meta_flags & NODE_FLAG_IS_SCROLL_CONTAINER) != 0;
            if is_scroll != was_scroll {
                self.sync_scroll_registration(id, is_scroll);
            }
        }
        if let Some(has_nz_z) = nonzero_z_state
            && let Some(parent_id) = parent_opt
        {
            let parent_idx: usize = parent_id.as_usize();
            if has_nz_z {
                if let Some(meta) = self.get_mut_meta().get_mut(parent_idx) {
                    let next_flags: u16 = meta.get_flags() | NODE_FLAG_HAS_NONZERO_Z_CHILD;
                    let _: &mut NodeMeta = meta.set_flags(next_flags);
                }
            } else if self.has_nonzero_z_child(parent_id) {
                self.recompute_nonzero_z_child(parent_idx);
            }
        }
        if (mask & DIRTY_FULL_DAMAGE_MASK) != 0 {
            self.set_layout_damage_pending(true);
            self.set_layout_invalidations(self.get_layout_invalidations().saturating_add(1));
        }
        let visual_mask: u16 = DIRTY_PAINT + DIRTY_SCROLL + DIRTY_COMPOSITE;
        if !self.get_full_damage_pending()
            && (mask & visual_mask) != 0
            && (prev_meta_flags & NODE_FLAG_IN_DIRTY_PAINT_QUEUE) == 0
        {
            if self.get_dirty_paint_nodes().len() >= DIRTY_PAINT_FULL_THRESHOLD {
                self.set_full_damage_pending(true);
                self.set_full_damage_overflow(true);
                self.clear_dirty_paint_queue();
            } else {
                self.get_mut_dirty_paint_nodes().push(id);
                if let Some(meta) = self.get_mut_meta().get_mut(node_idx) {
                    let next_flags: u16 = meta.get_flags() | NODE_FLAG_IN_DIRTY_PAINT_QUEUE;
                    let _: &mut NodeMeta = meta.set_flags(next_flags);
                }
            }
        }
        let mut ancestor_mask: u16 = DIRTY_NONE;
        if (mask & DIRTY_ANCESTOR_LAYOUT_TRIGGER) != 0 {
            ancestor_mask |= DIRTY_SUBTREE_LAYOUT;
        }
        if (mask & DIRTY_ANCESTOR_PAINT_TRIGGER) != 0 {
            ancestor_mask |= DIRTY_SUBTREE_PAINT;
        }
        if (mask & DIRTY_ANCESTOR_COMPOSITE_TRIGGER) != 0 {
            ancestor_mask |= DIRTY_SUBTREE_COMPOSITE;
        }
        if ancestor_mask != DIRTY_NONE {
            let root_has_mask: bool = {
                let root_id: NodeId = self.get_root();
                self.get_node(root_id)
                    .map(|root_node: &SceneNode| {
                        (root_node.get_dirty().get_bits() & ancestor_mask) == ancestor_mask
                    })
                    .unwrap_or(true)
            };
            let can_early_break: bool = root_has_mask && !self.get_has_stale_hidden_dirty();
            while let Some(ancestor_id) = parent_opt {
                let ancestor_idx: usize = ancestor_id.as_usize();
                if let Some(ancestor) = self.get_node_mut(ancestor_id) {
                    let already: bool =
                        (ancestor.get_dirty().get_bits() & ancestor_mask) == ancestor_mask;
                    ancestor.get_mut_dirty().insert(ancestor_mask);
                    parent_opt = ancestor.parent_id();
                    if let Some(meta) = self.get_mut_meta().get_mut(ancestor_idx) {
                        let next_dirty: u16 = meta.get_dirty() | ancestor_mask;
                        let _: &mut NodeMeta = meta.set_dirty(next_dirty);
                    }
                    if already && can_early_break {
                        break;
                    }
                } else {
                    break;
                }
            }
        }
        let next_rev: u64 = self.get_revision().wrapping_add(1);
        self.set_revision(next_rev);
        notify_frame_needed();
    }

    /// Returns `true` when `id` and every ancestor up to the root are alive, attached, non-`Display::None`, and visibly opaque.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Target node handle.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether the node is visibly rendered in the scene.
    #[must_use]
    pub fn is_node_visible(&self, id: NodeId) -> bool {
        let root: NodeId = self.get_root();
        let mut cursor: Option<NodeId> = Some(id);
        while let Some(cur) = cursor {
            let Some(node) = self.get_node(cur) else {
                return false;
            };
            let style: &Style = node.style_ref();
            if style.get_layout().get_display() == Display::None
                || style.get_paint().get_opacity() <= 0.001
            {
                return false;
            }
            if cur == root {
                return true;
            }
            cursor = node.parent_id();
        }
        false
    }

    /// Collects the tight physical damage region from dirty paint/scroll nodes in O(dirty) and clears paint dirty flags.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `f32` - Active display scale factor.
    ///
    /// # Returns
    ///
    /// - `DamageRegion` - Minimal damaged region, full damage on structural/layout change, or clean when idle.
    pub fn collect_paint_damage(&mut self, scale: f32) -> DamageRegion {
        let (damage, _): (DamageRegion, bool) = self.collect_surgical_paint_damage(scale, false);
        damage
    }

    /// Collects tight physical paint/scroll/removed-node damage while optionally deferring layout bounds diffing to `LayoutEngine`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `f32` - Active display scale factor.
    /// - `bool` - When `true`, allows surgical pre/post-layout damage diffing instead of promoting all layout mutations to full redraw.
    ///
    /// # Returns
    ///
    /// - `(DamageRegion, bool)` - Collected damage region and whether a layout pass is still pending.
    pub(crate) fn collect_surgical_paint_damage(
        &mut self,
        scale: f32,
        allow_partial_layout: bool,
    ) -> (DamageRegion, bool) {
        let clear_mask: u16 = DIRTY_PAINT_CLEAR_MASK;
        let layout_pending: bool = self.get_layout_damage_pending();
        let no_paint_nodes: bool = self.get_dirty_paint_nodes().is_empty();
        let no_extra: bool = self.get_extra_logical_damage().is_empty();
        if !self.get_full_damage_pending() && !layout_pending && no_paint_nodes && no_extra {
            self.set_created_since_damage(0);
            self.set_last_collect_composite_only(false);
            return (DamageRegion::default(), false);
        }
        let mut full: bool =
            self.get_full_damage_pending() || (!allow_partial_layout && layout_pending);
        let mut saw_paint_or_layout: bool = layout_pending;
        let mut saw_composite_or_scroll: bool = false;
        let mut region: DamageRegion = DamageRegion::default();
        if !full {
            let extra_len: usize = self.get_extra_logical_damage().len();
            for i in 0..extra_len {
                let logical_rect: Rect = self.get_extra_logical_damage()[i];
                if logical_rect.get_width() > 0.0 && logical_rect.get_height() > 0.0 {
                    region.add_rect(Self::scale_logical_to_phys_rect(logical_rect, scale));
                }
            }
            let dirty_len: usize = self.get_dirty_paint_nodes().len();
            let visual_mask: u16 = DIRTY_PAINT + DIRTY_SCROLL + DIRTY_COMPOSITE;
            for i in 0..dirty_len {
                let nid: NodeId = self.get_dirty_paint_nodes()[i];
                let Some(node) = self.get_node(nid) else {
                    continue;
                };
                let bits: u16 = node.get_dirty().get_bits();
                let has_layout_bits: bool = (bits & DIRTY_LAYOUT_PASS_MASK) != 0;
                if (bits & (DIRTY_PAINT | DIRTY_LAYOUT_PASS_MASK)) != 0 {
                    saw_paint_or_layout = true;
                }
                if (bits & (DIRTY_COMPOSITE | DIRTY_SCROLL)) != 0 {
                    saw_composite_or_scroll = true;
                }
                if !allow_partial_layout && (bits & DIRTY_FULL_DAMAGE_MASK) != 0 {
                    full = true;
                    break;
                }
                if (bits & DIRTY_SCROLL) != 0 && has_layout_bits {
                    full = true;
                    break;
                }
                if (bits & visual_mask) == 0 {
                    continue;
                }
                let raw_bounds: Rect = node.get_layout_box().get_bounds();
                if raw_bounds.get_width() > 0.0 && raw_bounds.get_height() > 0.0 {
                    match self.node_conservative_logical_rect(nid) {
                        Some(logical_rect) => {
                            region.add_rect(Self::scale_logical_to_phys_rect(logical_rect, scale));
                        }
                        None => {
                            full = true;
                            break;
                        }
                    }
                } else if (bits & (DIRTY_PAINT | DIRTY_COMPOSITE)) != 0
                    && !has_layout_bits
                    && node.style_ref().layout_ref().get_display() != Display::None
                {
                    full = true;
                    break;
                }
            }
        }
        self.set_last_collect_composite_only(
            !full && !layout_pending && !saw_paint_or_layout && saw_composite_or_scroll,
        );
        self.set_layout_damage_pending(false);
        self.set_created_since_damage(0);
        self.get_mut_extra_logical_damage().clear();
        if !full {
            let dirty_len: usize = self.get_dirty_paint_nodes().len();
            let ancestor_clear: u16 = DIRTY_SUBTREE_PAINT | DIRTY_SUBTREE_COMPOSITE;
            for i in 0..dirty_len {
                let nid: NodeId = self.get_dirty_paint_nodes()[i];
                let mut parent_opt: Option<NodeId> = match self.get_node_mut(nid) {
                    Some(node) => {
                        node.get_mut_dirty().remove(clear_mask);
                        node.parent_id()
                    }
                    None => None,
                };
                if let Some(meta) = self.get_mut_meta().get_mut(nid.get_index() as usize) {
                    let next_dirty: u16 = meta.get_dirty() & !clear_mask;
                    let next_flags: u16 = meta.get_flags() & !NODE_FLAG_IN_DIRTY_PAINT_QUEUE;
                    let _: &mut NodeMeta = meta.set_dirty(next_dirty).set_flags(next_flags);
                }
                while let Some(ancestor_id) = parent_opt {
                    let ancestor_idx: usize = ancestor_id.get_index() as usize;
                    if let Some(ancestor) = self.get_node_mut(ancestor_id) {
                        if (ancestor.get_dirty().get_bits() & ancestor_clear) == 0 {
                            break;
                        }
                        ancestor.get_mut_dirty().remove(ancestor_clear);
                        parent_opt = ancestor.parent_id();
                    } else {
                        break;
                    }
                    if let Some(meta) = self.get_mut_meta().get_mut(ancestor_idx) {
                        let next_dirty: u16 = meta.get_dirty() & !ancestor_clear;
                        let _: &mut NodeMeta = meta.set_dirty(next_dirty);
                    }
                }
            }
            self.get_mut_dirty_paint_nodes().clear();
            return (region, layout_pending);
        }
        self.set_full_damage_pending(false);
        self.clear_dirty_paint_queue();
        let node_count: usize = self.get_nodes().len();
        for idx in 0..node_count {
            let should_clear: bool = {
                let node: &SceneNode = &self.get_nodes()[idx];
                node.get_alive() && (node.get_dirty().get_bits() & clear_mask) != 0
            };
            if should_clear {
                self.get_mut_nodes()[idx].get_mut_dirty().remove(clear_mask);
                if let Some(meta) = self.get_mut_meta().get_mut(idx) {
                    let next_dirty: u16 = meta.get_dirty() & !clear_mask;
                    let _: &mut NodeMeta = meta.set_dirty(next_dirty);
                }
            }
        }
        (DamageRegion::full(), layout_pending)
    }

    /// Consumes and returns whether the most recent dirty-paint accumulation overflowed `DIRTY_PAINT_FULL_THRESHOLD`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if dirty paint nodes overflowed into full damage.
    pub(crate) fn take_full_damage_overflow(&mut self) -> bool {
        let was_overflow: bool = self.get_full_damage_overflow();
        self.set_full_damage_overflow(false);
        was_overflow
    }

    /// Recursively detaches and recycles `id`, returning all owned `Scope`s and `Lifecycle` observers for borrow-safe finalization.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Subtree root handle to dispose.
    ///
    /// # Returns
    ///
    /// - `DisposedSubtreePayload` - Collected scopes and lifecycle observers to finalize outside any borrow.
    pub fn dispose_subtree_collect(&mut self, id: NodeId) -> DisposedSubtreePayload {
        if id == self.get_root() || self.get_node(id).is_none() {
            return (Vec::new(), Vec::new());
        }
        self.record_subtree_logical_damage(id);
        self.cancel_subtree_transitions(id);
        let root_parent: u32 = self.get_topology()[id.as_usize()].get_parent();
        if root_parent != NODE_INDEX_NONE {
            self.unlink_child_at(root_parent as usize, id.as_usize());
        }
        let mut stack: Vec<NodeId> = vec![id];
        let mut scopes: Vec<Scope> = Vec::new();
        let mut observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
        while let Some(current) = stack.pop() {
            let cur_idx: usize = current.as_usize();
            let mut next_child: u32 = self.get_topology()[cur_idx].get_first_child();
            let mut removed_lifecycles: usize = 0;
            let (was_alive, prev_flags): (bool, u16) = match self.get_node_mut(current) {
                Some(node) => {
                    node.set_alive(false);
                    node.set_kind(NodeKind::View);
                    if node.has_extras() {
                        if let Some(scope) = node.owned_scope() {
                            scopes.push(scope);
                        }
                        let drained: Vec<Rc<dyn Lifecycle>> = node.take_lifecycles();
                        removed_lifecycles = drained.len();
                        for hook in drained.into_iter() {
                            observers.push((current, hook));
                        }
                        node.clear_extras();
                    }
                    node.set_parent(None);
                    let next_gen: u32 = node.get_generation().wrapping_add(1).max(1);
                    node.set_generation(next_gen);
                    (true, self.get_meta()[cur_idx].get_flags())
                }
                None => (false, 0),
            };
            if !was_alive {
                continue;
            }
            while next_child != NODE_INDEX_NONE {
                let ci: usize = next_child as usize;
                let sibling: u32 = self.get_topology()[ci].get_next_sibling();
                let child_gen: u32 = self.get_meta()[ci].get_generation();
                stack.push(NodeId::new(next_child, child_gen));
                next_child = sibling;
            }
            let next_gen: u32 = self.get_nodes()[cur_idx].get_generation();
            self.get_mut_meta()[cur_idx] = NodeMeta::new(next_gen, 0, DIRTY_NONE);
            self.get_mut_topology()[cur_idx] = NodeTopology::default();
            let prev_effect_id: u32 = self.get_compact_paints()[cur_idx].get_effect_id();
            if prev_effect_id != EFFECT_ID_NONE {
                self.get_mut_effect_table().remove(prev_effect_id);
                let _: &mut CompactPaintStyle =
                    self.get_mut_compact_paints()[cur_idx].set_effect_id(EFFECT_ID_NONE);
            }
            let next_live: usize = self.get_live_count().saturating_sub(1);
            self.set_live_count(next_live);
            if removed_lifecycles > 0 {
                let next_lc: usize = self
                    .get_live_lifecycle_count()
                    .saturating_sub(removed_lifecycles);
                self.set_live_lifecycle_count(next_lc);
            }
            if (prev_flags & NODE_FLAG_IS_PORTAL) != 0 && !self.portal_nodes().is_empty() {
                self.sync_portal_registration(current, false);
            }
            if (prev_flags & NODE_FLAG_IS_SCROLL_CONTAINER) != 0 && !self.scroll_nodes().is_empty()
            {
                self.sync_scroll_registration(current, false);
            }
            if !self.get_backdrop_blur_nodes().is_empty() {
                self.get_mut_backdrop_blur_nodes()
                    .retain(|entry: &(NodeId, f32)| entry.0 != current);
            }
            if self.get_focus().focused_node() == Some(current) {
                self.get_mut_focus().set_focused(None);
            }
            if self.get_focus().hovered_node() == Some(current) {
                self.get_mut_focus().set_hovered(None);
            }
            if self.get_focus().pressed_node() == Some(current) {
                self.get_mut_focus().set_pressed(None);
            }
            if self
                .text_selection()
                .map(|sel: SelectionState| sel.get_node_id())
                == Some(current)
            {
                self.set_text_selection(None);
            }
            self.get_mut_free_list().push(current.get_index());
        }
        (scopes, observers)
    }

    /// Recursively removes and disposes `id`, recycling all arena slots, running lifecycle hooks, and disposing scopes.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Subtree root handle to dispose.
    pub fn dispose_subtree(&mut self, id: NodeId) {
        let (scopes, observers): DisposedSubtreePayload = self.dispose_subtree_collect(id);
        finalize_disposed_subtree(scopes, observers);
    }

    /// Updates keyboard focus to `target`, emitting `Blur` and `Focus` events.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `Option<NodeId>` - Newly focused node, or `None` to clear focus.
    ///
    /// # Returns
    ///
    /// - `Vec<(UiEventHandler, UiEvent)>` - Callbacks to invoke outside the tree borrow.
    pub fn update_focus(&mut self, target: Option<NodeId>) -> Vec<(UiEventHandler, UiEvent)> {
        let prev: Option<NodeId> = self.get_focus().focused_node();
        if prev == target {
            return Vec::new();
        }
        let mut callbacks: Vec<(UiEventHandler, UiEvent)> = Vec::new();
        if let Some(old_id) = prev {
            if let Some(old_node) = self.get_node_mut(old_id) {
                old_node.get_mut_interaction().set_focused(false);
                if let Some(handler) = old_node.get_handlers().handler_for(&UiEventKind::Blur) {
                    callbacks.push((handler, UiEvent::new(old_id, UiEventKind::Blur)));
                }
            }
            self.mark_dirty(old_id, DIRTY_PAINT);
        }
        self.get_mut_focus().set_focused(target);
        if let Some(new_id) = target {
            if let Some(new_node) = self.get_node_mut(new_id) {
                new_node.get_mut_interaction().set_focused(true);
                if let Some(handler) = new_node.get_handlers().handler_for(&UiEventKind::Focus) {
                    callbacks.push((handler, UiEvent::new(new_id, UiEventKind::Focus)));
                }
            }
            self.mark_dirty(new_id, DIRTY_PAINT);
        }
        callbacks
    }

    /// Resolves whether `id` allows interactive text selection, walking ancestors unless an explicit opt-out is encountered.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Target scene node handle.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `id` or an ancestor enables `selectable` without an intervening explicit `selectable(false)`.
    #[must_use]
    pub fn is_node_selectable(&self, id: NodeId) -> bool {
        let mut cursor: Option<NodeId> = Some(id);
        while let Some(cur) = cursor {
            let Some(node) = self.get_node(cur) else {
                return false;
            };
            let text_style: &TextStyle = node.style_ref().text_ref();
            if text_style.get_selectable() {
                return true;
            }
            if text_style.get_selectable_explicit() {
                return false;
            }
            cursor = node.parent_id();
        }
        false
    }

    /// Resolves the effective text selection highlight color for `id`, inheriting from ancestors or falling back to default tint.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    /// - `NodeId` - Target text node handle.
    ///
    /// # Returns
    ///
    /// - `Color` - Selection highlight fill color.
    #[must_use]
    pub fn effective_selection_color(&self, id: NodeId) -> Color {
        let mut cursor: Option<NodeId> = Some(id);
        while let Some(cur) = cursor {
            let Some(node) = self.get_node(cur) else {
                break;
            };
            if let Some(color) = node.style_ref().text_ref().selection_color() {
                return color;
            }
            cursor = node.parent_id();
        }
        DEFAULT_TEXT_SELECTION_COLOR
    }

    /// Returns the active text selection state, if any.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    ///
    /// # Returns
    ///
    /// - `Option<SelectionState>` - Current selection state.
    #[must_use]
    pub fn text_selection(&self) -> Option<SelectionState> {
        let Self { text_selection, .. } = self;
        *text_selection
    }

    /// Updates the active text selection state and marks affected text nodes dirty for repaint.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `Option<SelectionState>` - Replacement selection state (`None` clears selection).
    pub fn set_text_selection(&mut self, selection: Option<SelectionState>) {
        let prev: Option<SelectionState> = self.text_selection();
        if prev == selection {
            return;
        }
        let Self { text_selection, .. } = self;
        *text_selection = selection;
        if let Some(old_sel) = prev {
            self.mark_dirty(old_sel.get_node_id(), DIRTY_PAINT);
        }
        if let Some(new_sel) = selection {
            self.mark_dirty(new_sel.get_node_id(), DIRTY_PAINT);
        }
    }

    /// Clears any active text selection and repaints the previously selected node.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    pub fn clear_text_selection(&mut self) {
        self.set_text_selection(None);
    }

    /// Returns the currently selected UTF-8 substring when a non-empty selection exists on a live text node.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene tree reference.
    ///
    /// # Returns
    ///
    /// - `Option<String>` - Selected text string, or `None` when no text is selected.
    #[must_use]
    pub fn get_selected_text(&self) -> Option<String> {
        let sel: SelectionState = self.text_selection()?;
        if sel.is_empty() {
            return None;
        }
        let node: &SceneNode = self.get_node(sel.get_node_id())?;
        let NodeKind::Text(content) = node.get_kind() else {
            return None;
        };
        let extracted: &str = sel.extract_from(content.as_str());
        if extracted.is_empty() {
            None
        } else {
            Some(extracted.to_string())
        }
    }

    /// Selects the entire character range of selectable `NodeKind::Text` node `id`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene tree.
    /// - `NodeId` - Target text node handle.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `id` is a live selectable non-empty text node and selection was applied.
    pub fn select_all_text(&mut self, id: NodeId) -> bool {
        if !self.is_node_selectable(id) {
            return false;
        }
        let char_len: Option<usize> = self.get_node(id).and_then(|node: &SceneNode| {
            if let NodeKind::Text(content) = node.get_kind() {
                Some(content.chars().count())
            } else {
                None
            }
        });
        let Some(len) = char_len else {
            return false;
        };
        if len == 0 {
            return false;
        }
        self.set_text_selection(Some(SelectionState::new(id, 0, len)));
        true
    }
}

/// RAII depth-tracking methods for `SceneBorrowGuard`.
impl SceneBorrowGuard {
    /// Increments the thread-local `SceneTree` borrow depth and returns a guard that decrements it on drop.
    ///
    /// # Returns
    ///
    /// - `Self` - Active borrow depth guard.
    #[inline(always)]
    pub(crate) fn enter() -> Self {
        let _: Result<(), _> = SCENE_BORROW_DEPTH.try_with(|depth: &Cell<u32>| {
            depth.set(depth.get().saturating_add(1));
        });
        Self
    }
}

/// Decrements the thread-local `SceneTree` borrow depth on scope exit.
impl Drop for SceneBorrowGuard {
    /// Decrements the active thread-local `SceneTree` borrow counter.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable guard being dropped.
    #[inline(always)]
    fn drop(&mut self) {
        let _: Result<(), _> = SCENE_BORROW_DEPTH.try_with(|depth: &Cell<u32>| {
            depth.set(depth.get().saturating_sub(1));
        });
    }
}

/// Shared scene handle operations enabling surgical reactive node updates.
impl SceneHandle {
    /// Creates a new `SceneHandle` wrapping a fresh `SceneTree`.
    ///
    /// # Returns
    ///
    /// - `Self` - Shared scene handle.
    #[must_use]
    pub fn new_tree() -> Self {
        Self {
            inner: Rc::new(SceneHandleInner {
                tree: RefCell::new(SceneTree::default()),
                has_deferred: Cell::new(false),
                deferred_writes: RefCell::new(Vec::new()),
            }),
        }
    }

    /// Returns `true` when re-entrant scene mutations are queued awaiting flush.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle reference.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether deferred scene mutations are pending.
    #[must_use]
    #[inline(always)]
    pub fn has_deferred_writes(&self) -> bool {
        let Self { inner } = self;
        inner.has_deferred.get()
    }

    /// Executes all queued re-entrant scene mutations under an already-held mutable `SceneTree` borrow.
    ///
    /// # Arguments
    ///
    /// - `&SceneHandleInner` - Shared scene storage holding the deferred queue.
    /// - `&mut SceneTree` - Active mutable scene tree borrow.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of deferred mutations executed.
    fn drain_deferred_locked(inner: &SceneHandleInner, tree: &mut SceneTree) -> usize {
        let mut executed: usize = 0;
        for _ in 0..MAX_FLUSH_ITERATIONS {
            let batch: Vec<DeferredSceneWrite> = match inner.deferred_writes.try_borrow_mut() {
                Ok(mut queue) => {
                    inner.has_deferred.set(false);
                    if queue.is_empty() {
                        break;
                    }
                    take(&mut *queue)
                }
                Err(_) => break,
            };
            for op in batch.into_iter() {
                op(tree);
                executed = executed.saturating_add(1);
            }
            if !inner.has_deferred.get() {
                break;
            }
        }
        executed
    }

    /// Executes any pending re-entrant scene mutations queued while `SceneTree` was borrowed.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle reference.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of deferred mutations executed (`0` if queue is empty or tree is still borrowed).
    pub fn flush_deferred_writes(&self) -> usize {
        let Self { inner } = self;
        if !inner.has_deferred.get() {
            return 0;
        }
        let executed: usize = match inner.tree.try_borrow_mut() {
            Ok(mut guard) => {
                let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
                Self::drain_deferred_locked(inner, &mut guard)
            }
            Err(_) => return 0,
        };
        if !is_scene_borrowed() && !panicking() && has_deferred_effect_flush() {
            self.flush_after_outer_borrow();
        }
        executed
    }

    /// Checks whether deferred writes or deferred reactive effects need flushing after an outer borrow drops.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle reference.
    #[inline(always)]
    fn finish_outer_borrow(&self) {
        if is_scene_borrowed() || panicking() {
            return;
        }
        let Self { inner } = self;
        if !inner.has_deferred.get() && !has_deferred_effect_flush() {
            return;
        }
        self.flush_after_outer_borrow();
    }

    /// Drains interleaved deferred scene writes and deferred reactive effect flushes once no `SceneTree` borrow is active.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle reference.
    #[cold]
    fn flush_after_outer_borrow(&self) {
        let Self { inner } = self;
        for _ in 0..MAX_FLUSH_ITERATIONS {
            let drained_writes: usize = if inner.has_deferred.get() {
                match inner.tree.try_borrow_mut() {
                    Ok(mut guard) => {
                        let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
                        Self::drain_deferred_locked(inner, &mut guard)
                    }
                    Err(_) => 0,
                }
            } else {
                0
            };
            let flushed_effects: bool = if take_deferred_effect_flush() {
                flush_effects();
                true
            } else {
                false
            };
            if drained_writes == 0 && !flushed_effects && !inner.has_deferred.get() {
                break;
            }
        }
    }

    /// Mutates the underlying `SceneTree` immediately when unborrowed (zero allocations) or queues `operation` re-entrantly until the outer borrow unwinds.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle reference.
    /// - `F` - Guaranteed-delivery scene mutation closure.
    pub fn mutate<F>(&self, operation: F)
    where
        F: FnOnce(&mut SceneTree) + 'static,
    {
        let ran_inline: bool = {
            let Self { inner } = self;
            match inner.tree.try_borrow_mut() {
                Ok(mut guard) => {
                    let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
                    operation(&mut guard);
                    if inner.has_deferred.get() {
                        let _: usize = Self::drain_deferred_locked(inner, &mut guard);
                    }
                    true
                }
                Err(_) => {
                    if let Ok(mut queue) = inner.deferred_writes.try_borrow_mut() {
                        queue.push(Box::new(operation));
                        inner.has_deferred.set(true);
                    }
                    notify_frame_needed();
                    false
                }
            }
        };
        if ran_inline {
            self.finish_outer_borrow();
        }
    }

    /// Updates virtualized scroll metrics `(scroll_y, content_height)` on `id` for accurate scrollbar thumbs.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle reference.
    /// - `NodeId` - Target virtualized scroll container.
    /// - `f32` - Active virtual vertical scroll offset in logical pixels.
    /// - `f32` - Total virtualized content height in logical pixels.
    pub fn set_virtual_scroll(&self, id: NodeId, scroll_y: f32, content_height: f32) {
        self.mutate(move |tree: &mut SceneTree| {
            tree.set_virtual_scroll(id, scroll_y, content_height);
        });
    }

    /// Computes screen-space logical bounds for `id` subtracting ancestor scroll offsets.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle reference.
    /// - `NodeId` - Target node handle.
    ///
    /// # Returns
    ///
    /// - `Option<Rect>` - Screen-space bounds if the node is alive.
    #[must_use]
    pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
        self.with_read(|tree: &SceneTree| tree.node_screen_bounds(id), None)
    }

    /// Starts or replaces a smooth paint/transform transition on the target node.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle reference.
    /// - `NodeTransition` - Transition specification to run.
    pub fn start_transition(&self, transition: NodeTransition) {
        self.mutate(move |tree: &mut SceneTree| {
            tree.start_transition(transition);
        });
    }

    /// Marks `id` dirty with `mask` for incremental repainting.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle reference.
    /// - `NodeId` - Target node handle.
    /// - `u16` - Dirty flag bits.
    pub fn mark_dirty(&self, id: NodeId, mask: u16) {
        self.mutate(move |tree: &mut SceneTree| {
            tree.mark_dirty(id, mask);
        });
    }

    /// Replaces all children of `parent` and finalizes disposed scopes and `Lifecycle` hooks outside the tree borrow.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle reference.
    /// - `NodeId` - Parent container node.
    /// - `Vec<NodeId>` - Replacement ordered children.
    pub fn replace_children_safe(&self, parent: NodeId, new_children: Vec<NodeId>) {
        let (scopes, observers): DisposedSubtreePayload = self.with_write(
            |tree: &mut SceneTree| {
                if tree.get_node(parent).is_none() {
                    return (Vec::new(), Vec::new());
                }
                let parent_idx: usize = parent.as_usize();
                let old_children: Vec<NodeId> = tree.children_vec(parent);
                tree.unlink_all_children_at(parent_idx);
                let mut all_scopes: Vec<Scope> = Vec::new();
                let mut all_obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
                if new_children.is_empty() {
                    for old_child in old_children.into_iter() {
                        let (sc, ob): DisposedSubtreePayload =
                            tree.dispose_subtree_collect(old_child);
                        all_scopes.extend(sc);
                        all_obs.extend(ob);
                    }
                } else if old_children.len() > 16 && new_children.len() > 16 {
                    let keep_set: HashSet<NodeId> = new_children.iter().copied().collect();
                    for old_child in old_children.into_iter() {
                        if !keep_set.contains(&old_child) {
                            let (sc, ob): DisposedSubtreePayload =
                                tree.dispose_subtree_collect(old_child);
                            all_scopes.extend(sc);
                            all_obs.extend(ob);
                        }
                    }
                } else {
                    for old_child in old_children.into_iter() {
                        if !new_children.contains(&old_child) {
                            let (sc, ob): DisposedSubtreePayload =
                                tree.dispose_subtree_collect(old_child);
                            all_scopes.extend(sc);
                            all_obs.extend(ob);
                        }
                    }
                }
                for child in new_children.into_iter() {
                    if child == parent || tree.get_node(child).is_none() {
                        continue;
                    }
                    let child_idx: usize = child.as_usize();
                    let prev_parent: u32 = tree.get_topology()[child_idx].get_parent();
                    if prev_parent != NODE_INDEX_NONE {
                        tree.unlink_child_at(prev_parent as usize, child_idx);
                    }
                    tree.link_child_tail_at(parent_idx, parent, child_idx);
                }
                tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
                (all_scopes, all_obs)
            },
            (Vec::new(), Vec::new()),
        );
        finalize_disposed_subtree(scopes, observers);
    }

    /// Removes `child` from `parent`, disposes its subtree, and invokes `on_unmount`/`on_destroy` outside any scene borrow.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle reference.
    /// - `NodeId` - Parent container handle.
    /// - `NodeId` - Child subtree root handle to remove and destroy.
    pub fn remove_and_dispose_child(&self, parent: NodeId, child: NodeId) {
        let (scopes, observers): DisposedSubtreePayload = self.with_write(
            |tree: &mut SceneTree| {
                if tree.get_node(parent).is_some() && tree.get_node(child).is_some() {
                    tree.unlink_child_at(parent.as_usize(), child.as_usize());
                }
                let out: DisposedSubtreePayload = tree.dispose_subtree_collect(child);
                tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
                out
            },
            (Vec::new(), Vec::new()),
        );
        finalize_disposed_subtree(scopes, observers);
    }

    /// Mutates a node's `Style` in place under one write lock, marking only minimal dirty flags when changed.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle reference.
    /// - `NodeId` - Target node handle.
    /// - `F` - In-place style mutator closure receiving `&mut Style`.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the node existed and its style changed.
    pub fn mutate_style<F>(&self, id: NodeId, mutator: F) -> bool
    where
        F: FnOnce(&mut Style),
    {
        self.with_write(|tree: &mut SceneTree| tree.mutate_style(id, mutator), false)
    }

    /// Freezes a subtree visually (`Display::None`), cancels its transitions, and dispatches `Lifecycle::on_freeze` outside any scene borrow.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle reference.
    /// - `NodeId` - Subtree root handle to freeze.
    pub fn freeze_subtree(&self, root: NodeId) {
        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
            |tree: &mut SceneTree| {
                let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
                tree.cancel_subtree_transitions(root);
                let changed: bool = if let Some(node) = tree.get_node_mut(root) {
                    let layout: &mut LayoutStyle = node.get_mut_style().get_mut_layout();
                    if layout.get_display() == Display::None {
                        false
                    } else {
                        layout.set_display(Display::None);
                        true
                    }
                } else {
                    false
                };
                if changed {
                    tree.clear_subtree_hover(root);
                    tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
                }
                obs
            },
            Vec::new(),
        );
        dispatch_lifecycle_freeze(&observers);
    }

    /// Freezes a subtree immediately for lifecycle/effects while animating its visual exit to `Display::None`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle reference.
    /// - `NodeId` - Subtree root handle to freeze and animate out.
    /// - `NodeTransition` - Exit transition specification (`hide_on_complete` is enforced).
    pub fn freeze_subtree_animated(&self, root: NodeId, exit_transition: NodeTransition) {
        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
            |tree: &mut SceneTree| {
                let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
                tree.cancel_subtree_transitions(root);
                let mut demoted_fixed: bool = false;
                let mut prev_z: i32 = 0;
                if let Some(node) = tree.get_node_mut(root) {
                    let is_portal: bool = matches!(node.get_kind(), NodeKind::Portal);
                    let st: &mut Style = node.get_mut_style();
                    prev_z = st.layout_ref().get_z_index();
                    demoted_fixed = !is_portal && st.layout_ref().get_position() == Position::Fixed;
                    st.get_mut_layout()
                        .set_position(Position::Absolute)
                        .set_top(Some(0.0))
                        .set_right(Some(0.0))
                        .set_bottom(None)
                        .set_left(Some(0.0))
                        .set_z_index(0);
                    st.get_mut_paint().set_pointer_events(PointerEvents::None);
                }
                if prev_z != 0 {
                    let parent_idx: u32 = tree.get_topology()[root.as_usize()].get_parent();
                    if parent_idx != NODE_INDEX_NONE {
                        tree.sync_parent_nonzero_z(parent_idx as usize, prev_z, 0);
                    }
                }
                tree.clear_subtree_hover(root);
                if demoted_fixed {
                    tree.sync_portal_registration(root, false);
                }
                tree.start_transition(exit_transition.with_hide_on_complete(true));
                tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
                obs
            },
            Vec::new(),
        );
        dispatch_lifecycle_freeze(&observers);
    }

    /// Resumes a previously frozen subtree (`Display::Flex`) and dispatches `Lifecycle::on_resume` outside any scene borrow.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle reference.
    /// - `NodeId` - Subtree root handle to resume.
    pub fn resume_subtree(&self, root: NodeId) {
        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
            |tree: &mut SceneTree| {
                let mut unhidden: bool = false;
                if let Some(node) = tree.get_node_mut(root) {
                    let layout: &mut LayoutStyle = node.get_mut_style().get_mut_layout();
                    if layout.get_display() == Display::None {
                        layout.set_display(Display::Flex);
                        unhidden = true;
                    }
                }
                if unhidden {
                    tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
                } else {
                    tree.mark_dirty(root, DIRTY_PAINT);
                }
                tree.collect_subtree_lifecycles(root)
            },
            Vec::new(),
        );
        dispatch_lifecycle_resume(&observers);
    }

    /// Dispatches `Lifecycle::on_activate` across all observers in the subtree rooted at `root`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle reference.
    /// - `NodeId` - Subtree root handle becoming active.
    pub fn activate_subtree(&self, root: NodeId) {
        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
            |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
            Vec::new(),
        );
        dispatch_lifecycle_activate(&observers);
    }

    /// Dispatches `Lifecycle::on_update` across all observers in the subtree rooted at `root`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle reference.
    /// - `NodeId` - Subtree root handle receiving updates.
    pub fn update_subtree(&self, root: NodeId) {
        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
            |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
            Vec::new(),
        );
        dispatch_lifecycle_update(&observers);
    }

    /// Dispatches `SystemEvent::Appear` to all `Lifecycle` observers and scoped hooks owned by `root`'s subtree.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle reference.
    /// - `NodeId` - Page or component subtree root handle becoming visible.
    pub fn emit_subtree_appear(&self, root: NodeId) {
        let (observers, scopes): SubtreeLifecycleTargets = self.with_read(
            |tree: &SceneTree| {
                (
                    tree.collect_subtree_lifecycles(root),
                    tree.collect_subtree_scope_ids(root),
                )
            },
            (Vec::new(), Vec::new()),
        );
        let ev: SystemEvent = SystemEvent::Appear;
        dispatch_lifecycle_system_event(&observers, &ev);
        dispatch_system_event_to_scopes(&scopes, &ev);
    }

    /// Dispatches `SystemEvent::Disappear` to all `Lifecycle` observers and scoped hooks owned by `root`'s subtree.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle reference.
    /// - `NodeId` - Page or component subtree root handle ceasing to be visible.
    pub fn emit_subtree_disappear(&self, root: NodeId) {
        let (observers, scopes): SubtreeLifecycleTargets = self.with_read(
            |tree: &SceneTree| {
                (
                    tree.collect_subtree_lifecycles(root),
                    tree.collect_subtree_scope_ids(root),
                )
            },
            (Vec::new(), Vec::new()),
        );
        let ev: SystemEvent = SystemEvent::Disappear;
        dispatch_lifecycle_system_event(&observers, &ev);
        dispatch_system_event_to_scopes(&scopes, &ev);
    }

    /// Returns `true` if any node transition is currently active.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle reference.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether animations are running.
    #[must_use]
    pub fn has_active_transitions(&self) -> bool {
        self.with_read(SceneTree::has_active_transitions, false)
    }

    /// Returns the currently selected text substring across the retained scene, if any.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle reference.
    ///
    /// # Returns
    ///
    /// - `Option<String>` - Active selected UTF-8 text.
    #[must_use]
    pub fn get_selected_text(&self) -> Option<String> {
        self.with_read(SceneTree::get_selected_text, None)
    }

    /// Clears any active text selection across the retained scene.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle reference.
    pub fn clear_text_selection(&self) {
        self.mutate(SceneTree::clear_text_selection);
    }

    /// Executes `operation` with immutable access to the underlying `SceneTree`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle.
    /// - `F` - Reader closure.
    /// - `R` - Fallback if re-entrantly borrowed.
    ///
    /// # Returns
    ///
    /// - `R` - Closure result or fallback.
    pub fn with_read<F, R>(&self, operation: F, fallback: R) -> R
    where
        F: FnOnce(&SceneTree) -> R,
    {
        let result: R = {
            let Self { inner } = self;
            match inner.tree.try_borrow() {
                Ok(guard) => {
                    let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
                    operation(&guard)
                }
                Err(_) => return fallback,
            }
        };
        self.finish_outer_borrow();
        result
    }

    /// Executes `operation` with mutable access to the underlying `SceneTree`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle.
    /// - `F` - Mutation closure.
    /// - `R` - Fallback if re-entrantly borrowed.
    ///
    /// # Returns
    ///
    /// - `R` - Closure result or fallback.
    pub fn with_write<F, R>(&self, operation: F, fallback: R) -> R
    where
        F: FnOnce(&mut SceneTree) -> R,
    {
        let result: R = {
            let Self { inner } = self;
            match inner.tree.try_borrow_mut() {
                Ok(mut guard) => {
                    let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
                    let out: R = operation(&mut guard);
                    if inner.has_deferred.get() {
                        let _: usize = Self::drain_deferred_locked(inner, &mut guard);
                    }
                    out
                }
                Err(_) => return fallback,
            }
        };
        self.finish_outer_borrow();
        result
    }

    /// Binds a reactive text expression to `node_id` via a surgical `Effect`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle.
    /// - `NodeId` - Target text node.
    /// - `F` - Reactive text producer closure.
    ///
    /// # Returns
    ///
    /// - `Effect` - Registered reactive effect.
    pub fn bind_text<F>(&self, node_id: NodeId, mut producer: F) -> Effect
    where
        F: FnMut() -> String + 'static,
    {
        let handle: Self = self.clone();
        Effect::new(move || {
            let value: String = producer();
            handle.mutate(move |tree: &mut SceneTree| {
                tree.set_text(node_id, value);
            });
        })
    }

    /// Binds a reactive `Style` expression to `node_id` via a surgical `Effect`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene handle.
    /// - `NodeId` - Target node.
    /// - `F` - Reactive style producer closure.
    ///
    /// # Returns
    ///
    /// - `Effect` - Registered reactive effect.
    pub fn bind_style<F>(&self, node_id: NodeId, mut producer: F) -> Effect
    where
        F: FnMut() -> Style + 'static,
    {
        let handle: Self = self.clone();
        Effect::new(move || {
            let style: Style = producer();
            handle.mutate(move |tree: &mut SceneTree| {
                tree.set_style(node_id, style);
            });
        })
    }
}

/// Disposes all context-owned detached signals when the final `Context` clone drops.
impl Drop for ContextShared {
    /// Releases every reactive signal allocated by `Context::new` so repeated mount/exit cycles retain zero heap entries.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Shared context state being dropped.
    fn drop(&mut self) {
        let Self {
            owned_signals,
            runtime_epoch,
            ..
        } = self;
        if *runtime_epoch != current_runtime_epoch() {
            return;
        }
        for sig_id in owned_signals.iter().copied() {
            let dropped: SignalSlot = with_runtime(
                |rt: &mut ReactiveRuntime| rt.dispose_signal(sig_id),
                SignalSlot::empty(),
            );
            drop(dropped);
        }
    }
}

/// High-level declarative building helpers on `Context`.
impl Context {
    /// Creates a new `Context` with reactive viewport, theme, and safe-area signals.
    ///
    /// # Arguments
    ///
    /// - `SceneHandle` - Shared scene handle.
    /// - `PlatformKind` - Active platform kind.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed build context.
    #[must_use]
    pub fn new(scene: SceneHandle, platform: PlatformKind) -> Self {
        let breakpoint: Signal<Breakpoint> = Signal::new_detached(Breakpoint::Expanded);
        let viewport_size: Signal<Size> = Signal::new_detached(Size::new(1200.0, 800.0));
        let theme_mode: Signal<ThemeMode> = Signal::new_detached(ThemeMode::Light);
        let safe_area: Signal<SafeAreaInsets> = Signal::new_detached(SafeAreaInsets::default());
        let gesture: Signal<Option<GestureEvent>> = Signal::new_detached(None);
        let swipe_drag_offset: Signal<f32> = Signal::new_detached(0.0);
        let system_back: Signal<u64> = Signal::new_detached(0);
        let fps_limit: Signal<Option<u32>> = Signal::new_detached(None);
        let live_fps: Signal<f32> = Signal::new_detached(60.0);
        let present_fps: Signal<f32> = Signal::new_detached(0.0);
        let is_idle: Signal<bool> = Signal::new_detached(true);
        let display_refresh_rate: Signal<f32> = Signal::new_detached(60.0);
        let active_touches: Signal<Vec<(u64, Point)>> = Signal::new_detached(Vec::new());
        let exit_requested: Signal<bool> = Signal::new_detached(false);
        let app_state: Signal<AppState> = Signal::new_detached(AppState::Active);
        let network_status: Signal<NetworkStatus> = Signal::new_detached(NetworkStatus::Online);
        let keyboard_visible: Signal<bool> = Signal::new_detached(false);
        let keyboard_height: Signal<f32> = Signal::new_detached(0.0);
        let orientation: Signal<ScreenOrientation> =
            Signal::new_detached(ScreenOrientation::Landscape);
        let low_power_mode: Signal<bool> = Signal::new_detached(false);
        let locale: Signal<String> = Signal::new_detached(DEFAULT_SYSTEM_LOCALE.to_string());
        let window_focused: Signal<bool> = Signal::new_detached(true);
        let immersive_fullscreen: Signal<bool> = Signal::new_detached(false);
        let device_motion: Signal<DeviceMotionSample> =
            Signal::new_detached(DeviceMotionSample::default());
        let owned_signals: [SignalId; 24] = [
            breakpoint.id(),
            viewport_size.id(),
            theme_mode.id(),
            safe_area.id(),
            gesture.id(),
            swipe_drag_offset.id(),
            system_back.id(),
            fps_limit.id(),
            live_fps.id(),
            present_fps.id(),
            is_idle.id(),
            display_refresh_rate.id(),
            active_touches.id(),
            exit_requested.id(),
            app_state.id(),
            network_status.id(),
            keyboard_visible.id(),
            keyboard_height.id(),
            orientation.id(),
            low_power_mode.id(),
            locale.id(),
            window_focused.id(),
            immersive_fullscreen.id(),
            device_motion.id(),
        ];
        Self {
            scene,
            breakpoint,
            viewport_size,
            theme_mode,
            platform,
            safe_area,
            gesture,
            swipe_drag_offset,
            system_back,
            dynamic_hub: DynamicUpdateHub::new(),
            fps_limit,
            live_fps,
            present_fps,
            is_idle,
            display_refresh_rate,
            active_touches,
            exit_requested,
            app_state,
            network_status,
            keyboard_visible,
            keyboard_height,
            orientation,
            low_power_mode,
            locale,
            window_focused,
            immersive_fullscreen,
            device_motion,
            shared: Rc::new(ContextShared {
                fullscreen_depth: Cell::new(0),
                clock_ms: Cell::new(0),
                owned_signals,
                runtime_epoch: current_runtime_epoch(),
            }),
        }
    }

    /// Returns the reactive `Signal<SafeAreaInsets>` updated on cold start, orientation changes, and Dynamic/Atomic Island updates.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Context reference.
    ///
    /// # Returns
    ///
    /// - `Signal<SafeAreaInsets>` - Reactive safe-area insets signal.
    #[must_use]
    pub fn safe_area_signal(&self) -> Signal<SafeAreaInsets> {
        self.get_safe_area()
    }

    /// Reads the current `SafeAreaInsets` reactively, subscribing the enclosing `Effect` or `Memo`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Context reference.
    ///
    /// # Returns
    ///
    /// - `SafeAreaInsets` - Active safe-area insets in logical pixels.
    #[must_use]
    pub fn safe_area(&self) -> SafeAreaInsets {
        self.get_safe_area().get()
    }

    /// Returns the reactive `Signal<bool>` indicating whether immersive fullscreen mode is active.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Context reference.
    ///
    /// # Returns
    ///
    /// - `Signal<bool>` - Reactive immersive fullscreen state signal.
    #[must_use]
    pub fn immersive_fullscreen_signal(&self) -> Signal<bool> {
        self.get_immersive_fullscreen()
    }

    /// Reads whether immersive fullscreen mode is currently active, subscribing the enclosing reactive scope.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Context reference.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` while immersive fullscreen is active.
    #[must_use]
    pub fn is_immersive_fullscreen(&self) -> bool {
        self.get_immersive_fullscreen().get()
    }

    /// Explicitly sets immersive fullscreen state across both reactive UI chrome and OS system bars.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Context reference.
    /// - `bool` - `true` to enter immersive fullscreen; `false` to exit and restore bars.
    pub fn set_immersive_fullscreen(&self, enabled: bool) {
        let Self { shared, .. } = self;
        if enabled {
            if shared.fullscreen_depth.get() == 0 {
                shared.fullscreen_depth.set(1);
            }
            let _: bool = self.get_immersive_fullscreen().set_if_changed(true);
        } else {
            shared.fullscreen_depth.set(0);
            let _: bool = self.get_immersive_fullscreen().set_if_changed(false);
        }
    }

    /// Increments the nested immersive fullscreen entry count and activates fullscreen mode.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Context reference.
    pub fn enter_immersive_fullscreen(&self) {
        let Self { shared, .. } = self;
        let next: u32 = shared.fullscreen_depth.get().saturating_add(1);
        shared.fullscreen_depth.set(next);
        let _: bool = self.get_immersive_fullscreen().set_if_changed(true);
    }

    /// Decrements the nested immersive fullscreen entry count and restores bars when the count reaches zero.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Context reference.
    pub fn exit_immersive_fullscreen(&self) {
        let Self { shared, .. } = self;
        let next: u32 = shared.fullscreen_depth.get().saturating_sub(1);
        shared.fullscreen_depth.set(next);
        if next == 0 {
            let _: bool = self.get_immersive_fullscreen().set_if_changed(false);
        }
    }

    /// Returns the reactive `Signal<AppState>` tracking canonical cross-platform application lifecycle state.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Context reference.
    ///
    /// # Returns
    ///
    /// - `Signal<AppState>` - Reactive lifecycle state signal.
    #[must_use]
    pub fn app_state_signal(&self) -> Signal<AppState> {
        self.get_app_state()
    }

    /// Dispatches a page-level `SystemEvent::Appear` to all currently active non-frozen hooks and visible observers.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Context reference.
    pub fn emit_page_appear(&self) {
        let ev: SystemEvent = SystemEvent::Appear;
        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self
            .get_scene()
            .with_read(SceneTree::collect_visible_lifecycles, Vec::new());
        dispatch_lifecycle_system_event(&observers, &ev);
        dispatch_system_event_listeners(&ev);
    }

    /// Dispatches a page-level `SystemEvent::Disappear` to all currently active non-frozen hooks and visible observers.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Context reference.
    pub fn emit_page_disappear(&self) {
        let ev: SystemEvent = SystemEvent::Disappear;
        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self
            .get_scene()
            .with_read(SceneTree::collect_visible_lifecycles, Vec::new());
        dispatch_lifecycle_system_event(&observers, &ev);
        dispatch_system_event_listeners(&ev);
    }

    /// Dispatches `SystemEvent::Appear` strictly to `Lifecycle` components and scoped hooks within `root`'s subtree.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Context reference.
    /// - `NodeId` - Routed page or component subtree root handle becoming active.
    pub fn emit_subtree_appear(&self, root: NodeId) {
        self.get_scene().emit_subtree_appear(root);
    }

    /// Dispatches `SystemEvent::Disappear` strictly to `Lifecycle` components and scoped hooks within `root`'s subtree.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Context reference.
    /// - `NodeId` - Routed page or component subtree root handle becoming hidden.
    pub fn emit_subtree_disappear(&self, root: NodeId) {
        self.get_scene().emit_subtree_disappear(root);
    }

    /// Returns the monotonic runtime elapsed clock in milliseconds.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Context reference.
    ///
    /// # Returns
    ///
    /// - `u64` - Elapsed runtime time in milliseconds.
    #[must_use]
    pub fn elapsed_ms(&self) -> u64 {
        let Self { shared, .. } = self;
        shared.clock_ms.get()
    }

    /// Advances the context's monotonic runtime clock by `delta_ms` milliseconds.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Context reference.
    /// - `u64` - Milliseconds elapsed since the previous frame.
    pub(crate) fn advance_clock_ms(&self, delta_ms: u64) {
        let Self { shared, .. } = self;
        shared
            .clock_ms
            .set(shared.clock_ms.get().saturating_add(delta_ms));
    }

    /// Requests graceful OS-level application termination across all platforms.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Context reference.
    pub fn request_exit(&self) {
        let _: bool = self.get_exit_requested().set_if_changed(true);
        let _: bool = dispatch_native_action(NATIVE_ACTION_EXIT, "", "");
    }

    /// Copies `text` to the host OS or browser clipboard via native clipboard hooks.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Context reference.
    /// - `&str` - UTF-8 text string to copy.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when a native or host clipboard bridge accepted `text`.
    pub fn copy_to_clipboard(&self, text: &str) -> bool {
        write_system_clipboard(text)
    }

    /// Creates a `View` node with the given style.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `Style` - Initial style.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Created node handle.
    pub fn view(&mut self, style: Style) -> NodeId {
        self.get_scene().with_write(
            |tree: &mut SceneTree| tree.create_view(style),
            NodeId::default(),
        )
    }

    /// Creates a `Text` node with static initial text.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `String` - Text content.
    /// - `Style` - Text style.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Created node handle.
    pub fn text(&mut self, content: String, style: Style) -> NodeId {
        self.get_scene().with_write(
            |tree: &mut SceneTree| tree.create_text(content, style),
            NodeId::default(),
        )
    }

    /// Creates a reactive `Text` node whose content updates surgically whenever tracked signals change.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `Style` - Text style.
    /// - `F` - Reactive text producer.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Created reactive text node handle.
    pub fn reactive_text<F>(&mut self, style: Style, producer: F) -> NodeId
    where
        F: FnMut() -> String + 'static,
    {
        let node_id: NodeId = self.text(String::new(), style);
        let handle: SceneHandle = self.get_scene().clone();
        let (scope, _): (Scope, Effect) =
            Scope::run(|_: Scope| handle.bind_text(node_id, producer));
        self.get_scene().with_write(
            |tree: &mut SceneTree| {
                tree.attach_scope(node_id, scope);
            },
            (),
        );
        node_id
    }

    /// Creates a `ScrollView` node with the given style.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `Style` - Scroll container style.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Created scroll view handle.
    pub fn scroll_view(&mut self, style: Style) -> NodeId {
        self.get_scene().with_write(
            |tree: &mut SceneTree| tree.create_scroll_view(style),
            NodeId::default(),
        )
    }

    /// Creates an `Input` node with initial state and style.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `InputNodeState` - Initial input state.
    /// - `Style` - Input style.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Created input handle.
    pub fn input(&mut self, state: InputNodeState, style: Style) -> NodeId {
        self.get_scene().with_write(
            |tree: &mut SceneTree| tree.create_input(state, style),
            NodeId::default(),
        )
    }

    /// Creates an `Image` node with decoded RGBA8 pixel data.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `ImageBuffer` - Image buffer.
    /// - `Style` - Image style.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Created image handle.
    pub fn image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
        self.get_scene().with_write(
            |tree: &mut SceneTree| tree.create_image(buffer, style),
            NodeId::default(),
        )
    }

    /// Creates a `Canvas` node bound to a custom draw callback.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `Style` - Canvas style.
    /// - `F` - Draw callback receiving node bounds and mutable `DisplayList`.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Created canvas handle.
    pub fn canvas<F>(&mut self, style: Style, painter: F) -> NodeId
    where
        F: FnMut(Rect, &mut DisplayList) + 'static,
    {
        self.canvas_with_caching(style, CanvasCaching::DynamicPerFrame, painter)
    }

    /// Creates a `Canvas` node bound to a custom draw callback with an explicit `CanvasCaching` strategy.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `Style` - Canvas style.
    /// - `CanvasCaching` - Fragment caching strategy (`DynamicPerFrame` or `RetainedStatic`).
    /// - `F` - Draw callback receiving node bounds and mutable `DisplayList`.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Created canvas handle.
    pub fn canvas_with_caching<F>(
        &mut self,
        style: Style,
        caching: CanvasCaching,
        painter: F,
    ) -> NodeId
    where
        F: FnMut(Rect, &mut DisplayList) + 'static,
    {
        let cb: CanvasDrawCallback = Rc::new(RefCell::new(painter));
        self.get_scene().with_write(
            |tree: &mut SceneTree| tree.create_canvas_with_caching(style, caching, cb),
            NodeId::default(),
        )
    }

    /// Creates an overlay `Portal` node.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `Style` - Portal style.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Created portal handle.
    pub fn portal(&mut self, style: Style) -> NodeId {
        self.get_scene().with_write(
            |tree: &mut SceneTree| tree.create_portal(style),
            NodeId::default(),
        )
    }

    /// Creates a transparent logical `Fragment` grouping container for sibling nodes.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Created fragment handle.
    pub fn fragment(&mut self) -> NodeId {
        self.get_scene().with_write(
            |tree: &mut SceneTree| tree.create_fragment(),
            NodeId::default(),
        )
    }

    /// Appends `child` to `parent`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `NodeId` - Parent container.
    /// - `NodeId` - Child node.
    pub fn append(&mut self, parent: NodeId, child: NodeId) {
        self.get_scene().with_write(
            |tree: &mut SceneTree| {
                tree.append_child(parent, child);
            },
            (),
        );
    }

    /// Appends a slice of `children` to `parent` under a single scene write lock and dirty pass.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `NodeId` - Parent container.
    /// - `&[NodeId]` - Ordered child node slice.
    pub fn append_many(&mut self, parent: NodeId, children: &[NodeId]) {
        if children.is_empty() {
            return;
        }
        self.get_scene().with_write(
            |tree: &mut SceneTree| {
                tree.append_children(parent, children);
            },
            (),
        );
    }

    /// Binds a reactive `Style` closure to `node_id` and attaches its disposal `Scope` automatically.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `NodeId` - Target scene node.
    /// - `F` - Reactive `Style` producer closure.
    pub fn bind_style<F>(&mut self, node_id: NodeId, producer: F)
    where
        F: FnMut() -> Style + 'static,
    {
        let handle: SceneHandle = self.get_scene().clone();
        let (scope, _): (Scope, Effect) =
            Scope::run(|_: Scope| handle.bind_style(node_id, producer));
        self.get_scene().with_write(
            |tree: &mut SceneTree| {
                tree.attach_scope(node_id, scope);
            },
            (),
        );
    }

    /// Registers a pointer-enter handler on `node_id`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `NodeId` - Target node handle.
    /// - `F` - Pointer-enter callback closure.
    pub fn on_pointer_enter<F>(&mut self, node_id: NodeId, callback: F)
    where
        F: FnMut(&UiEvent) + 'static,
    {
        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
        self.get_scene().with_write(
            |tree: &mut SceneTree| {
                if let Some(node) = tree.get_node_mut(node_id) {
                    node.get_mut_handlers().set_on_pointer_enter(Some(handler));
                }
            },
            (),
        );
    }

    /// Registers a pointer-leave handler on `node_id`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `NodeId` - Target node handle.
    /// - `F` - Pointer-leave callback closure.
    pub fn on_pointer_leave<F>(&mut self, node_id: NodeId, callback: F)
    where
        F: FnMut(&UiEvent) + 'static,
    {
        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
        self.get_scene().with_write(
            |tree: &mut SceneTree| {
                if let Some(node) = tree.get_node_mut(node_id) {
                    node.get_mut_handlers().set_on_pointer_leave(Some(handler));
                }
            },
            (),
        );
    }

    /// Registers a focus-gained handler on `node_id` and marks it focusable.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `NodeId` - Target node handle.
    /// - `F` - Focus callback closure receiving `UiEventKind::Focus`.
    pub fn on_focus<F>(&mut self, node_id: NodeId, callback: F)
    where
        F: FnMut(&UiEvent) + 'static,
    {
        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
        self.get_scene().with_write(
            |tree: &mut SceneTree| {
                if let Some(node) = tree.get_node_mut(node_id) {
                    node.get_mut_handlers().set_on_focus(Some(handler));
                    node.get_mut_interaction().set_focusable(true);
                }
            },
            (),
        );
    }

    /// Registers a focus-lost handler on `node_id`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `NodeId` - Target node handle.
    /// - `F` - Blur callback closure receiving `UiEventKind::Blur`.
    pub fn on_blur<F>(&mut self, node_id: NodeId, callback: F)
    where
        F: FnMut(&UiEvent) + 'static,
    {
        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
        self.get_scene().with_write(
            |tree: &mut SceneTree| {
                if let Some(node) = tree.get_node_mut(node_id) {
                    node.get_mut_handlers().set_on_blur(Some(handler));
                }
            },
            (),
        );
    }

    /// Configures whether `node_id` participates in keyboard focus navigation.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `NodeId` - Target node handle.
    /// - `bool` - Whether keyboard focus is enabled.
    pub fn set_focusable(&mut self, node_id: NodeId, focusable: bool) {
        self.get_scene().with_write(
            |tree: &mut SceneTree| {
                if let Some(node) = tree.get_node_mut(node_id) {
                    node.get_mut_interaction().set_focusable(focusable);
                }
            },
            (),
        );
    }

    /// Registers a click handler on `node_id` and sets pointer cursor automatically.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `NodeId` - Target node.
    /// - `F` - Click callback closure.
    pub fn on_click<F>(&mut self, node_id: NodeId, callback: F)
    where
        F: FnMut(&UiEvent) + 'static,
    {
        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
        self.get_scene().with_write(
            |tree: &mut SceneTree| {
                if let Some(node) = tree.get_node_mut(node_id) {
                    node.get_mut_handlers().set_on_click(Some(handler));
                    node.get_mut_interaction().set_focusable(true);
                    let paint: &mut PaintStyle = node.get_mut_style().get_mut_paint();
                    if paint.get_cursor() == CursorIcon::Default {
                        paint.set_cursor(CursorIcon::Pointer);
                    }
                }
            },
            (),
        );
    }

    /// Registers a change handler on an `Input` node.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `NodeId` - Target input node.
    /// - `F` - Change callback closure.
    pub fn on_change<F>(&mut self, node_id: NodeId, callback: F)
    where
        F: FnMut(&UiEvent) + 'static,
    {
        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
        self.get_scene().with_write(
            |tree: &mut SceneTree| {
                if let Some(node) = tree.get_node_mut(node_id) {
                    node.get_mut_handlers().set_on_change(Some(handler));
                }
            },
            (),
        );
    }

    /// Attaches semantic accessibility properties to `node_id`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `NodeId` - Target scene node.
    /// - `A11yProps` - Semantic role, label, hint, and state metadata.
    pub fn set_a11y(&mut self, node_id: NodeId, props: A11yProps) {
        self.get_scene().with_write(
            |tree: &mut SceneTree| {
                if let Some(node) = tree.get_node_mut(node_id) {
                    node.set_a11y(Some(props));
                }
            },
            (),
        );
    }

    /// Registers a scroll handler on a scrollable container node.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `NodeId` - Target scroll container node.
    /// - `F` - Scroll callback closure receiving `UiEventKind::Scroll(delta)`.
    pub fn on_scroll<F>(&mut self, node_id: NodeId, callback: F)
    where
        F: FnMut(&UiEvent) + 'static,
    {
        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
        self.get_scene().with_write(
            |tree: &mut SceneTree| {
                if let Some(node) = tree.get_node_mut(node_id) {
                    node.get_mut_handlers().set_on_scroll(Some(handler));
                }
            },
            (),
        );
    }

    /// Registers a pointer-down handler on `node_id` for draggable interactive controls.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `NodeId` - Target node handle.
    /// - `F` - Pointer-down callback closure.
    pub fn on_pointer_down<F>(&mut self, node_id: NodeId, callback: F)
    where
        F: FnMut(&UiEvent) + 'static,
    {
        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
        self.get_scene().with_write(
            |tree: &mut SceneTree| {
                if let Some(node) = tree.get_node_mut(node_id) {
                    node.get_mut_handlers().set_on_pointer_down(Some(handler));
                    let paint: &mut PaintStyle = node.get_mut_style().get_mut_paint();
                    if paint.get_cursor() == CursorIcon::Default {
                        paint.set_cursor(CursorIcon::Pointer);
                    }
                }
            },
            (),
        );
    }

    /// Registers a pointer-move handler on `node_id` receiving captured drag coordinates while pressed.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `NodeId` - Target node handle.
    /// - `F` - Pointer-move callback closure.
    pub fn on_pointer_move<F>(&mut self, node_id: NodeId, callback: F)
    where
        F: FnMut(&UiEvent) + 'static,
    {
        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
        self.get_scene().with_write(
            |tree: &mut SceneTree| {
                if let Some(node) = tree.get_node_mut(node_id) {
                    node.get_mut_handlers().set_on_pointer_move(Some(handler));
                }
            },
            (),
        );
    }

    /// Registers a pointer-up handler on `node_id` invoked when drag capture releases.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `NodeId` - Target node handle.
    /// - `F` - Pointer-up callback closure.
    pub fn on_pointer_up<F>(&mut self, node_id: NodeId, callback: F)
    where
        F: FnMut(&UiEvent) + 'static,
    {
        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
        self.get_scene().with_write(
            |tree: &mut SceneTree| {
                if let Some(node) = tree.get_node_mut(node_id) {
                    node.get_mut_handlers().set_on_pointer_up(Some(handler));
                }
            },
            (),
        );
    }

    /// Registers a pointer-cancel handler on `node_id` invoked when OS or gesture arbitration cancels a press.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `NodeId` - Target node handle.
    /// - `F` - Pointer-cancel callback closure receiving `UiEventKind::PointerCancel`.
    pub fn on_pointer_cancel<F>(&mut self, node_id: NodeId, callback: F)
    where
        F: FnMut(&UiEvent) + 'static,
    {
        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
        self.get_scene().with_write(
            |tree: &mut SceneTree| {
                if let Some(node) = tree.get_node_mut(node_id) {
                    node.get_mut_handlers().set_on_pointer_cancel(Some(handler));
                }
            },
            (),
        );
    }

    /// Registers a hover handler on `node_id` invoked on both `PointerEnter` and `PointerLeave`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `NodeId` - Target node handle.
    /// - `F` - Hover callback closure receiving `UiEventKind::PointerEnter` or `PointerLeave`.
    pub fn on_hover<F>(&mut self, node_id: NodeId, callback: F)
    where
        F: FnMut(&UiEvent) + 'static,
    {
        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
        let leave_handler: UiEventHandler = handler.clone();
        self.get_scene().with_write(
            |tree: &mut SceneTree| {
                if let Some(node) = tree.get_node_mut(node_id) {
                    node.get_mut_handlers().set_on_pointer_enter(Some(handler));
                    node.get_mut_handlers()
                        .set_on_pointer_leave(Some(leave_handler));
                }
            },
            (),
        );
    }

    /// Registers a keyboard key-down handler on `node_id` and marks it focusable.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `NodeId` - Target node handle.
    /// - `F` - Key-down callback closure receiving `UiEventKind::KeyDown`.
    pub fn on_key<F>(&mut self, node_id: NodeId, callback: F)
    where
        F: FnMut(&UiEvent) + 'static,
    {
        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
        self.get_scene().with_write(
            |tree: &mut SceneTree| {
                if let Some(node) = tree.get_node_mut(node_id) {
                    node.get_mut_handlers().set_on_key_down(Some(handler));
                    node.get_mut_interaction().set_focusable(true);
                }
            },
            (),
        );
    }

    /// Records virtualized scroll progress on `node_id` so the overlay scrollbar tracks accurately.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `NodeId` - Target virtualized scroll container.
    /// - `f32` - Active virtual vertical scroll offset in logical pixels.
    /// - `f32` - Full virtualized content height in logical pixels.
    pub fn set_virtual_scroll(&mut self, node_id: NodeId, scroll_y: f32, content_height: f32) {
        self.get_scene()
            .set_virtual_scroll(node_id, scroll_y, content_height);
    }

    /// Sets the concrete inner pixel scroll offset on `node_id` (used by virtualized lists for sub-pixel alignment).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `NodeId` - Target scroll container.
    /// - `Point` - Scroll offset `(x, y)` in logical pixels.
    pub fn set_scroll_offset(&mut self, node_id: NodeId, offset: Point) {
        self.get_scene().with_write(
            |tree: &mut SceneTree| {
                tree.set_scroll_offset(node_id, offset);
            },
            (),
        );
    }

    /// Starts a smooth paint/transform transition on `transition.get_node()`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `NodeTransition` - Transition specification.
    pub fn start_transition(&mut self, transition: NodeTransition) {
        self.get_scene().start_transition(transition);
    }

    /// Mounts a reactive dynamic subtree whose children rebuild cleanly inside an isolated `Scope`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `NodeId` - Host container node.
    /// - `F` - Reactive zero-`ctx` builder returning child `NodeId` values.
    pub fn bind_children<F>(&mut self, host: NodeId, mut builder: F)
    where
        F: FnMut() -> Vec<NodeId> + 'static,
    {
        let ctx_clone: Self = self.clone();
        let handle: SceneHandle = self.get_scene().clone();
        let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
            Effect::new(move || {
                let (child_scope, children): (Scope, Vec<NodeId>) =
                    Scope::run(|_: Scope| with_context(ctx_clone.clone(), &mut builder));
                let first_opt: Option<NodeId> = children.first().copied();
                handle.replace_children_safe(host, children);
                if let Some(first) = first_opt {
                    handle.mutate(move |tree: &mut SceneTree| {
                        tree.attach_scope(first, child_scope);
                    });
                } else {
                    child_scope.dispose();
                }
            })
        });
        self.get_scene().mutate(move |tree: &mut SceneTree| {
            tree.attach_scope(host, scope);
        });
    }

    /// Mounts a keyed reactive child list reconciling items in O(N) by key `K` so unchanged items retain their mounted `NodeId` and `Scope`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Build context.
    /// - `NodeId` - Host container node.
    /// - `Items` - Reactive producer returning the ordered list of item data `Vec<T>`.
    /// - `KeyFn` - Pure key extractor mapping `&T` to a stable key `K`.
    /// - `RenderFn` - Item builder mounting one child `NodeId` for a newly inserted item `T`.
    pub fn bind_children_keyed<T, K, Items, KeyFn, RenderFn>(
        &mut self,
        host: NodeId,
        mut items_fn: Items,
        mut key_fn: KeyFn,
        mut render_fn: RenderFn,
    ) where
        T: 'static,
        K: Eq + Hash + 'static,
        Items: FnMut() -> Vec<T> + 'static,
        KeyFn: FnMut(&T) -> K + 'static,
        RenderFn: FnMut(T) -> NodeId + 'static,
    {
        let ctx_clone: Self = self.clone();
        let handle: SceneHandle = self.get_scene().clone();
        let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
            let mut live_nodes: HashMap<K, NodeId> = HashMap::new();
            Effect::new(move || {
                let next_items: Vec<T> = items_fn();
                let mut next_map: HashMap<K, NodeId> = HashMap::with_capacity(next_items.len());
                let mut next_children: Vec<NodeId> = Vec::with_capacity(next_items.len());
                let mut new_scopes: Vec<(NodeId, Scope)> = Vec::new();
                for item in next_items.into_iter() {
                    let key: K = key_fn(&item);
                    if let Some(existing_id) = live_nodes.remove(&key) {
                        next_children.push(existing_id);
                        let _: Option<NodeId> = next_map.insert(key, existing_id);
                    } else {
                        let (item_scope, mounted_id): (Scope, NodeId) = Scope::run(|_: Scope| {
                            with_context(ctx_clone.clone(), || render_fn(item))
                        });
                        new_scopes.push((mounted_id, item_scope));
                        next_children.push(mounted_id);
                        let _: &mut NodeId = next_map.entry(key).or_insert(mounted_id);
                    }
                }
                live_nodes = next_map;
                handle.replace_children_safe(host, next_children);
                if !new_scopes.is_empty() {
                    handle.mutate(move |tree: &mut SceneTree| {
                        for (nid, item_scope) in new_scopes.into_iter() {
                            tree.attach_scope(nid, item_scope);
                        }
                    });
                }
            })
        });
        self.get_scene().mutate(move |tree: &mut SceneTree| {
            tree.attach_scope(host, scope);
        });
    }
}

/// Restores the previously bound ambient `Context` when leaving scope.
impl Drop for ContextGuard {
    /// Restores the saved thread-local `Context`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scope guard being dropped.
    fn drop(&mut self) {
        let Self { previous } = self;
        let restored: Option<Context> = previous.take();
        ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| {
            *slot.borrow_mut() = restored;
        });
    }
}

/// `NodeRefTarget` implementation storing a `NodeId` directly into a mutable local binding.
impl NodeRefTarget for NodeId {
    /// Assigns `id` to `self`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Target `NodeId` slot.
    /// - `NodeId` - Mounted node handle.
    fn bind_node_ref(&mut self, id: NodeId) {
        *self = id;
    }
}

/// `NodeRefTarget` implementation storing a `NodeId` into an `Option<NodeId>`.
impl NodeRefTarget for Option<NodeId> {
    /// Assigns `Some(id)` to `self`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Target optional `NodeId` slot.
    /// - `NodeId` - Mounted node handle.
    fn bind_node_ref(&mut self, id: NodeId) {
        *self = Some(id);
    }
}

/// `NodeRefTarget` implementation storing a `NodeId` into a `Cell<NodeId>`.
impl NodeRefTarget for Cell<NodeId> {
    /// Sets `self` to `id`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Target `Cell<NodeId>`.
    /// - `NodeId` - Mounted node handle.
    fn bind_node_ref(&mut self, id: NodeId) {
        self.set(id);
    }
}

/// `NodeRefTarget` implementation storing a `NodeId` into a shared `Rc<Cell<NodeId>>`.
impl NodeRefTarget for Rc<Cell<NodeId>> {
    /// Sets the shared cell value to `id`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Target shared `Cell<NodeId>`.
    /// - `NodeId` - Mounted node handle.
    fn bind_node_ref(&mut self, id: NodeId) {
        self.set(id);
    }
}

/// `NodeRefTarget` implementation storing a `NodeId` into a `Cell<Option<NodeId>>`.
impl NodeRefTarget for Cell<Option<NodeId>> {
    /// Sets `self` to `Some(id)`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Target `Cell<Option<NodeId>>`.
    /// - `NodeId` - Mounted node handle.
    fn bind_node_ref(&mut self, id: NodeId) {
        self.set(Some(id));
    }
}

/// `NodeRefTarget` implementation storing a `NodeId` into a shared `Rc<Cell<Option<NodeId>>>`.
impl NodeRefTarget for Rc<Cell<Option<NodeId>>> {
    /// Sets the shared cell value to `Some(id)`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Target shared `Cell<Option<NodeId>>`.
    /// - `NodeId` - Mounted node handle.
    fn bind_node_ref(&mut self, id: NodeId) {
        self.set(Some(id));
    }
}

/// `TextNodeContent` implementation mounting an owned `String` as a static text node.
impl TextNodeContent for String {
    /// Mounts a static text scene node from this `String`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Owned text string.
    /// - `&mut Context` - Active scene build context.
    /// - `Style` - Resolved text style.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Mounted text node handle.
    fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
        ctx.text(self, style)
    }

    /// Mounts a static text scene node from this `String` using the ambient `Context` without cloning it.
    ///
    /// # Arguments
    ///
    /// - `Self` - Owned text string.
    /// - `Style` - Resolved text style.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Mounted text node handle.
    fn mount_text_current(self, style: Style) -> NodeId {
        with_current_context(|ctx: &Context| {
            ctx.get_scene().with_write(
                |tree: &mut SceneTree| tree.create_text(self, style),
                NodeId::default(),
            )
        })
    }
}

/// `TextNodeContent` implementation mounting a string slice as a static text node.
impl TextNodeContent for &str {
    /// Mounts a static text scene node from this `&str`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Borrowed text slice.
    /// - `&mut Context` - Active scene build context.
    /// - `Style` - Resolved text style.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Mounted text node handle.
    fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
        ctx.text(self.to_string(), style)
    }

    /// Mounts a static text scene node from this `&str` using the ambient `Context` without cloning it.
    ///
    /// # Arguments
    ///
    /// - `Self` - Borrowed text slice.
    /// - `Style` - Resolved text style.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Mounted text node handle.
    fn mount_text_current(self, style: Style) -> NodeId {
        let owned: String = self.to_string();
        with_current_context(|ctx: &Context| {
            ctx.get_scene().with_write(
                |tree: &mut SceneTree| tree.create_text(owned, style),
                NodeId::default(),
            )
        })
    }
}

/// `TextNodeContent` implementation mounting a borrowed `&String` as a static text node.
impl TextNodeContent for &String {
    /// Mounts a static text scene node from this `&String`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Borrowed string reference.
    /// - `&mut Context` - Active scene build context.
    /// - `Style` - Resolved text style.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Mounted text node handle.
    fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
        ctx.text(self.clone(), style)
    }

    /// Mounts a static text scene node from this `&String` using the ambient `Context` without cloning it.
    ///
    /// # Arguments
    ///
    /// - `Self` - Borrowed string reference.
    /// - `Style` - Resolved text style.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Mounted text node handle.
    fn mount_text_current(self, style: Style) -> NodeId {
        let owned: String = self.clone();
        with_current_context(|ctx: &Context| {
            ctx.get_scene().with_write(
                |tree: &mut SceneTree| tree.create_text(owned, style),
                NodeId::default(),
            )
        })
    }
}

/// `TextNodeContent` implementation mounting a `Cow<str>` as a static text node.
impl TextNodeContent for Cow<'_, str> {
    /// Mounts a static text scene node from this `Cow<str>`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Copy-on-write string value.
    /// - `&mut Context` - Active scene build context.
    /// - `Style` - Resolved text style.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Mounted text node handle.
    fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
        ctx.text(self.into_owned(), style)
    }

    /// Mounts a static text scene node from this `Cow<str>` using the ambient `Context` without cloning it.
    ///
    /// # Arguments
    ///
    /// - `Self` - Copy-on-write string value.
    /// - `Style` - Resolved text style.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Mounted text node handle.
    fn mount_text_current(self, style: Style) -> NodeId {
        let owned: String = self.into_owned();
        with_current_context(|ctx: &Context| {
            ctx.get_scene().with_write(
                |tree: &mut SceneTree| tree.create_text(owned, style),
                NodeId::default(),
            )
        })
    }
}

/// `TextNodeContent` implementation mounting any `FnMut() -> S` closure or function item as a reactive text node.
impl<F, S> TextNodeContent for F
where
    F: FnMut() -> S + 'static,
    S: Into<String>,
{
    /// Mounts a reactive text scene node bound to this closure or function item.
    ///
    /// # Arguments
    ///
    /// - `Self` - Reactive text producer closure.
    /// - `&mut Context` - Active scene build context.
    /// - `Style` - Resolved text style.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Mounted reactive text node handle.
    fn mount_text_content(mut self, ctx: &mut Context, style: Style) -> NodeId {
        ctx.reactive_text(style, move || self().into())
    }

    /// Mounts a reactive text scene node bound to this closure or function item using the ambient `Context` without cloning it.
    ///
    /// # Arguments
    ///
    /// - `Self` - Reactive text producer closure.
    /// - `Style` - Resolved text style.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Mounted reactive text node handle.
    fn mount_text_current(mut self, style: Style) -> NodeId {
        mount_reactive_text(style, move || self().into())
    }
}