pax-runtime 0.39.1

Core shared runtime and rendering engine for Pax
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
use crate::api::TextInput;
use crate::node_interface::NodeLocal;
use pax_language::Computable;
use pax_runtime_api::pax_value::{ImplToFromPaxAny, PaxAny, ToFromPaxAny};
use pax_runtime_api::{
    borrow, borrow_mut, use_RefCell, AsyncError, AsyncScope, Focus, Interpolatable, Layer,
    LocalProperty, NativeLiquidGlassScope, OpacityScope, PaxValue, Percent, SelectStart, Variable,
};

use crate::api::math::Point2;
use crate::constants::{
    ACCEL_HANDLERS, BUTTON_CLICK_HANDLERS, CHECKBOX_CHANGE_HANDLERS, CLICK_HANDLERS,
    CONTEXT_MENU_HANDLERS, DOUBLE_CLICK_HANDLERS, DROP_HANDLERS, FOCUSED_HANDLERS, GYRO_HANDLERS,
    KEY_DOWN_HANDLERS, KEY_PRESS_HANDLERS, KEY_UP_HANDLERS, MOUSE_DOWN_HANDLERS,
    MOUSE_MOVE_HANDLERS, MOUSE_OUT_HANDLERS, MOUSE_OVER_HANDLERS, MOUSE_UP_HANDLERS,
    PHOTO_PICKER_CHANGE_HANDLERS, SCROLL_HANDLERS, SELECT_START_HANDLERS, SLIDER_CHANGE_HANDLERS,
    TAP_HANDLERS, TEXTBOX_CHANGE_HANDLERS, TEXTBOX_INPUT_HANDLERS, TEXT_INPUT_HANDLERS,
    TOUCH_CANCEL_HANDLERS, TOUCH_END_HANDLERS, TOUCH_MOVE_HANDLERS, TOUCH_START_HANDLERS,
    WHEEL_HANDLERS,
};
use_RefCell!();
use crate::cartridge::evaluate_timeline_duration;
use crate::{ExpandedNodeIdentifier, Globals, LayoutHull, LayoutProperties, TransformAndBounds};
use core::fmt;
use std::cell::Cell;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::rc::{Rc, Weak};

// Keep the source handles alive, not the parent node. Equality of current
// values is insufficient: a different source must establish a new subscription.
#[derive(Clone)]
struct ParentBindingSources {
    parent: ExpandedNodeIdentifier,
    properties: Vec<pax_runtime_api::properties::UntypedProperty>,
}

impl ParentBindingSources {
    fn same_as(&self, other: &Self) -> bool {
        self.parent == other.parent
            && self.properties.len() == other.properties.len()
            && self
                .properties
                .iter()
                .zip(&other.properties)
                .all(|(a, b)| a.get_id() == b.get_id())
    }
}

#[derive(PartialEq)]
struct ChildStructure {
    binding_generation: u64,
    rendered: Vec<ExpandedNodeIdentifier>,
    active: Vec<ExpandedNodeIdentifier>,
    exiting: Vec<ExpandedNodeIdentifier>,
}

use crate::api::{
    Accel, Axis, ButtonClick, CheckboxChange, Click, CommonProperties, ContextMenu, DoubleClick,
    Drop, Event, Gyro, KeyDown, KeyPress, KeyUp, LayoutRole, MouseDown, MouseMove, MouseOut,
    MouseOver, MouseUp, NodeContext, PhotoPickerChange, RenderContext, Scroll, Size, SliderChange,
    TextboxChange, TextboxInput, TouchCancel, TouchEnd, TouchMove, TouchStart, Wheel, Window,
};
use pax_manifest::cartridge_generation::{
    TRANSITION_GENERATION_SYMBOL, TRANSITION_PHASE_ENTER, TRANSITION_PHASE_EXIT,
    TRANSITION_PHASE_IDLE, TRANSITION_PHASE_SYMBOL, TRANSITION_PLAYHEAD_MILLIS_SYMBOL,
    TRANSITION_PLAYHEAD_SYMBOL, TRANSITION_TAKEOVER_SYMBOL,
};
use pax_manifest::{
    ExpressionInfo, LocationInfo, SelectorExpr, SettingsBlockElement, TypeId,
    UniqueTemplateNodeIdentifier, ValueDefinition,
};

use crate::{
    add_symmetric_padding_to_content_layout_hull, apply_container_frame, apply_padding_frame,
    compute_tab, ComponentInstance, ContainerFrame, HandlerLocation, InstanceNode, InstanceNodePtr,
    ReceivedChildrenSource, RuntimeContext, RuntimePropertiesStackFrame,
};

#[derive(Clone)]
pub struct RuntimeSettingsLayer {
    pub provider_id: ExpandedNodeIdentifier,
    pub provider_type_id: TypeId,
    /// The provider component's lexical scope. Imported settings expressions
    /// must resolve `self` and provider properties here, even though their
    /// resulting values are applied to a different node.
    pub provider_stack: Rc<RuntimePropertiesStackFrame>,
    pub settings: Vec<SettingsBlockElement>,
    pub transition: Option<LocalProperty<Option<crate::SettingsTransitionConfig>>>,
}

impl fmt::Debug for RuntimeSettingsLayer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RuntimeSettingsLayer")
            .field("provider_id", &self.provider_id)
            .field("provider_type_id", &self.provider_type_id)
            .field("provider_stack", &"<runtime scope>")
            .field("settings", &self.settings)
            .finish()
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RuntimeSettingsSignatureEntry {
    pub transition_enabled: bool,
    pub provider_id: ExpandedNodeIdentifier,
    pub provider_type_id: TypeId,
}

// Discovery runs every frame. Keep only handles until the ordered provider
// signature changes; copying settings also copies their entire expression trees.
struct DiscoveredSettingsProvider {
    node: Rc<ExpandedNode>,
    transition: Option<LocalProperty<Option<crate::SettingsTransitionConfig>>>,
}

impl DiscoveredSettingsProvider {
    fn signature(&self) -> RuntimeSettingsSignatureEntry {
        RuntimeSettingsSignatureEntry {
            transition_enabled: self
                .transition
                .as_ref()
                .and_then(|policy| policy.get())
                .is_some(),
            provider_id: self.node.id,
            provider_type_id: borrow!(self.node.instance_node)
                .base()
                .template_node_type_id
                .clone()
                .unwrap_or_default(),
        }
    }

    fn materialize(self) -> RuntimeSettingsLayer {
        let instance = borrow!(self.node.instance_node);
        #[cfg(test)]
        self.node
            .settings_layer_materializations
            .set(self.node.settings_layer_materializations.get() + 1);
        RuntimeSettingsLayer {
            provider_id: self.node.id,
            provider_type_id: instance
                .base()
                .template_node_type_id
                .clone()
                .unwrap_or_default(),
            provider_stack: self
                .node
                .stack
                .push(borrow!(self.node.properties_scope).clone()),
            settings: instance
                .base()
                .component_settings
                .as_ref()
                .expect("discovered provider has settings")
                .clone(),
            transition: self.transition,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RuntimeSettingsSource {
    ComponentSettings,
    ImportedLayer {
        provider_id: ExpandedNodeIdentifier,
        provider_type_id: TypeId,
    },
    Inline,
}

#[derive(Clone, Debug, Default)]
pub struct RuntimeSettingsCondition {
    pub positive: Vec<ExpressionInfo>,
    pub negative: Vec<ExpressionInfo>,
}

#[derive(Clone)]
pub struct RuntimeResolvedPropertyEntry {
    pub transition: Option<LocalProperty<Option<crate::SettingsTransitionConfig>>>,
    pub source: RuntimeSettingsSource,
    pub selector: Option<SelectorExpr>,
    pub source_location: Option<LocationInfo>,
    /// Overrides the receiving node's scope when this value came from an
    /// imported settings provider.
    pub source_stack: Option<Rc<RuntimePropertiesStackFrame>>,
    pub value: ValueDefinition,
    pub condition: Option<RuntimeSettingsCondition>,
    pub axis_index: Option<usize>,
}

impl fmt::Debug for RuntimeResolvedPropertyEntry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RuntimeResolvedPropertyEntry")
            .field("source", &self.source)
            .field("selector", &self.selector)
            .field("source_location", &self.source_location)
            .field(
                "source_stack",
                &self.source_stack.as_ref().map(|_| "<runtime scope>"),
            )
            .field("value", &self.value)
            .field("condition", &self.condition)
            .field("axis_index", &self.axis_index)
            .finish()
    }
}

pub type RuntimeResolvedPropertyColumns = BTreeMap<String, Vec<RuntimeResolvedPropertyEntry>>;

#[derive(Clone, Copy)]
enum PointerActivationSource {
    Mouse,
    Touch,
}

#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct FilteredRenderStats {
    pub path_nodes_visited: usize,
    pub dirty_nodes_rendered: usize,
    pub skipped_subtrees: usize,
}

/// This runtime owner stays on the UI thread. Transfer properties or delivery
/// handles to workers instead.
///
/// ```compile_fail
/// fn requires_send<T: Send>() {}
/// requires_send::<pax_runtime::ExpandedNode>();
/// ```
#[derive(Clone)]
pub struct ExpandedNode {
    property_binding_scope: RefCell<pax_runtime_api::properties::BindingScope>,
    async_scope: RefCell<Option<AsyncScope>>,
    #[allow(dead_code)]
    /// Unique ID of this expanded node, roughly encoding an address in the tree, where the first u32 is the instance ID
    /// and the subsequent u32s represent addresses within an expanded tree via Repeat.
    pub id: ExpandedNodeIdentifier,

    /// Pointer to the unexpanded `instance_node` underlying this ExpandedNode
    pub instance_node: RefCell<InstanceNodePtr>,

    /// Pointer (`Weak` to avoid Rc cycle memory leaks) to the ExpandedNode
    /// rendered directly above this one.
    pub render_parent: RefCell<Weak<ExpandedNode>>,

    /// Pointer (`Weak` to avoid Rc cycle memory leaks) to the ExpandedNode
    /// in the template directly above this one.
    pub template_parent: Weak<ExpandedNode>,

    /// Id of closest frame present in the node tree.
    /// included as a parameter on AnyCreatePatch when
    /// creating a native element to know what clipping context
    /// to attach to
    pub parent_frame: LocalProperty<Option<ExpandedNodeIdentifier>>,

    /// Nearest active native liquid-glass scope inherited by descendants.
    pub liquid_glass_scope: LocalProperty<Option<NativeLiquidGlassScope>>,

    /// Reference to the _component for which this `ExpandedNode` is a template member._ Used at least for
    /// resolving projected children for `slot`. `Option`al because the very root instance node (root component, root instance node)
    /// has a corollary "root component expanded node."  That very root expanded node _does not have_ a containing ExpandedNode component,
    /// thus `containing_component` is `Option`al.
    pub containing_component: Weak<ExpandedNode>,

    /// Persistent clone of the state of the `PropertiesTreeShared#runtime_properties_stack` at the time that this node was expanded (this is expected to remain immutable
    /// through the lifetime of the program after the initial expansion; however, if that constraint changes, this should be
    /// explicitly updated to accommodate.)
    pub stack: Rc<RuntimePropertiesStackFrame>,
    pub(crate) stores: crate::store::NodeStores,

    /// Pointers to the ExpandedNode beneath this one. Used for rendering
    /// recursion and other render-tree traversals.
    pub children: LocalProperty<Vec<Rc<ExpandedNode>>>,

    /// The concrete render-tree children currently attached beneath this node.
    ///
    /// This may temporarily include children retained for exit transitions, so
    /// it should not be confused with the semantic payload exposed through
    /// `NodeContext::received_children`.
    pub mounted_children: RefCell<Vec<Rc<ExpandedNode>>>,

    /// Children that represent the currently selected control-flow/template output.
    ///
    /// When this node's received-child source is `Owned`, this is the internal
    /// source for `NodeContext::received_children`.
    pub active_children: RefCell<Vec<Rc<ExpandedNode>>>,
    /// Reactive mirror of `active_children` for consumers that need the active
    /// semantic set.
    pub active_children_view: LocalProperty<Vec<Rc<ExpandedNode>>>,

    /// Children retained only so exit transitions can finish before unmount.
    ///
    /// When this node's received-child source is `Owned`, this is the internal
    /// source for `NodeContext::retained_received_children`.
    pub exiting_children: RefCell<Vec<Rc<ExpandedNode>>>,
    /// Retention token captured when each exiting child is queued. Rescuing a
    /// child advances its token so stale cleanup work cannot unmount it.
    exiting_child_generations: RefCell<HashMap<ExpandedNodeIdentifier, u64>>,
    /// Reactive mirror of `exiting_children` for consumers that need retained exits.
    pub exiting_children_view: LocalProperty<Vec<Rc<ExpandedNode>>>,

    /// Auxiliary children are not presented directly. Mask sources have a normal
    /// logical mount lifetime; other sidecar consumers choose their own lifetime.
    pub sidecar_children: RefCell<Vec<Rc<ExpandedNode>>>,

    /// Mask receiving this node's visual output, rather than the visible scene.
    /// The identifier avoids keeping the owner alive through its descendants.
    render_source_owner: Cell<Option<ExpandedNodeIdentifier>>,

    /// Each ExpandedNode has a unique "stamp" of computed properties
    pub properties: RefCell<Rc<RefCell<PaxAny>>>,

    /// Each ExpandedNode has unique, computed `CommonProperties`
    pub common_properties: RefCell<Rc<RefCell<CommonProperties>>>,
    /// Measured bounds reported by chassis/native layout or by container-owned bottom-up layout.
    /// When width/height are omitted, these values are used as the fallback concrete size.
    pub measured_size: LocalProperty<Option<(f64, f64)>>,
    /// Selector-facing metadata used by runtime and designtime queries.
    pub selector_metadata: RefCell<RuntimeSelectorMetadata>,

    /// The layout information (width, height, transform) used to render this node.
    /// computed property based on parent bounds + common properties
    pub transform_and_bounds: LocalProperty<TransformAndBounds<NodeLocal, Window>>,
    /// Engine-owned subtree hull used by container measurement.
    pub subtree_layout_hull: LocalProperty<LayoutHull>,
    /// Optional container-assigned virtual wrapper frame applied before this node's own layout.
    pub container_frame: LocalProperty<Option<ContainerFrame>>,

    /// The accumulated opacity inherited from render ancestors and this node's
    /// own common opacity value.
    pub computed_opacity: LocalProperty<f64>,
    /// Authored opacity scopes retained independently of their multiplied world opacity.
    /// Keeping the factors avoids division by zero and detects changes under a hidden ancestor.
    pub computed_opacity_scopes: LocalProperty<Vec<OpacityScope>>,

    /// For nodes that own projection, tracks projected children in their
    /// expanded, non-collapsed form.
    ///
    /// Projection is a transport detail used to deliver received payload into a
    /// node's encapsulated implementation, typically for `slot(...)`.
    /// Repeat/conditional descendants are still present here.
    pub expanded_projected_children: RefCell<Option<Vec<Rc<ExpandedNode>>>>,
    /// Flattened version of the projected children above, where repeat and
    /// conditionals are recursively replaced by their current outputs.
    ///
    /// This is the raw projected family, not necessarily the same thing as the
    /// semantic `received_children` view seen by all consumers.
    pub expanded_and_flattened_projected_children: LocalProperty<Vec<Rc<ExpandedNode>>>,
    /// Number of expanded and flattened projected children.
    pub flattened_projected_children_count: LocalProperty<usize>,

    /// Flag that is > 0 if this node is part of the root tree. If it is,
    /// updates to this nodes children also marks them as attached (+1), triggering
    /// mount and dismount on addition/removal. This is needed mainly for slot,
    /// since an entire "shadow tree" needs to be expanded and updated for
    /// each slot child, but only the ones that have a "connected" slot should
    /// trigger mount/dismount updates
    pub attached: Cell<u32>,

    /// Logical render-layer assignment plus z-order for the current render tree pass.
    ///
    /// Layer 0 is the root surface stack, and non-root layers are reserved for scroller-owned
    /// vector islands.
    pub occlusion: LocalProperty<Occlusion>,

    /// Hash of the last native occlusion mask emitted for this node.
    pub native_mask_hash: Cell<u64>,

    /// Last browser-owned descendant content layer published for scroller-style native hosts.
    pub browser_content_layer_id: Cell<Option<u32>>,

    /// Hash of the last presentation metadata emitted for clipping/scrolling chassis consumers.
    pub presentation_cache_hash: Cell<u64>,

    /// A map of all properties available on this expanded node.
    /// Used by the RuntimePropertiesStackFrame to resolve symbols.
    pub properties_scope: RefCell<HashMap<String, Variable>>,

    /// The flattened index of this node in its container (if this container
    /// cares about slot children, ex: component, path).
    pub slot_index: LocalProperty<Option<usize>>,

    /// property used to "freeze" (stop firing tick) on a node and all it's children
    pub suspended: LocalProperty<bool>,

    /// used by native elements to trigger sending of native messages
    /// used by canvas elements to dirtify their canvas
    pub changed_listener: LocalProperty<()>,
    selector_classes_listener: LocalProperty<()>,

    /// Tracks whether this node's occlusion-affecting inputs changed.
    pub occlusion_listener: LocalProperty<()>,

    /// Pulls the node's children property only when its upstream dependencies changed.
    pub children_listener: LocalProperty<()>,
    /// Rebinds `subtree_layout_hull` when the child list changes.
    pub subtree_layout_hull_listener: LocalProperty<()>,
    parent_binding_sources: RefCell<Option<ParentBindingSources>>,
    layout_binding_generation: Cell<u64>,
    #[cfg(test)]
    pub(crate) parent_binding_rebuilds: Cell<usize>,
    #[cfg(test)]
    pub(crate) layout_hull_rebuilds: Cell<usize>,
    #[cfg(test)]
    pub(crate) structural_children_updates: Cell<usize>,
    /// Reactive content-measurement effect used by autosize-style container features.
    pub content_measurement_listener: LocalProperty<()>,
    /// Rebinds `content_measurement_listener` when the content child list changes.
    pub content_measurement_rebind_listener: LocalProperty<()>,
    /// Guards one-time setup of the reactive content-measurement listener pair.
    pub content_measurement_bound: Cell<bool>,
    #[cfg(feature = "shaders")]
    pub(crate) shader_effect_bound: Cell<bool>,
    /// Cached update traversal state. Structural effects mark ancestors dirty when child
    /// ownership changes; the update pass clears this for subtrees with no remaining
    /// imperative update work.
    subtree_requires_non_reactive_update: Cell<bool>,

    /// Dirty signal emitted when the projected child set changes structurally.
    pub projected_children_changed: LocalProperty<()>,

    /// Dirty signal emitted when active slot sites or slot-index expressions
    /// may change the component-local projection resolution.
    pub slot_projection_changed: LocalProperty<()>,

    /// subscription properties: added to this expanded node by calling ctx.subscribe in a node event handler
    pub subscriptions: RefCell<Vec<LocalProperty<()>>>,

    /// Current lifecycle transition phase for this node.
    pub transition_phase: LocalProperty<u64>,
    /// Monotonic identity for each lifecycle transition run.
    pub transition_generation: LocalProperty<u64>,
    /// Whether the current run directly reversed the opposite lifecycle phase.
    pub transition_takeover: LocalProperty<bool>,
    /// Class membership captured at lifecycle-transition start. Ordinary settings continue to
    /// follow live classes, while transition tracks keep the selector membership that launched
    /// the current run.
    pub transition_selector_classes: RefCell<Option<Vec<String>>>,
    /// Parent-owned exit retention generation for stale cleanup protection.
    exit_retention_generation: Cell<u64>,
    /// Frame at which the active lifecycle transition began.
    pub transition_origin_frame: LocalProperty<u64>,
    /// Millisecond clock value at which the active lifecycle transition began.
    pub transition_origin_millis: LocalProperty<u64>,
    /// Local playhead, in frames, for the active lifecycle transition.
    pub transition_playhead: LocalProperty<f64>,
    /// Local playhead, in milliseconds, for the active lifecycle transition.
    pub transition_playhead_millis: LocalProperty<f64>,
    /// Effect property used to stop enter-transition clock dependencies.
    pub enter_cleanup_listener: LocalProperty<()>,
    /// Whether enter cleanup should do work on frame ticks.
    pub enter_cleanup_active: Cell<bool>,
    /// Wall-clock start for exit timeout enforcement.
    pub exit_started_millis: Cell<Option<u128>>,
    /// Whether this node has already warned about truncating its current exit transition.
    exit_timeout_warning_emitted: Cell<bool>,
    /// Effect property used to release deferred exit children.
    pub exit_cleanup_listener: LocalProperty<()>,
    /// Whether exit cleanup should do work on frame ticks.
    pub exit_cleanup_active: Cell<bool>,
    /// Imported provider layers currently active for this component instance.
    pub imported_settings_layers: RefCell<Vec<RuntimeSettingsLayer>>,
    #[cfg(test)]
    pub(crate) settings_layer_materializations: Cell<usize>,
    pub import_settings_transition:
        RefCell<Option<LocalProperty<Option<crate::SettingsTransitionConfig>>>>,
    pub(crate) settings_motion: Rc<RefCell<HashMap<String, Box<dyn std::any::Any>>>>,
    pub(crate) settings_birth_frame: u64,
    /// Ordered provider-node ids used to detect when the imported layer stack changed.
    pub imported_settings_signature: RefCell<Vec<RuntimeSettingsSignatureEntry>>,
    /// Layered property entries ordered from lowest to highest precedence.
    pub resolved_property_columns: RefCell<RuntimeResolvedPropertyColumns>,
    /// Winning property entry per key after layering and inline override.
    pub resolved_property_provenance: RefCell<BTreeMap<String, RuntimeResolvedPropertyEntry>>,
    /// Requests a materialization pass that resets properties removed from the prior columns.
    pub reset_removed_runtime_properties: Cell<bool>,
}

#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
pub struct Occlusion {
    /// Logical render layer: 0 for the root surface stack, >0 for scroller-owned vector islands.
    pub render_layer_id: usize,
    pub z_index: i32,
    // this is used to perform last patches logic,
    // and is updated to reflect this nodes parent_frame
    // when occlusion is calculated
    pub parent_frame: Option<u32>,
}

impl Interpolatable for Occlusion {}

impl ImplToFromPaxAny for ExpandedNode {}
impl Interpolatable for ExpandedNode {}

#[derive(Clone)]
/// Live selector identity for one expanded runtime node.
pub struct RuntimeSelectorMetadata {
    /// Concrete element/component type used by type selectors.
    pub type_id: TypeId,
    /// Reactive node id used by id selectors.
    pub id: LocalProperty<Option<String>>,
    /// Reactive, normalized class names in left-to-right cascade order.
    pub classes: LocalProperty<Vec<String>>,
}

impl RuntimeSelectorMetadata {
    fn from_base(
        base: &crate::rendering::BaseInstance,
        common_properties: &Rc<RefCell<CommonProperties>>,
        stack: &Rc<RuntimePropertiesStackFrame>,
    ) -> Self {
        let classes = base
            .template_node_selector_info
            .as_ref()
            .and_then(|info| {
                info.class_binding.as_ref().map(|binding| {
                    build_selector_classes_property(binding, info.source_location.as_ref(), stack)
                })
            })
            .unwrap_or_else(|| LocalProperty::new_with_name(Vec::new(), "selector classes"));

        Self {
            type_id: base.template_node_type_id.clone().unwrap_or_default(),
            id: common_properties.borrow().id.clone(),
            classes,
        }
    }

    pub fn matches(&self, selector: &SelectorExpr) -> bool {
        match selector {
            SelectorExpr::Id(id) => self.id.get().as_deref() == Some(id.as_str()),
            SelectorExpr::Class(class_name) => self
                .classes
                .get()
                .into_iter()
                .any(|node_class| node_class == *class_name),
            SelectorExpr::Type(type_name) => {
                self.type_id.to_string() == *type_name
                    || self.type_id.get_pascal_identifier().as_deref() == Some(type_name.as_str())
            }
        }
    }
}

fn warn_selector_class_once(
    warnings: &Rc<RefCell<HashSet<String>>>,
    key: String,
    message: impl FnOnce() -> String,
) {
    if warnings.borrow_mut().insert(key) {
        log::warn!("{}", message());
    }
}

fn normalize_selector_classes(
    value: PaxValue,
    warnings: &Rc<RefCell<HashSet<String>>>,
    source_location: Option<&LocationInfo>,
) -> Vec<String> {
    let location = source_location
        .map(|location| {
            format!(
                " at {}:{}",
                location.start_line_col.0, location.start_line_col.1
            )
        })
        .unwrap_or_default();
    let candidates = match value {
        PaxValue::String(value) => vec![value],
        PaxValue::Vec(values) => values
            .into_iter()
            .filter_map(|value| match value {
                PaxValue::String(value) => Some(value),
                other => {
                    warn_selector_class_once(warnings, format!("list-type:{other}"), || {
                        format!("ignoring non-string value in class list{location}: {other}")
                    });
                    None
                }
            })
            .collect(),
        other => {
            warn_selector_class_once(warnings, format!("binding-type:{other}"), || {
                format!(
                    "class binding{location} must evaluate to String or Vec<String>; received {other}"
                )
            });
            return Vec::new();
        }
    };

    let mut seen = HashSet::new();
    let mut normalized = candidates
        .into_iter()
        .rev()
        .filter(|class_name| {
            if class_name.is_empty() {
                return false;
            }
            if !matches!(
                SelectorExpr::parse(&format!(".{class_name}")),
                Ok(SelectorExpr::Class(_))
            ) {
                warn_selector_class_once(warnings, format!("invalid-name:{class_name}"), || {
                    format!("ignoring invalid class name '{class_name}'{location}")
                });
                return false;
            }
            seen.insert(class_name.clone())
        })
        .collect::<Vec<_>>();
    normalized.reverse();
    normalized
}

fn build_selector_classes_property(
    binding: &ValueDefinition,
    source_location: Option<&LocationInfo>,
    stack: &Rc<RuntimePropertiesStackFrame>,
) -> LocalProperty<Vec<String>> {
    let warnings = Rc::new(RefCell::new(HashSet::new()));
    let source_location = source_location.cloned();
    match binding {
        ValueDefinition::LiteralValue(value) => LocalProperty::new_with_name(
            normalize_selector_classes(value.clone(), &warnings, source_location.as_ref()),
            "selector classes",
        ),
        ValueDefinition::Expression(info) => {
            let dependencies = info
                .dependencies
                .iter()
                .filter_map(|dependency| {
                    stack
                        .resolve_symbol_as_erased_property(dependency)
                        .or_else(|| {
                            log::warn!("failed to resolve class binding symbol {dependency}");
                            None
                        })
                })
                .collect::<Vec<_>>();
            let expression = info.expression.clone();
            let expression_label = expression.to_string();
            let stack = Rc::clone(stack);
            let warnings = Rc::clone(&warnings);
            LocalProperty::computed_with_name(
                move || match expression.compute(stack.clone()) {
                    Ok(value) => {
                        normalize_selector_classes(value, &warnings, source_location.as_ref())
                    }
                    Err(error) => {
                        warn_selector_class_once(
                            &warnings,
                            format!("evaluation:{expression_label}:{error:?}"),
                            || {
                                let location = source_location
                                    .as_ref()
                                    .map(|location| {
                                        format!(
                                            " at {}:{}",
                                            location.start_line_col.0, location.start_line_col.1
                                        )
                                    })
                                    .unwrap_or_default();
                                format!(
                                    "failed to evaluate class binding `{expression_label}`{location}: {error:?}"
                                )
                            },
                        );
                        Vec::new()
                    }
                },
                &dependencies,
                "selector classes",
            )
        }
        other => {
            log::warn!("unsupported class binding definition: {other}");
            LocalProperty::new_with_name(Vec::new(), "selector classes")
        }
    }
}

#[cfg(test)]
mod selector_class_tests {
    use super::{build_selector_classes_property, normalize_selector_classes};
    use crate::RuntimePropertiesStackFrame;
    use pax_language::parse_pax_expression;
    use pax_manifest::{ExpressionInfo, ValueDefinition};
    use pax_runtime_api::{LocalProperty, PaxValue, Variable};
    use std::cell::RefCell;
    use std::collections::{HashMap, HashSet};
    use std::rc::Rc;

    #[test]
    fn normalizes_order_duplicates_and_invalid_names() {
        let warnings = Rc::new(RefCell::new(HashSet::new()));
        let classes = normalize_selector_classes(
            PaxValue::Vec(vec![
                PaxValue::String("base".to_string()),
                PaxValue::String("bad name".to_string()),
                PaxValue::String("active".to_string()),
                PaxValue::String("base".to_string()),
                PaxValue::Numeric(1.into()),
            ]),
            &warnings,
            None,
        );

        assert_eq!(classes, vec!["active", "base"]);
        assert_eq!(warnings.borrow().len(), 2);
    }

    #[test]
    fn expression_backed_classes_track_string_and_vector_properties() {
        let constant_binding = ValueDefinition::Expression(ExpressionInfo::new(
            parse_pax_expression(r#""temporary""#).unwrap(),
        ));
        let constant_classes = build_selector_classes_property(
            &constant_binding,
            None,
            &RuntimePropertiesStackFrame::new(HashMap::new()),
        );
        assert_eq!(constant_classes.get(), vec!["temporary"]);

        let scalar = LocalProperty::new("base".to_string());
        let stack = RuntimePropertiesStackFrame::new(HashMap::from([(
            "current_class".to_string(),
            Variable::new_from_typed_property(scalar.clone()),
        )]));
        let scalar_binding = ValueDefinition::Expression(ExpressionInfo::new(
            parse_pax_expression("current_class").unwrap(),
        ));
        let scalar_classes = build_selector_classes_property(&scalar_binding, None, &stack);
        assert_eq!(scalar_classes.get(), vec!["base"]);
        scalar.set("active".to_string());
        assert_eq!(scalar_classes.get(), vec!["active"]);

        let vector = LocalProperty::new(vec!["base".to_string(), "selected".to_string()]);
        let stack = RuntimePropertiesStackFrame::new(HashMap::from([(
            "current_classes".to_string(),
            Variable::new_from_typed_property(vector.clone()),
        )]));
        let vector_binding = ValueDefinition::Expression(ExpressionInfo::new(
            parse_pax_expression("current_classes").unwrap(),
        ));
        let vector_classes = build_selector_classes_property(&vector_binding, None, &stack);
        assert_eq!(vector_classes.get(), vec!["base", "selected"]);
        vector.set(Vec::new());
        assert!(vector_classes.get().is_empty());
    }
}

macro_rules! dispatch_event_handler {
    ($fn_name:ident, $arg_type:ty, $handler_key:ident, $recurse:expr) => {
        pub fn $fn_name(
            self: &Rc<Self>,
            event: Event<$arg_type>,
            globals: &Globals,
            ctx: &Rc<RuntimeContext>,
        ) -> bool {
            if self.is_render_source() {
                return event.cancelled();
            }
            self.run_event_handlers_for_key($handler_key, &event, ctx);

            if $recurse {
                if let Some(parent) = self.template_parent.upgrade() {
                    return parent.$fn_name(event, globals, ctx);
                }
            }
            event.cancelled()
        }
    };
}

impl ExpandedNode {
    /// Whether this live node supplies a mask rather than visible scene content.
    pub fn is_render_source(&self) -> bool {
        self.render_source_owner.get().is_some()
    }

    /// Initialize a detached source using ordinary component lifetime machinery.
    /// Presentation and native-resource allocation remain disabled for this tree.
    pub fn mount_as_render_source(self: &Rc<Self>, owner: &Rc<Self>, context: &Rc<RuntimeContext>) {
        assert_eq!(
            self.attached.get(),
            0,
            "a mask cannot borrow a mounted scene node"
        );
        self.render_source_owner.set(Some(owner.id));
        self.recurse_mount(context);
    }

    pub(crate) fn render_source_owner(&self) -> Option<ExpandedNodeIdentifier> {
        self.render_source_owner.get()
    }

    fn suppresses_native_presentation(&self) -> bool {
        self.is_render_source() && borrow!(self.instance_node).base().flags().layer == Layer::Native
    }

    pub fn initialize_root(template: Rc<ComponentInstance>, ctx: &Rc<RuntimeContext>) -> Rc<Self> {
        let root_node = Self::new(
            template,
            ctx.globals().stack_frame(),
            ctx,
            Weak::new(),
            Weak::new(),
        );
        root_node.bind_to_parent_bounds(ctx);
        Rc::clone(&root_node).recurse_mount(ctx);
        root_node
    }

    fn has_event_handlers(&self, handler_key: &str) -> bool {
        borrow!(self.instance_node)
            .base()
            .get_handler_registry()
            .is_some_and(|registry| {
                borrow!(*registry)
                    .handlers
                    .get(handler_key)
                    .is_some_and(|handlers| !handlers.is_empty())
            })
    }

    fn handler_owner(self: &Rc<Self>, location: &HandlerLocation) -> Rc<Self> {
        // Ownership follows the authored component, not the render parent.
        // Resolve current state at dispatch time so reload cannot leave a stale handle.
        match location {
            HandlerLocation::Component => self.clone(),
            HandlerLocation::Inline => self
                .containing_component
                .upgrade()
                .unwrap_or_else(|| self.clone()),
        }
    }

    fn run_event_handlers_for_key<T: Clone + 'static>(
        self: &Rc<Self>,
        handler_key: &str,
        event: &Event<T>,
        ctx: &Rc<RuntimeContext>,
    ) {
        if self.is_render_source() {
            return;
        }
        // Input can retain a hover/focus target across a tree replacement. Its
        // final platform event must not re-enter a detached binding lifetime.
        if self.attached.get() == 0 {
            return;
        }
        let _graph = ctx.property_graph.enter();
        if let Some(registry) = borrow!(self.instance_node).base().get_handler_registry() {
            let borrowed_registry = &borrow!(*registry);
            if let Some(handlers) = borrowed_registry.handlers.get(handler_key) {
                let context = self.get_node_context(ctx);
                for handler in handlers {
                    let owner = self.handler_owner(&handler.location);
                    if owner.attached.get() == 0 {
                        continue;
                    }
                    // LocalProperty bindings created by a handler belong to the
                    // component whose state it mutates. The context's async
                    // lifetime still identifies the exact event target node.
                    let _scope = owner.property_binding_scope.borrow().enter();
                    let properties = Rc::clone(&*borrow!(owner.properties));
                    (handler.function)(properties, &context, Some(event.clone().to_pax_any()));
                }
            }
        }
    }

    fn run_lifecycle_handlers_for_key(
        self: &Rc<Self>,
        handler_key: &str,
        context: &Rc<RuntimeContext>,
    ) {
        if let Some(registry) = borrow!(self.instance_node).base().get_handler_registry() {
            if let Some(handlers) = borrow!(registry).handlers.get(handler_key) {
                for handler in handlers {
                    // Refresh target-local layout for each callback, then enter
                    // the authored owner's scope for any bindings it creates.
                    let target_context = self.get_node_context(context);
                    let owner = self.handler_owner(&handler.location);
                    let _scope = owner.property_binding_scope.borrow().enter();
                    // Final unmount marks ancestors detached before invoking
                    // children; their state and binding scopes are still live here.
                    (handler.function)(
                        Rc::clone(&*borrow!(owner.properties)),
                        &target_context,
                        None,
                    );
                }
            }
        }
    }

    fn run_viewport_event_handlers<T: Clone + 'static>(
        self: &Rc<Self>,
        key: &str,
        event: Event<T>,
        ctx: &Rc<RuntimeContext>,
    ) {
        let handlers: Vec<_> = borrow!(self.instance_node)
            .base()
            .get_handler_registry()
            .map(|registry| {
                borrow!(registry)
                    .handlers
                    .get(key)
                    .map(|handlers| {
                        handlers
                            .iter()
                            .map(|h| (h.function, matches!(h.location, HandlerLocation::Component)))
                            .collect()
                    })
                    .unwrap_or_default()
            })
            .unwrap_or_default();
        for (function, component) in handlers {
            if self.attached.get() == 0 || self.suspended.get() {
                break;
            }
            let properties = if component {
                Rc::clone(&borrow!(self.properties))
            } else {
                self.containing_component
                    .upgrade()
                    .map(|owner| Rc::clone(&borrow!(owner.properties)))
                    .unwrap_or_else(|| Rc::clone(&borrow!(self.properties)))
            };
            function(
                properties,
                &self.get_node_context(ctx),
                Some(event.clone().to_pax_any()),
            );
        }
    }

    pub(crate) fn dispatch_viewport_proximity_enter(
        self: &Rc<Self>,
        event: Event<crate::api::ViewportProximityEnter>,
        ctx: &Rc<RuntimeContext>,
    ) {
        self.run_viewport_event_handlers(
            crate::constants::VIEWPORT_PROXIMITY_ENTER_HANDLERS,
            event,
            ctx,
        );
    }
    pub(crate) fn dispatch_viewport_proximity_change(
        self: &Rc<Self>,
        event: Event<crate::api::ViewportProximityChange>,
        ctx: &Rc<RuntimeContext>,
    ) {
        self.run_viewport_event_handlers(
            crate::constants::VIEWPORT_PROXIMITY_CHANGE_HANDLERS,
            event,
            ctx,
        );
    }
    pub(crate) fn dispatch_viewport_proximity_exit(
        self: &Rc<Self>,
        event: Event<crate::api::ViewportProximityExit>,
        ctx: &Rc<RuntimeContext>,
    ) {
        self.run_viewport_event_handlers(
            crate::constants::VIEWPORT_PROXIMITY_EXIT_HANDLERS,
            event,
            ctx,
        );
    }

    fn new(
        template: Rc<dyn InstanceNode>,
        env: Rc<RuntimePropertiesStackFrame>,
        context: &Rc<RuntimeContext>,
        containing_component: Weak<ExpandedNode>,
        parent: Weak<ExpandedNode>,
    ) -> Rc<Self> {
        let _graph = context.property_graph.enter();
        let property_binding_scope = context.property_graph.binding_scope();
        let _scope = property_binding_scope.enter();
        let transition_config = template.base().transition_config().clone();
        let has_transition_bindings = transition_config.has_enter || transition_config.has_exit;
        let transition_phase =
            LocalProperty::new_with_name(TRANSITION_PHASE_IDLE, "transition phase");
        let transition_generation = LocalProperty::new_with_name(0, "transition generation");
        let transition_takeover = LocalProperty::new_with_name(false, "transition takeover");
        let transition_origin_frame = LocalProperty::new_with_name(
            context.globals().elapsed_frames.get(),
            "transition origin",
        );
        let transition_origin_millis = LocalProperty::new_with_name(
            context.globals().elapsed_millis.get(),
            "transition origin millis",
        );
        let transition_playhead = LocalProperty::new_with_name(0.0, "transition playhead");
        let transition_playhead_millis =
            LocalProperty::new_with_name(0.0, "transition playhead millis");

        let env = if has_transition_bindings {
            env.push(
                vec![
                    (
                        TRANSITION_PHASE_SYMBOL.to_string(),
                        Variable::new_from_typed_property(transition_phase.clone()),
                    ),
                    (
                        TRANSITION_GENERATION_SYMBOL.to_string(),
                        Variable::new_from_typed_property(transition_generation.clone()),
                    ),
                    (
                        TRANSITION_TAKEOVER_SYMBOL.to_string(),
                        Variable::new_from_typed_property(transition_takeover.clone()),
                    ),
                    (
                        TRANSITION_PLAYHEAD_SYMBOL.to_string(),
                        Variable::new_from_typed_property(transition_playhead.clone()),
                    ),
                    (
                        TRANSITION_PLAYHEAD_MILLIS_SYMBOL.to_string(),
                        Variable::new_from_typed_property(transition_playhead_millis.clone()),
                    ),
                ]
                .into_iter()
                .collect(),
            )
        } else {
            env
        };

        // Legacy callbacks may inspect pre-bound state. Local self-timelines
        // also need sibling double-binding aliases installed before capturing
        // their scope. Keep their pre-node phase until alias installation is a
        // separate descriptor operation; ordinary structured nodes just allocate.
        let legacy_initialization = template.base().requires_pre_node_binding();
        let properties_init = &template.base().instance_prototypical_properties;
        let common_init = &template.base().instance_prototypical_common_properties;
        let properties = if legacy_initialization {
            properties_init.materialize(env.clone(), None).unwrap()
        } else {
            properties_init.allocate(env.clone())
        };
        let common_properties = if legacy_initialization {
            common_init.materialize(env.clone(), None).unwrap()
        } else {
            common_init.allocate(env.clone())
        };
        let selector_metadata =
            RuntimeSelectorMetadata::from_base(template.base(), &common_properties, &env);

        let property_scope = if legacy_initialization {
            let mut scope = borrow!(*common_properties).retrieve_property_scope();
            scope.extend(template.base().properties_scope.build(properties.clone()));
            scope
        } else {
            // Publish after binding so double-binding aliases are final and
            // conversion-adapter properties are allocated only once.
            HashMap::new()
        };

        let id = context.gen_uid();
        let render_source_owner = parent
            .upgrade()
            .and_then(|parent| parent.render_source_owner.get());
        let res = Rc::new(ExpandedNode {
            property_binding_scope: RefCell::new(property_binding_scope),
            async_scope: RefCell::new(None),
            id,
            stores: crate::store::NodeStores::new(parent.upgrade().as_deref()),
            stack: env,
            instance_node: RefCell::new(Rc::clone(&template)),
            attached: Cell::new(0),
            properties: RefCell::new(properties),
            common_properties: RefCell::new(common_properties),
            measured_size: LocalProperty::default(),
            selector_metadata: RefCell::new(selector_metadata),

            // these two refer to their rendering parent, not their
            // template parent
            render_parent: Default::default(),
            parent_frame: Default::default(),
            liquid_glass_scope: Default::default(),
            template_parent: parent,

            containing_component,
            children: LocalProperty::new_with_name(
                Vec::new(),
                &format!("node children (node id: {})", id.0),
            ),
            mounted_children: RefCell::new(Vec::new()),
            active_children: RefCell::new(Vec::new()),
            active_children_view: LocalProperty::new(Vec::new()),
            exiting_children: RefCell::new(Vec::new()),
            exiting_child_generations: RefCell::new(HashMap::new()),
            exiting_children_view: LocalProperty::new(Vec::new()),
            sidecar_children: RefCell::new(Vec::new()),
            render_source_owner: Cell::new(render_source_owner),
            transform_and_bounds: LocalProperty::new(TransformAndBounds::default()),
            subtree_layout_hull: LocalProperty::new(LayoutHull::default()),
            container_frame: LocalProperty::new(None),
            computed_opacity: LocalProperty::new(1.0),
            computed_opacity_scopes: LocalProperty::new(Vec::new()),
            expanded_projected_children: Default::default(),
            expanded_and_flattened_projected_children: Default::default(),
            flattened_projected_children_count: LocalProperty::new(0),
            occlusion: LocalProperty::new(Occlusion::default()),
            native_mask_hash: Cell::new(0),
            browser_content_layer_id: Cell::new(None),
            presentation_cache_hash: Cell::new(0),
            properties_scope: RefCell::new(property_scope),
            slot_index: LocalProperty::default(),
            suspended: LocalProperty::new(false),
            changed_listener: LocalProperty::default(),
            selector_classes_listener: LocalProperty::default(),
            occlusion_listener: LocalProperty::default(),
            children_listener: LocalProperty::default(),
            subtree_layout_hull_listener: LocalProperty::default(),
            parent_binding_sources: RefCell::new(None),
            layout_binding_generation: Cell::new(0),
            #[cfg(test)]
            parent_binding_rebuilds: Cell::new(0),
            #[cfg(test)]
            layout_hull_rebuilds: Cell::new(0),
            #[cfg(test)]
            structural_children_updates: Cell::new(0),
            content_measurement_listener: LocalProperty::default(),
            content_measurement_rebind_listener: LocalProperty::default(),
            content_measurement_bound: Cell::new(false),
            #[cfg(feature = "shaders")]
            shader_effect_bound: Cell::new(false),
            subtree_requires_non_reactive_update: Cell::new(true),
            projected_children_changed: LocalProperty::default(),
            slot_projection_changed: LocalProperty::default(),
            subscriptions: Default::default(),
            transition_phase,
            transition_generation,
            transition_takeover,
            transition_selector_classes: RefCell::new(None),
            exit_retention_generation: Cell::new(0),
            transition_origin_frame,
            transition_origin_millis,
            transition_playhead,
            transition_playhead_millis,
            enter_cleanup_listener: LocalProperty::default(),
            enter_cleanup_active: Cell::new(false),
            exit_started_millis: Cell::new(None),
            exit_timeout_warning_emitted: Cell::new(false),
            exit_cleanup_listener: LocalProperty::default(),
            exit_cleanup_active: Cell::new(false),
            imported_settings_layers: RefCell::new(Vec::new()),
            #[cfg(test)]
            settings_layer_materializations: Cell::new(0),
            import_settings_transition: RefCell::new(None),
            settings_motion: Rc::new(RefCell::new(HashMap::new())),
            settings_birth_frame: context.globals().elapsed_frames.get(),
            imported_settings_signature: RefCell::new(Vec::new()),
            resolved_property_columns: RefCell::new(BTreeMap::new()),
            resolved_property_provenance: RefCell::new(BTreeMap::new()),
            reset_removed_runtime_properties: Cell::new(false),
        });
        template.base().bind_properties(&res);
        if legacy_initialization {
            let common_properties = Rc::clone(&*borrow!(res.common_properties));
            *res.selector_metadata.borrow_mut() =
                RuntimeSelectorMetadata::from_base(template.base(), &common_properties, &res.stack);
        }
        res.refresh_properties_scope(&template);
        res.bind_selector_classes_listener(context);
        res.bind_occlusion_listener(context);
        res.bind_children_listener(context);
        res.bind_subtree_layout_hull(context);
        res
    }

    pub fn recreate_with_new_data(
        self: &Rc<Self>,
        template: Rc<dyn InstanceNode>,
        context: &Rc<RuntimeContext>,
    ) {
        let _graph = context.property_graph.enter();
        let _scope = self.property_binding_scope.borrow().enter();
        // A replacement may change bindings or clipping dependencies. Revoke the
        // old generation before it can receive more of a frozen event batch.
        context.unregister_viewport_proximity(self.id.to_u32());
        let previous = self.stores.has_providers().then(|| {
            borrow!(self.properties_scope)
                .iter()
                .filter(|(name, _)| !name.starts_with('$'))
                .map(|(name, value)| (name.clone(), value.get_untyped_property().get_id()))
                .collect::<HashMap<_, _>>()
        });
        *borrow_mut!(self.instance_node) = Rc::clone(&template);
        template.base().bind_properties(self);
        self.refresh_properties_scope(&template);
        if let Some(previous) = previous {
            // Stores can retain any exposed property handle. Recreate the
            // provider and its consumers if a template edit changes an alias.
            let current: HashMap<_, _> = borrow!(self.properties_scope)
                .iter()
                .filter(|(name, _)| !name.starts_with('$'))
                .map(|(name, value)| (name.clone(), value.get_untyped_property().get_id()))
                .collect();
            if current != previous {
                self.fully_recreate_with_new_data(template, context);
                return;
            }
        }
        let common_properties = Rc::clone(&*borrow!(self.common_properties));
        *self.selector_metadata.borrow_mut() =
            RuntimeSelectorMetadata::from_base(template.base(), &common_properties, &self.stack);
        self.refresh_properties_scope(&template);
        self.bind_selector_classes_listener(context);
        self.reapply_runtime_settings(context);
        self.bind_to_parent_bounds(context);
        self.bind_occlusion_listener(context);
        self.mark_non_reactive_update_subtree_dirty();
        context.mark_occlusion_dirty();
        context.set_canvas_dirty(self.occlusion.get().render_layer_id);
        if self.attached.get() > 0 {
            context.refresh_scene_lighting_node(self);
            context.viewport_structure_changed();
            context.register_viewport_proximity(self);
            context.invalidate_scene_geometry(self.id.to_u32());
        }
    }

    pub fn fully_recreate_with_new_data(
        self: &Rc<Self>,
        template: Rc<dyn InstanceNode>,
        context: &Rc<RuntimeContext>,
    ) {
        let _graph = context.property_graph.enter();
        let _scope = self.property_binding_scope.borrow().enter();
        Rc::clone(self).recurse_unmount(context);
        *borrow_mut!(self.instance_node) = template;
        self.prepare_remount(context);
        let _scope = self.property_binding_scope.borrow().enter();

        self.bind_to_parent_bounds(context);
        self.mark_non_reactive_update_subtree_dirty();
        context.mark_occlusion_dirty();
        Rc::clone(self).recurse_mount(context);
        context.drain_node_effects();
        self.recurse_emit_mount_updates();
    }

    fn prepare_remount(self: &Rc<Self>, context: &Rc<RuntimeContext>) {
        let template = Rc::clone(&*borrow!(self.instance_node));
        let new_expanded_node = Self::new(
            template.clone(),
            Rc::clone(&self.stack),
            context,
            Weak::clone(&self.containing_component),
            Weak::clone(&self.template_parent),
        );
        *self.property_binding_scope.borrow_mut() =
            new_expanded_node.property_binding_scope.borrow().clone();
        let _scope = self.property_binding_scope.borrow().enter();
        *borrow_mut!(self.instance_node) = Rc::clone(&*borrow!(new_expanded_node.instance_node));
        *borrow_mut!(self.properties) = Rc::clone(&*borrow!(new_expanded_node.properties));
        *borrow_mut!(self.properties_scope) = borrow!(new_expanded_node.properties_scope).clone();
        *borrow_mut!(self.common_properties) =
            Rc::clone(&*borrow!(new_expanded_node.common_properties));
        *self.selector_metadata.borrow_mut() = new_expanded_node.selector_metadata.borrow().clone();
        self.occlusion.set(Default::default());

        self.bind_to_parent_bounds(context);
        self.bind_selector_classes_listener(context);
        self.bind_occlusion_listener(context);
        self.bind_children_listener(context);
        self.bind_subtree_layout_hull(context);
        self.stores.mount(self.template_parent.upgrade().as_deref());
    }

    fn recurse_emit_mount_updates(self: &Rc<Self>) {
        // `fully_recreate_with_new_data` can remount native-backed nodes after the main
        // update traversal has already consumed `changed_listener`. Emit the initial
        // native updates here so the chassis does not paint a frame with skeletal defaults.
        self.changed_listener.get();
        self.occlusion_listener.get();
        for child in self.children.get().iter() {
            child.recurse_emit_mount_updates();
        }
        for child in borrow!(self.sidecar_children).iter() {
            child.recurse_emit_mount_updates();
        }
    }

    fn refresh_properties_scope(self: &Rc<Self>, template: &Rc<dyn InstanceNode>) {
        let common_properties = Rc::clone(&*borrow!(self.common_properties));
        let mut refreshed_scope = borrow!(*common_properties).retrieve_property_scope();
        refreshed_scope.extend(
            template
                .base()
                .properties_scope
                .build(Rc::clone(&*borrow!(self.properties))),
        );
        *borrow_mut!(self.properties_scope) = refreshed_scope;
    }

    /// Returns whether this node is a descendant of the ExpandedNode described by `other_expanded_node_id` (id)
    /// Currently requires traversing linked list of ancestry, incurring a O(log(n)) cost for a tree of `n` elements.
    /// This could be mitigated with caching/memoization, perhaps by storing a HashSet on each ExpandedNode describing its ancestry chain.
    pub fn is_descendant_of(&self, other_expanded_node_id: &ExpandedNodeIdentifier) -> bool {
        if let Some(parent) = borrow!(self.render_parent).upgrade() {
            // We have a parent — if it matches the ID, this node is indeed an ancestor of other_expanded_node_id.  Otherwise, recurse upward.
            if parent.id.eq(other_expanded_node_id) {
                true
            } else {
                parent.is_descendant_of(other_expanded_node_id)
            }
        } else {
            false
        }
    }

    pub fn create_children_detached(
        self: &Rc<Self>,
        templates: impl IntoIterator<Item = (Rc<dyn InstanceNode>, Rc<RuntimePropertiesStackFrame>)>,
        context: &Rc<RuntimeContext>,
        template_parent: &Weak<ExpandedNode>,
    ) -> Vec<Rc<ExpandedNode>> {
        let containing_component = if borrow!(self.instance_node).base().flags().is_component {
            Rc::downgrade(&self)
        } else {
            Weak::clone(&self.containing_component)
        };

        let mut children = Vec::new();

        for (template, env) in templates {
            children.push(Self::new(
                template,
                env,
                context,
                Weak::clone(&containing_component),
                Weak::clone(&template_parent),
            ));
        }
        children
    }

    pub(crate) fn current_attached_children(&self) -> Vec<Rc<ExpandedNode>> {
        borrow!(self.mounted_children).clone()
    }

    pub(crate) fn rescue_exiting_child_matching(
        self: &Rc<Self>,
        predicate: impl Fn(&Rc<ExpandedNode>) -> bool,
    ) -> Option<Rc<ExpandedNode>> {
        let position = borrow!(self.exiting_children).iter().position(predicate)?;
        let child = borrow_mut!(self.exiting_children).remove(position);
        child
            .exit_retention_generation
            .set(child.exit_retention_generation.get().wrapping_add(1));
        borrow_mut!(self.exiting_child_generations).remove(&child.id);
        if borrow!(self.exiting_children).is_empty() {
            self.exit_cleanup_active.set(false);
            self.exit_cleanup_listener
                .replace_with(LocalProperty::new_with_name((), "exit transition cleanup"));
        }
        Some(child)
    }

    fn sync_mounted_children_from_active_and_exiting(&self) -> Vec<Rc<ExpandedNode>> {
        let active_children = borrow!(self.active_children).clone();
        let exiting_children = borrow!(self.exiting_children).clone();
        if !self
            .active_children_view
            .read(|old| Self::same_children(old, &active_children))
        {
            self.active_children_view.set(active_children.clone());
        }
        if !self
            .exiting_children_view
            .read(|old| Self::same_children(old, &exiting_children))
        {
            self.exiting_children_view.set(exiting_children.clone());
        }
        let mut combined = exiting_children;
        combined.extend(active_children);
        *borrow_mut!(self.mounted_children) = combined.clone();
        combined
    }

    fn has_child(children: &[Rc<ExpandedNode>], target: &Rc<ExpandedNode>) -> bool {
        children.iter().any(|child| Rc::ptr_eq(child, target))
    }

    fn same_children(a: &[Rc<ExpandedNode>], b: &[Rc<ExpandedNode>]) -> bool {
        a.len() == b.len() && a.iter().zip(b).all(|(a, b)| Rc::ptr_eq(a, b))
    }

    fn detach_child_for_reparent(&self, target: &Rc<ExpandedNode>) {
        let mut removed = false;
        {
            let active_children = &mut *borrow_mut!(self.active_children);
            let old_len = active_children.len();
            active_children.retain(|child| !Rc::ptr_eq(child, target));
            removed |= active_children.len() != old_len;
        }
        {
            let exiting_children = &mut *borrow_mut!(self.exiting_children);
            let old_len = exiting_children.len();
            exiting_children.retain(|child| !Rc::ptr_eq(child, target));
            removed |= exiting_children.len() != old_len;
        }
        if removed {
            self.sync_mounted_children_from_active_and_exiting();
            self.mark_non_reactive_update_subtree_dirty();
        }
    }

    fn template_node_identifier(&self) -> Option<UniqueTemplateNodeIdentifier> {
        borrow!(self.instance_node)
            .base()
            .template_node_identifier
            .clone()
    }

    fn transition_source_matches(
        sources: &[UniqueTemplateNodeIdentifier],
        own_identifier: Option<&UniqueTemplateNodeIdentifier>,
        requested_source: Option<&UniqueTemplateNodeIdentifier>,
    ) -> bool {
        if let Some(source) = requested_source {
            return sources.contains(source);
        }
        if sources.is_empty() {
            return true;
        }
        own_identifier
            .map(|identifier| sources.contains(identifier))
            .unwrap_or(false)
    }

    fn has_exit_transition_for_source(
        &self,
        requested_source: Option<&UniqueTemplateNodeIdentifier>,
    ) -> bool {
        let instance_node = borrow!(self.instance_node);
        let transition_config = instance_node.base().transition_config();
        transition_config.has_exit
            && Self::transition_source_matches(
                &transition_config.exit_sources,
                instance_node.base().template_node_identifier.as_ref(),
                requested_source,
            )
    }

    fn mark_non_reactive_update_subtree_dirty(&self) {
        if self.subtree_requires_non_reactive_update.replace(true) {
            return;
        }
        if let Some(parent) = borrow!(self.render_parent).upgrade() {
            parent.mark_non_reactive_update_subtree_dirty();
        }
    }

    fn start_self_enter_transition_for_source(
        self: &Rc<Self>,
        context: &Rc<RuntimeContext>,
        requested_source: Option<&UniqueTemplateNodeIdentifier>,
    ) -> bool {
        let instance_node = borrow!(self.instance_node);
        let transition_config = instance_node.base().transition_config();
        if !transition_config.has_enter
            || !Self::transition_source_matches(
                &transition_config.enter_sources,
                instance_node.base().template_node_identifier.as_ref(),
                requested_source,
            )
        {
            return false;
        }
        drop(instance_node);
        self.begin_transition_run(context, TRANSITION_PHASE_ENTER);
        self.exit_started_millis.set(None);
        self.exit_timeout_warning_emitted.set(false);
        self.enable_enter_cleanup_listener(context);
        true
    }

    fn start_self_enter_transition(self: &Rc<Self>, context: &Rc<RuntimeContext>) {
        let started = self.start_self_enter_transition_for_source(context, None);
        if started {
            if let Some(source) = self.template_node_identifier() {
                self.start_bound_enter_transitions(context, &source);
            }
        }
    }

    fn start_self_exit_transition_for_source(
        self: &Rc<Self>,
        context: &Rc<RuntimeContext>,
        requested_source: Option<&UniqueTemplateNodeIdentifier>,
    ) -> bool {
        if !self.has_exit_transition_for_source(requested_source) {
            return false;
        }
        self.begin_transition_run(context, TRANSITION_PHASE_EXIT);
        self.disable_enter_cleanup_listener();
        self.exit_started_millis
            .set(Some((context.globals().get_elapsed_millis)()));
        self.exit_timeout_warning_emitted.set(false);
        true
    }

    fn start_self_exit_transition(self: &Rc<Self>, context: &Rc<RuntimeContext>) -> bool {
        let started = self.start_self_exit_transition_for_source(context, None);
        if started {
            if let Some(source) = self.template_node_identifier() {
                self.start_bound_exit_transitions(context, &source);
            }
        }
        started
    }

    fn begin_transition_run(self: &Rc<Self>, context: &Rc<RuntimeContext>, phase: u64) {
        let previous_phase = self.transition_phase.get();
        let is_takeover = matches!(
            (previous_phase, phase),
            (TRANSITION_PHASE_ENTER, TRANSITION_PHASE_EXIT)
                | (TRANSITION_PHASE_EXIT, TRANSITION_PHASE_ENTER)
        );
        self.transition_origin_frame
            .set(context.globals().elapsed_frames.get());
        self.transition_origin_millis
            .set(context.globals().elapsed_millis.get());
        self.transition_takeover.set(is_takeover);
        self.transition_generation
            .set(self.transition_generation.get().wrapping_add(1));
        self.activate_transition_clock(context);
        self.transition_phase.set(phase);
        *self.transition_selector_classes.borrow_mut() =
            Some(self.selector_metadata.borrow().classes.get());
        self.reset_removed_runtime_properties.set(true);
        self.reapply_runtime_settings(context);
    }

    fn activate_transition_clock(&self, context: &Rc<RuntimeContext>) {
        let elapsed_frames = context.globals().elapsed_frames.clone();
        let origin_frame = self.transition_origin_frame.clone();
        let elapsed_frames_for_playhead = elapsed_frames.clone();
        let origin_frame_for_playhead = origin_frame.clone();
        self.transition_playhead
            .replace_with(LocalProperty::computed_with_name(
                move || {
                    elapsed_frames_for_playhead
                        .get()
                        .saturating_sub(origin_frame_for_playhead.get()) as f64
                },
                &[elapsed_frames.untyped(), origin_frame.untyped()],
                "transition playhead",
            ));

        let elapsed_millis = context.globals().elapsed_millis.clone();
        let origin_millis = self.transition_origin_millis.clone();
        let elapsed_millis_for_playhead = elapsed_millis.clone();
        let origin_millis_for_playhead = origin_millis.clone();
        self.transition_playhead_millis
            .replace_with(LocalProperty::computed_with_name(
                move || {
                    elapsed_millis_for_playhead
                        .get()
                        .saturating_sub(origin_millis_for_playhead.get()) as f64
                },
                &[elapsed_millis.untyped(), origin_millis.untyped()],
                "transition playhead millis",
            ));
    }

    fn deactivate_transition_clock(&self) {
        self.transition_playhead
            .replace_with(LocalProperty::new_with_name(0.0, "transition playhead"));
        self.transition_playhead_millis
            .replace_with(LocalProperty::new_with_name(
                0.0,
                "transition playhead millis",
            ));
    }

    fn start_bound_enter_transitions(
        self: &Rc<Self>,
        context: &Rc<RuntimeContext>,
        source: &UniqueTemplateNodeIdentifier,
    ) {
        if let Some(containing_component) = self.containing_component.upgrade() {
            containing_component.start_descendant_enter_transitions_for_source(context, source);
        }
    }

    fn start_bound_exit_transitions(
        self: &Rc<Self>,
        context: &Rc<RuntimeContext>,
        source: &UniqueTemplateNodeIdentifier,
    ) {
        if let Some(containing_component) = self.containing_component.upgrade() {
            containing_component.start_descendant_exit_transitions_for_source(context, source);
        }
    }

    fn start_descendant_enter_transitions_for_source(
        self: &Rc<Self>,
        context: &Rc<RuntimeContext>,
        source: &UniqueTemplateNodeIdentifier,
    ) {
        for child in borrow!(self.mounted_children).iter() {
            child.start_enter_transition_for_source_recursive(context, source);
        }
        for child in borrow!(self.sidecar_children).iter() {
            child.start_enter_transition_for_source_recursive(context, source);
        }
    }

    fn start_descendant_exit_transitions_for_source(
        self: &Rc<Self>,
        context: &Rc<RuntimeContext>,
        source: &UniqueTemplateNodeIdentifier,
    ) {
        for child in borrow!(self.mounted_children).iter() {
            child.start_exit_transition_for_source_recursive(context, source);
        }
        for child in borrow!(self.sidecar_children).iter() {
            child.start_exit_transition_for_source_recursive(context, source);
        }
    }

    fn start_enter_transition_for_source_recursive(
        self: &Rc<Self>,
        context: &Rc<RuntimeContext>,
        source: &UniqueTemplateNodeIdentifier,
    ) {
        if self.template_node_identifier().as_ref() != Some(source) {
            self.start_self_enter_transition_for_source(context, Some(source));
        }
        for child in borrow!(self.mounted_children).iter() {
            child.start_enter_transition_for_source_recursive(context, source);
        }
        for child in borrow!(self.sidecar_children).iter() {
            child.start_enter_transition_for_source_recursive(context, source);
        }
    }

    fn trigger_bound_enter_transitions_for_mounted_sources_recursive(
        self: &Rc<Self>,
        context: &Rc<RuntimeContext>,
    ) {
        if let Some(source) = self.template_node_identifier() {
            let should_trigger = {
                let instance_node = borrow!(self.instance_node);
                instance_node
                    .base()
                    .transition_config()
                    .enter_sources
                    .contains(&source)
            };
            if should_trigger {
                self.start_bound_enter_transitions(context, &source);
            }
        }
        for child in borrow!(self.mounted_children).iter() {
            child.trigger_bound_enter_transitions_for_mounted_sources_recursive(context);
        }
        for child in borrow!(self.sidecar_children).iter() {
            child.trigger_bound_enter_transitions_for_mounted_sources_recursive(context);
        }
    }

    fn start_exit_transition_for_source_recursive(
        self: &Rc<Self>,
        context: &Rc<RuntimeContext>,
        source: &UniqueTemplateNodeIdentifier,
    ) {
        if self.template_node_identifier().as_ref() != Some(source) {
            self.start_self_exit_transition_for_source(context, Some(source));
        }
        for child in borrow!(self.mounted_children).iter() {
            child.start_exit_transition_for_source_recursive(context, source);
        }
        for child in borrow!(self.sidecar_children).iter() {
            child.start_exit_transition_for_source_recursive(context, source);
        }
    }

    fn start_exit_transition_tree(self: &Rc<Self>, context: &Rc<RuntimeContext>) -> bool {
        let mut started = self.start_self_exit_transition(context);
        for child in borrow!(self.mounted_children).iter() {
            started |= child.start_exit_transition_tree(context);
        }
        started
    }

    fn start_enter_transition_tree(self: &Rc<Self>, context: &Rc<RuntimeContext>) -> bool {
        let was_exiting = self.transition_phase.get() == TRANSITION_PHASE_EXIT;
        let started_here = self.start_self_enter_transition_for_source(context, None);
        if was_exiting && !started_here {
            self.transition_phase.set(TRANSITION_PHASE_IDLE);
            self.transition_takeover.set(false);
            self.deactivate_transition_clock();
            self.exit_started_millis.set(None);
            self.transition_selector_classes.borrow_mut().take();
            self.reset_removed_runtime_properties.set(true);
            self.reapply_runtime_settings(context);
        }
        let mut started = started_here;
        for child in borrow!(self.mounted_children).iter() {
            started |= child.start_enter_transition_tree(context);
        }
        if started_here {
            if let Some(source) = self.template_node_identifier() {
                self.start_bound_enter_transitions(context, &source);
            }
        }
        started
    }

    fn retain_exiting_child(
        self: &Rc<Self>,
        child: Rc<ExpandedNode>,
        context: &Rc<RuntimeContext>,
    ) {
        if Self::has_child(&borrow!(self.exiting_children), &child) {
            return;
        }
        let generation = child.exit_retention_generation.get().wrapping_add(1);
        child.exit_retention_generation.set(generation);
        borrow_mut!(self.exiting_child_generations).insert(child.id, generation);
        borrow_mut!(self.exiting_children).push(child);
        self.enable_exit_cleanup_listener(context);
    }

    fn self_exit_transition_complete(&self, context: &Rc<RuntimeContext>) -> bool {
        if self.transition_phase.get() != TRANSITION_PHASE_EXIT {
            return true;
        }
        let instance_node = borrow!(self.instance_node);
        let base = instance_node.base();
        let transition_config = base.transition_config().clone();
        let template_node_identifier = base.template_node_identifier.clone();
        let template_node_type_id = base.template_node_type_id.clone();
        drop(instance_node);
        let duration_complete = self.transition_duration_complete(
            transition_config.exit_frame_count,
            transition_config.exit_millis_count,
            &transition_config.exit_dynamic_durations,
        );
        let timeout_complete = self
            .exit_started_millis
            .get()
            .map(|started| {
                (context.globals().get_elapsed_millis)().saturating_sub(started)
                    >= transition_config.timeout_ms as u128
            })
            .unwrap_or(false);
        if timeout_complete
            && !duration_complete
            && !self.exit_timeout_warning_emitted.replace(true)
        {
            log::warn!(
                "Exit transition timed out after {}ms and will be truncated for node {:?}{}{}. Check @out/@transition duration, percent keyframes, and dynamic duration expressions.",
                transition_config.timeout_ms,
                self.id,
                template_node_identifier
                    .as_ref()
                    .map(|identifier| format!(" template={}", identifier))
                    .unwrap_or_default(),
                template_node_type_id
                    .as_ref()
                    .map(|type_id| format!(" type={}", type_id))
                    .unwrap_or_default(),
            );
        }
        duration_complete || timeout_complete
    }

    fn transition_duration_complete(
        &self,
        frame_count: u64,
        millis_count: Option<u64>,
        dynamic_durations: &[ValueDefinition],
    ) -> bool {
        let mut frame_count = frame_count as f64;
        let mut millis_count = millis_count.map(|value| value as f64).unwrap_or_default();
        let mut unresolved_dynamic_duration = false;

        for duration_definition in dynamic_durations {
            match evaluate_timeline_duration(duration_definition, &self.stack) {
                Some(duration) if duration.is_frame_based() => {
                    frame_count = frame_count.max(duration.as_frames_f64().max(0.0).ceil());
                }
                Some(duration) => {
                    millis_count = millis_count.max(duration.as_milliseconds_f64().max(0.0).ceil());
                }
                None => unresolved_dynamic_duration = true,
            }
        }

        if unresolved_dynamic_duration
            && frame_count <= f64::EPSILON
            && millis_count <= f64::EPSILON
        {
            frame_count = 100.0;
        }

        let frame_complete =
            frame_count <= f64::EPSILON || self.transition_playhead.get() >= frame_count;
        let millis_complete =
            millis_count <= f64::EPSILON || self.transition_playhead_millis.get() >= millis_count;
        frame_complete && millis_complete
    }

    fn self_enter_transition_complete(&self) -> bool {
        if self.transition_phase.get() != TRANSITION_PHASE_ENTER {
            return true;
        }
        let instance_node = borrow!(self.instance_node);
        let transition_config = instance_node.base().transition_config().clone();
        drop(instance_node);
        self.transition_duration_complete(
            transition_config.enter_frame_count,
            transition_config.enter_millis_count,
            &transition_config.enter_dynamic_durations,
        )
    }

    fn enable_enter_cleanup_listener(self: &Rc<Self>, context: &Rc<RuntimeContext>) {
        if self.enter_cleanup_active.get() {
            return;
        }
        self.enter_cleanup_active.set(true);
        let weak_self = Rc::downgrade(self);
        let runtime_context = Rc::clone(context);
        let elapsed_frames = context.globals().elapsed_frames.clone();
        let elapsed_frames_dep = elapsed_frames.untyped();
        self.enter_cleanup_listener
            .replace_with(LocalProperty::computed_with_name(
                move || {
                    let _ = elapsed_frames.get();
                    if let Some(node) = weak_self.upgrade() {
                        node.complete_self_enter_transition_if_needed(&runtime_context);
                    }
                },
                &[elapsed_frames_dep],
                "enter transition cleanup",
            ));
        context.register_expanded_node_effect_property_named(
            self,
            &self.enter_cleanup_listener,
            "enter transition cleanup",
        );
    }

    fn complete_self_enter_transition_if_needed(self: &Rc<Self>, context: &Rc<RuntimeContext>) {
        if !self.enter_cleanup_active.get() {
            return;
        }
        if self.transition_phase.get() != TRANSITION_PHASE_ENTER {
            self.disable_enter_cleanup_listener();
            return;
        }
        if self.self_enter_transition_complete() {
            self.transition_phase.set(TRANSITION_PHASE_IDLE);
            self.deactivate_transition_clock();
            self.disable_enter_cleanup_listener();
            self.transition_selector_classes.borrow_mut().take();
            self.reset_removed_runtime_properties.set(true);
            self.reapply_runtime_settings(context);
        }
    }

    fn disable_enter_cleanup_listener(&self) {
        self.enter_cleanup_active.set(false);
        self.enter_cleanup_listener
            .replace_with(LocalProperty::new_with_name((), "enter transition cleanup"));
    }

    fn exit_transition_tree_complete(self: &Rc<Self>, context: &Rc<RuntimeContext>) -> bool {
        self.self_exit_transition_complete(context)
            && borrow!(self.mounted_children)
                .iter()
                .all(|child| child.exit_transition_tree_complete(context))
    }

    fn enable_exit_cleanup_listener(self: &Rc<Self>, context: &Rc<RuntimeContext>) {
        if self.exit_cleanup_active.get() {
            return;
        }
        self.exit_cleanup_active.set(true);
        let weak_self = Rc::downgrade(self);
        let cloned_context = Rc::clone(context);
        let elapsed_frames = context.globals().elapsed_frames.clone();
        let elapsed_frames_dep = elapsed_frames.untyped();
        self.exit_cleanup_listener
            .replace_with(LocalProperty::computed_with_name(
                move || {
                    let _ = elapsed_frames.get();
                    if let Some(node) = weak_self.upgrade() {
                        node.prune_completed_exit_children(&cloned_context);
                    }
                },
                &[elapsed_frames_dep],
                "exit transition cleanup",
            ));
        context.register_expanded_node_effect_property_named(
            self,
            &self.exit_cleanup_listener,
            "exit transition cleanup",
        );
    }

    fn prune_completed_exit_children(self: &Rc<Self>, context: &Rc<RuntimeContext>) {
        let exiting = std::mem::take(&mut *borrow_mut!(self.exiting_children));
        if exiting.is_empty() {
            self.exit_cleanup_active.set(false);
            self.exit_cleanup_listener
                .replace_with(LocalProperty::new_with_name((), "exit transition cleanup"));
            return;
        }

        let mut retained = Vec::new();
        let active = borrow!(self.active_children).clone();
        for child in exiting {
            let expected_generation = borrow_mut!(self.exiting_child_generations).remove(&child.id);
            if Self::has_child(&active, &child)
                || expected_generation != Some(child.exit_retention_generation.get())
            {
                continue;
            }
            if child.exit_transition_tree_complete(context) {
                child.recurse_unmount(context);
            } else {
                borrow_mut!(self.exiting_child_generations)
                    .insert(child.id, child.exit_retention_generation.get());
                retained.push(child);
            }
        }
        *borrow_mut!(self.exiting_children) = retained;
        self.sync_mounted_children_from_active_and_exiting();
        // `children` is computed for control-flow nodes. A direct write here can
        // mark a pending branch update clean if cleanup and selection change in
        // the same frame, so invalidate it and let its evaluator reconcile.
        self.children.invalidate();
        context.mark_occlusion_dirty();

        if borrow!(self.exiting_children).is_empty() {
            self.exit_cleanup_active.set(false);
            self.exit_cleanup_listener
                .replace_with(LocalProperty::new_with_name((), "exit transition cleanup"));
        }
    }

    pub fn attach_children(
        self: &Rc<Self>,
        new_children: Vec<Rc<ExpandedNode>>,
        context: &Rc<RuntimeContext>,
        parent_frame: &LocalProperty<Option<ExpandedNodeIdentifier>>,
    ) -> Vec<Rc<ExpandedNode>> {
        self.attach_children_with_liquid_glass_scope(
            new_children,
            context,
            parent_frame,
            &self.liquid_glass_scope,
        )
    }

    pub fn attach_children_with_liquid_glass_scope(
        self: &Rc<Self>,
        new_children: Vec<Rc<ExpandedNode>>,
        context: &Rc<RuntimeContext>,
        parent_frame: &LocalProperty<Option<ExpandedNodeIdentifier>>,
        liquid_glass_scope: &LocalProperty<Option<NativeLiquidGlassScope>>,
    ) -> Vec<Rc<ExpandedNode>> {
        let mut bindings_changed = false;
        for child in new_children.iter() {
            let previous_parent = borrow!(child.render_parent).upgrade();
            let is_reparented = child.attached.get() > 0
                && previous_parent
                    .as_ref()
                    .is_some_and(|parent| parent.id != self.id);
            if is_reparented {
                child.mark_canvas_subtree_dirty_for_reparent(context, true);
                if let Some(previous_parent) = previous_parent.as_ref() {
                    previous_parent.detach_child_for_reparent(child);
                }
            }

            bindings_changed |=
                child.ensure_parent_bindings(self, context, parent_frame, liquid_glass_scope);
            if is_reparented {
                child.rebind_parent_bounds_for_mounted_subtree(context);
                child.mark_canvas_subtree_dirty_for_reparent(context, false);
            }
        }
        // Reconciliation still evaluates item data and parent context before
        // this fast path. Exiting children remain managed by their cleanup lane.
        if Self::same_children(&borrow!(self.active_children), &new_children)
            && (self.attached.get() == 0
                || new_children.iter().all(|child| child.attached.get() > 0))
        {
            if bindings_changed {
                self.mark_non_reactive_update_subtree_dirty();
            }
            return self.current_attached_children();
        }
        let mut newly_mounted_children = Vec::new();
        if self.attached.get() > 0 {
            let old_active_children = borrow!(self.active_children).clone();
            for child in old_active_children.iter() {
                if Self::has_child(&new_children, child) {
                    continue;
                }
                if child.transition_phase.get() == TRANSITION_PHASE_EXIT {
                    if child.exit_transition_tree_complete(context) {
                        Rc::clone(child).recurse_unmount(context);
                    } else {
                        self.retain_exiting_child(Rc::clone(child), context);
                    }
                    continue;
                }
                if child.start_exit_transition_tree(context) {
                    self.retain_exiting_child(Rc::clone(child), context);
                } else {
                    Rc::clone(child).recurse_unmount(context);
                }
            }
            for child in new_children.iter() {
                if !Self::has_child(&old_active_children, child) || child.attached.get() == 0 {
                    if child.attached.get() > 0 {
                        child.start_enter_transition_tree(context);
                    } else {
                        Rc::clone(child).recurse_mount(context);
                        newly_mounted_children.push(Rc::clone(child));
                    }
                }
            }
        }
        *borrow_mut!(self.active_children) = new_children;
        let mounted = self.sync_mounted_children_from_active_and_exiting();
        for child in newly_mounted_children {
            child.trigger_bound_enter_transitions_for_mounted_sources_recursive(context);
        }
        self.mark_non_reactive_update_subtree_dirty();
        mounted
    }

    pub fn attach_sidecar_children(
        self: &Rc<Self>,
        new_children: Vec<Rc<ExpandedNode>>,
        context: &Rc<RuntimeContext>,
        parent_frame: &LocalProperty<Option<ExpandedNodeIdentifier>>,
    ) -> Vec<Rc<ExpandedNode>> {
        for child in new_children.iter() {
            child.ensure_parent_bindings(self, context, parent_frame, &self.liquid_glass_scope);
        }
        *borrow_mut!(self.sidecar_children) = new_children.clone();
        self.mark_non_reactive_update_subtree_dirty();
        new_children
    }

    fn ensure_parent_bindings(
        self: &Rc<Self>,
        parent: &Rc<Self>,
        context: &Rc<RuntimeContext>,
        frame: &LocalProperty<Option<ExpandedNodeIdentifier>>,
        glass: &LocalProperty<Option<NativeLiquidGlassScope>>,
    ) -> bool {
        if let Some(owner) = parent.render_source_owner.get() {
            self.render_source_owner.set(Some(owner));
        }
        let properties = {
            let parent_cp = parent.get_common_properties();
            let parent_cp = borrow!(parent_cp);
            let cp = self.get_common_properties();
            let cp = borrow!(cp);
            vec![
                frame.untyped(),
                glass.untyped(),
                parent.suspended.untyped(),
                parent.transform_and_bounds.untyped(),
                parent.computed_opacity.untyped(),
                parent.computed_opacity_scopes.untyped(),
                parent_cp.padding_x.untyped(),
                parent_cp.padding_y.untyped(),
                self.container_frame.untyped(),
                self.measured_size.untyped(),
                cp._suspended.untyped(),
                cp.opacity.untyped(),
                cp.transform.untyped(),
                cp.width.untyped(),
                cp.height.untyped(),
                cp.x.untyped(),
                cp.y.untyped(),
                cp.anchor_x.untyped(),
                cp.anchor_y.untyped(),
                cp.scale_x.untyped(),
                cp.scale_y.untyped(),
                cp.skew_x.untyped(),
                cp.skew_y.untyped(),
                cp.rotate.untyped(),
            ]
        };
        let sources = ParentBindingSources {
            parent: parent.id,
            properties,
        };
        let same_parent = borrow!(self.render_parent)
            .upgrade()
            .is_some_and(|old| Rc::ptr_eq(&old, parent));
        if same_parent
            && borrow!(self.parent_binding_sources)
                .as_ref()
                .is_some_and(|old| old.same_as(&sources))
        {
            return false;
        }
        if self.attached.get() > 0 && context.viewport_dependency(self.id.to_u32()) {
            context.viewport_structure_changed();
        }
        *borrow_mut!(self.render_parent) = Rc::downgrade(parent);
        let frame = frame.clone();
        let deps = [frame.untyped()];
        self.parent_frame
            .replace_with(LocalProperty::computed(move || frame.get(), &deps));
        let glass = glass.clone();
        let deps = [glass.untyped()];
        self.liquid_glass_scope
            .replace_with(LocalProperty::computed(move || glass.get(), &deps));
        self.inherit_suspend(parent);
        self.bind_to_parent_bounds(context);
        *borrow_mut!(self.parent_binding_sources) = Some(sources);
        true
    }

    fn rebind_parent_bounds_for_mounted_subtree(self: &Rc<Self>, context: &Rc<RuntimeContext>) {
        self.bind_to_parent_bounds(context);
        self.bind_occlusion_listener(context);
        let mounted_children = borrow!(self.mounted_children).clone();
        for child in mounted_children {
            child.rebind_parent_bounds_for_mounted_subtree(context);
        }
        let sidecar_children = borrow!(self.sidecar_children).clone();
        for child in sidecar_children {
            child.rebind_parent_bounds_for_mounted_subtree(context);
        }
    }

    fn mark_canvas_subtree_dirty_for_reparent(
        self: &Rc<Self>,
        context: &Rc<RuntimeContext>,
        queue_retained_removal: bool,
    ) {
        let layer = self.occlusion.get().render_layer_id;
        context.set_canvas_dirty(layer);
        if borrow!(self.instance_node).base().flags().layer == Layer::Canvas {
            if queue_retained_removal {
                context.enqueue_canvas_node_removal(layer, self.id.to_u32());
            }
            context.mark_canvas_node_dirty(self.id);
        }
        context.mark_occlusion_dirty();

        let mounted_children = borrow!(self.mounted_children).clone();
        for child in mounted_children {
            child.mark_canvas_subtree_dirty_for_reparent(context, queue_retained_removal);
        }
        let sidecar_children = borrow!(self.sidecar_children).clone();
        for child in sidecar_children {
            child.mark_canvas_subtree_dirty_for_reparent(context, queue_retained_removal);
        }
    }

    fn bind_to_parent_bounds(self: &Rc<Self>, ctx: &Rc<RuntimeContext>) {
        // Explicit reload/reparent rebuilds invalidate the attachment fast path.
        self.parent_binding_sources.borrow_mut().take();
        self.layout_binding_generation
            .set(self.layout_binding_generation.get().wrapping_add(1));
        self.subtree_layout_hull_listener.invalidate();
        self.children_listener.invalidate();
        #[cfg(test)]
        self.parent_binding_rebuilds
            .set(self.parent_binding_rebuilds.get() + 1);
        let render_parent = borrow!(self.render_parent).upgrade();
        let parent_transform_and_bounds = render_parent
            .as_ref()
            .map(|n| n.transform_and_bounds.clone())
            .unwrap_or_else(|| ctx.globals().viewport);
        let (parent_padding_x, parent_padding_y) = render_parent
            .as_ref()
            .map(|n| {
                let common_props = n.get_common_properties();
                let common_props = borrow!(common_props);
                (
                    common_props.padding_x.clone(),
                    common_props.padding_y.clone(),
                )
            })
            .unwrap_or_default();
        let container_frame = self.container_frame.clone();
        let deps = [
            parent_transform_and_bounds.untyped(),
            parent_padding_x.untyped(),
            parent_padding_y.untyped(),
            container_frame.untyped(),
        ];
        let effective_parent_transform_and_bounds = LocalProperty::computed(
            move || {
                apply_container_frame(
                    apply_padding_frame(
                        parent_transform_and_bounds.get(),
                        parent_padding_x.get(),
                        parent_padding_y.get(),
                    ),
                    container_frame.get(),
                )
            },
            &deps,
        );
        let common_props = borrow!(self.common_properties);
        let extra_transform = borrow!(common_props).transform.clone();

        let transform_and_bounds = compute_tab(
            self.layout_properties(),
            extra_transform,
            effective_parent_transform_and_bounds,
        );
        self.transform_and_bounds.replace_with(transform_and_bounds);

        let parent_opacity = borrow!(self.render_parent)
            .upgrade()
            .map(|n| n.computed_opacity.clone())
            .unwrap_or_else(|| LocalProperty::new(1.0));
        let common_props = self.get_common_properties();
        let self_opacity = borrow!(common_props).opacity.clone();
        let parent_scopes = render_parent
            .as_ref()
            .map(|n| n.computed_opacity_scopes.clone())
            .unwrap_or_else(|| LocalProperty::new(Vec::new()));
        let local_opacity = self_opacity.clone();
        let node_id = self.id.to_u32();
        let scope_deps = [parent_scopes.untyped(), local_opacity.untyped()];
        self.computed_opacity_scopes
            .replace_with(LocalProperty::computed(
                move || {
                    let mut scopes = parent_scopes.get();
                    if let Some(opacity) = local_opacity.get() {
                        scopes.push(OpacityScope {
                            node_id,
                            opacity: opacity.to_float_0_1().clamp(0.0, 1.0) as f32,
                        });
                    }
                    scopes
                },
                &scope_deps,
            ));
        let deps = [parent_opacity.untyped(), self_opacity.untyped()];
        self.computed_opacity.replace_with(LocalProperty::computed(
            move || {
                let parent = parent_opacity.get().clamp(0.0, 1.0);
                let local = self_opacity
                    .get()
                    .unwrap_or_default()
                    .to_float_0_1()
                    .clamp(0.0, 1.0);
                (parent * local).clamp(0.0, 1.0)
            },
            &deps,
        ));
    }

    fn bind_occlusion_listener(self: &Rc<Self>, ctx: &Rc<RuntimeContext>) {
        let instance_node = borrow!(self.instance_node);
        let mut deps: Vec<_> = borrow!(self.properties_scope)
            .iter()
            .filter(|(name, _)| instance_node.property_requires_occlusion_recompute(name))
            .map(|(_, v)| v.get_untyped_property().clone())
            .collect();
        drop(instance_node);

        // Structural child changes are handled by children_listener after
        // reconciliation; data-only repeat invalidation is not an occlusion change.
        deps.extend([
            self.transform_and_bounds.untyped(),
            self.computed_opacity.untyped(),
            self.liquid_glass_scope.untyped(),
            self.get_common_properties().borrow().unclippable.untyped(),
        ]);

        let context = Rc::clone(ctx);
        let id = self.id.to_u32();
        self.occlusion_listener
            .replace_with(LocalProperty::computed_with_name(
                move || {
                    context.mark_node_occlusion_dirty(id);
                },
                &deps,
                "occlusion listener",
            ));
        ctx.register_expanded_node_effect_property_named(
            self,
            &self.occlusion_listener,
            "occlusion listener",
        );
    }

    fn reapply_runtime_settings(self: &Rc<Self>, context: &Rc<RuntimeContext>) {
        let instance = Rc::clone(&*borrow!(self.instance_node));
        instance.base().bind_properties(self);
        self.reset_removed_runtime_properties.set(false);
        self.refresh_properties_scope(&instance);
        self.mark_non_reactive_update_subtree_dirty();
        context.mark_occlusion_dirty();
        context.set_canvas_dirty(self.occlusion.get().render_layer_id);
    }

    fn bind_selector_classes_listener(self: &Rc<Self>, context: &Rc<RuntimeContext>) {
        let classes = self.selector_metadata.borrow().classes.clone();
        let previous = Rc::new(RefCell::new(classes.get()));
        let weak_self = Rc::downgrade(self);
        let runtime_context = Rc::clone(context);
        self.selector_classes_listener
            .replace_with(LocalProperty::computed_with_name(
                move || {
                    let current = classes.get();
                    if *previous.borrow() == current {
                        return;
                    }
                    *previous.borrow_mut() = current;
                    let Some(node) = weak_self.upgrade() else {
                        return;
                    };
                    node.reset_removed_runtime_properties.set(true);
                    node.reapply_runtime_settings(&runtime_context);
                },
                &[self.selector_metadata.borrow().classes.untyped()],
                "selector classes listener",
            ));
        context.register_expanded_node_effect_property_named(
            self,
            &self.selector_classes_listener,
            "selector classes listener",
        );
    }

    fn bind_children_listener(self: &Rc<Self>, ctx: &Rc<RuntimeContext>) {
        let deps = [self.children.untyped()];
        let weak_self = Rc::downgrade(self);
        let context = Rc::clone(ctx);
        let previous = RefCell::new(None);
        self.children_listener
            .replace_with(LocalProperty::computed_with_name(
                move || {
                    let Some(node) = weak_self.upgrade() else {
                        return;
                    };
                    if !node.child_structure_changed(&previous) {
                        return;
                    }
                    #[cfg(test)]
                    node.structural_children_updates
                        .set(node.structural_children_updates.get() + 1);
                    if borrow!(node.instance_node).base().flags().is_component
                        || borrow!(node.expanded_projected_children).is_some()
                    {
                        node.compute_flattened_projected_children();
                    }
                    // Projected if/for nodes are flattened out of the render
                    // tree. Their structural changes must refresh the receiving
                    // component's input list, even when it was previously empty.
                    if borrow!(node.instance_node).base().flags().invisible_to_slot {
                        let mut ancestor = node.template_parent.upgrade();
                        while let Some(parent) = ancestor {
                            if borrow!(parent.expanded_projected_children).is_some() {
                                parent.compute_flattened_projected_children();
                                break;
                            }
                            if !borrow!(parent.instance_node)
                                .base()
                                .flags()
                                .invisible_to_slot
                            {
                                break;
                            }
                            ancestor = parent.template_parent.upgrade();
                        }
                    }
                    context.mark_occlusion_dirty();

                    let (is_slot, is_component) = {
                        let instance = borrow!(node.instance_node);
                        let flags = instance.base().flags();
                        (flags.is_slot, flags.is_component)
                    };
                    if !is_slot {
                        if is_component {
                            node.slot_projection_changed.set(());
                        } else if let Some(containing_component) =
                            node.containing_component.upgrade()
                        {
                            containing_component.slot_projection_changed.set(());
                        }
                    }
                },
                &deps,
                "children listener",
            ));
        ctx.register_expanded_node_effect_property_named(
            self,
            &self.children_listener,
            "children listener",
        );
    }

    fn bind_subtree_layout_hull(self: &Rc<Self>, ctx: &Rc<RuntimeContext>) {
        self.rebind_subtree_layout_hull();
        let deps = [self.children.untyped()];
        let weak_self = Rc::downgrade(self);
        let previous = RefCell::new(None);
        self.subtree_layout_hull_listener
            .replace_with(LocalProperty::computed_with_name(
                move || {
                    let Some(node) = weak_self.upgrade() else {
                        return;
                    };
                    if node.child_structure_changed(&previous) {
                        node.rebind_subtree_layout_hull();
                    }
                },
                &deps,
                "subtree layout hull listener",
            ));
        ctx.register_expanded_node_effect_property_named(
            self,
            &self.subtree_layout_hull_listener,
            "subtree layout hull listener",
        );
    }
    fn child_structure_changed(&self, previous: &RefCell<Option<ChildStructure>>) -> bool {
        // Always evaluate first: reconciliation may update data, rescue an exit,
        // or remove a completed exit even when the source keys are unchanged.
        let children = self.children.get();
        let ids = |children: &[Rc<ExpandedNode>]| {
            children.iter().map(|child| child.id).collect::<Vec<_>>()
        };
        // Slot projection distinguishes active from exiting children even when
        // their combined render order is unchanged at the start of an exit.
        let current = ChildStructure {
            binding_generation: self.layout_binding_generation.get(),
            rendered: ids(&children),
            active: ids(&borrow!(self.active_children)),
            exiting: ids(&borrow!(self.exiting_children)),
        };
        let mut previous = previous.borrow_mut();
        if previous.as_ref() == Some(&current) {
            return false;
        }
        *previous = Some(current);
        true
    }

    fn rebind_subtree_layout_hull(self: &Rc<Self>) {
        #[cfg(test)]
        self.layout_hull_rebuilds
            .set(self.layout_hull_rebuilds.get() + 1);
        let self_transform_and_bounds = self.transform_and_bounds.clone();
        let layout_properties = self.layout_properties();
        let common_props = self.get_common_properties();
        let (width, height, x, y, padding_x, padding_y) = {
            let common_props = borrow!(common_props);
            (
                common_props.width.clone(),
                common_props.height.clone(),
                common_props.x.clone(),
                common_props.y.clone(),
                common_props.padding_x.clone(),
                common_props.padding_y.clone(),
            )
        };
        let children = self.children.get();
        let has_children = !children.is_empty();
        let bounds_name = format!("layout bounds (node id: {})", self.id.0);
        let bounds_transform_and_bounds = self_transform_and_bounds.clone();
        let bounds = LocalProperty::computed_with_cutoff_and_name(
            move || bounds_transform_and_bounds.get().bounds,
            &[self_transform_and_bounds.untyped()],
            <(f64, f64)>::eq,
            &bounds_name,
        );
        let mut own_deps = vec![bounds.untyped()];
        if has_children {
            own_deps.extend([width.untyped(), height.untyped(), x.untyped(), y.untyped()]);
        } else {
            own_deps.push(layout_properties.untyped());
        }

        let own_hull_name = format!("own layout hull (node id: {})", self.id.0);
        let own_hull = LocalProperty::computed_with_cutoff_and_name(
            move || {
                let bounds = bounds.get();
                let (contributes_x, contributes_y) = if has_children {
                    (
                        layout_axis_can_contribute_from_parts(width.get(), x.get()),
                        layout_axis_can_contribute_from_parts(height.get(), y.get()),
                    )
                } else {
                    let layout_properties = layout_properties.get();
                    (
                        layout_axis_can_contribute(&layout_properties, Axis::X),
                        layout_axis_can_contribute(&layout_properties, Axis::Y),
                    )
                };
                LayoutHull::from_axis_ranges(
                    contributes_x.then_some((0.0, bounds.0)),
                    contributes_y.then_some((0.0, bounds.1)),
                )
            },
            &own_deps,
            crate::layout_hulls_equivalent,
            &own_hull_name,
        );

        if !has_children {
            self.subtree_layout_hull.replace_with(own_hull);
            return;
        }

        let mut projected_child_hulls = Vec::with_capacity(children.len());
        for child in children.iter() {
            let child_cp = child.get_common_properties();
            let child_layout_role = borrow!(child_cp).layout_role.clone();
            let projection_name = format!(
                "projected child layout hull (parent id: {}, child id: {})",
                self.id.0, child.id.0
            );
            projected_child_hulls.push(crate::projected_child_layout_hull_property(
                self_transform_and_bounds.clone(),
                padding_x.clone(),
                padding_y.clone(),
                child.transform_and_bounds.clone(),
                child.subtree_layout_hull.clone(),
                child_layout_role,
                &projection_name,
            ));
        }

        let mut deps = vec![own_hull.untyped(), padding_x.untyped(), padding_y.untyped()];
        deps.extend(projected_child_hulls.iter().map(LocalProperty::untyped));

        let property_name = format!("subtree layout hull (node id: {})", self.id.0);
        self.subtree_layout_hull
            .replace_with(LocalProperty::computed_with_cutoff_and_name(
                move || {
                    let mut hull = own_hull.get();
                    let mut children_hull = LayoutHull::default();
                    for projected_hull in &projected_child_hulls {
                        children_hull = children_hull.union(projected_hull.get());
                    }
                    hull = hull.union(add_symmetric_padding_to_content_layout_hull(
                        children_hull,
                        padding_x.get(),
                        padding_y.get(),
                    ));

                    hull
                },
                &deps,
                crate::layout_hulls_equivalent,
                &property_name,
            ));
    }

    pub fn inherit_suspend(self: &Rc<Self>, node: &Rc<Self>) {
        self.parent_binding_sources.borrow_mut().take();
        let cp = self.get_common_properties();
        let self_suspended = borrow!(cp)._suspended.clone();
        let parent_suspended = node.suspended.clone();
        let deps = [parent_suspended.untyped(), self_suspended.untyped()];
        self.suspended.replace_with(LocalProperty::computed(
            move || {
                self_suspended
                    .get()
                    .unwrap_or_else(|| parent_suspended.get())
            },
            &deps,
        ));
    }

    pub fn generate_children(
        self: &Rc<Self>,
        templates: impl IntoIterator<Item = (Rc<dyn InstanceNode>, Rc<RuntimePropertiesStackFrame>)>,
        context: &Rc<RuntimeContext>,
        parent_frame: &LocalProperty<Option<ExpandedNodeIdentifier>>,
        is_mount: bool,
    ) -> Vec<Rc<ExpandedNode>> {
        self.generate_children_with_liquid_glass_scope(
            templates,
            context,
            parent_frame,
            &self.liquid_glass_scope,
            is_mount,
        )
    }

    pub fn generate_children_with_liquid_glass_scope(
        self: &Rc<Self>,
        templates: impl IntoIterator<Item = (Rc<dyn InstanceNode>, Rc<RuntimePropertiesStackFrame>)>,
        context: &Rc<RuntimeContext>,
        parent_frame: &LocalProperty<Option<ExpandedNodeIdentifier>>,
        liquid_glass_scope: &LocalProperty<Option<NativeLiquidGlassScope>>,
        is_mount: bool,
    ) -> Vec<Rc<ExpandedNode>> {
        let new_children = self.create_children_detached(templates, context, &Rc::downgrade(&self));
        let res = if is_mount {
            self.attach_children_with_liquid_glass_scope(
                new_children,
                context,
                parent_frame,
                liquid_glass_scope,
            )
        } else {
            for child in new_children.iter() {
                child.recurse_control_flow_expansion(context);
            }

            new_children
        };
        res
    }

    /// Run tick or pre-render handlers on this node unless it is detached or suspended.
    /// Inline handlers receive their authored component's state and this node's context.
    pub fn run_lifecycle_handlers(
        self: &Rc<Self>,
        handler_key: &str,
        context: &Rc<RuntimeContext>,
    ) {
        if self.attached.get() == 0 || self.suspended.get() {
            return;
        }
        let _graph = context.property_graph.enter();
        let _scope = self.property_binding_scope.borrow().enter();
        self.run_lifecycle_handlers_for_key(handler_key, context);
    }

    pub fn recurse_update(self: &Rc<Self>, context: &Rc<RuntimeContext>) {
        // Settle queued reactive effects before checking which subtrees still need
        // imperative work, then flush any effects produced by that non-reactive pass.
        context.drain_node_effects();
        self.recurse_update_mounted(context);
        context.drain_node_effects();
    }

    fn recurse_update_mounted(self: &Rc<Self>, context: &Rc<RuntimeContext>) {
        if self.attached.get() == 0 || !self.subtree_requires_non_reactive_update.get() {
            return;
        }
        let _graph = context.property_graph.enter();
        let _scope = self.property_binding_scope.borrow().enter();
        let instance_node = Rc::clone(&*borrow!(self.instance_node));
        if !self.suppresses_native_presentation()
            && instance_node.requires_non_reactive_update(self)
        {
            instance_node.update(&self, context);
        }
        let mut subtree_requires_non_reactive_update = !self.suppresses_native_presentation()
            && Rc::clone(&*borrow!(self.instance_node)).requires_non_reactive_update(self);
        let children = borrow!(self.mounted_children).clone();
        for child in children.iter() {
            child.recurse_update_mounted(context);
            subtree_requires_non_reactive_update |=
                child.subtree_requires_non_reactive_update.get();
        }
        let sidecar_children = borrow!(self.sidecar_children).clone();
        for child in sidecar_children.iter() {
            child.recurse_update_mounted(context);
            subtree_requires_non_reactive_update |=
                child.subtree_requires_non_reactive_update.get();
        }
        self.subtree_requires_non_reactive_update
            .set(subtree_requires_non_reactive_update);
    }

    pub fn recurse_sync_import_settings(self: &Rc<Self>, context: &Rc<RuntimeContext>) {
        if borrow!(self.instance_node).base().flags().is_component {
            self.sync_imported_settings(context);
        }
        for child in self.children.get().iter() {
            child.recurse_sync_import_settings(context);
        }
        for child in borrow!(self.sidecar_children).iter() {
            child.recurse_sync_import_settings(context);
        }
    }

    fn recurse_reapply_runtime_settings_for_component_owner(
        self: &Rc<Self>,
        owner_component_id: ExpandedNodeIdentifier,
        context: &Rc<RuntimeContext>,
    ) {
        if self.is_import_settings_node() {
            return;
        }

        let owned_by_component = self
            .containing_component
            .upgrade()
            .map(|component| component.id == owner_component_id)
            .unwrap_or(false);

        if owned_by_component {
            self.reset_removed_runtime_properties.set(true);
            let instance = borrow!(self.instance_node).clone();
            self.recreate_with_new_data(instance, context);
        }

        let children = self.children.get();
        for child in children.iter() {
            child.recurse_reapply_runtime_settings_for_component_owner(owner_component_id, context);
        }

        let sidecar_children = borrow!(self.sidecar_children).clone();
        for child in sidecar_children.iter() {
            child.recurse_reapply_runtime_settings_for_component_owner(owner_component_id, context);
        }
    }

    pub fn recurse_control_flow_expansion(self: &Rc<Self>, context: &Rc<RuntimeContext>) {
        borrow!(self.instance_node)
            .clone()
            .handle_control_flow_node_expansion(&self, context);
    }

    pub fn recurse_mount(self: &Rc<Self>, context: &Rc<RuntimeContext>) {
        let _graph = context.property_graph.enter();
        if self.attached.get() == 0 && self.stores.is_closed() {
            self.prepare_remount(context);
        }
        self.property_binding_scope.borrow().resume();
        let _scope = self.property_binding_scope.borrow().enter();
        if self.attached.get() == 0 {
            self.stores.mount(self.template_parent.upgrade().as_deref());
            // All bindings are installed before mount. Materialize their local
            // views now so shared snapshots seen by handlers are initialized.
            let scope: Vec<_> = borrow!(self.properties_scope).values().cloned().collect();
            for property in scope {
                property.get_as_pax_value();
            }
            // Materialize projected children before mount so Slot can resolve them.
            borrow!(self.instance_node)
                .clone()
                .handle_setup_projected_children(&self, context);

            // Pre-mount pass to make sure projected children are expanded and we compute the correct flattened list.
            if let Some(projected_children) = borrow!(self.expanded_projected_children).as_ref() {
                for projected_child in projected_children {
                    projected_child.recurse_control_flow_expansion(context);
                }
                // This is needed to resolve slot connections in a single tick.
                self.compute_flattened_projected_children();
            }
            self.attached.set(self.attached.get() + 1);
            self.start_self_enter_transition(context);
            context.add_to_cache(&self);
            self.run_lifecycle_handlers_for_key("mount", context);
            // Native source leaves have no GPU coverage. Keep their properties
            // available to component logic, but create no native surfaces or
            // native update subscriptions.
            if !self.suppresses_native_presentation() {
                borrow!(self.instance_node)
                    .clone()
                    .handle_mount(&self, context);
            }
            context.register_expanded_node_effect_property_named(
                self,
                &self.changed_listener,
                "changed listener",
            );
            context.register_viewport_proximity(self);
        }
    }

    pub fn async_scope(&self, context: &Rc<RuntimeContext>) -> Result<AsyncScope, AsyncError> {
        if self.attached.get() == 0 {
            return Err(AsyncError::Closed);
        }
        if let Some(scope) = self.async_scope.borrow().as_ref() {
            return Ok(scope.clone());
        }
        let scope = context.application.context().async_scope()?.child()?;
        let binding = self.property_binding_scope.borrow().clone();
        scope.set_callback_context(move |callback| binding.with_graph(callback));
        *self.async_scope.borrow_mut() = Some(scope.clone());
        Ok(scope)
    }

    pub fn recurse_unmount(self: Rc<Self>, context: &Rc<RuntimeContext>) {
        if self.attached.get() != 1 {
            return;
        }
        let _graph = context.property_graph.enter();
        let _scope = self.property_binding_scope.borrow().enter();
        // WARNING: do NOT make recurse_unmount result in expr evaluation,
        // in this case: do not refer to self.children expression.
        // expr evaluation in this context can trigger get's of "old data", ie try to get
        // an index of a for loop source that doesn't exist anymore
        if self.attached.get() == 1 {
            if let Some(scope) = self.async_scope.borrow_mut().take() {
                scope.cancel();
            }
            self.attached.set(self.attached.get() - 1);
            context.remove_from_cache(&self);
            for child in borrow!(self.mounted_children).iter() {
                Rc::clone(child).recurse_unmount(context);
            }
            if !self.suppresses_native_presentation() {
                borrow!(self.instance_node).handle_unmount(&self, context);
            }
            self.run_lifecycle_handlers_for_key("unmount", context);

            if !self.is_render_source()
                && self.instance_node.borrow().base().flags().layer == Layer::Canvas
            {
                context.enqueue_canvas_node_removal(
                    self.occlusion.get().render_layer_id,
                    self.id.to_u32(),
                );
                context.set_canvas_dirty(self.occlusion.get().render_layer_id);
            }

            // Needed because occlusion updates are only sent on diffs so we reset it when unmounting
            self.occlusion.set(Default::default());
            self.browser_content_layer_id.set(None);
            self.changed_listener.replace_with(LocalProperty::default());
            self.selector_classes_listener
                .replace_with(LocalProperty::default());
            borrow_mut!(self.subscriptions).clear();
            borrow_mut!(self.active_children).clear();
            borrow_mut!(self.exiting_children).clear();
            borrow_mut!(self.exiting_child_generations).clear();
            borrow_mut!(self.mounted_children).clear();
            borrow_mut!(self.settings_motion).clear();
            borrow_mut!(self.import_settings_transition).take();
            borrow_mut!(self.imported_settings_layers).clear();
            borrow_mut!(self.imported_settings_signature).clear();
            borrow_mut!(self.resolved_property_columns).clear();
            borrow_mut!(self.resolved_property_provenance).clear();
            self.reset_removed_runtime_properties.set(false);
            self.active_children_view.set(Vec::new());
            self.exiting_children_view.set(Vec::new());
            self.transition_phase.set(TRANSITION_PHASE_IDLE);
            self.transition_takeover.set(false);
            self.transition_selector_classes.borrow_mut().take();
            self.deactivate_transition_clock();
            self.enter_cleanup_active.set(false);
            self.enter_cleanup_listener
                .replace_with(LocalProperty::new_with_name((), "enter transition cleanup"));
            self.exit_cleanup_active.set(false);
            self.exit_cleanup_listener
                .replace_with(LocalProperty::default());
            self.stores.close();
            // Final unmount releases component-owned state without evaluating
            // bindings against potentially removed repeat items. Remount allocates
            // fresh properties; externally shared handles remain their owner's.
            self.children.replace_with(LocalProperty::new(Vec::new()));
            self.children_listener
                .replace_with(LocalProperty::default());
            self.occlusion_listener
                .replace_with(LocalProperty::default());
            self.subtree_layout_hull_listener
                .replace_with(LocalProperty::default());
            self.content_measurement_listener
                .replace_with(LocalProperty::default());
            self.content_measurement_rebind_listener
                .replace_with(LocalProperty::default());
            self.content_measurement_bound.set(false);
            borrow_mut!(self.sidecar_children).clear();
            borrow_mut!(self.expanded_projected_children).take();
            self.expanded_and_flattened_projected_children
                .set(Vec::new());
            self.flattened_projected_children_count.set(0);
            self.parent_binding_sources.borrow_mut().take();
            self.transform_and_bounds
                .replace_with(LocalProperty::default());
            self.computed_opacity.replace_with(LocalProperty::new(1.0));
            self.subtree_layout_hull
                .replace_with(LocalProperty::default());
            self.measured_size.set(None);
            *borrow_mut!(self.common_properties) =
                Rc::new(RefCell::new(CommonProperties::default()));
            self.selector_metadata.borrow_mut().id = LocalProperty::default();
            self.selector_metadata.borrow_mut().classes = LocalProperty::default();
            borrow_mut!(self.properties_scope).clear();
            *borrow_mut!(self.properties) =
                Rc::new(RefCell::new(PaxAny::Builtin(PaxValue::default())));
            self.property_binding_scope.borrow().close();
        }
    }

    pub fn is_import_settings_node(&self) -> bool {
        borrow!(self.instance_node)
            .base()
            .template_node_type_id
            .as_ref()
            .and_then(|type_id| type_id.get_pascal_identifier())
            .as_deref()
            == Some("ImportSettings")
    }

    pub fn is_in_import_settings_subtree(&self) -> bool {
        let mut current = borrow!(self.render_parent).upgrade();
        while let Some(node) = current {
            if node.is_import_settings_node() {
                return true;
            }
            current = borrow!(node.render_parent).upgrade();
        }
        false
    }

    fn collect_imported_settings_from_node(
        node: &Rc<Self>,
        in_import_settings: bool,
        descend_components: bool,
        providers: &mut Vec<DiscoveredSettingsProvider>,
        transition: Option<LocalProperty<Option<crate::SettingsTransitionConfig>>>,
    ) {
        if node.is_import_settings_node() {
            let sidecar_children = borrow!(node.sidecar_children).clone();
            for child in sidecar_children.iter() {
                Self::collect_imported_settings_from_node(
                    child,
                    true,
                    true,
                    providers,
                    transition
                        .clone()
                        .or_else(|| node.import_settings_transition.borrow().clone()),
                );
            }
            return;
        }

        if borrow!(node.instance_node).base().flags().is_component {
            if in_import_settings {
                if borrow!(node.instance_node)
                    .base()
                    .component_settings
                    .as_ref()
                    .is_some_and(|settings| !settings.is_empty())
                {
                    providers.push(DiscoveredSettingsProvider {
                        node: Rc::clone(node),
                        transition: transition.clone(),
                    });
                }
                let children = node.children.get();
                for child in children.iter() {
                    Self::collect_imported_settings_from_node(
                        child,
                        false,
                        true,
                        providers,
                        transition.clone(),
                    );
                }
                let sidecar_children = borrow!(node.sidecar_children).clone();
                for child in sidecar_children.iter() {
                    Self::collect_imported_settings_from_node(
                        child,
                        false,
                        true,
                        providers,
                        transition.clone(),
                    );
                }
                return;
            }
            if !descend_components {
                return;
            }
        }

        let children = node.children.get();
        for child in children.iter() {
            Self::collect_imported_settings_from_node(
                child,
                in_import_settings,
                descend_components,
                providers,
                transition.clone(),
            );
        }
        let sidecar_children = borrow!(node.sidecar_children).clone();
        for child in sidecar_children.iter() {
            Self::collect_imported_settings_from_node(
                child,
                in_import_settings,
                descend_components,
                providers,
                transition.clone(),
            );
        }
    }

    pub fn sync_imported_settings(self: &Rc<Self>, context: &Rc<RuntimeContext>) {
        let mut providers = Vec::new();
        let children = self.children.get();
        for child in children.iter() {
            Self::collect_imported_settings_from_node(child, false, false, &mut providers, None);
        }
        let sidecar_children = borrow!(self.sidecar_children).clone();
        for child in sidecar_children.iter() {
            Self::collect_imported_settings_from_node(child, false, false, &mut providers, None);
        }

        let signature = providers
            .iter()
            .map(DiscoveredSettingsProvider::signature)
            .collect::<Vec<_>>();
        if *borrow!(self.imported_settings_signature) == signature {
            return;
        }

        *borrow_mut!(self.imported_settings_signature) = signature;
        *borrow_mut!(self.imported_settings_layers) = providers
            .into_iter()
            .map(DiscoveredSettingsProvider::materialize)
            .collect();

        let root_children = self.children.get();
        for child in root_children.iter() {
            if child.is_import_settings_node() {
                continue;
            }
            child.recurse_reapply_runtime_settings_for_component_owner(self.id, context);
            child.recurse_emit_mount_updates();
        }
    }

    pub fn recurse_render_queue(
        self: &Rc<Self>,
        ctx: &Rc<RuntimeContext>,
        rcs: &mut dyn RenderContext,
    ) {
        if self.is_render_source() {
            return;
        }
        let cp = self.get_common_properties();
        let cp = borrow!(cp);
        if cp.unclippable.get().unwrap_or(false) {
            ctx.queue_render(Rc::clone(&self));
        } else {
            self.recurse_render(ctx, rcs);
        }
    }

    pub(crate) fn render_parent_node(&self) -> Option<Rc<ExpandedNode>> {
        borrow!(self.render_parent).upgrade()
    }

    pub(crate) fn is_unclippable(&self) -> bool {
        let cp = self.get_common_properties();
        let cp = borrow!(cp);
        cp.unclippable.get().unwrap_or(false)
    }

    pub(crate) fn recurse_render_filtered(
        self: &Rc<Self>,
        ctx: &Rc<RuntimeContext>,
        rcs: &mut dyn RenderContext,
        render_path_nodes: &HashSet<ExpandedNodeIdentifier>,
        dirty_nodes: &HashSet<ExpandedNodeIdentifier>,
        stats: &mut FilteredRenderStats,
    ) {
        if self.is_render_source() {
            return;
        }
        stats.path_nodes_visited += 1;
        #[cfg(feature = "shaders")]
        if self.render_shader_effect(ctx, rcs) {
            return;
        }
        borrow!(self.instance_node).handle_pre_render(&self, ctx, rcs);
        for child in self.children.get().iter().rev() {
            if render_path_nodes.contains(&child.id) {
                child.recurse_render_filtered(ctx, rcs, render_path_nodes, dirty_nodes, stats);
            } else {
                stats.skipped_subtrees += 1;
            }
        }
        if dirty_nodes.contains(&self.id) {
            borrow!(self.instance_node).render(&self, ctx, rcs);
            stats.dirty_nodes_rendered += 1;
        }
        borrow!(self.instance_node).handle_post_render(&self, ctx, rcs);
    }

    pub fn recurse_render(self: &Rc<Self>, ctx: &Rc<RuntimeContext>, rcs: &mut dyn RenderContext) {
        if self.is_render_source() {
            return;
        }
        #[cfg(feature = "shaders")]
        if self.render_shader_effect(ctx, rcs) {
            return;
        }
        borrow!(self.instance_node).handle_pre_render(&self, ctx, rcs);
        for child in self.children.get().iter().rev() {
            child.recurse_render_queue(ctx, rcs);
        }
        borrow!(self.instance_node).render(&self, ctx, rcs);
        borrow!(self.instance_node).handle_post_render(&self, ctx, rcs);
    }

    /// Records a detached source using ordinary vector hooks without presenting it or allocating
    /// native surfaces. Structural components retain their normal back-to-front child order.
    pub fn recurse_render_alpha_source(
        self: &Rc<Self>,
        ctx: &Rc<RuntimeContext>,
        rcs: &mut dyn RenderContext,
    ) {
        assert!(self.is_render_source() && rcs.alpha_source_layer().is_some());
        let mut deferred = Vec::new();
        self.render_alpha_source_inner(ctx, rcs, &mut deferred);
        let mut next = 0;
        while next < deferred.len() {
            let node = Rc::clone(&deferred[next]);
            next += 1;
            node.render_alpha_source_inner(ctx, rcs, &mut deferred);
        }
    }

    fn render_alpha_source_inner(
        self: &Rc<Self>,
        ctx: &Rc<RuntimeContext>,
        rcs: &mut dyn RenderContext,
        deferred: &mut Vec<Rc<ExpandedNode>>,
    ) {
        #[cfg(feature = "shaders")]
        assert!(
            borrow!(self.instance_node).shader_effect(self).is_none(),
            "shader effects inside detached mask sources are unsupported"
        );
        let supported = borrow!(self.instance_node).supports_alpha_source_render();
        let structural = {
            let instance = borrow!(self.instance_node);
            let flags = instance.base().flags();
            flags.layer == Layer::DontCare || flags.is_component
        };
        if !supported && !structural {
            return;
        }
        if supported {
            borrow!(self.instance_node).handle_pre_render(self, ctx, rcs);
        }
        for child in self.children.get().iter().rev() {
            if child.is_unclippable() {
                deferred.push(Rc::clone(child));
            } else {
                child.render_alpha_source_inner(ctx, rcs, deferred);
            }
        }
        if supported {
            borrow!(self.instance_node).render(self, ctx, rcs);
            borrow!(self.instance_node).handle_post_render(self, ctx, rcs);
        }
    }

    /// Manages unpacking an `Rc<RefCell<PaxValue>>`, downcasting into
    /// the parameterized `target_type`, and executing a provided closure `body` in the
    /// context of that unwrapped variant (including support for mutable operations),
    /// the closure is executed.  Used at least by calculating properties in `expand_node` and
    /// passing `&mut self` into event handlers (where the typed `self` is retrieved from an instance of `PaxValue`)
    pub fn with_properties_unwrapped<T: ToFromPaxAny, R>(
        &self,
        callback: impl FnOnce(&mut T) -> R,
    ) -> R {
        self.try_with_properties_unwrapped(callback)
            .expect("properties not of expected type")
    }

    pub fn try_with_properties_unwrapped<T: ToFromPaxAny, R>(
        &self,
        callback: impl FnOnce(&mut T) -> R,
    ) -> Option<R> {
        // Borrow the contents of the RefCell mutably.
        let properties = borrow_mut!(self.properties);
        let mut borrowed = borrow_mut!(properties);
        // Downcast the unwrapped value to the specified `target_type` (or panic)
        let Ok(mut val) = T::mut_from_pax_any(&mut *borrowed) else {
            return None;
        };
        self.property_binding_scope
            .borrow()
            .with_graph(|| Some(callback(&mut val)))
    }

    pub fn recurse_visit_postorder(self: &Rc<Self>, func: &mut impl FnMut(&Rc<Self>)) {
        // NOTE: This is to make sure the projected children list is updated before trying to access children,
        // to make stacker/scroller behave correctly when the number of children is dynamic.
        self.compute_flattened_projected_children();
        for child in self.children.get().iter().rev() {
            child.recurse_visit_postorder(func)
        }
        func(self);
    }

    pub fn get_node_context(self: &Rc<Self>, ctx: &Rc<RuntimeContext>) -> NodeContext {
        let globals = ctx.globals();
        let viewport = super::viewport_info_property(&globals.viewport);
        let target = LocalProperty::new(globals.target);
        let t_and_b = self.transform_and_bounds.clone();
        let deps = [t_and_b.untyped()];
        let bounds_name = format!("node context bounds (node id: {})", self.id.0);
        let bounds_self = LocalProperty::computed_with_cutoff_and_name(
            move || t_and_b.get().bounds,
            &deps,
            <(f64, f64)>::eq,
            &bounds_name,
        );
        let render_parent = borrow!(self.render_parent).upgrade();
        let t_and_b_parent = render_parent
            .as_ref()
            .map(|parent| parent.transform_and_bounds.clone())
            .unwrap_or_else(|| globals.viewport.clone());
        let (parent_padding_x, parent_padding_y) = render_parent
            .as_ref()
            .map(|parent| {
                let common_props = parent.get_common_properties();
                let common_props = borrow!(common_props);
                (
                    common_props.padding_x.clone(),
                    common_props.padding_y.clone(),
                )
            })
            .unwrap_or_default();
        let deps = [
            t_and_b_parent.untyped(),
            parent_padding_x.untyped(),
            parent_padding_y.untyped(),
        ];
        let bounds_parent = LocalProperty::computed(
            move || {
                apply_padding_frame(
                    t_and_b_parent.get(),
                    parent_padding_x.get(),
                    parent_padding_y.get(),
                )
                .bounds
            },
            &deps,
        );

        let owns_projected_children = borrow!(self.instance_node).base().flags().is_component
            || borrow!(self.expanded_projected_children).is_some();

        let projected_children_count = if owns_projected_children {
            self.flattened_projected_children_count.clone()
        } else {
            self.containing_component
                .upgrade()
                .map(|v| v.flattened_projected_children_count.clone())
                .unwrap_or_default()
        };

        let projected_children = if owns_projected_children {
            self.expanded_and_flattened_projected_children.clone()
        } else {
            self.containing_component
                .upgrade()
                .map(|v| v.expanded_and_flattened_projected_children.clone())
                .unwrap_or_default()
        };

        let projected_children_changed = if owns_projected_children {
            self.projected_children_changed.clone()
        } else {
            self.containing_component
                .upgrade()
                .map(|v| v.projected_children_changed.clone())
                .unwrap_or_default()
        };
        // Normalize semantic payload for container consumers. This hides the
        // engine transport distinction (`Owned` vs `Projected`) behind the
        // single concept "received children".
        let received_children = match borrow!(self.instance_node).received_children_source() {
            ReceivedChildrenSource::Owned => self.active_children_view.clone(),
            ReceivedChildrenSource::Projected => {
                if owns_projected_children {
                    self.expanded_and_flattened_projected_children.clone()
                } else {
                    self.containing_component
                        .upgrade()
                        .map(|v| v.expanded_and_flattened_projected_children.clone())
                        .unwrap_or_default()
                }
            }
        };
        let received_children_count_source = received_children.clone();
        let received_children_count = LocalProperty::computed(
            move || received_children_count_source.get().len(),
            &[received_children.untyped()],
        );
        let received_children_signal = received_children.clone();
        let received_children_changed = LocalProperty::computed(
            move || {
                let _ = received_children_signal.get();
            },
            &[received_children.untyped()],
        );
        // Normalize the corresponding exit-retained payload set. These nodes
        // are no longer active content, but containers may still need them for
        // ghosting or overlay placement while `@out` transitions finish.
        let retained_received_children =
            match borrow!(self.instance_node).received_children_source() {
                ReceivedChildrenSource::Owned => self.exiting_children_view.clone(),
                ReceivedChildrenSource::Projected
                    if borrow!(self.expanded_projected_children).is_some() =>
                {
                    self.exiting_children_view.clone()
                }
                ReceivedChildrenSource::Projected => LocalProperty::default(),
            };
        let retained_received_children_signal = retained_received_children.clone();
        let retained_received_children_changed = LocalProperty::computed(
            move || {
                let _ = retained_received_children_signal.get();
            },
            &[retained_received_children.untyped()],
        );

        let last_frame = Rc::new(RefCell::new(globals.elapsed_frames.get()));
        let suspended = self.suspended.clone();
        let elapsed_frames = globals.elapsed_frames.clone();
        let elapsed_millis = globals.elapsed_millis.clone();
        let deps = [elapsed_frames.untyped(), suspended.untyped()];
        // TODO: this still triggers the dirty dag dependencies of elapsed
        // frames even if the value is the same. Try to make it not trigger
        // dependencides when frozen
        let elapsed_frames_frozen_if_suspended = LocalProperty::computed(
            move || {
                if suspended.get() {
                    *borrow!(last_frame)
                } else {
                    let val = elapsed_frames.get();
                    *borrow_mut!(last_frame) = val;
                    val
                }
            },
            &deps,
        );
        // PREF: possibly change this to just take a reference to expanded node, and
        // expose methods to retrieve these values from the expanded noe when
        // needed, instead of re-creating/copying
        NodeContext {
            slot_index: self.slot_index.clone(),
            expression_stack: Rc::clone(&self.stack),
            store_generation: self.stores.generation(),
            expanded_node: Rc::downgrade(&self),
            containing_component: Weak::clone(&self.containing_component),
            elapsed_frames: elapsed_frames_frozen_if_suspended,
            elapsed_millis,
            gyro: globals.gyro.clone(),
            accel: globals.accel.clone(),
            bounds_self,
            bounds_parent,
            measured_size: self.measured_size.clone(),
            subtree_layout_hull: self.subtree_layout_hull.clone(),
            runtime_context: ctx.clone(),
            platform: globals.platform.clone(),
            os: globals.os.clone(),
            target,
            viewport,
            get_elapsed_millis: globals.get_elapsed_millis,
            projected_children_count,
            projected_children,
            node_transform_and_bounds: self.transform_and_bounds.get(),
            projected_children_changed,
            received_children,
            received_children_count,
            received_children_changed,
            retained_received_children,
            retained_received_children_changed,
            #[cfg(feature = "designtime")]
            designtime: globals.designtime.clone(),
        }
    }

    pub fn get_common_properties(&self) -> Rc<RefCell<CommonProperties>> {
        Rc::clone(&*borrow!(self.common_properties))
    }

    pub fn is_layout_breakout(&self) -> bool {
        let common_props = self.get_common_properties();
        let is_breakout = borrow!(common_props).layout_role.get() == Some(LayoutRole::Breakout);
        is_breakout
    }

    /// Determines whether the provided ray, orthogonal to the view plane,
    /// intersects this `ExpandedNode`.
    pub fn ray_cast_test(&self, ray: Point2<Window>) -> bool {
        if self.is_render_source() {
            return false;
        }
        let cp = borrow!(self.common_properties);

        // skip raycast if false
        if !borrow!(&*cp)._raycastable.get().unwrap_or(true) {
            return false;
        }
        drop(cp);
        borrow!(self.instance_node).ray_cast_test(self, ray)
    }

    pub fn compute_flattened_projected_children(&self) {
        // All of this should ideally be reactively updated,
        // but currently doesn't exist a way to "listen to"
        // an entire node tree, and generate the flattened list
        // only when changed.
        if let Some(projected_children) = borrow!(self.expanded_projected_children).as_ref() {
            let new_flattened = flatten_expanded_nodes_for_projection(projected_children);
            let old_and_new_filtered_same =
                self.expanded_and_flattened_projected_children
                    .read(|flattened| {
                        flattened
                            .iter()
                            .map(|n| n.id)
                            .eq(new_flattened.iter().map(|n| n.id))
                    });

            if !old_and_new_filtered_same {
                self.flattened_projected_children_count
                    .set(new_flattened.len());
                self.expanded_and_flattened_projected_children
                    .set(new_flattened);
                for (i, projected_child) in self
                    .expanded_and_flattened_projected_children
                    .get()
                    .iter()
                    .enumerate()
                {
                    if projected_child.slot_index.get() != Some(i) {
                        projected_child.slot_index.set(Some(i));
                    };
                }
            }
        }
    }

    dispatch_event_handler!(dispatch_scroll, Scroll, SCROLL_HANDLERS, true);
    dispatch_event_handler!(dispatch_touch_start, TouchStart, TOUCH_START_HANDLERS, true);

    dispatch_event_handler!(dispatch_touch_move, TouchMove, TOUCH_MOVE_HANDLERS, true);
    dispatch_event_handler!(dispatch_touch_end, TouchEnd, TOUCH_END_HANDLERS, true);
    dispatch_event_handler!(
        dispatch_touch_cancel,
        TouchCancel,
        TOUCH_CANCEL_HANDLERS,
        true
    );
    dispatch_event_handler!(dispatch_key_down, KeyDown, KEY_DOWN_HANDLERS, false);
    dispatch_event_handler!(dispatch_key_up, KeyUp, KEY_UP_HANDLERS, false);
    dispatch_event_handler!(dispatch_key_press, KeyPress, KEY_PRESS_HANDLERS, false);
    dispatch_event_handler!(
        dispatch_checkbox_change,
        CheckboxChange,
        CHECKBOX_CHANGE_HANDLERS,
        true
    );
    dispatch_event_handler!(
        dispatch_slider_change,
        SliderChange,
        SLIDER_CHANGE_HANDLERS,
        true
    );
    dispatch_event_handler!(
        dispatch_textbox_change,
        TextboxChange,
        TEXTBOX_CHANGE_HANDLERS,
        true
    );
    dispatch_event_handler!(dispatch_text_input, TextInput, TEXT_INPUT_HANDLERS, true);
    dispatch_event_handler!(
        dispatch_textbox_input,
        TextboxInput,
        TEXTBOX_INPUT_HANDLERS,
        true
    );
    dispatch_event_handler!(
        dispatch_button_click,
        ButtonClick,
        BUTTON_CLICK_HANDLERS,
        true
    );
    dispatch_event_handler!(
        dispatch_photo_picker_change,
        PhotoPickerChange,
        PHOTO_PICKER_CHANGE_HANDLERS,
        true
    );
    dispatch_event_handler!(dispatch_mouse_down, MouseDown, MOUSE_DOWN_HANDLERS, true);
    dispatch_event_handler!(dispatch_mouse_up, MouseUp, MOUSE_UP_HANDLERS, true);
    dispatch_event_handler!(dispatch_mouse_move, MouseMove, MOUSE_MOVE_HANDLERS, true);
    dispatch_event_handler!(dispatch_mouse_over, MouseOver, MOUSE_OVER_HANDLERS, false);
    dispatch_event_handler!(dispatch_mouse_out, MouseOut, MOUSE_OUT_HANDLERS, false);
    dispatch_event_handler!(
        dispatch_double_click,
        DoubleClick,
        DOUBLE_CLICK_HANDLERS,
        true
    );
    dispatch_event_handler!(
        dispatch_context_menu,
        ContextMenu,
        CONTEXT_MENU_HANDLERS,
        true
    );
    fn dispatch_pointer_activation(
        self: &Rc<Self>,
        event: Event<Click>,
        source: PointerActivationSource,
        ctx: &Rc<RuntimeContext>,
    ) -> bool {
        let has_click = self.has_event_handlers(CLICK_HANDLERS);
        let has_tap = self.has_event_handlers(TAP_HANDLERS);
        let handler_key = match (has_click, has_tap, source) {
            (true, true, PointerActivationSource::Mouse) => Some(CLICK_HANDLERS),
            (true, true, PointerActivationSource::Touch) => Some(TAP_HANDLERS),
            (true, false, _) => Some(CLICK_HANDLERS),
            (false, true, _) => Some(TAP_HANDLERS),
            (false, false, _) => None,
        };

        if let Some(handler_key) = handler_key {
            self.run_event_handlers_for_key(handler_key, &event, ctx);
        }

        if let Some(parent) = self.template_parent.upgrade() {
            return parent.dispatch_pointer_activation(event, source, ctx);
        }
        event.cancelled()
    }

    pub fn dispatch_click(
        self: &Rc<Self>,
        event: Event<Click>,
        _globals: &Globals,
        ctx: &Rc<RuntimeContext>,
    ) -> bool {
        self.dispatch_pointer_activation(event, PointerActivationSource::Mouse, ctx)
    }

    pub fn dispatch_tap(
        self: &Rc<Self>,
        event: Event<Click>,
        _globals: &Globals,
        ctx: &Rc<RuntimeContext>,
    ) -> bool {
        self.dispatch_pointer_activation(event, PointerActivationSource::Touch, ctx)
    }

    dispatch_event_handler!(dispatch_wheel, Wheel, WHEEL_HANDLERS, true);
    dispatch_event_handler!(dispatch_drop, Drop, DROP_HANDLERS, true);
    dispatch_event_handler!(dispatch_gyro, Gyro, GYRO_HANDLERS, false);
    dispatch_event_handler!(dispatch_accel, Accel, ACCEL_HANDLERS, false);
    dispatch_event_handler!(dispatch_focus, Focus, FOCUSED_HANDLERS, false);
    dispatch_event_handler!(
        dispatch_select_start,
        SelectStart,
        SELECT_START_HANDLERS,
        false
    );

    pub fn dispatch_custom_event(
        self: &Rc<Self>,
        identifier: &str,
        ctx: &Rc<RuntimeContext>,
    ) -> Result<(), String> {
        if self.attached.get() == 0 {
            return Ok(());
        }
        let _graph = ctx.property_graph.enter();
        let component_origin_instance = borrow!(self.instance_node);
        let registry = component_origin_instance
            .base()
            .handler_registry
            .as_ref()
            .ok_or_else(|| "no registry present".to_owned())?;

        let parent_component = self
            .containing_component
            .upgrade()
            .ok_or_else(|| "can't dispatch from root (has no parent)".to_owned())?;
        if parent_component.attached.get() == 0 {
            return Ok(());
        }
        let _scope = parent_component.property_binding_scope.borrow().enter();
        let properties = borrow!(parent_component.properties);

        for handler in borrow!(registry)
            .handlers
            .get(identifier)
            .expect("presence should have been checked when added to custom_event_queue")
        {
            (handler.function)(Rc::clone(&*properties), &self.get_node_context(ctx), None)
        }
        Ok(())
    }

    // Sets measured bounds when the chassis or container layout resolves them empirically.
    pub fn set_measured_size(self: &Rc<ExpandedNode>, width: f64, height: f64) {
        self.measured_size.set(Some((width, height)));
    }

    // Backward-compatible alias used by chassis interrupt plumbing.
    pub fn chassis_resize_request(self: &Rc<ExpandedNode>, width: f64, height: f64) {
        self.set_measured_size(width, height);
    }

    /// Helper method that returns a collection of common properties
    /// related to layout (position, size, scale, anchor, etc),
    pub fn layout_properties(self: &Rc<ExpandedNode>) -> LocalProperty<LayoutProperties> {
        let common_props = self.get_common_properties();
        let common_props = borrow!(common_props);
        let cp_width = common_props.width.clone();
        let cp_height = common_props.height.clone();
        let cp_transform = common_props.transform.clone();
        let cp_anchor_x = common_props.anchor_x.clone();
        let cp_anchor_y = common_props.anchor_y.clone();
        let cp_scale_x = common_props.scale_x.clone();
        let cp_scale_y = common_props.scale_y.clone();
        let cp_skew_x = common_props.skew_x.clone();
        let cp_skew_y = common_props.skew_y.clone();
        let cp_rotate = common_props.rotate.clone();
        let cp_x = common_props.x.clone();
        let cp_y = common_props.y.clone();
        let measured_size = self.measured_size.clone();
        let deps = [
            cp_width.untyped(),
            cp_height.untyped(),
            cp_transform.untyped(),
            cp_anchor_x.untyped(),
            cp_anchor_y.untyped(),
            cp_scale_x.untyped(),
            cp_scale_y.untyped(),
            cp_skew_x.untyped(),
            cp_skew_y.untyped(),
            cp_rotate.untyped(),
            cp_x.untyped(),
            cp_y.untyped(),
            measured_size.untyped(),
        ];

        LocalProperty::computed(
            move || {
                // Used for auto sized text, might be used for other things later
                let fallback = measured_size.get();
                let (w_fallback, h_fallback) = match fallback {
                    Some((wf, hf)) => (Some(wf), Some(hf)),
                    None => (None, None),
                };

                LayoutProperties {
                    x: cp_x.get(),
                    y: cp_y.get(),
                    width: cp_width
                        .get()
                        .or(w_fallback.map(|v| Size::Pixels(v.into()))),
                    height: cp_height
                        .get()
                        .or(h_fallback.map(|v| Size::Pixels(v.into()))),
                    rotate: cp_rotate.get(),
                    // TODO make the common prop only accept percent
                    scale_x: cp_scale_x
                        .get()
                        .map(|v| Percent((100.0 * v.expect_percent()).into())),
                    scale_y: cp_scale_y
                        .get()
                        .map(|v| Percent((100.0 * v.expect_percent()).into())),
                    anchor_x: cp_anchor_x.get(),
                    anchor_y: cp_anchor_y.get(),
                    skew_x: cp_skew_x.get(),
                    skew_y: cp_skew_y.get(),
                }
            },
            &deps,
        )
    }
}

fn layout_axis_can_contribute(layout: &LayoutProperties, axis: Axis) -> bool {
    let size = match axis {
        Axis::X => layout.width,
        Axis::Y => layout.height,
    };
    let position = match axis {
        Axis::X => layout.x,
        Axis::Y => layout.y,
    };

    size.is_some_and(|size| !size_depends_on_parent(size))
        && !position.is_some_and(size_depends_on_parent)
}

fn layout_axis_can_contribute_from_parts(size: Option<Size>, position: Option<Size>) -> bool {
    size.is_some_and(|size| !size_depends_on_parent(size))
        && !position.is_some_and(size_depends_on_parent)
}

fn size_depends_on_parent(size: Size) -> bool {
    match size {
        Size::Pixels(_) => false,
        Size::Percent(percent) => percent.to_float().abs() > f64::EPSILON,
        Size::Combined(_, percent) => percent.to_float().abs() > f64::EPSILON,
    }
}

/// Given a projected child list, flatten away "slot-invisible" nodes (namely, `if` and `for`)
/// and return a top-level list of renderable projected children.
fn flatten_expanded_nodes_for_projection(nodes: &[Rc<ExpandedNode>]) -> Vec<Rc<ExpandedNode>> {
    let mut result: Vec<Rc<ExpandedNode>> = vec![];
    for node in nodes {
        if borrow!(node.instance_node).base().flags().invisible_to_slot {
            result.extend(flatten_expanded_nodes_for_projection(
                node.children
                    .get()
                    .clone()
                    .into_iter()
                    .collect::<Vec<_>>()
                    .as_slice(),
            ));
        } else {
            result.push(Rc::clone(&node))
        }
    }
    result
}

impl std::fmt::Debug for ExpandedNode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        //see: https://users.rust-lang.org/t/reusing-an-fmt-formatter/8531/4
        //maybe this utility should be moved to a more accessible place?
        pub struct Fmt<F>(pub F)
        where
            F: Fn(&mut fmt::Formatter) -> fmt::Result;

        impl<F> fmt::Debug for Fmt<F>
        where
            F: Fn(&mut fmt::Formatter) -> fmt::Result,
        {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                (self.0)(f)
            }
        }

        f.debug_struct("ExpandedNode")
            .field(
                "instance_node",
                &Fmt(|f| borrow!(self.instance_node).resolve_debug(f, Some(self))),
            )
            .field("id", &self.id)
            .field("common_properties", &borrow!(self.common_properties))
            .field("transform_and_bounds", &self.transform_and_bounds)
            .field("children", &self.children.get().iter().collect::<Vec<_>>())
            .field(
                "projected_children",
                &self
                    .expanded_and_flattened_projected_children
                    .get()
                    .iter()
                    .map(|v| v.id)
                    .collect::<Vec<_>>(),
            )
            .field("render_placement", &self.occlusion.get())
            .field(
                "containing_component",
                &self.containing_component.upgrade().map(|v| v.id.clone()),
            )
            .finish()
    }
}