azul-core 0.0.7

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

#[cfg(not(feature = "std"))]
use alloc::string::ToString;
use alloc::{boxed::Box, collections::btree_map::BTreeMap, string::String, vec::Vec};
use core::{
    fmt,
    hash::{Hash, Hasher},
    iter::FromIterator,
    mem,
    sync::atomic::{AtomicUsize, Ordering},
};

use azul_css::{
    css::{Css, NodeTypeTag},
    format_rust_code::GetHash,
    props::{
        basic::{FloatValue, FontRef},
        layout::{LayoutDisplay, LayoutFloat, LayoutPosition},
        property::CssProperty,
    },
    AzString, OptionString,
};

// Re-export event filters from events module (moved in Phase 3.5)
pub use crate::events::{
    ApplicationEventFilter, ComponentEventFilter, EventFilter, FocusEventFilter, HoverEventFilter,
    NotEventFilter, WindowEventFilter,
};
pub use crate::id::{Node, NodeHierarchy, NodeId};
use crate::{
    callbacks::{
        CoreCallback, CoreCallbackData, CoreCallbackDataVec, CoreCallbackType, IFrameCallback,
        IFrameCallbackType,
    },
    geom::LogicalPosition,
    id::{NodeDataContainer, NodeDataContainerRef, NodeDataContainerRefMut},
    menu::Menu,
    prop_cache::{CssPropertyCache, CssPropertyCachePtr},
    refany::{OptionRefAny, RefAny},
    resources::{
        image_ref_get_hash, CoreImageCallback, ImageMask, ImageRef, ImageRefHash, RendererResources,
    },
    styled_dom::{
        CompactDom, NodeHierarchyItemId, StyleFontFamilyHash, StyledDom, StyledNode,
        StyledNodeState,
    },
    window::OptionVirtualKeyCodeCombo,
};
pub use azul_css::dynamic_selector::{CssPropertyWithConditions, CssPropertyWithConditionsVec};

static TAG_ID: AtomicUsize = AtomicUsize::new(1);

/// Strongly-typed input element types for HTML `<input>` elements.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub enum InputType {
    /// Text input (default)
    Text,
    /// Button
    Button,
    /// Checkbox
    Checkbox,
    /// Color picker
    Color,
    /// Date picker
    Date,
    /// Date and time picker
    Datetime,
    /// Date and time picker (local)
    DatetimeLocal,
    /// Email address input
    Email,
    /// File upload
    File,
    /// Hidden input
    Hidden,
    /// Image button
    Image,
    /// Month picker
    Month,
    /// Number input
    Number,
    /// Password input
    Password,
    /// Radio button
    Radio,
    /// Range slider
    Range,
    /// Reset button
    Reset,
    /// Search input
    Search,
    /// Submit button
    Submit,
    /// Telephone number input
    Tel,
    /// Time picker
    Time,
    /// URL input
    Url,
    /// Week picker
    Week,
}

impl InputType {
    /// Returns the HTML attribute value for this input type
    pub const fn as_str(&self) -> &'static str {
        match self {
            InputType::Text => "text",
            InputType::Button => "button",
            InputType::Checkbox => "checkbox",
            InputType::Color => "color",
            InputType::Date => "date",
            InputType::Datetime => "datetime",
            InputType::DatetimeLocal => "datetime-local",
            InputType::Email => "email",
            InputType::File => "file",
            InputType::Hidden => "hidden",
            InputType::Image => "image",
            InputType::Month => "month",
            InputType::Number => "number",
            InputType::Password => "password",
            InputType::Radio => "radio",
            InputType::Range => "range",
            InputType::Reset => "reset",
            InputType::Search => "search",
            InputType::Submit => "submit",
            InputType::Tel => "tel",
            InputType::Time => "time",
            InputType::Url => "url",
            InputType::Week => "week",
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
#[repr(C)]
pub struct TagId {
    pub inner: u64,
}

impl ::core::fmt::Display for TagId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("TagId").field("inner", &self.inner).finish()
    }
}

impl_option!(
    TagId,
    OptionTagId,
    [Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash]
);

impl TagId {
    pub const fn into_crate_internal(&self) -> TagId {
        TagId { inner: self.inner }
    }
    pub const fn from_crate_internal(t: TagId) -> Self {
        TagId { inner: t.inner }
    }

    /// Creates a new, unique hit-testing tag ID.
    /// Wraps around to 1 on overflow (0 is reserved for "no tag").
    pub fn unique() -> Self {
        loop {
            let current = TAG_ID.load(Ordering::SeqCst);
            let next = if current == usize::MAX { 1 } else { current + 1 };
            if TAG_ID.compare_exchange(current, next, Ordering::SeqCst, Ordering::SeqCst).is_ok() {
                return TagId { inner: current as u64 };
            }
        }
    }
}

/// Same as the `TagId`, but only for scrollable nodes.
/// This provides a typed distinction for tags associated with scrolling containers.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
#[repr(C)]
pub struct ScrollTagId {
    pub inner: TagId,
}

impl ::core::fmt::Display for ScrollTagId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("ScrollTagId")
            .field("inner", &self.inner)
            .finish()
    }
}

impl ::core::fmt::Debug for ScrollTagId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self)
    }
}

impl ScrollTagId {
    /// Creates a new, unique scroll tag ID. Note that this should not
    /// be used for identifying nodes, use the `DomNodeHash` instead.
    pub fn unique() -> ScrollTagId {
        ScrollTagId {
            inner: TagId::unique(),
        }
    }
}

/// Orientation of a scrollbar.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub enum ScrollbarOrientation {
    Horizontal,
    Vertical,
}

/// Calculated hash of a DOM node, used for identifying identical DOM
/// nodes across frames for efficient diffing and state preservation.
#[derive(Copy, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
#[repr(C)]
pub struct DomNodeHash {
    pub inner: u64,
}

impl ::core::fmt::Debug for DomNodeHash {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "DomNodeHash({})", self.inner)
    }
}

/// List of core DOM node types built into `azul`.
/// This enum defines the building blocks of the UI, similar to HTML tags.
#[derive(Debug, Clone, PartialEq, Hash, Eq, PartialOrd, Ord)]
#[repr(C, u8)]
pub enum NodeType {
    // Root and container elements
    /// Root HTML element.
    Html,
    /// Document head (metadata container).
    Head,
    /// Root element of the document body.
    Body,
    /// Generic block-level container.
    Div,
    /// Paragraph.
    P,
    /// Article content.
    Article,
    /// Section of a document.
    Section,
    /// Navigation links.
    Nav,
    /// Sidebar/tangential content.
    Aside,
    /// Header section.
    Header,
    /// Footer section.
    Footer,
    /// Main content.
    Main,
    /// Figure with optional caption.
    Figure,
    /// Caption for figure element.
    FigCaption,
    /// Headings.
    H1,
    H2,
    H3,
    H4,
    H5,
    H6,
    /// Line break.
    Br,
    /// Horizontal rule.
    Hr,
    /// Preformatted text.
    Pre,
    /// Block quote.
    BlockQuote,
    /// Address.
    Address,
    /// Details disclosure widget.
    Details,
    /// Summary for details element.
    Summary,
    /// Dialog box or window.
    Dialog,

    // List elements
    /// Unordered list.
    Ul,
    /// Ordered list.
    Ol,
    /// List item.
    Li,
    /// Definition list.
    Dl,
    /// Definition term.
    Dt,
    /// Definition description.
    Dd,
    /// Menu list.
    Menu,
    /// Menu item.
    MenuItem,
    /// Directory list (deprecated).
    Dir,

    // Table elements
    /// Table container.
    Table,
    /// Table caption.
    Caption,
    /// Table header.
    THead,
    /// Table body.
    TBody,
    /// Table footer.
    TFoot,
    /// Table row.
    Tr,
    /// Table header cell.
    Th,
    /// Table data cell.
    Td,
    /// Table column group.
    ColGroup,
    /// Table column.
    Col,

    // Form elements
    /// Form container.
    Form,
    /// Form fieldset.
    FieldSet,
    /// Fieldset legend.
    Legend,
    /// Label for form controls.
    Label,
    /// Input control.
    Input,
    /// Button control.
    Button,
    /// Select dropdown.
    Select,
    /// Option group.
    OptGroup,
    /// Select option.
    SelectOption,
    /// Multiline text input.
    TextArea,
    /// Form output element.
    Output,
    /// Progress indicator.
    Progress,
    /// Scalar measurement within a known range.
    Meter,
    /// List of predefined options for input.
    DataList,

    // Inline elements
    /// Generic inline container.
    Span,
    /// Anchor/hyperlink.
    A,
    /// Emphasized text.
    Em,
    /// Strongly emphasized text.
    Strong,
    /// Bold text (deprecated - use `Dom::create_strong()` for semantic importance).
    B,
    /// Italic text (deprecated - use `Dom::create_em()` for emphasis or `Dom::create_cite()` for citations).
    I,
    /// Underline text.
    U,
    /// Strikethrough text.
    S,
    /// Marked/highlighted text.
    Mark,
    /// Deleted text.
    Del,
    /// Inserted text.
    Ins,
    /// Code.
    Code,
    /// Sample output.
    Samp,
    /// Keyboard input.
    Kbd,
    /// Variable.
    Var,
    /// Citation.
    Cite,
    /// Defining instance of a term.
    Dfn,
    /// Abbreviation.
    Abbr,
    /// Acronym.
    Acronym,
    /// Inline quotation.
    Q,
    /// Date/time.
    Time,
    /// Subscript.
    Sub,
    /// Superscript.
    Sup,
    /// Small text (deprecated - use CSS `font-size` instead).
    Small,
    /// Big text (deprecated - use CSS `font-size` instead).
    Big,
    /// Bi-directional override.
    Bdo,
    /// Bi-directional isolate.
    Bdi,
    /// Word break opportunity.
    Wbr,
    /// Ruby annotation.
    Ruby,
    /// Ruby text.
    Rt,
    /// Ruby text container.
    Rtc,
    /// Ruby parenthesis.
    Rp,
    /// Machine-readable data.
    Data,

    // Embedded content
    /// Canvas for graphics.
    Canvas,
    /// Embedded object.
    Object,
    /// Embedded object parameter.
    Param,
    /// External resource embed.
    Embed,
    /// Audio content.
    Audio,
    /// Video content.
    Video,
    /// Media source.
    Source,
    /// Text track for media.
    Track,
    /// Image map.
    Map,
    /// Image map area.
    Area,
    /// SVG graphics.
    Svg,

    // Metadata elements
    /// Document title.
    Title,
    /// Metadata.
    Meta,
    /// External resource link.
    Link,
    /// Embedded or referenced script.
    Script,
    /// Style information.
    Style,
    /// Base URL for relative URLs.
    Base,

    // Pseudo-elements (transformed into real elements)
    /// ::before pseudo-element.
    Before,
    /// ::after pseudo-element.
    After,
    /// ::marker pseudo-element.
    Marker,
    /// ::placeholder pseudo-element.
    Placeholder,

    // Special content types
    /// Text content, ::text
    Text(AzString),
    /// Image element, ::image
    Image(ImageRef),
    /// IFrame (embedded content)
    IFrame(IFrameNode),
    /// Icon element - resolved to actual content by IconProvider
    /// The string is the icon name (e.g., "home", "settings", "search")
    Icon(AzString),
}

impl NodeType {
    fn into_library_owned_nodetype(&self) -> Self {
        use self::NodeType::*;
        match self {
            Html => Html,
            Head => Head,
            Body => Body,
            Div => Div,
            P => P,
            Article => Article,
            Section => Section,
            Nav => Nav,
            Aside => Aside,
            Header => Header,
            Footer => Footer,
            Main => Main,
            Figure => Figure,
            FigCaption => FigCaption,
            H1 => H1,
            H2 => H2,
            H3 => H3,
            H4 => H4,
            H5 => H5,
            H6 => H6,
            Br => Br,
            Hr => Hr,
            Pre => Pre,
            BlockQuote => BlockQuote,
            Address => Address,
            Details => Details,
            Summary => Summary,
            Dialog => Dialog,
            Ul => Ul,
            Ol => Ol,
            Li => Li,
            Dl => Dl,
            Dt => Dt,
            Dd => Dd,
            Menu => Menu,
            MenuItem => MenuItem,
            Dir => Dir,
            Table => Table,
            Caption => Caption,
            THead => THead,
            TBody => TBody,
            TFoot => TFoot,
            Tr => Tr,
            Th => Th,
            Td => Td,
            ColGroup => ColGroup,
            Col => Col,
            Form => Form,
            FieldSet => FieldSet,
            Legend => Legend,
            Label => Label,
            Input => Input,
            Button => Button,
            Select => Select,
            OptGroup => OptGroup,
            SelectOption => SelectOption,
            TextArea => TextArea,
            Output => Output,
            Progress => Progress,
            Meter => Meter,
            DataList => DataList,
            Span => Span,
            A => A,
            Em => Em,
            Strong => Strong,
            B => B,
            I => I,
            U => U,
            S => S,
            Mark => Mark,
            Del => Del,
            Ins => Ins,
            Code => Code,
            Samp => Samp,
            Kbd => Kbd,
            Var => Var,
            Cite => Cite,
            Dfn => Dfn,
            Abbr => Abbr,
            Acronym => Acronym,
            Q => Q,
            Time => Time,
            Sub => Sub,
            Sup => Sup,
            Small => Small,
            Big => Big,
            Bdo => Bdo,
            Bdi => Bdi,
            Wbr => Wbr,
            Ruby => Ruby,
            Rt => Rt,
            Rtc => Rtc,
            Rp => Rp,
            Data => Data,
            Canvas => Canvas,
            Object => Object,
            Param => Param,
            Embed => Embed,
            Audio => Audio,
            Video => Video,
            Source => Source,
            Track => Track,
            Map => Map,
            Area => Area,
            Svg => Svg,
            Title => Title,
            Meta => Meta,
            Link => Link,
            Script => Script,
            Style => Style,
            Base => Base,
            Before => Before,
            After => After,
            Marker => Marker,
            Placeholder => Placeholder,

            Text(s) => Text(s.clone_self()),
            Image(i) => Image(i.clone()), // note: shallow clone
            IFrame(i) => IFrame(IFrameNode {
                callback: i.callback.clone(),
                refany: i.refany.clone(),
            }),
            Icon(s) => Icon(s.clone_self()),
        }
    }

    pub fn format(&self) -> Option<String> {
        use self::NodeType::*;
        match self {
            Text(s) => Some(format!("{}", s)),
            Image(id) => Some(format!("image({:?})", id)),
            IFrame(i) => Some(format!("iframe({:?})", i)),
            Icon(s) => Some(format!("icon({})", s)),
            _ => None,
        }
    }

    /// Returns the NodeTypeTag for CSS selector matching.
    pub fn get_path(&self) -> NodeTypeTag {
        match self {
            Self::Html => NodeTypeTag::Html,
            Self::Head => NodeTypeTag::Head,
            Self::Body => NodeTypeTag::Body,
            Self::Div => NodeTypeTag::Div,
            Self::P => NodeTypeTag::P,
            Self::Article => NodeTypeTag::Article,
            Self::Section => NodeTypeTag::Section,
            Self::Nav => NodeTypeTag::Nav,
            Self::Aside => NodeTypeTag::Aside,
            Self::Header => NodeTypeTag::Header,
            Self::Footer => NodeTypeTag::Footer,
            Self::Main => NodeTypeTag::Main,
            Self::Figure => NodeTypeTag::Figure,
            Self::FigCaption => NodeTypeTag::FigCaption,
            Self::H1 => NodeTypeTag::H1,
            Self::H2 => NodeTypeTag::H2,
            Self::H3 => NodeTypeTag::H3,
            Self::H4 => NodeTypeTag::H4,
            Self::H5 => NodeTypeTag::H5,
            Self::H6 => NodeTypeTag::H6,
            Self::Br => NodeTypeTag::Br,
            Self::Hr => NodeTypeTag::Hr,
            Self::Pre => NodeTypeTag::Pre,
            Self::BlockQuote => NodeTypeTag::BlockQuote,
            Self::Address => NodeTypeTag::Address,
            Self::Details => NodeTypeTag::Details,
            Self::Summary => NodeTypeTag::Summary,
            Self::Dialog => NodeTypeTag::Dialog,
            Self::Ul => NodeTypeTag::Ul,
            Self::Ol => NodeTypeTag::Ol,
            Self::Li => NodeTypeTag::Li,
            Self::Dl => NodeTypeTag::Dl,
            Self::Dt => NodeTypeTag::Dt,
            Self::Dd => NodeTypeTag::Dd,
            Self::Menu => NodeTypeTag::Menu,
            Self::MenuItem => NodeTypeTag::MenuItem,
            Self::Dir => NodeTypeTag::Dir,
            Self::Table => NodeTypeTag::Table,
            Self::Caption => NodeTypeTag::Caption,
            Self::THead => NodeTypeTag::THead,
            Self::TBody => NodeTypeTag::TBody,
            Self::TFoot => NodeTypeTag::TFoot,
            Self::Tr => NodeTypeTag::Tr,
            Self::Th => NodeTypeTag::Th,
            Self::Td => NodeTypeTag::Td,
            Self::ColGroup => NodeTypeTag::ColGroup,
            Self::Col => NodeTypeTag::Col,
            Self::Form => NodeTypeTag::Form,
            Self::FieldSet => NodeTypeTag::FieldSet,
            Self::Legend => NodeTypeTag::Legend,
            Self::Label => NodeTypeTag::Label,
            Self::Input => NodeTypeTag::Input,
            Self::Button => NodeTypeTag::Button,
            Self::Select => NodeTypeTag::Select,
            Self::OptGroup => NodeTypeTag::OptGroup,
            Self::SelectOption => NodeTypeTag::SelectOption,
            Self::TextArea => NodeTypeTag::TextArea,
            Self::Output => NodeTypeTag::Output,
            Self::Progress => NodeTypeTag::Progress,
            Self::Meter => NodeTypeTag::Meter,
            Self::DataList => NodeTypeTag::DataList,
            Self::Span => NodeTypeTag::Span,
            Self::A => NodeTypeTag::A,
            Self::Em => NodeTypeTag::Em,
            Self::Strong => NodeTypeTag::Strong,
            Self::B => NodeTypeTag::B,
            Self::I => NodeTypeTag::I,
            Self::U => NodeTypeTag::U,
            Self::S => NodeTypeTag::S,
            Self::Mark => NodeTypeTag::Mark,
            Self::Del => NodeTypeTag::Del,
            Self::Ins => NodeTypeTag::Ins,
            Self::Code => NodeTypeTag::Code,
            Self::Samp => NodeTypeTag::Samp,
            Self::Kbd => NodeTypeTag::Kbd,
            Self::Var => NodeTypeTag::Var,
            Self::Cite => NodeTypeTag::Cite,
            Self::Dfn => NodeTypeTag::Dfn,
            Self::Abbr => NodeTypeTag::Abbr,
            Self::Acronym => NodeTypeTag::Acronym,
            Self::Q => NodeTypeTag::Q,
            Self::Time => NodeTypeTag::Time,
            Self::Sub => NodeTypeTag::Sub,
            Self::Sup => NodeTypeTag::Sup,
            Self::Small => NodeTypeTag::Small,
            Self::Big => NodeTypeTag::Big,
            Self::Bdo => NodeTypeTag::Bdo,
            Self::Bdi => NodeTypeTag::Bdi,
            Self::Wbr => NodeTypeTag::Wbr,
            Self::Ruby => NodeTypeTag::Ruby,
            Self::Rt => NodeTypeTag::Rt,
            Self::Rtc => NodeTypeTag::Rtc,
            Self::Rp => NodeTypeTag::Rp,
            Self::Data => NodeTypeTag::Data,
            Self::Canvas => NodeTypeTag::Canvas,
            Self::Object => NodeTypeTag::Object,
            Self::Param => NodeTypeTag::Param,
            Self::Embed => NodeTypeTag::Embed,
            Self::Audio => NodeTypeTag::Audio,
            Self::Video => NodeTypeTag::Video,
            Self::Source => NodeTypeTag::Source,
            Self::Track => NodeTypeTag::Track,
            Self::Map => NodeTypeTag::Map,
            Self::Area => NodeTypeTag::Area,
            Self::Svg => NodeTypeTag::Svg,
            Self::Title => NodeTypeTag::Title,
            Self::Meta => NodeTypeTag::Meta,
            Self::Link => NodeTypeTag::Link,
            Self::Script => NodeTypeTag::Script,
            Self::Style => NodeTypeTag::Style,
            Self::Base => NodeTypeTag::Base,
            Self::Text(_) => NodeTypeTag::Text,
            Self::Image(_) => NodeTypeTag::Img,
            Self::IFrame(_) => NodeTypeTag::IFrame,
            Self::Icon(_) => NodeTypeTag::Icon,
            Self::Before => NodeTypeTag::Before,
            Self::After => NodeTypeTag::After,
            Self::Marker => NodeTypeTag::Marker,
            Self::Placeholder => NodeTypeTag::Placeholder,
        }
    }

    /// Returns whether this node type is a semantic HTML element that should
    /// automatically generate an accessibility tree node.
    ///
    /// These are elements with inherent semantic meaning that assistive
    /// technologies should be aware of, even without explicit ARIA attributes.
    pub const fn is_semantic_for_accessibility(&self) -> bool {
        matches!(
            self,
            Self::Button
                | Self::Input
                | Self::TextArea
                | Self::Select
                | Self::A
                | Self::H1
                | Self::H2
                | Self::H3
                | Self::H4
                | Self::H5
                | Self::H6
                | Self::Article
                | Self::Section
                | Self::Nav
                | Self::Main
                | Self::Header
                | Self::Footer
                | Self::Aside
        )
    }
}

/// Represents the CSS formatting context for an element
#[derive(Clone, PartialEq)]
pub enum FormattingContext {
    /// Block-level formatting context
    Block {
        /// Whether this element establishes a new block formatting context
        establishes_new_context: bool,
    },
    /// Inline-level formatting context
    Inline,
    /// Inline-block (participates in an IFC but creates a BFC)
    InlineBlock,
    /// Flex formatting context
    Flex,
    /// Float (left or right)
    Float(LayoutFloat),
    /// Absolutely positioned (out of flow)
    OutOfFlow(LayoutPosition),
    /// Table formatting context (container)
    Table,
    /// Table row group formatting context (thead, tbody, tfoot)
    TableRowGroup,
    /// Table row formatting context
    TableRow,
    /// Table cell formatting context (td, th)
    TableCell,
    /// Table column group formatting context
    TableColumnGroup,
    /// Table caption formatting context
    TableCaption,
    /// Grid formatting context
    Grid,
    /// No formatting context (display: none)
    None,
}

impl fmt::Debug for FormattingContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FormattingContext::Block {
                establishes_new_context,
            } => write!(
                f,
                "Block {{ establishes_new_context: {establishes_new_context:?} }}"
            ),
            FormattingContext::Inline => write!(f, "Inline"),
            FormattingContext::InlineBlock => write!(f, "InlineBlock"),
            FormattingContext::Flex => write!(f, "Flex"),
            FormattingContext::Float(layout_float) => write!(f, "Float({layout_float:?})"),
            FormattingContext::OutOfFlow(layout_position) => {
                write!(f, "OutOfFlow({layout_position:?})")
            }
            FormattingContext::Grid => write!(f, "Grid"),
            FormattingContext::None => write!(f, "None"),
            FormattingContext::Table => write!(f, "Table"),
            FormattingContext::TableRowGroup => write!(f, "TableRowGroup"),
            FormattingContext::TableRow => write!(f, "TableRow"),
            FormattingContext::TableCell => write!(f, "TableCell"),
            FormattingContext::TableColumnGroup => write!(f, "TableColumnGroup"),
            FormattingContext::TableCaption => write!(f, "TableCaption"),
        }
    }
}

impl Default for FormattingContext {
    fn default() -> Self {
        FormattingContext::Block {
            establishes_new_context: false,
        }
    }
}

/// Defines the type of event that can trigger a callback action.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub enum On {
    /// Mouse cursor is hovering over the element.
    MouseOver,
    /// Mouse cursor has is over element and is pressed
    /// (not good for "click" events - use `MouseUp` instead).
    MouseDown,
    /// (Specialization of `MouseDown`). Fires only if the left mouse button
    /// has been pressed while cursor was over the element.
    LeftMouseDown,
    /// (Specialization of `MouseDown`). Fires only if the middle mouse button
    /// has been pressed while cursor was over the element.
    MiddleMouseDown,
    /// (Specialization of `MouseDown`). Fires only if the right mouse button
    /// has been pressed while cursor was over the element.
    RightMouseDown,
    /// Mouse button has been released while cursor was over the element.
    MouseUp,
    /// (Specialization of `MouseUp`). Fires only if the left mouse button has
    /// been released while cursor was over the element.
    LeftMouseUp,
    /// (Specialization of `MouseUp`). Fires only if the middle mouse button has
    /// been released while cursor was over the element.
    MiddleMouseUp,
    /// (Specialization of `MouseUp`). Fires only if the right mouse button has
    /// been released while cursor was over the element.
    RightMouseUp,
    /// Mouse cursor has entered the element.
    MouseEnter,
    /// Mouse cursor has left the element.
    MouseLeave,
    /// Mousewheel / touchpad scrolling.
    Scroll,
    /// The window received a unicode character (also respects the system locale).
    /// Check `keyboard_state.current_char` to get the current pressed character.
    TextInput,
    /// A **virtual keycode** was pressed. Note: This is only the virtual keycode,
    /// not the actual char. If you want to get the character, use `TextInput` instead.
    /// A virtual key does not have to map to a printable character.
    ///
    /// You can get all currently pressed virtual keycodes in the
    /// `keyboard_state.current_virtual_keycodes` and / or just the last keycode in the
    /// `keyboard_state.latest_virtual_keycode`.
    VirtualKeyDown,
    /// A **virtual keycode** was release. See `VirtualKeyDown` for more info.
    VirtualKeyUp,
    /// A file has been dropped on the element.
    HoveredFile,
    /// A file is being hovered on the element.
    DroppedFile,
    /// A file was hovered, but has exited the window.
    HoveredFileCancelled,
    /// Equivalent to `onfocus`.
    FocusReceived,
    /// Equivalent to `onblur`.
    FocusLost,

    // Accessibility-specific events
    /// Default action triggered by screen reader (usually same as click/activate)
    Default,
    /// Element should collapse (e.g., accordion panel, tree node)
    Collapse,
    /// Element should expand (e.g., accordion panel, tree node)
    Expand,
    /// Increment value (e.g., number input, slider)
    Increment,
    /// Decrement value (e.g., number input, slider)
    Decrement,
}

// NOTE: EventFilter types moved to core/src/events.rs (Phase 3.5)
//
// The following types are now defined in events.rs and re-exported above:
// - EventFilter
// - HoverEventFilter
// - FocusEventFilter
// - WindowEventFilter
// - NotEventFilter
// - ComponentEventFilter
// - ApplicationEventFilter
//
// This consolidates all event-related logic in one place.

/// Contains the necessary information to render an embedded `IFrame` node.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct IFrameNode {
    /// The callback function that returns the DOM for the iframe's content.
    pub callback: IFrameCallback,
    /// The application data passed to the iframe's layout callback.
    pub refany: RefAny,
}

/// An enum that holds either a CSS ID or a class name as a string.
#[repr(C, u8)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum IdOrClass {
    Id(AzString),
    Class(AzString),
}

impl_option!(
    IdOrClass,
    OptionIdOrClass,
    copy = false,
    [Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord]
);

impl_vec!(IdOrClass, IdOrClassVec, IdOrClassVecDestructor, IdOrClassVecDestructorType, IdOrClassVecSlice, OptionIdOrClass);
impl_vec_debug!(IdOrClass, IdOrClassVec);
impl_vec_partialord!(IdOrClass, IdOrClassVec);
impl_vec_ord!(IdOrClass, IdOrClassVec);
impl_vec_clone!(IdOrClass, IdOrClassVec, IdOrClassVecDestructor);
impl_vec_partialeq!(IdOrClass, IdOrClassVec);
impl_vec_eq!(IdOrClass, IdOrClassVec);
impl_vec_hash!(IdOrClass, IdOrClassVec);

impl IdOrClass {
    pub fn as_id(&self) -> Option<&str> {
        match self {
            IdOrClass::Id(s) => Some(s.as_str()),
            IdOrClass::Class(_) => None,
        }
    }
    pub fn as_class(&self) -> Option<&str> {
        match self {
            IdOrClass::Class(s) => Some(s.as_str()),
            IdOrClass::Id(_) => None,
        }
    }
}

/// Name-value pair for custom attributes (data-*, aria-*, etc.)
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct AttributeNameValue {
    pub attr_name: AzString,
    pub value: AzString,
}

/// Strongly-typed HTML attribute with type-safe values.
///
/// This enum provides a type-safe way to represent HTML attributes, ensuring that
/// values are validated at compile-time and properly converted to their string
/// representations at runtime.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C, u8)]
pub enum AttributeType {
    /// Element ID attribute (`id="..."`)
    Id(AzString),
    /// CSS class attribute (`class="..."`)
    Class(AzString),
    /// Accessible name/label (`aria-label="..."`)
    AriaLabel(AzString),
    /// Element that labels this one (`aria-labelledby="..."`)
    AriaLabelledBy(AzString),
    /// Element that describes this one (`aria-describedby="..."`)
    AriaDescribedBy(AzString),
    /// Role for accessibility (`role="..."`)
    AriaRole(AzString),
    /// Current state of an element (`aria-checked`, `aria-selected`, etc.)
    AriaState(AttributeNameValue),
    /// ARIA property (`aria-*`)
    AriaProperty(AttributeNameValue),

    /// Hyperlink target URL (`href="..."`)
    Href(AzString),
    /// Link relationship (`rel="..."`)
    Rel(AzString),
    /// Link target frame (`target="..."`)
    Target(AzString),

    /// Image source URL (`src="..."`)
    Src(AzString),
    /// Alternative text for images (`alt="..."`)
    Alt(AzString),
    /// Image title (tooltip) (`title="..."`)
    Title(AzString),

    /// Form input name (`name="..."`)
    Name(AzString),
    /// Form input value (`value="..."`)
    Value(AzString),
    /// Input type (`type="text|password|email|..."`)
    InputType(AzString),
    /// Placeholder text (`placeholder="..."`)
    Placeholder(AzString),
    /// Input is required (`required`)
    Required,
    /// Input is disabled (`disabled`)
    Disabled,
    /// Input is readonly (`readonly`)
    Readonly,
    /// Input is checked (checkbox/radio) (`checked`)
    Checked,
    /// Input is selected (option) (`selected`)
    Selected,
    /// Maximum value for number inputs (`max="..."`)
    Max(AzString),
    /// Minimum value for number inputs (`min="..."`)
    Min(AzString),
    /// Step value for number inputs (`step="..."`)
    Step(AzString),
    /// Input pattern for validation (`pattern="..."`)
    Pattern(AzString),
    /// Minimum length (`minlength="..."`)
    MinLength(i32),
    /// Maximum length (`maxlength="..."`)
    MaxLength(i32),
    /// Autocomplete behavior (`autocomplete="on|off|..."`)
    Autocomplete(AzString),

    /// Table header scope (`scope="row|col|rowgroup|colgroup"`)
    Scope(AzString),
    /// Number of columns to span (`colspan="..."`)
    ColSpan(i32),
    /// Number of rows to span (`rowspan="..."`)
    RowSpan(i32),

    /// Tab index for keyboard navigation (`tabindex="..."`)
    TabIndex(i32),
    /// Element can receive focus (`tabindex="0"` equivalent)
    Focusable,

    /// Language code (`lang="..."`)
    Lang(AzString),
    /// Text direction (`dir="ltr|rtl|auto"`)
    Dir(AzString),

    /// Content is editable (`contenteditable="true|false"`)
    ContentEditable(bool),
    /// Element is draggable (`draggable="true|false"`)
    Draggable(bool),
    /// Element is hidden (`hidden`)
    Hidden,

    /// Generic data attribute (`data-*="..."`)
    Data(AttributeNameValue),
    /// Generic custom attribute (for future extensibility)
    Custom(AttributeNameValue),
}

impl_option!(
    AttributeType,
    OptionAttributeType,
    copy = false,
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);

impl_vec!(AttributeType, AttributeTypeVec, AttributeTypeVecDestructor, AttributeTypeVecDestructorType, AttributeTypeVecSlice, OptionAttributeType);
impl_vec_debug!(AttributeType, AttributeTypeVec);
impl_vec_partialord!(AttributeType, AttributeTypeVec);
impl_vec_ord!(AttributeType, AttributeTypeVec);
impl_vec_clone!(AttributeType, AttributeTypeVec, AttributeTypeVecDestructor);
impl_vec_partialeq!(AttributeType, AttributeTypeVec);
impl_vec_eq!(AttributeType, AttributeTypeVec);
impl_vec_hash!(AttributeType, AttributeTypeVec);

impl AttributeType {
    /// Get the attribute name (e.g., "href", "aria-label", "data-foo")
    pub fn name(&self) -> &str {
        match self {
            AttributeType::Id(_) => "id",
            AttributeType::Class(_) => "class",
            AttributeType::AriaLabel(_) => "aria-label",
            AttributeType::AriaLabelledBy(_) => "aria-labelledby",
            AttributeType::AriaDescribedBy(_) => "aria-describedby",
            AttributeType::AriaRole(_) => "role",
            AttributeType::AriaState(nv) => nv.attr_name.as_str(),
            AttributeType::AriaProperty(nv) => nv.attr_name.as_str(),
            AttributeType::Href(_) => "href",
            AttributeType::Rel(_) => "rel",
            AttributeType::Target(_) => "target",
            AttributeType::Src(_) => "src",
            AttributeType::Alt(_) => "alt",
            AttributeType::Title(_) => "title",
            AttributeType::Name(_) => "name",
            AttributeType::Value(_) => "value",
            AttributeType::InputType(_) => "type",
            AttributeType::Placeholder(_) => "placeholder",
            AttributeType::Required => "required",
            AttributeType::Disabled => "disabled",
            AttributeType::Readonly => "readonly",
            AttributeType::Checked => "checked",
            AttributeType::Selected => "selected",
            AttributeType::Max(_) => "max",
            AttributeType::Min(_) => "min",
            AttributeType::Step(_) => "step",
            AttributeType::Pattern(_) => "pattern",
            AttributeType::MinLength(_) => "minlength",
            AttributeType::MaxLength(_) => "maxlength",
            AttributeType::Autocomplete(_) => "autocomplete",
            AttributeType::Scope(_) => "scope",
            AttributeType::ColSpan(_) => "colspan",
            AttributeType::RowSpan(_) => "rowspan",
            AttributeType::TabIndex(_) => "tabindex",
            AttributeType::Focusable => "tabindex",
            AttributeType::Lang(_) => "lang",
            AttributeType::Dir(_) => "dir",
            AttributeType::ContentEditable(_) => "contenteditable",
            AttributeType::Draggable(_) => "draggable",
            AttributeType::Hidden => "hidden",
            AttributeType::Data(nv) => nv.attr_name.as_str(),
            AttributeType::Custom(nv) => nv.attr_name.as_str(),
        }
    }

    /// Get the attribute value as a string
    pub fn value(&self) -> AzString {
        match self {
            AttributeType::Id(v)
            | AttributeType::Class(v)
            | AttributeType::AriaLabel(v)
            | AttributeType::AriaLabelledBy(v)
            | AttributeType::AriaDescribedBy(v)
            | AttributeType::AriaRole(v)
            | AttributeType::Href(v)
            | AttributeType::Rel(v)
            | AttributeType::Target(v)
            | AttributeType::Src(v)
            | AttributeType::Alt(v)
            | AttributeType::Title(v)
            | AttributeType::Name(v)
            | AttributeType::Value(v)
            | AttributeType::InputType(v)
            | AttributeType::Placeholder(v)
            | AttributeType::Max(v)
            | AttributeType::Min(v)
            | AttributeType::Step(v)
            | AttributeType::Pattern(v)
            | AttributeType::Autocomplete(v)
            | AttributeType::Scope(v)
            | AttributeType::Lang(v)
            | AttributeType::Dir(v) => v.clone(),

            AttributeType::AriaState(nv)
            | AttributeType::AriaProperty(nv)
            | AttributeType::Data(nv)
            | AttributeType::Custom(nv) => nv.value.clone(),

            AttributeType::MinLength(n)
            | AttributeType::MaxLength(n)
            | AttributeType::ColSpan(n)
            | AttributeType::RowSpan(n)
            | AttributeType::TabIndex(n) => n.to_string().into(),

            AttributeType::Focusable => "0".into(),
            AttributeType::ContentEditable(b) | AttributeType::Draggable(b) => {
                if *b {
                    "true".into()
                } else {
                    "false".into()
                }
            }

            AttributeType::Required
            | AttributeType::Disabled
            | AttributeType::Readonly
            | AttributeType::Checked
            | AttributeType::Selected
            | AttributeType::Hidden => "".into(), // Boolean attributes
        }
    }

    /// Check if this is a boolean attribute (present = true, absent = false)
    pub fn is_boolean(&self) -> bool {
        matches!(
            self,
            AttributeType::Required
                | AttributeType::Disabled
                | AttributeType::Readonly
                | AttributeType::Checked
                | AttributeType::Selected
                | AttributeType::Hidden
        )
    }
}

/// Compact accessibility information for common use cases.
///
/// This is a lighter-weight alternative to `AccessibilityInfo` for cases where
/// only basic accessibility properties are needed. Developers must explicitly
/// pass `None` if they choose not to provide accessibility information.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[repr(C)]
pub struct SmallAriaInfo {
    /// Accessible label/name
    pub label: OptionString,
    /// Element's role (button, link, etc.)
    pub role: OptionAccessibilityRole,
    /// Additional description
    pub description: OptionString,
}

impl_option!(
    SmallAriaInfo,
    OptionSmallAriaInfo,
    copy = false,
    [Debug, Clone, PartialEq, Eq, Hash]
);

impl SmallAriaInfo {
    pub fn label<S: Into<AzString>>(text: S) -> Self {
        Self {
            label: OptionString::Some(text.into()),
            role: OptionAccessibilityRole::None,
            description: OptionString::None,
        }
    }

    pub fn with_role(mut self, role: AccessibilityRole) -> Self {
        self.role = OptionAccessibilityRole::Some(role);
        self
    }

    pub fn with_description<S: Into<AzString>>(mut self, desc: S) -> Self {
        self.description = OptionString::Some(desc.into());
        self
    }

    /// Convert to full `AccessibilityInfo`
    pub fn to_full_info(&self) -> AccessibilityInfo {
        AccessibilityInfo {
            accessibility_name: self.label.clone(),
            accessibility_value: OptionString::None,
            role: match self.role {
                OptionAccessibilityRole::Some(r) => r,
                OptionAccessibilityRole::None => AccessibilityRole::Unknown,
            },
            states: Vec::new().into(),
            accelerator: OptionVirtualKeyCodeCombo::None,
            default_action: OptionString::None,
            supported_actions: Vec::new().into(),
            is_live_region: false,
            labelled_by: OptionDomNodeId::None,
            described_by: OptionDomNodeId::None,
        }
    }
}

/// Represents all data associated with a single DOM node, such as its type,
/// classes, IDs, callbacks, and inline styles.
#[repr(C)]
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct NodeData {
    /// `div`, `p`, `img`, etc.
    pub node_type: NodeType,
    /// `data-*` attributes for this node, useful to store UI-related data on the node itself.
    pub dataset: OptionRefAny,
    /// Stores all ids and classes as one vec - size optimization since
    /// most nodes don't have any classes or IDs.
    pub ids_and_classes: IdOrClassVec,
    /// Strongly-typed HTML attributes (aria-*, href, alt, etc.)
    pub attributes: AttributeTypeVec,
    /// Callbacks attached to this node:
    ///
    /// `On::MouseUp` -> `Callback(my_button_click_handler)`
    pub callbacks: CoreCallbackDataVec,
    /// Conditional CSS properties with dynamic selectors.
    /// These are evaluated at runtime based on OS, viewport, container, theme, and pseudo-state.
    /// Uses "last wins" semantics - properties are evaluated in order, last match wins.
    pub css_props: CssPropertyWithConditionsVec,
    /// Tab index (commonly used property).
    pub tab_index: OptionTabIndex,
    /// Whether this node is contenteditable (accepts text input).
    /// Equivalent to HTML `contenteditable="true"` attribute.
    pub contenteditable: bool,
    /// Stores "extra", not commonly used data of the node: accessibility, clip-mask, tab-index,
    /// etc.
    ///
    /// SHOULD NOT EXPOSED IN THE API - necessary to retroactively add functionality
    /// to the node without breaking the ABI.
    extra: Option<Box<NodeDataExt>>,
}

impl_option!(
    NodeData,
    OptionNodeData,
    copy = false,
    [Debug, PartialEq, Eq, PartialOrd, Ord]
);

impl Hash for NodeData {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.node_type.hash(state);
        self.dataset.hash(state);
        self.ids_and_classes.as_ref().hash(state);
        self.attributes.as_ref().hash(state);
        self.contenteditable.hash(state);

        // NOTE: callbacks are NOT hashed regularly, otherwise
        // they'd cause inconsistencies because of the scroll callback
        for callback in self.callbacks.as_ref().iter() {
            callback.event.hash(state);
            callback.callback.hash(state);
            callback.refany.get_type_id().hash(state);
        }

        // Hash CSS props (conditional CSS with dynamic selectors)
        for prop in self.css_props.as_ref().iter() {
            // Hash property type as a simple discriminant
            core::mem::discriminant(&prop.property).hash(state);
        }
        if let Some(ext) = self.extra.as_ref() {
            if let Some(c) = ext.clip_mask.as_ref() {
                c.hash(state);
            }
            // Note: AccessibilityInfo doesn't implement Hash (has non-hashable fields)
            // Skipping accessibility field in hash
            if let Some(c) = ext.menu_bar.as_ref() {
                c.hash(state);
            }
            if let Some(c) = ext.context_menu.as_ref() {
                c.hash(state);
            }
        }
    }
}

/// NOTE: NOT EXPOSED IN THE API! Stores extra,
/// not commonly used information for the NodeData.
/// This helps keep the primary `NodeData` struct smaller for common cases.
#[repr(C)]
#[derive(Debug, Default, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub struct NodeDataExt {
    /// Optional clip mask for this DOM node.
    pub clip_mask: Option<ImageMask>,
    /// Optional extra accessibility information about this DOM node (MSAA, AT-SPI, UA).
    pub accessibility: Option<Box<AccessibilityInfo>>,
    /// Menu bar that should be displayed at the top of this nodes rect.
    pub menu_bar: Option<Box<Menu>>,
    /// Context menu that should be opened when the item is left-clicked.
    pub context_menu: Option<Box<Menu>>,
    /// Whether this node is an anonymous box (generated for table layout).
    /// Anonymous boxes are not part of the original DOM tree and are created
    /// by the layout engine to satisfy table layout requirements (e.g., wrapping
    /// non-table children of table elements in anonymous table-row/table-cell boxes).
    pub is_anonymous: bool,
    /// Stable key for reconciliation. If provided, allows the framework to track
    /// this node across frames even if its position in the array changes.
    /// This is crucial for correct lifecycle events when lists are reordered.
    pub key: Option<u64>,
    /// Callback to merge dataset state from a previous frame's node into the current node.
    /// This enables heavy resource preservation (video decoders, GL textures) across frames.
    pub dataset_merge_callback: Option<DatasetMergeCallback>,
    // ... insert further API extensions here...
}

/// A callback function used to merge the state of an old dataset into a new one.
///
/// This enables components with heavy internal state (video players, WebGL contexts)
/// to preserve their resources across frames, while the DOM tree is recreated.
///
/// The callback receives both the old and new datasets as `RefAny` (cheap shallow clones)
/// and returns the dataset that should be used for the new node.
///
/// # Example
///
/// ```rust,ignore
/// fn merge_video_state(new_data: RefAny, old_data: RefAny) -> RefAny {
///     // Transfer heavy resources from old to new
///     if let (Some(mut new), Some(old)) = (
///         new_data.downcast_mut::<VideoState>(),
///         old_data.downcast_ref::<VideoState>()
///     ) {
///         new.decoder = old.decoder.take();
///         new.gl_texture = old.gl_texture.take();
///     }
///     new_data // Return the merged state
/// }
/// ```
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub struct DatasetMergeCallback {
    /// The function pointer that performs the merge.
    /// Signature: `fn(new_data: RefAny, old_data: RefAny) -> RefAny`
    pub cb: DatasetMergeCallbackType,
    /// Optional callable for FFI language bindings (Python, etc.)
    /// When set, the FFI layer can invoke this instead of `cb`.
    pub callable: OptionRefAny,
}

impl core::fmt::Debug for DatasetMergeCallback {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DatasetMergeCallback")
            .field("cb", &(self.cb as usize))
            .field("callable", &self.callable)
            .finish()
    }
}

/// Allow creating DatasetMergeCallback from a raw function pointer.
/// This enables the `Into<DatasetMergeCallback>` pattern for Python bindings.
impl From<DatasetMergeCallbackType> for DatasetMergeCallback {
    fn from(cb: DatasetMergeCallbackType) -> Self {
        DatasetMergeCallback { 
            cb,
            callable: OptionRefAny::None,
        }
    }
}

impl_option!(
    DatasetMergeCallback,
    OptionDatasetMergeCallback,
    copy = false,
    [Debug, Clone]
);

/// Function pointer type for dataset merge callbacks.
/// 
/// Arguments:
/// - `new_data`: The new node's dataset (shallow clone, cheap)
/// - `old_data`: The old node's dataset (shallow clone, cheap)
/// 
/// Returns:
/// - The `RefAny` that should be used as the dataset for the new node
pub type DatasetMergeCallbackType = extern "C" fn(RefAny, RefAny) -> RefAny;

/// Holds information about a UI element for accessibility purposes (e.g., screen readers).
/// This is a wrapper for platform-specific accessibility APIs like MSAA.
#[derive(Debug, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
#[repr(C)]
pub struct AccessibilityInfo {
    /// Get the "name" of the `IAccessible`, for example the
    /// name of a button, checkbox or menu item. Try to use unique names
    /// for each item in a dialog so that voice dictation software doesn't
    /// have to deal with extra ambiguity.
    pub accessibility_name: OptionString,
    /// Get the "value" of the `IAccessible`, for example a number in a slider,
    /// a URL for a link, the text a user entered in a field.
    pub accessibility_value: OptionString,
    /// Get an enumerated value representing what this IAccessible is used for,
    /// for example is it a link, static text, editable text, a checkbox, or a table cell, etc.
    pub role: AccessibilityRole,
    /// Possible on/off states, such as focused, focusable, selected, selectable,
    /// visible, protected (for passwords), checked, etc.
    pub states: AccessibilityStateVec,
    /// Optional keyboard accelerator.
    pub accelerator: OptionVirtualKeyCodeCombo,
    /// Optional "default action" description. Only used when there is at least
    /// one `ComponentEventFilter::DefaultAction` callback present on this node.
    pub default_action: OptionString,
    /// A list of actions the user can perform on this element.
    /// Maps to accesskit's Action enum.
    pub supported_actions: AccessibilityActionVec,
    /// For live regions that update automatically (e.g., chat messages, timers).
    /// Maps to accesskit's `Live` property.
    pub is_live_region: bool,
    /// ID of another node that labels this one (for `aria-labelledby`).
    pub labelled_by: OptionDomNodeId,
    /// ID of another node that describes this one (for `aria-describedby`).
    pub described_by: OptionDomNodeId,
}

/// Actions that can be performed on an accessible element.
/// This is a simplified version of accesskit::Action to avoid direct dependency in core.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C, u8)]
pub enum AccessibilityAction {
    /// The default action for the element (usually a click).
    Default,
    /// Set focus to this element.
    Focus,
    /// Remove focus from this element.
    Blur,
    /// Collapse an expandable element (e.g., tree node, accordion).
    Collapse,
    /// Expand a collapsible element (e.g., tree node, accordion).
    Expand,
    /// Scroll this element into view.
    ScrollIntoView,
    /// Increment a numeric value (e.g., slider, spinner).
    Increment,
    /// Decrement a numeric value (e.g., slider, spinner).
    Decrement,
    /// Show a context menu.
    ShowContextMenu,
    /// Hide a tooltip.
    HideTooltip,
    /// Show a tooltip.
    ShowTooltip,
    /// Scroll up.
    ScrollUp,
    /// Scroll down.
    ScrollDown,
    /// Scroll left.
    ScrollLeft,
    /// Scroll right.
    ScrollRight,
    /// Replace selected text with new text.
    ReplaceSelectedText(AzString),
    /// Scroll to a specific point.
    ScrollToPoint(LogicalPosition),
    /// Set scroll offset.
    SetScrollOffset(LogicalPosition),
    /// Set text selection.
    SetTextSelection(TextSelectionStartEnd),
    /// Set sequential focus navigation starting point.
    SetSequentialFocusNavigationStartingPoint,
    /// Set the value of a control.
    SetValue(AzString),
    /// Set numeric value of a control.
    SetNumericValue(FloatValue),
    /// Custom action with ID.
    CustomAction(i32),
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct TextSelectionStartEnd {
    pub selection_start: usize,
    pub selection_end: usize,
}

impl_vec!(AccessibilityAction, AccessibilityActionVec, AccessibilityActionVecDestructor, AccessibilityActionVecDestructorType, AccessibilityActionVecSlice, OptionAccessibilityAction);
impl_vec_debug!(AccessibilityAction, AccessibilityActionVec);
impl_vec_clone!(
    AccessibilityAction,
    AccessibilityActionVec,
    AccessibilityActionVecDestructor
);
impl_vec_partialeq!(AccessibilityAction, AccessibilityActionVec);
impl_vec_eq!(AccessibilityAction, AccessibilityActionVec);
impl_vec_partialord!(AccessibilityAction, AccessibilityActionVec);
impl_vec_ord!(AccessibilityAction, AccessibilityActionVec);
impl_vec_hash!(AccessibilityAction, AccessibilityActionVec);

impl_option![
    AccessibilityAction,
    OptionAccessibilityAction,
    copy = false,
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
];

impl_option!(
    AccessibilityInfo,
    OptionAccessibilityInfo,
    copy = false,
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);

/// Defines the element's purpose for accessibility APIs, informing assistive technologies
/// like screen readers about the function of a UI element. Each variant corresponds to a
/// standard control type or UI structure.
///
/// For more details, see the [MSDN Role Constants page](https://docs.microsoft.com/en-us/windows/winauto/object-roles).
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub enum AccessibilityRole {
    /// Represents the title or caption bar of a window.
    /// - **Purpose**: To identify the title bar containing the window title and system commands.
    /// - **When to use**: This role is typically inserted by the operating system for standard
    ///   windows.
    /// - **Example**: The bar at the top of an application window displaying its name and the
    ///   minimize, maximize, and close buttons.
    TitleBar,

    /// Represents a menu bar at the top of a window.
    /// - **Purpose**: To contain a set of top-level menus for an application.
    /// - **When to use**: For the main menu bar of an application, such as one containing "File,"
    ///   "Edit," and "View."
    /// - **Example**: The "File", "Edit", "View" menu bar at the top of a text editor.
    MenuBar,

    /// Represents a vertical or horizontal scroll bar.
    /// - **Purpose**: To enable scrolling through content that is larger than the visible area.
    /// - **When to use**: For any scrollable region of content.
    /// - **Example**: The bar on the side of a web page that allows the user to scroll up and
    ///   down.
    ScrollBar,

    /// Represents a handle or grip used for moving or resizing.
    /// - **Purpose**: To provide a user interface element for manipulating another element's size
    ///   or position.
    /// - **When to use**: For handles that allow resizing of windows, panes, or other objects.
    /// - **Example**: The small textured area in the bottom-right corner of a window that can be
    ///   dragged to resize it.
    Grip,

    /// Represents a system sound indicating an event.
    /// - **Purpose**: To associate a sound with a UI event, providing an auditory cue.
    /// - **When to use**: When a sound is the primary representation of an event.
    /// - **Example**: A system notification sound that plays when a new message arrives.
    Sound,

    /// Represents the system's mouse pointer or other pointing device.
    /// - **Purpose**: To indicate the screen position of the user's pointing device.
    /// - **When to use**: This role is managed by the operating system.
    /// - **Example**: The arrow that moves on the screen as you move the mouse.
    Cursor,

    /// Represents the text insertion point indicator.
    /// - **Purpose**: To show the current text entry or editing position.
    /// - **When to use**: This role is typically managed by the operating system for text input
    ///   fields.
    /// - **Example**: The blinking vertical line in a text box that shows where the next character
    ///   will be typed.
    Caret,

    /// Represents an alert or notification.
    /// - **Purpose**: To convey an important, non-modal message to the user.
    /// - **When to use**: For non-intrusive notifications that do not require immediate user
    ///   interaction.
    /// - **Example**: A small, temporary "toast" notification that appears to confirm an action,
    ///   like "Email sent."
    Alert,

    /// Represents a window frame.
    /// - **Purpose**: To serve as the container for other objects like a title bar and client
    ///   area.
    /// - **When to use**: This is a fundamental role, typically managed by the windowing system.
    /// - **Example**: The main window of any application, which contains all other UI elements.
    Window,

    /// Represents a window's client area, where the main content is displayed.
    /// - **Purpose**: To define the primary content area of a window.
    /// - **When to use**: For the main content region of a window. It's often the default role for
    ///   a custom control container.
    /// - **Example**: The area of a web browser where the web page content is rendered.
    Client,

    /// Represents a pop-up menu.
    /// - **Purpose**: To display a list of `MenuItem` objects that appears when a user performs an
    ///   action.
    /// - **When to use**: For context menus (right-click menus) or drop-down menus.
    /// - **Example**: The menu that appears when you right-click on a file in a file explorer.
    MenuPopup,

    /// Represents an individual item within a menu.
    /// - **Purpose**: To represent a single command, option, or separator within a menu.
    /// - **When to use**: For individual options inside a `MenuBar` or `MenuPopup`.
    /// - **Example**: The "Save" option within the "File" menu.
    MenuItem,

    /// Represents a small pop-up window that provides information.
    /// - **Purpose**: To offer brief, contextual help or information about a UI element.
    /// - **When to use**: For informational pop-ups that appear on mouse hover.
    /// - **Example**: The small box of text that appears when you hover over a button in a
    ///   toolbar.
    Tooltip,

    /// Represents the main window of an application.
    /// - **Purpose**: To identify the top-level window of an application.
    /// - **When to use**: For the primary window that represents the application itself.
    /// - **Example**: The main window of a calculator or notepad application.
    Application,

    /// Represents a document window within an application.
    /// - **Purpose**: To represent a contained document, typically in a Multiple Document
    ///   Interface (MDI) application.
    /// - **When to use**: For individual document windows inside a larger application shell.
    /// - **Example**: In a photo editor that allows multiple images to be open in separate
    ///   windows, each image window would be a `Document`.
    Document,

    /// Represents a pane or a distinct section of a window.
    /// - **Purpose**: To divide a window into visually and functionally distinct areas.
    /// - **When to use**: For sub-regions of a window, like a navigation pane, preview pane, or
    ///   sidebar.
    /// - **Example**: The preview pane in an email client that shows the content of the selected
    ///   email.
    Pane,

    /// Represents a graphical chart or graph.
    /// - **Purpose**: To display data visually in a chart format.
    /// - **When to use**: For any type of chart, such as a bar chart, line chart, or pie chart.
    /// - **Example**: A bar chart displaying monthly sales figures.
    Chart,

    /// Represents a dialog box or message box.
    /// - **Purpose**: To create a secondary window that requires user interaction before returning
    ///   to the main application.
    /// - **When to use**: For modal or non-modal windows that prompt the user for information or a
    ///   response.
    /// - **Example**: The "Open File" or "Print" dialog in most applications.
    Dialog,

    /// Represents a window's border.
    /// - **Purpose**: To identify the border of a window, which is often used for resizing.
    /// - **When to use**: This role is typically managed by the windowing system.
    /// - **Example**: The decorative and functional frame around a window.
    Border,

    /// Represents a group of related controls.
    /// - **Purpose**: To logically group other objects that share a common purpose.
    /// - **When to use**: For grouping controls like a set of radio buttons or a fieldset with a
    ///   legend.
    /// - **Example**: A "Settings" group box in a dialog that contains several related checkboxes.
    Grouping,

    /// Represents a visual separator.
    /// - **Purpose**: To visually divide a space or a group of controls.
    /// - **When to use**: For visual separators in menus, toolbars, or between panes.
    /// - **Example**: The horizontal line in a menu that separates groups of related menu items.
    Separator,

    /// Represents a toolbar containing a group of controls.
    /// - **Purpose**: To group controls, typically buttons, for quick access to frequently used
    ///   functions.
    /// - **When to use**: For a bar of buttons or other controls, usually at the top of a window
    ///   or pane.
    /// - **Example**: The toolbar at the top of a word processor with buttons for "Bold,"
    ///   "Italic," and "Underline."
    Toolbar,

    /// Represents a status bar for displaying information.
    /// - **Purpose**: To display status information about the current state of the application.
    /// - **When to use**: For a bar, typically at the bottom of a window, that displays messages.
    /// - **Example**: The bar at the bottom of a web browser that shows the loading status of a
    ///   page.
    StatusBar,

    /// Represents a data table.
    /// - **Purpose**: To present data in a two-dimensional grid of rows and columns.
    /// - **When to use**: For grid-like data presentation.
    /// - **Example**: A spreadsheet or a table of data in a database application.
    Table,

    /// Represents a column header in a table.
    /// - **Purpose**: To provide a label for a column of data.
    /// - **When to use**: For the headers of columns in a `Table`.
    /// - **Example**: The header row in a spreadsheet with labels like "Name," "Date," and
    ///   "Amount."
    ColumnHeader,

    /// Represents a row header in a table.
    /// - **Purpose**: To provide a label for a row of data.
    /// - **When to use**: For the headers of rows in a `Table`.
    /// - **Example**: The numbered rows on the left side of a spreadsheet.
    RowHeader,

    /// Represents a full column of cells in a table.
    /// - **Purpose**: To represent an entire column as a single accessible object.
    /// - **When to use**: When it is useful to interact with a column as a whole.
    /// - **Example**: The "Amount" column in a financial data table.
    Column,

    /// Represents a full row of cells in a table.
    /// - **Purpose**: To represent an entire row as a single accessible object.
    /// - **When to use**: When it is useful to interact with a row as a whole.
    /// - **Example**: A row representing a single customer's information in a customer list.
    Row,

    /// Represents a single cell within a table.
    /// - **Purpose**: To represent a single data point or control within a `Table`.
    /// - **When to use**: For individual cells in a grid or table.
    /// - **Example**: A single cell in a spreadsheet containing a specific value.
    Cell,

    /// Represents a hyperlink to a resource.
    /// - **Purpose**: To provide a navigational link to another document or location.
    /// - **When to use**: For text or images that, when clicked, navigate to another resource.
    /// - **Example**: A clickable link on a web page.
    Link,

    /// Represents a help balloon or pop-up.
    /// - **Purpose**: To provide more detailed help information than a standard tooltip.
    /// - **When to use**: For a pop-up that offers extended help text, often initiated by a help
    ///   button.
    /// - **Example**: A pop-up balloon with a paragraph of help text that appears when a user
    ///   clicks a help icon.
    HelpBalloon,

    /// Represents an animated, character-like graphic object.
    /// - **Purpose**: To provide an animated agent for user assistance or entertainment.
    /// - **When to use**: For animated characters or avatars that provide help or guidance.
    /// - **Example**: An animated paperclip that offers tips in a word processor (e.g.,
    ///   Microsoft's Clippy).
    Character,

    /// Represents a list of items.
    /// - **Purpose**: To contain a set of `ListItem` objects.
    /// - **When to use**: For list boxes or similar controls that present a list of selectable
    ///   items.
    /// - **Example**: The list of files in a file selection dialog.
    List,

    /// Represents an individual item within a list.
    /// - **Purpose**: To represent a single, selectable item within a `List`.
    /// - **When to use**: For each individual item in a list box or combo box.
    /// - **Example**: A single file name in a list of files.
    ListItem,

    /// Represents an outline or tree structure.
    /// - **Purpose**: To display a hierarchical view of data.
    /// - **When to use**: For tree-view controls that show nested items.
    /// - **Example**: A file explorer's folder tree view.
    Outline,

    /// Represents an individual item within an outline or tree.
    /// - **Purpose**: To represent a single node (which can be a leaf or a branch) in an
    ///   `Outline`.
    /// - **When to use**: For each node in a tree view.
    /// - **Example**: A single folder in a file explorer's tree view.
    OutlineItem,

    /// Represents a single tab in a tabbed interface.
    /// - **Purpose**: To provide a control for switching between different `PropertyPage` views.
    /// - **When to use**: For the individual tabs that the user can click to switch pages.
    /// - **Example**: The "General" and "Security" tabs in a file properties dialog.
    PageTab,

    /// Represents the content of a page in a property sheet.
    /// - **Purpose**: To serve as a container for the controls displayed when a `PageTab` is
    ///   selected.
    /// - **When to use**: For the content area associated with a specific tab.
    /// - **Example**: The set of options displayed when the "Security" tab is active.
    PropertyPage,

    /// Represents a visual indicator, like a slider thumb.
    /// - **Purpose**: To visually indicate the current value or position of another control.
    /// - **When to use**: For a sub-element that indicates status, like the thumb of a scrollbar.
    /// - **Example**: The draggable thumb of a scrollbar that indicates the current scroll
    ///   position.
    Indicator,

    /// Represents a picture or graphical image.
    /// - **Purpose**: To display a non-interactive image.
    /// - **When to use**: For images and icons that are purely decorative or informational.
    /// - **Example**: A company logo displayed in an application's "About" dialog.
    Graphic,

    /// Represents read-only text.
    /// - **Purpose**: To provide a non-editable text label for another control or for displaying
    ///   information.
    /// - **When to use**: For text that the user cannot edit.
    /// - **Example**: The label "Username:" next to a text input field.
    StaticText,

    /// Represents editable text or a text area.
    /// - **Purpose**: To allow for user text input or selection.
    /// - **When to use**: For text input fields where the user can type.
    /// - **Example**: A text box for entering a username or password.
    Text,

    /// Represents a standard push button.
    /// - **Purpose**: To initiate an immediate action.
    /// - **When to use**: For standard buttons that perform an action when clicked.
    /// - **Example**: An "OK" or "Cancel" button in a dialog.
    PushButton,

    /// Represents a check box control.
    /// - **Purpose**: To allow the user to make a binary choice (checked or unchecked).
    /// - **When to use**: For options that can be toggled on or off independently.
    /// - **Example**: A "Remember me" checkbox on a login form.
    CheckButton,

    /// Represents a radio button.
    /// - **Purpose**: To allow the user to select one option from a mutually exclusive group.
    /// - **When to use**: For a choice where only one option from a `Grouping` can be selected.
    /// - **Example**: "Male" and "Female" radio buttons for selecting gender.
    RadioButton,

    /// Represents a combination of a text field and a drop-down list.
    /// - **Purpose**: To allow the user to either type a value or select one from a list.
    /// - **When to use**: For controls that offer a list of suggestions but also allow custom
    ///   input.
    /// - **Example**: A font selector that allows you to type a font name or choose one from a
    ///   list.
    ComboBox,

    /// Represents a drop-down list box.
    /// - **Purpose**: To allow the user to select an item from a non-editable list that drops
    ///   down.
    /// - **When to use**: For selecting a single item from a predefined list of options.
    /// - **Example**: A country selection drop-down menu.
    DropList,

    /// Represents a progress bar.
    /// - **Purpose**: To indicate the progress of a lengthy operation.
    /// - **When to use**: To provide feedback for tasks like file downloads or installations.
    /// - **Example**: The bar that fills up to show the progress of a file copy operation.
    ProgressBar,

    /// Represents a dial or knob.
    /// - **Purpose**: To allow selecting a value from a continuous or discrete range, often
    ///   circularly.
    /// - **When to use**: For controls that resemble real-world dials, like a volume knob.
    /// - **Example**: A volume control knob in a media player application.
    Dial,

    /// Represents a control for entering a keyboard shortcut.
    /// - **Purpose**: To capture a key combination from the user.
    /// - **When to use**: In settings where users can define their own keyboard shortcuts.
    /// - **Example**: A text field in a settings dialog where a user can press a key combination
    ///   to assign it to a command.
    HotkeyField,

    /// Represents a slider for selecting a value within a range.
    /// - **Purpose**: To allow the user to adjust a setting along a continuous or discrete range.
    /// - **When to use**: For adjusting values like volume, brightness, or zoom level.
    /// - **Example**: A slider to control the volume of a video.
    Slider,

    /// Represents a spin button (up/down arrows) for incrementing or decrementing a value.
    /// - **Purpose**: To provide fine-tuned adjustment of a value, typically numeric.
    /// - **When to use**: For controls that allow stepping through a range of values.
    /// - **Example**: The up and down arrows next to a number input for setting the font size.
    SpinButton,

    /// Represents a diagram or flowchart.
    /// - **Purpose**: To represent data or relationships in a schematic form.
    /// - **When to use**: For visual representations of structures that are not charts, like a
    ///   database schema diagram.
    /// - **Example**: A flowchart illustrating a business process.
    Diagram,

    /// Represents an animation control.
    /// - **Purpose**: To display a sequence of images or indicate an ongoing process.
    /// - **When to use**: For animations that show that an operation is in progress.
    /// - **Example**: The animation that plays while files are being copied.
    Animation,

    /// Represents a mathematical equation.
    /// - **Purpose**: To display a mathematical formula in the correct format.
    /// - **When to use**: For displaying mathematical equations.
    /// - **Example**: A rendered mathematical equation in a scientific document editor.
    Equation,

    /// Represents a button that drops down a list of items.
    /// - **Purpose**: To combine a default action button with a list of alternative actions.
    /// - **When to use**: For buttons that have a primary action and a secondary list of options.
    /// - **Example**: A "Send" button with a dropdown arrow that reveals "Send and Archive."
    ButtonDropdown,

    /// Represents a button that drops down a full menu.
    /// - **Purpose**: To provide a button that opens a menu of choices rather than performing a
    ///   single action.
    /// - **When to use**: When a button's primary purpose is to reveal a menu.
    /// - **Example**: A "Tools" button that opens a menu with various tool options.
    ButtonMenu,

    /// Represents a button that drops down a grid for selection.
    /// - **Purpose**: To allow selection from a two-dimensional grid of options.
    /// - **When to use**: For buttons that open a grid-based selection UI.
    /// - **Example**: A color picker button that opens a grid of color swatches.
    ButtonDropdownGrid,

    /// Represents blank space between other objects.
    /// - **Purpose**: To represent significant empty areas in a UI that are part of the layout.
    /// - **When to use**: Sparingly, to signify that a large area is intentionally blank.
    /// - **Example**: A large empty panel in a complex layout might use this role.
    Whitespace,

    /// Represents the container for a set of tabs.
    /// - **Purpose**: To group a set of `PageTab` elements.
    /// - **When to use**: To act as the parent container for a row or column of tabs.
    /// - **Example**: The entire row of tabs at the top of a properties dialog.
    PageTabList,

    /// Represents a clock control.
    /// - **Purpose**: To display the current time.
    /// - **When to use**: For any UI element that displays time.
    /// - **Example**: The clock in the system tray of the operating system.
    Clock,

    /// Represents a button with two parts: a default action and a dropdown.
    /// - **Purpose**: To combine a frequently used action with a set of related, less-used
    ///   actions.
    /// - **When to use**: When a button has a default action and other related actions available
    ///   in a dropdown.
    /// - **Example**: A "Save" split button where the primary part saves, and the dropdown offers
    ///   "Save As."
    SplitButton,

    /// Represents a control for entering an IP address.
    /// - **Purpose**: To provide a specialized input field for IP addresses, often with formatting
    ///   and validation.
    /// - **When to use**: For dedicated IP address input fields.
    /// - **Example**: A network configuration dialog with a field for entering a static IP
    ///   address.
    IpAddress,

    /// Represents an element with no specific role.
    /// - **Purpose**: To indicate an element that has no semantic meaning for accessibility.
    /// - **When to use**: Should be used sparingly for purely decorative elements that should be
    ///   ignored by assistive technologies.
    /// - **Example**: A decorative graphical flourish that has no function or information to
    ///   convey.
    Nothing,

    /// Unknown or unspecified role.
    /// - **Purpose**: Default fallback when no specific role is assigned.
    /// - **When to use**: As a default value or when role information is unavailable.
    Unknown,
}

impl_option!(
    AccessibilityRole,
    OptionAccessibilityRole,
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);

/// Defines the current state of an element for accessibility APIs (e.g., focused, checked).
/// These states provide dynamic information to assistive technologies about the element's
/// condition.
///
/// See the [MSDN State Constants page](https://docs.microsoft.com/en-us/windows/win32/winauto/object-state-constants) for more details.
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[repr(C)]
pub enum AccessibilityState {
    /// The element is unavailable and cannot be interacted with.
    /// - **Purpose**: To indicate that a control is disabled or grayed out.
    /// - **When to use**: For disabled buttons, non-interactive menu items, or any control that is
    ///   temporarily non-functional.
    /// - **Example**: A "Save" button that is disabled until the user makes changes to a document.
    Unavailable,

    /// The element is selected.
    /// - **Purpose**: To indicate that an item is currently chosen or highlighted. This is
    ///   distinct from having focus.
    /// - **When to use**: For selected items in a list, highlighted text, or the currently active
    ///   tab in a tab list.
    /// - **Example**: A file highlighted in a file explorer, or multiple selected emails in an
    ///   inbox.
    Selected,

    /// The element has the keyboard focus.
    /// - **Purpose**: To identify the single element that will receive keyboard input.
    /// - **When to use**: For the control that is currently active and ready to be manipulated by
    ///   the keyboard.
    /// - **Example**: A text box with a blinking cursor, or a button with a dotted outline around
    ///   it.
    Focused,

    /// The element is checked, toggled, or in a mixed state.
    /// - **Purpose**: To represent the state of controls like checkboxes, radio buttons, and
    ///   toggle buttons.
    /// - **When to use**: For checkboxes that are ticked, selected radio buttons, or toggle
    ///   buttons that are "on."
    /// - **Example**: A checked "I agree" checkbox, a selected "Yes" radio button, or an active
    ///   "Bold" button in a toolbar.
    Checked,

    /// The element's content cannot be edited by the user.
    /// - **Purpose**: To indicate that the element's value can be viewed and copied, but not
    ///   modified.
    /// - **When to use**: For display-only text fields or documents.
    /// - **Example**: A text box displaying a license agreement that the user can scroll through
    ///   but cannot edit.
    Readonly,

    /// The element is the default action in a dialog or form.
    /// - **Purpose**: To identify the button that will be activated if the user presses the Enter
    ///   key.
    /// - **When to use**: For the primary confirmation button in a dialog.
    /// - **Example**: The "OK" button in a dialog box, which often has a thicker or colored
    ///   border.
    Default,

    /// The element is expanded, showing its child items.
    /// - **Purpose**: To indicate that a collapsible element is currently open and its contents
    ///   are visible.
    /// - **When to use**: For tree view nodes, combo boxes with their lists open, or expanded
    ///   accordion panels.
    /// - **Example**: A folder in a file explorer's tree view that has been clicked to show its
    ///   subfolders.
    Expanded,

    /// The element is collapsed, hiding its child items.
    /// - **Purpose**: To indicate that a collapsible element is closed and its contents are
    ///   hidden.
    /// - **When to use**: The counterpart to `Expanded` for any collapsible UI element.
    /// - **Example**: A closed folder in a file explorer's tree view, hiding its contents.
    Collapsed,

    /// The element is busy and cannot respond to user interaction.
    /// - **Purpose**: To indicate that the element or application is performing an operation and
    ///   is temporarily unresponsive.
    /// - **When to use**: When an application is loading, processing refany, or otherwise occupied.
    /// - **Example**: A window that is grayed out and shows a spinning cursor while saving a large
    ///   file.
    Busy,

    /// The element is not currently visible on the screen.
    /// - **Purpose**: To indicate that an element exists but is currently scrolled out of the
    ///   visible area.
    /// - **When to use**: For items in a long list or a large document that are not within the
    ///   current viewport.
    /// - **Example**: A list item in a long dropdown that you would have to scroll down to see.
    Offscreen,

    /// The element can accept keyboard focus.
    /// - **Purpose**: To indicate that the user can navigate to this element using the keyboard
    ///   (e.g., with the Tab key).
    /// - **When to use**: On all interactive elements like buttons, links, and input fields,
    ///   whether they currently have focus or not.
    /// - **Example**: A button that can receive focus, even if it is not the currently focused
    ///   element.
    Focusable,

    /// The element is a container whose children can be selected.
    /// - **Purpose**: To indicate that the element contains items that can be chosen.
    /// - **When to use**: On container controls like list boxes, tree views, or text spans where
    ///   text can be highlighted.
    /// - **Example**: A list box control is `Selectable`, while its individual list items have the
    ///   `Selected` state when chosen.
    Selectable,

    /// The element is a hyperlink.
    /// - **Purpose**: To identify an object that navigates to another resource or location when
    ///   activated.
    /// - **When to use**: On any object that functions as a hyperlink.
    /// - **Example**: Text or an image that, when clicked, opens a web page.
    Linked,

    /// The element is a hyperlink that has been visited.
    /// - **Purpose**: To indicate that a hyperlink has already been followed by the user.
    /// - **When to use**: On a `Linked` object that the user has previously activated.
    /// - **Example**: A hyperlink on a web page that has changed color to show it has been
    ///   visited.
    Traversed,

    /// The element allows multiple of its children to be selected at once.
    /// - **Purpose**: To indicate that a container control supports multi-selection.
    /// - **When to use**: On container controls like list boxes or file explorers that support
    ///   multiple selections (e.g., with Ctrl-click).
    /// - **Example**: A file list that allows the user to select several files at once for a copy
    ///   operation.
    Multiselectable,

    /// The element contains protected content that should not be read aloud.
    /// - **Purpose**: To prevent assistive technologies from speaking the content of a sensitive
    ///   field.
    /// - **When to use**: Primarily for password input fields.
    /// - **Example**: A password text box where typed characters are masked with asterisks or
    ///   dots.
    Protected,
}

impl_option!(
    AccessibilityState,
    OptionAccessibilityState,
    [Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash]
);

impl_vec!(AccessibilityState, AccessibilityStateVec, AccessibilityStateVecDestructor, AccessibilityStateVecDestructorType, AccessibilityStateVecSlice, OptionAccessibilityState);
impl_vec_clone!(
    AccessibilityState,
    AccessibilityStateVec,
    AccessibilityStateVecDestructor
);
impl_vec_debug!(AccessibilityState, AccessibilityStateVec);
impl_vec_partialeq!(AccessibilityState, AccessibilityStateVec);
impl_vec_partialord!(AccessibilityState, AccessibilityStateVec);
impl_vec_eq!(AccessibilityState, AccessibilityStateVec);
impl_vec_ord!(AccessibilityState, AccessibilityStateVec);
impl_vec_hash!(AccessibilityState, AccessibilityStateVec);

impl Clone for NodeData {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            node_type: self.node_type.into_library_owned_nodetype(),
            dataset: match &self.dataset {
                OptionRefAny::None => OptionRefAny::None,
                OptionRefAny::Some(s) => OptionRefAny::Some(s.clone()),
            },
            ids_and_classes: self.ids_and_classes.clone(), /* do not clone the IDs and classes if
                                                            * they are &'static */
            attributes: self.attributes.clone(),
            css_props: self.css_props.clone(),
            callbacks: self.callbacks.clone(),
            tab_index: self.tab_index,
            contenteditable: self.contenteditable,
            extra: self.extra.clone(),
        }
    }
}

// Clone, PartialEq, Eq, Hash, PartialOrd, Ord
impl_vec!(NodeData, NodeDataVec, NodeDataVecDestructor, NodeDataVecDestructorType, NodeDataVecSlice, OptionNodeData);
impl_vec_clone!(NodeData, NodeDataVec, NodeDataVecDestructor);
impl_vec_mut!(NodeData, NodeDataVec);
impl_vec_debug!(NodeData, NodeDataVec);
impl_vec_partialord!(NodeData, NodeDataVec);
impl_vec_ord!(NodeData, NodeDataVec);
impl_vec_partialeq!(NodeData, NodeDataVec);
impl_vec_eq!(NodeData, NodeDataVec);
impl_vec_hash!(NodeData, NodeDataVec);

impl NodeDataVec {
    #[inline]
    pub fn as_container<'a>(&'a self) -> NodeDataContainerRef<'a, NodeData> {
        NodeDataContainerRef {
            internal: self.as_ref(),
        }
    }
    #[inline]
    pub fn as_container_mut<'a>(&'a mut self) -> NodeDataContainerRefMut<'a, NodeData> {
        NodeDataContainerRefMut {
            internal: self.as_mut(),
        }
    }
}

unsafe impl Send for NodeData {}

/// Determines the behavior of an element in sequential focus navigation
// (e.g., using the Tab key).
#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
#[repr(C, u8)]
pub enum TabIndex {
    /// Automatic tab index, similar to simply setting `focusable = "true"` or `tabindex = 0`
    /// (both have the effect of making the element focusable).
    ///
    /// Sidenote: See https://www.w3.org/TR/html5/editing.html#sequential-focus-navigation-and-the-tabindex-attribute
    /// for interesting notes on tabindex and accessibility
    Auto,
    /// Set the tab index in relation to its parent element. I.e. if you have a list of elements,
    /// the focusing order is restricted to the current parent.
    ///
    /// When pressing tab repeatedly, the focusing order will be
    /// determined by OverrideInParent elements taking precedence among global order.
    OverrideInParent(u32),
    /// Elements can be focused in callbacks, but are not accessible via
    /// keyboard / tab navigation (-1).
    NoKeyboardFocus,
}

impl_option!(
    TabIndex,
    OptionTabIndex,
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);

impl TabIndex {
    /// Returns the HTML-compatible number of the `tabindex` element.
    pub fn get_index(&self) -> isize {
        use self::TabIndex::*;
        match self {
            Auto => 0,
            OverrideInParent(x) => *x as isize,
            NoKeyboardFocus => -1,
        }
    }
}

impl Default for TabIndex {
    fn default() -> Self {
        TabIndex::Auto
    }
}

impl Default for NodeData {
    fn default() -> Self {
        NodeData::create_node(NodeType::Div)
    }
}

impl fmt::Display for NodeData {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let html_type = self.node_type.get_path();
        let attributes_string = node_data_to_string(&self);

        match self.node_type.format() {
            Some(content) => write!(
                f,
                "<{}{}>{}</{}>",
                html_type, attributes_string, content, html_type
            ),
            None => write!(f, "<{}{}/>", html_type, attributes_string),
        }
    }
}

fn node_data_to_string(node_data: &NodeData) -> String {
    let mut id_string = String::new();
    let ids = node_data
        .ids_and_classes
        .as_ref()
        .iter()
        .filter_map(|s| s.as_id())
        .collect::<Vec<_>>()
        .join(" ");

    if !ids.is_empty() {
        id_string = format!(" id=\"{}\" ", ids);
    }

    let mut class_string = String::new();
    let classes = node_data
        .ids_and_classes
        .as_ref()
        .iter()
        .filter_map(|s| s.as_class())
        .collect::<Vec<_>>()
        .join(" ");

    if !classes.is_empty() {
        class_string = format!(" class=\"{}\" ", classes);
    }

    let mut tabindex_string = String::new();
    if let Some(tab_index) = node_data.get_tab_index() {
        tabindex_string = format!(" tabindex=\"{}\" ", tab_index.get_index());
    };

    format!("{}{}{}", id_string, class_string, tabindex_string)
}

impl NodeData {
    /// Creates a new `NodeData` instance from a given `NodeType`.
    #[inline]
    pub const fn create_node(node_type: NodeType) -> Self {
        Self {
            node_type,
            dataset: OptionRefAny::None,
            ids_and_classes: IdOrClassVec::from_const_slice(&[]),
            attributes: AttributeTypeVec::from_const_slice(&[]),
            callbacks: CoreCallbackDataVec::from_const_slice(&[]),
            css_props: CssPropertyWithConditionsVec::from_const_slice(&[]),
            tab_index: OptionTabIndex::None,
            contenteditable: false,
            extra: None,
        }
    }

    /// Shorthand for `NodeData::create_node(NodeType::Body)`.
    #[inline(always)]
    pub const fn create_body() -> Self {
        Self::create_node(NodeType::Body)
    }

    /// Shorthand for `NodeData::create_node(NodeType::Div)`.
    #[inline(always)]
    pub const fn create_div() -> Self {
        Self::create_node(NodeType::Div)
    }

    /// Shorthand for `NodeData::create_node(NodeType::Br)`.
    #[inline(always)]
    pub const fn create_br() -> Self {
        Self::create_node(NodeType::Br)
    }

    /// Shorthand for `NodeData::create_node(NodeType::Text(value.into()))`.
    #[inline(always)]
    pub fn create_text<S: Into<AzString>>(value: S) -> Self {
        Self::create_node(NodeType::Text(value.into()))
    }

    /// Shorthand for `NodeData::create_node(NodeType::Image(image_id))`.
    #[inline(always)]
    pub fn create_image(image: ImageRef) -> Self {
        Self::create_node(NodeType::Image(image))
    }

    #[inline(always)]
    pub fn create_iframe(data: RefAny, callback: impl Into<IFrameCallback>) -> Self {
        Self::create_node(NodeType::IFrame(IFrameNode {
            callback: callback.into(),
            refany: data,
        }))
    }

    /// Checks whether this node is of the given node type (div, image, text).
    #[inline]
    pub fn is_node_type(&self, searched_type: NodeType) -> bool {
        self.node_type == searched_type
    }

    /// Checks whether this node has the searched ID attached.
    pub fn has_id(&self, id: &str) -> bool {
        self.ids_and_classes
            .iter()
            .any(|id_or_class| id_or_class.as_id() == Some(id))
    }

    /// Checks whether this node has the searched class attached.
    pub fn has_class(&self, class: &str) -> bool {
        self.ids_and_classes
            .iter()
            .any(|id_or_class| id_or_class.as_class() == Some(class))
    }

    pub fn has_context_menu(&self) -> bool {
        self.extra
            .as_ref()
            .map(|m| m.context_menu.is_some())
            .unwrap_or(false)
    }

    pub fn is_text_node(&self) -> bool {
        match self.node_type {
            NodeType::Text(_) => true,
            _ => false,
        }
    }

    pub fn is_iframe_node(&self) -> bool {
        match self.node_type {
            NodeType::IFrame(_) => true,
            _ => false,
        }
    }

    // NOTE: Getters are used here in order to allow changing the memory allocator for the NodeData
    // in the future (which is why the fields are all private).

    #[inline(always)]
    pub const fn get_node_type(&self) -> &NodeType {
        &self.node_type
    }
    #[inline(always)]
    pub fn get_dataset_mut(&mut self) -> &mut OptionRefAny {
        &mut self.dataset
    }
    #[inline(always)]
    pub const fn get_dataset(&self) -> &OptionRefAny {
        &self.dataset
    }
    #[inline(always)]
    pub const fn get_ids_and_classes(&self) -> &IdOrClassVec {
        &self.ids_and_classes
    }
    #[inline(always)]
    pub const fn get_callbacks(&self) -> &CoreCallbackDataVec {
        &self.callbacks
    }
    #[inline(always)]
    pub const fn get_css_props(&self) -> &CssPropertyWithConditionsVec {
        &self.css_props
    }

    #[inline]
    pub fn get_clip_mask(&self) -> Option<&ImageMask> {
        self.extra.as_ref().and_then(|e| e.clip_mask.as_ref())
    }
    #[inline]
    pub fn get_tab_index(&self) -> Option<&TabIndex> {
        self.tab_index.as_ref()
    }
    #[inline]
    pub fn get_accessibility_info(&self) -> Option<&Box<AccessibilityInfo>> {
        self.extra.as_ref().and_then(|e| e.accessibility.as_ref())
    }
    #[inline]
    pub fn get_menu_bar(&self) -> Option<&Box<Menu>> {
        self.extra.as_ref().and_then(|e| e.menu_bar.as_ref())
    }
    #[inline]
    pub fn get_context_menu(&self) -> Option<&Box<Menu>> {
        self.extra.as_ref().and_then(|e| e.context_menu.as_ref())
    }

    /// Returns whether this node is an anonymous box generated for table layout.
    #[inline]
    pub fn is_anonymous(&self) -> bool {
        self.extra.as_ref().map(|e| e.is_anonymous).unwrap_or(false)
    }

    #[inline(always)]
    pub fn set_node_type(&mut self, node_type: NodeType) {
        self.node_type = node_type;
    }
    #[inline(always)]
    pub fn set_dataset(&mut self, data: OptionRefAny) {
        self.dataset = data;
    }
    #[inline(always)]
    pub fn set_ids_and_classes(&mut self, ids_and_classes: IdOrClassVec) {
        self.ids_and_classes = ids_and_classes;
    }
    #[inline(always)]
    pub fn set_callbacks(&mut self, callbacks: CoreCallbackDataVec) {
        self.callbacks = callbacks;
    }
    #[inline(always)]
    pub fn set_css_props(&mut self, css_props: CssPropertyWithConditionsVec) {
        self.css_props = css_props;
    }
    #[inline]
    pub fn set_clip_mask(&mut self, clip_mask: ImageMask) {
        self.extra
            .get_or_insert_with(|| Box::new(NodeDataExt::default()))
            .clip_mask = Some(clip_mask);
    }
    #[inline]
    pub fn set_tab_index(&mut self, tab_index: TabIndex) {
        self.tab_index = Some(tab_index).into();
    }
    #[inline]
    pub fn set_contenteditable(&mut self, contenteditable: bool) {
        self.contenteditable = contenteditable;
    }
    #[inline]
    pub fn is_contenteditable(&self) -> bool {
        self.contenteditable
    }
    #[inline]
    pub fn set_accessibility_info(&mut self, accessibility_info: AccessibilityInfo) {
        self.extra
            .get_or_insert_with(|| Box::new(NodeDataExt::default()))
            .accessibility = Some(Box::new(accessibility_info));
    }

    /// Marks this node as an anonymous box (generated for table layout).
    #[inline]
    pub fn set_anonymous(&mut self, is_anonymous: bool) {
        self.extra
            .get_or_insert_with(|| Box::new(NodeDataExt::default()))
            .is_anonymous = is_anonymous;
    }
    #[inline]
    pub fn set_menu_bar(&mut self, menu_bar: Menu) {
        self.extra
            .get_or_insert_with(|| Box::new(NodeDataExt::default()))
            .menu_bar = Some(Box::new(menu_bar));
    }
    #[inline]
    pub fn set_context_menu(&mut self, context_menu: Menu) {
        self.extra
            .get_or_insert_with(|| Box::new(NodeDataExt::default()))
            .context_menu = Some(Box::new(context_menu));
    }

    /// Sets a stable key for this node used in reconciliation.
    ///
    /// This key is used to track node identity across DOM updates, enabling
    /// the framework to distinguish between "moving" a node and "destroying/creating" one.
    /// This is crucial for correct lifecycle events when lists are reordered.
    ///
    /// # Example
    /// ```rust
    /// node_data.set_key("user-123");
    /// ```
    #[inline]
    pub fn set_key<K: core::hash::Hash>(&mut self, key: K) {
        use highway::{HighwayHash, HighwayHasher, Key};
        let mut hasher = HighwayHasher::new(Key([0; 4]));
        key.hash(&mut hasher);
        self.extra
            .get_or_insert_with(|| Box::new(NodeDataExt::default()))
            .key = Some(hasher.finalize64());
    }

    /// Gets the key for this node, if set.
    #[inline]
    pub fn get_key(&self) -> Option<u64> {
        self.extra.as_ref().and_then(|ext| ext.key)
    }

    /// Sets a dataset merge callback for this node.
    ///
    /// The merge callback is invoked during reconciliation when a node from the
    /// previous frame is matched with a node in the new frame. It allows heavy
    /// resources (video decoders, GL textures, network connections) to be
    /// transferred from the old node to the new node instead of being destroyed.
    ///
    /// # Type Safety
    ///
    /// The callback stores the `TypeId` of `T`. During execution, both the old
    /// and new datasets must match this type, otherwise the merge is skipped.
    ///
    /// # Example
    /// ```rust
    /// struct VideoPlayer {
    ///     url: String,
    ///     decoder: Option<DecoderHandle>,
    /// }
    /// 
    /// extern "C" fn merge_video(new_data: RefAny, old_data: RefAny) -> RefAny {
    ///     // Transfer the heavy decoder handle from old to new
    ///     if let (Some(mut new), Some(old)) = (
    ///         new_data.downcast_mut::<VideoPlayer>(),
    ///         old_data.downcast_ref::<VideoPlayer>()
    ///     ) {
    ///         new.decoder = old.decoder.take();
    ///     }
    ///     new_data
    /// }
    /// 
    /// node_data.set_merge_callback(merge_video);
    /// ```
    #[inline]
    pub fn set_merge_callback<C: Into<DatasetMergeCallback>>(&mut self, callback: C) {
        self.extra
            .get_or_insert_with(|| Box::new(NodeDataExt::default()))
            .dataset_merge_callback = Some(callback.into());
    }

    /// Gets the merge callback for this node, if set.
    #[inline]
    pub fn get_merge_callback(&self) -> Option<DatasetMergeCallback> {
        self.extra.as_ref().and_then(|ext| ext.dataset_merge_callback.clone())
    }

    #[inline]
    pub fn with_menu_bar(mut self, menu_bar: Menu) -> Self {
        self.set_menu_bar(menu_bar);
        self
    }

    #[inline]
    pub fn with_context_menu(mut self, context_menu: Menu) -> Self {
        self.set_context_menu(context_menu);
        self
    }

    #[inline]
    pub fn add_callback<C: Into<CoreCallback>>(
        &mut self,
        event: EventFilter,
        data: RefAny,
        callback: C,
    ) {
        let callback = callback.into();
        let mut v: CoreCallbackDataVec = Vec::new().into();
        mem::swap(&mut v, &mut self.callbacks);
        let mut v = v.into_library_owned_vec();
        v.push(CoreCallbackData {
            event,
            refany: data,
            callback,
        });
        self.callbacks = v.into();
    }

    #[inline]
    pub fn add_id(&mut self, s: AzString) {
        let mut v: IdOrClassVec = Vec::new().into();
        mem::swap(&mut v, &mut self.ids_and_classes);
        let mut v = v.into_library_owned_vec();
        v.push(IdOrClass::Id(s));
        self.ids_and_classes = v.into();
    }
    #[inline]
    pub fn add_class(&mut self, s: AzString) {
        let mut v: IdOrClassVec = Vec::new().into();
        mem::swap(&mut v, &mut self.ids_and_classes);
        let mut v = v.into_library_owned_vec();
        v.push(IdOrClass::Class(s));
        self.ids_and_classes = v.into();
    }

    /// Add a CSS property with optional conditions (hover, focus, active, etc.)
    #[inline]
    pub fn add_css_property(&mut self, p: CssPropertyWithConditions) {
        let mut v: CssPropertyWithConditionsVec = Vec::new().into();
        mem::swap(&mut v, &mut self.css_props);
        let mut v = v.into_library_owned_vec();
        v.push(p);
        self.css_props = v.into();
    }

    /// Calculates a deterministic node hash for this node.
    pub fn calculate_node_data_hash(&self) -> DomNodeHash {
        use highway::{HighwayHash, HighwayHasher, Key};
        let mut hasher = HighwayHasher::new(Key([0; 4]));
        self.hash(&mut hasher);
        let h = hasher.finalize64();
        DomNodeHash { inner: h }
    }

    /// Calculates a structural hash for DOM reconciliation that ignores text content.
    /// 
    /// This hash is used for matching nodes across DOM frames where the text content
    /// may have changed (e.g., contenteditable text being edited). It hashes:
    /// - Node type discriminant (but NOT the text content for Text nodes)
    /// - IDs and classes
    /// - Attributes (but NOT contenteditable state which may change with focus)
    /// - Callback events and types
    /// 
    /// This allows a Text("Hello") node to match Text("Hello World") during reconciliation,
    /// preserving cursor position and selection state.
    pub fn calculate_structural_hash(&self) -> DomNodeHash {
        use highway::{HighwayHash, HighwayHasher, Key};
        use core::hash::Hasher as StdHasher;
        
        let mut hasher = HighwayHasher::new(Key([0; 4]));
        
        // Hash node type discriminant only, not content
        // This means Text("A") and Text("B") have the same structural hash
        core::mem::discriminant(&self.node_type).hash(&mut hasher);
        
        // For IFrame nodes, hash the callback to distinguish different iframes
        if let NodeType::IFrame(ref iframe) = self.node_type {
            // Hash iframe callback (it implements Hash)
            iframe.hash(&mut hasher);
        }
        
        // For Image nodes, hash the image reference to distinguish different images
        if let NodeType::Image(ref img_ref) = self.node_type {
            img_ref.hash(&mut hasher);
        }
        
        // Hash IDs and classes - these are structural and shouldn't change
        self.ids_and_classes.as_ref().hash(&mut hasher);
        
        // Hash attributes - but skip contenteditable since that might change
        for attr in self.attributes.as_ref().iter() {
            // Skip ContentEditable attribute - it's state, not structure
            if !matches!(attr, AttributeType::ContentEditable(_)) {
                attr.hash(&mut hasher);
            }
        }
        
        // Hash callback events (not the actual callback function pointers)
        for callback in self.callbacks.as_ref().iter() {
            callback.event.hash(&mut hasher);
        }
        
        let h = hasher.finalize64();
        DomNodeHash { inner: h }
    }

    #[inline(always)]
    pub fn with_tab_index(mut self, tab_index: TabIndex) -> Self {
        self.set_tab_index(tab_index);
        self
    }
    #[inline(always)]
    pub fn with_contenteditable(mut self, contenteditable: bool) -> Self {
        self.set_contenteditable(contenteditable);
        self
    }
    #[inline(always)]
    pub fn with_node_type(mut self, node_type: NodeType) -> Self {
        self.set_node_type(node_type);
        self
    }
    #[inline(always)]
    pub fn with_callback<C: Into<CoreCallback>>(
        mut self,
        event: EventFilter,
        data: RefAny,
        callback: C,
    ) -> Self {
        self.add_callback(event, data, callback);
        self
    }
    #[inline(always)]
    pub fn with_dataset(mut self, data: OptionRefAny) -> Self {
        self.dataset = data;
        self
    }
    #[inline(always)]
    pub fn with_ids_and_classes(mut self, ids_and_classes: IdOrClassVec) -> Self {
        self.ids_and_classes = ids_and_classes;
        self
    }
    #[inline(always)]
    pub fn with_callbacks(mut self, callbacks: CoreCallbackDataVec) -> Self {
        self.callbacks = callbacks;
        self
    }
    #[inline(always)]
    pub fn with_css_props(mut self, css_props: CssPropertyWithConditionsVec) -> Self {
        self.css_props = css_props;
        self
    }

    /// Assigns a stable key to this node for reconciliation.
    ///
    /// This is crucial for performance and correct state preservation when
    /// lists of items change order or items are inserted/removed. Without keys,
    /// the reconciliation algorithm falls back to hash-based matching.
    ///
    /// # Example
    /// ```rust
    /// NodeData::create_div()
    ///     .with_key("user-avatar-123")
    /// ```
    #[inline]
    pub fn with_key<K: core::hash::Hash>(mut self, key: K) -> Self {
        self.set_key(key);
        self
    }

    /// Registers a callback to merge dataset state from the previous frame.
    ///
    /// This is used for components that maintain heavy internal state (video players,
    /// WebGL contexts, network connections) that should not be destroyed and recreated
    /// on every render frame.
    ///
    /// The callback receives both datasets as `RefAny` (cheap shallow clones) and
    /// returns the `RefAny` that should be used for the new node.
    ///
    /// # Example
    /// ```rust
    /// struct VideoPlayer {
    ///     url: String,
    ///     decoder_handle: Option<DecoderHandle>,
    /// }
    ///
    /// extern "C" fn merge_video(new_data: RefAny, old_data: RefAny) -> RefAny {
    ///     if let (Some(mut new), Some(old)) = (
    ///         new_data.downcast_mut::<VideoPlayer>(),
    ///         old_data.downcast_ref::<VideoPlayer>()
    ///     ) {
    ///         new.decoder_handle = old.decoder_handle.take();
    ///     }
    ///     new_data
    /// }
    ///
    /// NodeData::create_div()
    ///     .with_dataset(RefAny::new(VideoPlayer::new("movie.mp4")).into())
    ///     .with_merge_callback(merge_video)
    /// ```
    #[inline]
    pub fn with_merge_callback<C: Into<DatasetMergeCallback>>(mut self, callback: C) -> Self {
        self.set_merge_callback(callback);
        self
    }

    /// Parse CSS from a string and add as unconditional properties
    /// 
    /// Deprecated: Use `set_css()` for full selector support
    pub fn set_inline_style(&mut self, style: &str) {
        let parsed = CssPropertyWithConditionsVec::parse(style);
        let parsed_vec = parsed.into_library_owned_vec();
        let mut current = Vec::new().into();
        mem::swap(&mut current, &mut self.css_props);
        let mut v = current.into_library_owned_vec();
        v.extend(parsed_vec);
        self.css_props = v.into();
    }

    /// Builder method for setting inline CSS styles for the normal state
    /// 
    /// Deprecated: Use `with_css()` for full selector support
    pub fn with_inline_style(mut self, style: &str) -> Self {
        self.set_inline_style(style);
        self
    }
    
    /// Parse and set CSS styles with full selector support.
    /// 
    /// This is the unified API for setting inline CSS on a node. It supports:
    /// - Simple properties: `color: red; font-size: 14px;`
    /// - Pseudo-selectors: `:hover { background: blue; }`
    /// - @-rules: `@os linux { font-size: 14px; }`
    /// - Nesting: `@os linux { font-size: 14px; :hover { color: red; }}`
    /// 
    /// # Examples
    /// ```rust
    /// NodeData::create_div().with_css("
    ///     color: blue;
    ///     :hover { color: red; }
    ///     @os linux { font-size: 14px; }
    /// ")
    /// ```
    pub fn set_css(&mut self, style: &str) {
        let parsed = CssPropertyWithConditionsVec::parse(style);
        let mut current = Vec::new().into();
        mem::swap(&mut current, &mut self.css_props);
        let mut v = current.into_library_owned_vec();
        v.extend(parsed.into_library_owned_vec());
        self.css_props = v.into();
    }
    
    /// Builder method for `set_css`
    pub fn with_css(mut self, style: &str) -> Self {
        self.set_css(style);
        self
    }

    /// Sets inline CSS styles for the hover state, parsing from a CSS string
    /// 
    /// Deprecated: Use `with_css(":hover { ... }")` instead
    pub fn set_inline_hover_style(&mut self, style: &str) {
        let parsed = CssPropertyWithConditionsVec::parse_hover(style);
        let mut current = Vec::new().into();
        mem::swap(&mut current, &mut self.css_props);
        let mut v = current.into_library_owned_vec();
        v.extend(parsed.into_library_owned_vec());
        self.css_props = v.into();
    }

    /// Builder method for setting inline CSS styles for the hover state
    /// 
    /// Deprecated: Use `with_css(":hover { ... }")` instead
    pub fn with_inline_hover_style(mut self, style: &str) -> Self {
        self.set_inline_hover_style(style);
        self
    }

    /// Sets inline CSS styles for the active state, parsing from a CSS string
    /// 
    /// Deprecated: Use `with_css(":active { ... }")` instead
    pub fn set_inline_active_style(&mut self, style: &str) {
        let parsed = CssPropertyWithConditionsVec::parse_active(style);
        let mut current = Vec::new().into();
        mem::swap(&mut current, &mut self.css_props);
        let mut v = current.into_library_owned_vec();
        v.extend(parsed.into_library_owned_vec());
        self.css_props = v.into();
    }

    /// Builder method for setting inline CSS styles for the active state
    /// 
    /// Deprecated: Use `with_css(":active { ... }")` instead
    pub fn with_inline_active_style(mut self, style: &str) -> Self {
        self.set_inline_active_style(style);
        self
    }

    /// Sets inline CSS styles for the focus state, parsing from a CSS string
    /// 
    /// Deprecated: Use `with_css(":focus { ... }")` instead
    pub fn set_inline_focus_style(&mut self, style: &str) {
        let parsed = CssPropertyWithConditionsVec::parse_focus(style);
        let mut current = Vec::new().into();
        mem::swap(&mut current, &mut self.css_props);
        let mut v = current.into_library_owned_vec();
        v.extend(parsed.into_library_owned_vec());
        self.css_props = v.into();
    }

    /// Builder method for setting inline CSS styles for the focus state
    /// 
    /// Deprecated: Use `with_css(":focus { ... }")` instead
    pub fn with_inline_focus_style(mut self, style: &str) -> Self {
        self.set_inline_focus_style(style);
        self
    }

    #[inline(always)]
    pub fn swap_with_default(&mut self) -> Self {
        let mut s = NodeData::create_div();
        mem::swap(&mut s, self);
        s
    }

    #[inline]
    pub fn copy_special(&self) -> Self {
        Self {
            node_type: self.node_type.into_library_owned_nodetype(),
            dataset: match &self.dataset {
                OptionRefAny::None => OptionRefAny::None,
                OptionRefAny::Some(s) => OptionRefAny::Some(s.clone()),
            },
            ids_and_classes: self.ids_and_classes.clone(), /* do not clone the IDs and classes if
                                                            * they are &'static */
            attributes: self.attributes.clone(),
            css_props: self.css_props.clone(),
            callbacks: self.callbacks.clone(),
            tab_index: self.tab_index,
            contenteditable: self.contenteditable,
            extra: self.extra.clone(),
        }
    }

    pub fn is_focusable(&self) -> bool {
        // Element is focusable if it has a tab index or any focus-related callback
        self.get_tab_index().is_some()
            || self
                .get_callbacks()
                .iter()
                .any(|cb| cb.event.is_focus_callback())
    }

    /// Returns true if this element has "activation behavior" per HTML5 spec.
    ///
    /// Elements with activation behavior can be activated via Enter or Space key
    /// when focused, which generates a synthetic click event.
    ///
    /// Per HTML5 spec, elements with activation behavior include:
    /// - Button elements
    /// - Input elements (submit, button, reset, checkbox, radio)
    /// - Anchor elements with href
    /// - Any element with a click callback (implicit activation)
    ///
    /// See: https://html.spec.whatwg.org/multipage/interaction.html#activation-behavior
    pub fn has_activation_behavior(&self) -> bool {
        use crate::events::{EventFilter, HoverEventFilter};
        
        // Check for click callback (most common case for Azul)
        // In Azul, "click" is typically LeftMouseUp
        let has_click_callback = self
            .get_callbacks()
            .iter()
            .any(|cb| matches!(
                cb.event, 
                EventFilter::Hover(HoverEventFilter::MouseUp) 
                | EventFilter::Hover(HoverEventFilter::LeftMouseUp)
            ));

        if has_click_callback {
            return true;
        }

        // Check accessibility role for button-like elements
        if let Some(ref ext) = self.extra {
            if let Some(ref accessibility) = ext.accessibility {
                use crate::dom::AccessibilityRole;
                match accessibility.role {
                    AccessibilityRole::PushButton  // Button
                    | AccessibilityRole::Link
                    | AccessibilityRole::CheckButton  // Checkbox
                    | AccessibilityRole::RadioButton  // Radio
                    | AccessibilityRole::MenuItem
                    | AccessibilityRole::PageTab  // Tab
                    => return true,
                    _ => {}
                }
            }
        }

        false
    }

    /// Returns true if this element is currently activatable.
    ///
    /// An element is activatable if it has activation behavior AND is not disabled.
    /// This checks for common disability patterns (aria-disabled, disabled attribute).
    pub fn is_activatable(&self) -> bool {
        if !self.has_activation_behavior() {
            return false;
        }

        // Check for disabled state in accessibility info
        if let Some(ref ext) = self.extra {
            if let Some(ref accessibility) = ext.accessibility {
                // Check if explicitly marked as unavailable
                if accessibility
                    .states
                    .as_ref()
                    .iter()
                    .any(|s| matches!(s, AccessibilityState::Unavailable))
                {
                    return false;
                }
            }
        }

        // Not disabled, so activatable
        true
    }

    /// Returns the tab index for this element.
    ///
    /// Tab index determines keyboard navigation order:
    /// - `None`: Not in tab order (unless naturally focusable)
    /// - `Some(-1)`: Focusable programmatically but not via Tab
    /// - `Some(0)`: In natural tab order
    /// - `Some(n > 0)`: In tab order with priority n (higher = later)
    pub fn get_effective_tabindex(&self) -> Option<i32> {
        match self.tab_index {
            OptionTabIndex::None => {
                // Check if naturally focusable (has focus callback)
                if self.get_callbacks().iter().any(|cb| cb.event.is_focus_callback()) {
                    Some(0)
                } else {
                    None
                }
            }
            OptionTabIndex::Some(tab_idx) => {
                match tab_idx {
                    TabIndex::Auto => Some(0),
                    TabIndex::OverrideInParent(n) => Some(n as i32),
                    TabIndex::NoKeyboardFocus => Some(-1),
                }
            }
        }
    }

    pub fn get_iframe_node(&mut self) -> Option<&mut IFrameNode> {
        match &mut self.node_type {
            NodeType::IFrame(i) => Some(i),
            _ => None,
        }
    }

    pub fn get_render_image_callback_node<'a>(
        &'a mut self,
    ) -> Option<(&'a mut CoreImageCallback, ImageRefHash)> {
        match &mut self.node_type {
            NodeType::Image(img) => {
                let hash = image_ref_get_hash(&img);
                img.get_image_callback_mut().map(|r| (r, hash))
            }
            _ => None,
        }
    }

    pub fn debug_print_start(
        &self,
        css_cache: &CssPropertyCache,
        node_id: &NodeId,
        node_state: &StyledNodeState,
    ) -> String {
        let html_type = self.node_type.get_path();
        let attributes_string = node_data_to_string(&self);
        let style = css_cache.get_computed_css_style_string(&self, node_id, node_state);
        format!(
            "<{} data-az-node-id=\"{}\" {} {style}>",
            html_type,
            node_id.index(),
            attributes_string,
            style = if style.trim().is_empty() {
                String::new()
            } else {
                format!("style=\"{style}\"")
            }
        )
    }

    pub fn debug_print_end(&self) -> String {
        let html_type = self.node_type.get_path();
        format!("</{}>", html_type)
    }
}

/// A unique, runtime-generated identifier for a single `Dom` instance.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
#[repr(C)]
pub struct DomId {
    pub inner: usize,
}

impl fmt::Display for DomId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.inner)
    }
}

impl DomId {
    pub const ROOT_ID: DomId = DomId { inner: 0 };
}

impl Default for DomId {
    fn default() -> DomId {
        DomId::ROOT_ID
    }
}

impl_option!(
    DomId,
    OptionDomId,
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);

impl_vec!(DomId, DomIdVec, DomIdVecDestructor, DomIdVecDestructorType, DomIdVecSlice, OptionDomId);
impl_vec_debug!(DomId, DomIdVec);
impl_vec_clone!(DomId, DomIdVec, DomIdVecDestructor);
impl_vec_partialeq!(DomId, DomIdVec);
impl_vec_partialord!(DomId, DomIdVec);

/// A UUID for a DOM node within a `LayoutWindow`.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct DomNodeId {
    /// The ID of the `Dom` this node belongs to.
    pub dom: DomId,
    /// The hierarchical ID of the node within its `Dom`.
    pub node: NodeHierarchyItemId,
}

impl_option!(
    DomNodeId,
    OptionDomNodeId,
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);

impl DomNodeId {
    pub const ROOT: DomNodeId = DomNodeId {
        dom: DomId::ROOT_ID,
        node: NodeHierarchyItemId::NONE,
    };
}

/// The document model, similar to HTML. This is a create-only structure, you don't actually read
/// anything back from it. It's designed for ease of construction.
#[repr(C)]
#[derive(PartialEq, Clone, Eq, Hash, PartialOrd, Ord)]
pub struct Dom {
    /// The data for the root node of this DOM (or sub-DOM).
    pub root: NodeData,
    /// The children of this DOM node.
    pub children: DomVec,
    // Tracks the number of sub-children of the current children, so that
    // the `Dom` can be converted into a `CompactDom`.
    pub estimated_total_children: usize,
}

impl_option!(
    Dom,
    OptionDom,
    copy = false,
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);

impl_vec!(Dom, DomVec, DomVecDestructor, DomVecDestructorType, DomVecSlice, OptionDom);
impl_vec_clone!(Dom, DomVec, DomVecDestructor);
impl_vec_mut!(Dom, DomVec);
impl_vec_debug!(Dom, DomVec);
impl_vec_partialord!(Dom, DomVec);
impl_vec_ord!(Dom, DomVec);
impl_vec_partialeq!(Dom, DomVec);
impl_vec_eq!(Dom, DomVec);
impl_vec_hash!(Dom, DomVec);

impl Dom {
    // ----- DOM CONSTRUCTORS

    /// Creates an empty DOM with a give `NodeType`. Note: This is a `const fn` and
    /// doesn't allocate, it only allocates once you add at least one child node.
    #[inline(always)]
    pub fn create_node(node_type: NodeType) -> Self {
        Self {
            root: NodeData::create_node(node_type),
            children: Vec::new().into(),
            estimated_total_children: 0,
        }
    }
    #[inline(always)]
    pub fn from_data(node_data: NodeData) -> Self {
        Self {
            root: node_data,
            children: Vec::new().into(),
            estimated_total_children: 0,
        }
    }

    // Document Structure Elements

    /// Creates the root HTML element.
    ///
    /// **Accessibility**: The `<html>` element is the root of an HTML document and should have a
    /// `lang` attribute.
    #[inline(always)]
    pub const fn create_html() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Html),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates the document head element.
    ///
    /// **Accessibility**: The `<head>` contains metadata. Use `<title>` for page titles.
    #[inline(always)]
    pub const fn create_head() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Head),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    #[inline(always)]
    pub const fn create_body() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Body),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates a generic block-level container.
    ///
    /// **Accessibility**: Prefer semantic elements like `<article>`, `<section>`, `<nav>` when
    /// applicable.
    #[inline(always)]
    pub const fn create_div() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Div),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    // Semantic Structure Elements

    /// Creates an article element.
    ///
    /// **Accessibility**: Represents self-contained content that could be distributed
    /// independently. Screen readers can navigate by articles. Consider adding aria-label for
    /// multiple articles.
    #[inline(always)]
    pub const fn create_article() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Article),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates a section element.
    ///
    /// **Accessibility**: Represents a thematic grouping of content with a heading.
    /// Should typically have a heading (h1-h6) as a child. Consider aria-labelledby.
    #[inline(always)]
    pub const fn create_section() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Section),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates a navigation element.
    ///
    /// **Accessibility**: Represents navigation links. Screen readers can jump to navigation.
    /// Use aria-label to distinguish multiple nav elements (e.g., "Main navigation", "Footer
    /// links").
    #[inline(always)]
    pub const fn create_nav() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Nav),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates an aside element.
    ///
    /// **Accessibility**: Represents content tangentially related to main content (sidebars,
    /// callouts). Screen readers announce this as complementary content.
    #[inline(always)]
    pub const fn create_aside() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Aside),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates a header element.
    ///
    /// **Accessibility**: Represents introductory content or navigational aids.
    /// Can be used for page headers or section headers.
    #[inline(always)]
    pub const fn create_header() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Header),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates a footer element.
    ///
    /// **Accessibility**: Represents footer for nearest section or page.
    /// Typically contains copyright, author info, or related links.
    #[inline(always)]
    pub const fn create_footer() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Footer),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates a main content element.
    ///
    /// **Accessibility**: Represents the dominant content. There should be only ONE main per page.
    /// Screen readers can jump directly to main content. Do not nest inside
    /// article/aside/footer/header/nav.
    #[inline(always)]
    pub const fn create_main() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Main),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates a figure element.
    ///
    /// **Accessibility**: Represents self-contained content like diagrams, photos, code listings.
    /// Use with `<figcaption>` to provide a caption. Screen readers associate caption with figure.
    #[inline(always)]
    pub const fn create_figure() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Figure),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates a figure caption element.
    ///
    /// **Accessibility**: Provides a caption for `<figure>`. Screen readers announce this as the
    /// figure description.
    #[inline(always)]
    pub const fn create_figcaption() -> Self {
        Self {
            root: NodeData::create_node(NodeType::FigCaption),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    // Interactive Elements

    /// Creates a details disclosure element.
    ///
    /// **Accessibility**: Creates a disclosure widget. Screen readers announce expanded/collapsed
    /// state. Must contain a `<summary>` element. Keyboard accessible by default.
    #[inline(always)]
    pub const fn create_details() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Details),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates a summary element for details.
    ///
    /// **Accessibility**: The visible heading/label for `<details>`.
    /// Must be the first child of details. Keyboard accessible (Enter/Space to toggle).
    #[inline]
    pub fn summary<S: Into<AzString>>(text: S) -> Self {
        Self {
            root: NodeData::create_node(NodeType::Summary),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
        .with_child(Self::create_text(text))
    }

    /// Creates a dialog element.
    ///
    /// **Accessibility**: Represents a modal or non-modal dialog.
    /// When opened as modal, focus is trapped. Use aria-label or aria-labelledby.
    /// Escape key should close modal dialogs.
    #[inline(always)]
    pub const fn create_dialog() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Dialog),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    // Basic Structural Elements

    #[inline(always)]
    pub const fn create_br() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Br),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }
    #[inline(always)]
    pub fn create_text<S: Into<AzString>>(value: S) -> Self {
        Self::create_node(NodeType::Text(value.into()))
    }
    #[inline(always)]
    pub fn create_image(image: ImageRef) -> Self {
        Self::create_node(NodeType::Image(image))
    }
    /// Creates an icon node with the given icon name.
    ///
    /// The icon name should match names from the icon provider (e.g., "home", "settings", "search").
    /// Icons are resolved to actual content (font glyph, image, etc.) during StyledDom creation
    /// based on the configured IconProvider.
    ///
    /// # Example
    /// ```rust,ignore
    /// Dom::create_icon("home")
    ///     .with_class("nav-icon")
    /// ```
    #[inline(always)]
    pub fn create_icon<S: Into<AzString>>(icon_name: S) -> Self {
        Self::create_node(NodeType::Icon(icon_name.into()))
    }

    #[inline(always)]
    pub fn create_iframe(data: RefAny, callback: impl Into<IFrameCallback>) -> Self {
        Self::create_node(NodeType::IFrame(IFrameNode {
            callback: callback.into(),
            refany: data,
        }))
    }

    // Semantic HTML Elements with Accessibility Guidance

    /// Creates a paragraph element.
    ///
    /// **Accessibility**: Paragraphs provide semantic structure for screen readers.
    #[inline(always)]
    pub const fn create_p() -> Self {
        Self {
            root: NodeData::create_node(NodeType::P),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates a heading level 1 element.
    ///
    /// **Accessibility**: Use `h1` for the main page title. There should typically be only one `h1`
    /// per page.
    ///
    /// **Parameters:**
    /// - `text`: Heading text
    #[inline]
    pub fn h1<S: Into<AzString>>(text: S) -> Self {
        Self {
            root: NodeData::create_node(NodeType::H1),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
        .with_child(Self::create_text(text))
    }

    /// Creates a heading level 2 element.
    ///
    /// **Accessibility**: Use `h2` for major section headings under `h1`.
    ///
    /// **Parameters:**
    /// - `text`: Heading text
    #[inline]
    pub fn h2<S: Into<AzString>>(text: S) -> Self {
        Self {
            root: NodeData::create_node(NodeType::H2),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
        .with_child(Self::create_text(text))
    }

    /// Creates a heading level 3 element.
    ///
    /// **Accessibility**: Use `h3` for subsections under `h2`.
    ///
    /// **Parameters:**
    /// - `text`: Heading text
    #[inline]
    pub fn h3<S: Into<AzString>>(text: S) -> Self {
        Self {
            root: NodeData::create_node(NodeType::H3),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
        .with_child(Self::create_text(text))
    }

    /// Creates a heading level 4 element.
    ///
    /// **Parameters:**
    /// - `text`: Heading text
    #[inline]
    pub fn h4<S: Into<AzString>>(text: S) -> Self {
        Self {
            root: NodeData::create_node(NodeType::H4),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
        .with_child(Self::create_text(text))
    }

    /// Creates a heading level 5 element.
    ///
    /// **Parameters:**
    /// - `text`: Heading text
    #[inline]
    pub fn h5<S: Into<AzString>>(text: S) -> Self {
        Self {
            root: NodeData::create_node(NodeType::H5),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
        .with_child(Self::create_text(text))
    }

    /// Creates a heading level 6 element.
    ///
    /// **Parameters:**
    /// - `text`: Heading text
    #[inline]
    pub fn h6<S: Into<AzString>>(text: S) -> Self {
        Self {
            root: NodeData::create_node(NodeType::H6),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
        .with_child(Self::create_text(text))
    }

    /// Creates a generic inline container (span).
    ///
    /// **Accessibility**: Prefer semantic elements like `strong`, `em`, `code`, etc. when
    /// applicable.
    ///
    /// **Parameters:**
    /// - `text`: Span content
    #[inline]
    pub fn span<S: Into<AzString>>(text: S) -> Self {
        Self {
            root: NodeData::create_node(NodeType::Span),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
        .with_child(Self::create_text(text))
    }

    /// Creates a strongly emphasized text element (strong importance).
    ///
    /// **Accessibility**: Use `strong` instead of `b` for semantic meaning. Screen readers can
    /// convey the importance. Use for text that has strong importance, seriousness, or urgency.
    ///
    /// **Parameters:**
    /// - `text`: Text to emphasize
    #[inline]
    pub fn strong<S: Into<AzString>>(text: S) -> Self {
        Self {
            root: NodeData::create_node(NodeType::Strong),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
        .with_child(Self::create_text(text))
    }

    /// Creates an emphasized text element (stress emphasis).
    ///
    /// **Accessibility**: Use `em` instead of `i` for semantic meaning. Screen readers can
    /// convey the emphasis. Use for text that has stress emphasis.
    ///
    /// **Parameters:**
    /// - `text`: Text to emphasize
    #[inline]
    pub fn em<S: Into<AzString>>(text: S) -> Self {
        Self {
            root: NodeData::create_node(NodeType::Em),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
        .with_child(Self::create_text(text))
    }

    /// Creates a code/computer code element.
    ///
    /// **Accessibility**: Represents a fragment of computer code. Screen readers can identify
    /// this as code content.
    ///
    /// **Parameters:**
    /// - `code`: Code content
    #[inline]
    pub fn code<S: Into<AzString>>(code: S) -> Self {
        Self::create_node(NodeType::Code).with_child(Self::create_text(code))
    }

    /// Creates a preformatted text element.
    ///
    /// **Accessibility**: Preserves whitespace and line breaks. Useful for code blocks or
    /// ASCII art. Screen readers will read the content as-is.
    ///
    /// **Parameters:**
    /// - `text`: Preformatted content
    #[inline]
    pub fn pre<S: Into<AzString>>(text: S) -> Self {
        Self::create_node(NodeType::Pre).with_child(Self::create_text(text))
    }

    /// Creates a blockquote element.
    ///
    /// **Accessibility**: Represents a section quoted from another source. Screen readers
    /// can identify quoted content. Consider adding a `cite` attribute.
    ///
    /// **Parameters:**
    /// - `text`: Quote content
    #[inline]
    pub fn blockquote<S: Into<AzString>>(text: S) -> Self {
        Self::create_node(NodeType::BlockQuote).with_child(Self::create_text(text))
    }

    /// Creates a citation element.
    ///
    /// **Accessibility**: Represents a reference to a creative work. Screen readers can
    /// identify citations.
    ///
    /// **Parameters:**
    /// - `text`: Citation text
    #[inline]
    pub fn cite<S: Into<AzString>>(text: S) -> Self {
        Self::create_node(NodeType::Cite).with_child(Self::create_text(text))
    }

    /// Creates an abbreviation element.
    ///
    /// **Accessibility**: Represents an abbreviation or acronym. Use with a `title` attribute
    /// to provide the full expansion for screen readers.
    ///
    /// **Parameters:**
    /// - `abbr_text`: Abbreviated text
    /// - `title`: Full expansion
    #[inline]
    pub fn create_abbr(abbr_text: AzString, title: AzString) -> Self {
        Self::create_node(NodeType::Abbr)
            .with_attribute(AttributeType::Title(title))
            .with_child(Self::create_text(abbr_text))
    }

    /// Creates a keyboard input element.
    ///
    /// **Accessibility**: Represents keyboard input or key combinations. Screen readers can
    /// identify keyboard instructions.
    ///
    /// **Parameters:**
    /// - `text`: Keyboard instruction
    #[inline]
    pub fn kbd<S: Into<AzString>>(text: S) -> Self {
        Self::create_node(NodeType::Kbd).with_child(Self::create_text(text))
    }

    /// Creates a sample output element.
    ///
    /// **Accessibility**: Represents sample output from a program or computing system.
    ///
    /// **Parameters:**
    /// - `text`: Sample text
    #[inline]
    pub fn samp<S: Into<AzString>>(text: S) -> Self {
        Self::create_node(NodeType::Samp).with_child(Self::create_text(text))
    }

    /// Creates a variable element.
    ///
    /// **Accessibility**: Represents a variable in mathematical expressions or programming.
    ///
    /// **Parameters:**
    /// - `text`: Variable name
    #[inline]
    pub fn var<S: Into<AzString>>(text: S) -> Self {
        Self::create_node(NodeType::Var).with_child(Self::create_text(text))
    }

    /// Creates a subscript element.
    ///
    /// **Accessibility**: Screen readers may announce subscript formatting.
    ///
    /// **Parameters:**
    /// - `text`: Subscript content
    #[inline]
    pub fn sub<S: Into<AzString>>(text: S) -> Self {
        Self::create_node(NodeType::Sub).with_child(Self::create_text(text))
    }

    /// Creates a superscript element.
    ///
    /// **Accessibility**: Screen readers may announce superscript formatting.
    ///
    /// **Parameters:**
    /// - `text`: Superscript content
    #[inline]
    pub fn sup<S: Into<AzString>>(text: S) -> Self {
        Self::create_node(NodeType::Sup).with_child(Self::create_text(text))
    }

    /// Creates an underline text element.
    ///
    /// **Accessibility**: Screen readers typically don't announce underline formatting.
    /// Use semantic elements when possible (e.g., `<em>` for emphasis).
    #[inline]
    pub fn u<S: Into<AzString>>(text: S) -> Self {
        Self::create_node(NodeType::U).with_child(Self::create_text(text))
    }

    /// Creates a strikethrough text element.
    ///
    /// **Accessibility**: Represents text that is no longer accurate or relevant.
    /// Consider using `<del>` for deleted content with datetime attribute.
    #[inline]
    pub fn s<S: Into<AzString>>(text: S) -> Self {
        Self::create_node(NodeType::S).with_child(Self::create_text(text))
    }

    /// Creates a marked/highlighted text element.
    ///
    /// **Accessibility**: Represents text marked for reference or notation purposes.
    /// Screen readers may announce this as "highlighted".
    #[inline]
    pub fn mark<S: Into<AzString>>(text: S) -> Self {
        Self::create_node(NodeType::Mark).with_child(Self::create_text(text))
    }

    /// Creates a deleted text element.
    ///
    /// **Accessibility**: Represents deleted content in document edits.
    /// Use with `datetime` and `cite` attributes for edit tracking.
    #[inline]
    pub fn del<S: Into<AzString>>(text: S) -> Self {
        Self::create_node(NodeType::Del).with_child(Self::create_text(text))
    }

    /// Creates an inserted text element.
    ///
    /// **Accessibility**: Represents inserted content in document edits.
    /// Use with `datetime` and `cite` attributes for edit tracking.
    #[inline]
    pub fn ins<S: Into<AzString>>(text: S) -> Self {
        Self::create_node(NodeType::Ins).with_child(Self::create_text(text))
    }

    /// Creates a definition element.
    ///
    /// **Accessibility**: Represents the defining instance of a term.
    /// Often used within a definition list or with `<abbr>`.
    #[inline]
    pub fn dfn<S: Into<AzString>>(text: S) -> Self {
        Self::create_node(NodeType::Dfn).with_child(Self::create_text(text))
    }

    /// Creates a time element.
    ///
    /// **Accessibility**: Represents a specific time or date.
    /// Use `datetime` attribute for machine-readable format.
    ///
    /// **Parameters:**
    /// - `text`: Human-readable time/date
    /// - `datetime`: Optional machine-readable datetime
    #[inline]
    pub fn create_time(text: AzString, datetime: OptionString) -> Self {
        let mut element = Self::create_node(NodeType::Time).with_child(Self::create_text(text));
        if let OptionString::Some(dt) = datetime {
            element = element.with_attribute(AttributeType::Custom(AttributeNameValue {
                attr_name: "datetime".into(),
                value: dt,
            }));
        }
        element
    }

    /// Creates a bi-directional override element.
    ///
    /// **Accessibility**: Overrides text direction. Use `dir` attribute (ltr/rtl).
    #[inline]
    pub fn bdo<S: Into<AzString>>(text: S) -> Self {
        Self::create_node(NodeType::Bdo).with_child(Self::create_text(text))
    }

    /// Creates an anchor/hyperlink element.
    ///
    /// **Accessibility**: Always provide meaningful link text. Avoid "click here" or "read more".
    /// Screen readers often navigate by links, so descriptive text is crucial.
    ///
    /// **Parameters:**
    /// - `href`: Link destination URL
    /// - `label`: Link text (pass `None` for image-only links with alt text)
    #[inline]
    pub fn create_a(href: AzString, label: OptionString) -> Self {
        let mut link = Self::create_node(NodeType::A).with_attribute(AttributeType::Href(href));
        if let OptionString::Some(text) = label {
            link = link.with_child(Self::create_text(text));
        }
        link
    }

    /// Creates a button element.
    ///
    /// **Accessibility**: Buttons are keyboard accessible by default. Always provide clear
    /// button text or an `aria-label` for icon-only buttons.
    ///
    /// **Parameters:**
    /// - `text`: Button label text
    #[inline]
    pub fn create_button(text: AzString) -> Self {
        Self::create_node(NodeType::Button).with_child(Self::create_text(text))
    }

    /// Creates a label element for form controls.
    ///
    /// **Accessibility**: Always associate labels with form controls using `for` attribute
    /// or by wrapping the control. This is critical for screen reader users.
    ///
    /// **Parameters:**
    /// - `for_id`: ID of the associated form control
    /// - `text`: Label text
    #[inline]
    pub fn create_label(for_id: AzString, text: AzString) -> Self {
        Self::create_node(NodeType::Label)
            .with_attribute(AttributeType::Custom(AttributeNameValue {
                attr_name: "for".into(),
                value: for_id,
            }))
            .with_child(Self::create_text(text))
    }

    /// Creates an input element.
    ///
    /// **Accessibility**: Always provide a label or `aria-label`. Set appropriate `type`
    /// and `aria-` attributes for the input's purpose.
    ///
    /// **Parameters:**
    /// - `input_type`: Input type (text, password, email, etc.)
    /// - `name`: Form field name
    /// - `label`: Accessibility label (required)
    #[inline]
    pub fn create_input(input_type: AzString, name: AzString, label: AzString) -> Self {
        Self::create_node(NodeType::Input)
            .with_attribute(AttributeType::InputType(input_type))
            .with_attribute(AttributeType::Name(name))
            .with_attribute(AttributeType::AriaLabel(label))
    }

    /// Creates a textarea element.
    ///
    /// **Accessibility**: Always provide a label or `aria-label`. Consider `aria-describedby`
    /// for additional instructions.
    ///
    /// **Parameters:**
    /// - `name`: Form field name
    /// - `label`: Accessibility label (required)
    #[inline]
    pub fn create_textarea(name: AzString, label: AzString) -> Self {
        Self::create_node(NodeType::TextArea)
            .with_attribute(AttributeType::Name(name))
            .with_attribute(AttributeType::AriaLabel(label))
    }

    /// Creates a select dropdown element.
    ///
    /// **Accessibility**: Always provide a label. Group related options with `optgroup`.
    ///
    /// **Parameters:**
    /// - `name`: Form field name
    /// - `label`: Accessibility label (required)
    #[inline]
    pub fn create_select(name: AzString, label: AzString) -> Self {
        Self::create_node(NodeType::Select)
            .with_attribute(AttributeType::Name(name))
            .with_attribute(AttributeType::AriaLabel(label))
    }

    /// Creates an option element for select dropdowns.
    ///
    /// **Parameters:**
    /// - `value`: Option value
    /// - `text`: Display text
    #[inline]
    pub fn create_option(value: AzString, text: AzString) -> Self {
        Self::create_node(NodeType::SelectOption)
            .with_attribute(AttributeType::Value(value))
            .with_child(Self::create_text(text))
    }

    /// Creates an unordered list element.
    ///
    /// **Accessibility**: Screen readers announce lists and item counts, helping users
    /// understand content structure.
    #[inline(always)]
    pub fn create_ul() -> Self {
        Self::create_node(NodeType::Ul)
    }

    /// Creates an ordered list element.
    ///
    /// **Accessibility**: Screen readers announce lists and item counts, helping users
    /// understand content structure and numbering.
    #[inline(always)]
    pub fn create_ol() -> Self {
        Self::create_node(NodeType::Ol)
    }

    /// Creates a list item element.
    ///
    /// **Accessibility**: Must be a child of `ul`, `ol`, or `menu`. Screen readers announce
    /// list item position (e.g., "2 of 5").
    #[inline(always)]
    pub fn create_li() -> Self {
        Self::create_node(NodeType::Li)
    }

    /// Creates a table element.
    ///
    /// **Accessibility**: Use proper table structure with `thead`, `tbody`, `th`, and `td`.
    /// Provide a `caption` for table purpose. Use `scope` attribute on header cells.
    #[inline(always)]
    pub fn create_table() -> Self {
        Self::create_node(NodeType::Table)
    }

    /// Creates a table caption element.
    ///
    /// **Accessibility**: Describes the purpose of the table. Screen readers announce this first.
    #[inline(always)]
    pub fn create_caption() -> Self {
        Self::create_node(NodeType::Caption)
    }

    /// Creates a table header element.
    ///
    /// **Accessibility**: Groups header rows. Screen readers can navigate table structure.
    #[inline(always)]
    pub fn create_thead() -> Self {
        Self::create_node(NodeType::THead)
    }

    /// Creates a table body element.
    ///
    /// **Accessibility**: Groups body rows. Screen readers can navigate table structure.
    #[inline(always)]
    pub fn create_tbody() -> Self {
        Self::create_node(NodeType::TBody)
    }

    /// Creates a table footer element.
    ///
    /// **Accessibility**: Groups footer rows. Screen readers can navigate table structure.
    #[inline(always)]
    pub fn create_tfoot() -> Self {
        Self::create_node(NodeType::TFoot)
    }

    /// Creates a table row element.
    #[inline(always)]
    pub fn create_tr() -> Self {
        Self::create_node(NodeType::Tr)
    }

    /// Creates a table header cell element.
    ///
    /// **Accessibility**: Use `scope` attribute ("col" or "row") to associate headers with
    /// data cells. Screen readers use this to announce cell context.
    #[inline(always)]
    pub fn create_th() -> Self {
        Self::create_node(NodeType::Th)
    }

    /// Creates a table data cell element.
    #[inline(always)]
    pub fn create_td() -> Self {
        Self::create_node(NodeType::Td)
    }

    /// Creates a form element.
    ///
    /// **Accessibility**: Group related form controls with `fieldset` and `legend`.
    /// Provide clear labels for all inputs. Consider `aria-describedby` for instructions.
    #[inline(always)]
    pub fn create_form() -> Self {
        Self::create_node(NodeType::Form)
    }

    /// Creates a fieldset element for grouping form controls.
    ///
    /// **Accessibility**: Groups related form controls. Always include a `legend` as the
    /// first child to describe the group. Screen readers announce the legend when entering
    /// the fieldset.
    #[inline(always)]
    pub fn create_fieldset() -> Self {
        Self::create_node(NodeType::FieldSet)
    }

    /// Creates a legend element for fieldsets.
    ///
    /// **Accessibility**: Describes the purpose of a fieldset. Must be the first child of
    /// a fieldset. Screen readers announce this when entering the fieldset.
    #[inline(always)]
    pub fn create_legend() -> Self {
        Self::create_node(NodeType::Legend)
    }

    /// Creates a horizontal rule element.
    ///
    /// **Accessibility**: Represents a thematic break. Screen readers may announce this as
    /// a separator. Consider using CSS borders for purely decorative lines.
    #[inline(always)]
    pub fn create_hr() -> Self {
        Self::create_node(NodeType::Hr)
    }

    // Additional Element Constructors

    /// Creates an address element.
    ///
    /// **Accessibility**: Represents contact information. Screen readers identify this
    /// as address content.
    #[inline(always)]
    pub const fn create_address() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Address),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates a definition list element.
    ///
    /// **Accessibility**: Screen readers announce definition lists and their structure.
    #[inline(always)]
    pub const fn create_dl() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Dl),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates a definition term element.
    ///
    /// **Accessibility**: Must be a child of `dl`. Represents the term being defined.
    #[inline(always)]
    pub const fn create_dt() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Dt),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates a definition description element.
    ///
    /// **Accessibility**: Must be a child of `dl`. Provides the definition for the term.
    #[inline(always)]
    pub const fn create_dd() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Dd),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates a table column group element.
    #[inline(always)]
    pub const fn create_colgroup() -> Self {
        Self {
            root: NodeData::create_node(NodeType::ColGroup),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates a table column element.
    #[inline]
    pub fn create_col(span: i32) -> Self {
        Self::create_node(NodeType::Col).with_attribute(AttributeType::ColSpan(span))
    }

    /// Creates an optgroup element for grouping select options.
    ///
    /// **Parameters:**
    /// - `label`: Label for the option group
    #[inline]
    pub fn create_optgroup(label: AzString) -> Self {
        Self::create_node(NodeType::OptGroup).with_attribute(AttributeType::AriaLabel(label))
    }

    /// Creates a quotation element.
    ///
    /// **Accessibility**: Represents an inline quotation.
    #[inline(always)]
    pub const fn create_q() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Q),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates an acronym element.
    ///
    /// **Note**: Deprecated in HTML5. Consider using `abbr()` instead.
    #[inline(always)]
    pub const fn acronym() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Acronym),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates a menu element.
    ///
    /// **Accessibility**: Represents a list of commands. Similar to `<ul>` but semantic for
    /// toolbars/menus.
    #[inline(always)]
    pub const fn create_menu() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Menu),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates a menu item element.
    ///
    /// **Accessibility**: Represents a command in a menu. Use with appropriate role/aria
    /// attributes.
    #[inline(always)]
    pub const fn menuitem() -> Self {
        Self {
            root: NodeData::create_node(NodeType::MenuItem),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates an output element.
    ///
    /// **Accessibility**: Represents the result of a calculation or user action.
    /// Use `for` attribute to associate with input elements. Screen readers announce updates.
    #[inline(always)]
    pub const fn create_output() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Output),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates a progress indicator element.
    ///
    /// **Accessibility**: Represents task progress. Use `value` and `max` attributes.
    /// Screen readers announce progress percentage. Use aria-label to describe the task.
    #[inline]
    pub fn create_progress(value: f32, max: f32) -> Self {
        Self::create_node(NodeType::Progress)
            .with_attribute(AttributeType::Custom(AttributeNameValue {
                attr_name: "value".into(),
                value: value.to_string().into(),
            }))
            .with_attribute(AttributeType::Custom(AttributeNameValue {
                attr_name: "max".into(),
                value: max.to_string().into(),
            }))
    }

    /// Creates a meter gauge element.
    ///
    /// **Accessibility**: Represents a scalar measurement within a known range.
    /// Use `value`, `min`, `max`, `low`, `high`, `optimum` attributes.
    /// Screen readers announce the measurement. Provide aria-label for context.
    #[inline]
    pub fn create_meter(value: f32, min: f32, max: f32) -> Self {
        Self::create_node(NodeType::Meter)
            .with_attribute(AttributeType::Custom(AttributeNameValue {
                attr_name: "value".into(),
                value: value.to_string().into(),
            }))
            .with_attribute(AttributeType::Custom(AttributeNameValue {
                attr_name: "min".into(),
                value: min.to_string().into(),
            }))
            .with_attribute(AttributeType::Custom(AttributeNameValue {
                attr_name: "max".into(),
                value: max.to_string().into(),
            }))
    }

    /// Creates a datalist element for input suggestions.
    ///
    /// **Accessibility**: Provides autocomplete options for inputs.
    /// Associate with input using `list` attribute. Screen readers announce available options.
    #[inline(always)]
    pub const fn create_datalist() -> Self {
        Self {
            root: NodeData::create_node(NodeType::DataList),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    // Embedded Content Elements

    /// Creates a canvas element for graphics.
    ///
    /// **Accessibility**: Canvas content is not accessible by default.
    /// Always provide fallback content as children and/or detailed aria-label.
    /// Consider using SVG for accessible graphics when possible.
    #[inline(always)]
    pub const fn create_canvas() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Canvas),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates an object element for embedded content.
    ///
    /// **Accessibility**: Provide fallback content as children. Use aria-label to describe content.
    #[inline(always)]
    pub const fn create_object() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Object),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates a param element for object parameters.
    ///
    /// **Parameters:**
    /// - `name`: Parameter name
    /// - `value`: Parameter value
    #[inline]
    pub fn create_param(name: AzString, value: AzString) -> Self {
        Self::create_node(NodeType::Param)
            .with_attribute(AttributeType::Name(name))
            .with_attribute(AttributeType::Value(value))
    }

    /// Creates an embed element.
    ///
    /// **Accessibility**: Provide alternative content or link. Use aria-label to describe embedded
    /// content.
    #[inline(always)]
    pub const fn create_embed() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Embed),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates an audio element.
    ///
    /// **Accessibility**: Always provide controls. Use `<track>` for captions/subtitles.
    /// Provide fallback text for unsupported browsers.
    #[inline(always)]
    pub const fn create_audio() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Audio),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates a video element.
    ///
    /// **Accessibility**: Always provide controls. Use `<track>` for
    /// captions/subtitles/descriptions. Provide fallback text. Consider providing transcript.
    #[inline(always)]
    pub const fn create_video() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Video),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates a source element for media.
    ///
    /// **Parameters:**
    /// - `src`: Media source URL
    /// - `media_type`: MIME type (e.g., "video/mp4", "audio/ogg")
    #[inline]
    pub fn create_source(src: AzString, media_type: AzString) -> Self {
        Self::create_node(NodeType::Source)
            .with_attribute(AttributeType::Src(src))
            .with_attribute(AttributeType::Custom(AttributeNameValue {
                attr_name: "type".into(),
                value: media_type,
            }))
    }

    /// Creates a track element for media captions/subtitles.
    ///
    /// **Accessibility**: Essential for deaf/hard-of-hearing users and non-native speakers.
    /// Use `kind` (subtitles/captions/descriptions), `srclang`, and `label` attributes.
    ///
    /// **Parameters:**
    /// - `src`: Track file URL (WebVTT format)
    /// - `kind`: Track kind ("subtitles", "captions", "descriptions", "chapters", "metadata")
    #[inline]
    pub fn create_track(src: AzString, kind: AzString) -> Self {
        Self::create_node(NodeType::Track)
            .with_attribute(AttributeType::Src(src))
            .with_attribute(AttributeType::Custom(AttributeNameValue {
                attr_name: "kind".into(),
                value: kind,
            }))
    }

    /// Creates a map element for image maps.
    ///
    /// **Accessibility**: Provide text alternatives. Ensure all areas have alt text.
    #[inline(always)]
    pub const fn create_map() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Map),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates an area element for image map regions.
    ///
    /// **Accessibility**: Always provide `alt` text describing the region/link purpose.
    /// Keyboard users should be able to navigate areas.
    #[inline(always)]
    pub const fn create_area() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Area),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    // Metadata Elements

    /// Creates a title element for document title.
    ///
    /// **Accessibility**: Required for all pages. Screen readers announce this first.
    /// Should be unique and descriptive. Keep under 60 characters.
    #[inline]
    pub fn title<S: Into<AzString>>(text: S) -> Self {
        Self::create_node(NodeType::Title).with_child(Self::create_text(text))
    }

    /// Creates a meta element.
    ///
    /// **Accessibility**: Use for charset, viewport, description. Crucial for proper text display.
    #[inline(always)]
    pub const fn meta() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Meta),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates a link element for external resources.
    ///
    /// **Accessibility**: Use for stylesheets, icons, alternate versions.
    /// Provide meaningful `title` attribute for alternate stylesheets.
    #[inline(always)]
    pub const fn create_link() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Link),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates a script element.
    ///
    /// **Accessibility**: Ensure scripted content is accessible.
    /// Provide noscript fallbacks for critical functionality.
    #[inline(always)]
    pub const fn create_script() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Script),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates a style element for embedded CSS.
    ///
    /// **Note**: In Azul, use the `.style()` method instead for styling.
    /// This creates a `<style>` HTML element for embedded stylesheets.
    #[inline(always)]
    pub const fn style_element() -> Self {
        Self {
            root: NodeData::create_node(NodeType::Style),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        }
    }

    /// Creates a base element for document base URL.
    ///
    /// **Parameters:**
    /// - `href`: Base URL for relative URLs in the document
    #[inline]
    pub fn base(href: AzString) -> Self {
        Self::create_node(NodeType::Base).with_attribute(AttributeType::Href(href))
    }

    // Advanced Constructors with Parameters

    /// Creates a table header cell with scope.
    ///
    /// **Parameters:**
    /// - `scope`: "col", "row", "colgroup", or "rowgroup"
    /// - `text`: Header text
    ///
    /// **Accessibility**: The scope attribute is crucial for associating headers with data cells.
    #[inline]
    pub fn th_with_scope(scope: AzString, text: AzString) -> Self {
        Self::create_node(NodeType::Th)
            .with_attribute(AttributeType::Scope(scope))
            .with_child(Self::create_text(text))
    }

    /// Creates a table data cell with text.
    ///
    /// **Parameters:**
    /// - `text`: Cell content
    #[inline]
    pub fn td_with_text<S: Into<AzString>>(text: S) -> Self {
        Self::create_td().with_child(Self::create_text(text))
    }

    /// Creates a table header cell with text.
    ///
    /// **Parameters:**
    /// - `text`: Header text
    #[inline]
    pub fn th_with_text<S: Into<AzString>>(text: S) -> Self {
        Self::create_th().with_child(Self::create_text(text))
    }

    /// Creates a list item with text.
    ///
    /// **Parameters:**
    /// - `text`: List item content
    #[inline]
    pub fn li_with_text<S: Into<AzString>>(text: S) -> Self {
        Self::create_li().with_child(Self::create_text(text))
    }

    /// Creates a paragraph with text.
    ///
    /// **Parameters:**
    /// - `text`: Paragraph content
    #[inline]
    pub fn p_with_text<S: Into<AzString>>(text: S) -> Self {
        Self::create_p().with_child(Self::create_text(text))
    }

    // Accessibility-Aware Constructors
    // These constructors require explicit accessibility information.

    /// Creates a button with text content and accessibility information.
    ///
    /// **Parameters:**
    /// - `text`: The visible button text
    /// - `aria`: Accessibility information (role, description, etc.)
    #[inline]
    pub fn button_with_aria<S: Into<AzString>>(text: S, aria: SmallAriaInfo) -> Self {
        let mut btn = Self::create_button(text.into());
        btn.root.set_accessibility_info(aria.to_full_info());
        btn
    }

    /// Creates a link (anchor) with href, text, and accessibility information.
    ///
    /// **Parameters:**
    /// - `href`: The link destination
    /// - `text`: The visible link text
    /// - `aria`: Accessibility information (expanded description, etc.)
    #[inline]
    pub fn link_with_aria<S1: Into<AzString>, S2: Into<AzString>>(
        href: S1,
        text: S2,
        aria: SmallAriaInfo,
    ) -> Self {
        let mut link = Self::create_a(href.into(), OptionString::Some(text.into()));
        link.root.set_accessibility_info(aria.to_full_info());
        link
    }

    /// Creates an input element with type, name, and accessibility information.
    ///
    /// **Parameters:**
    /// - `input_type`: The input type (text, password, email, etc.)
    /// - `name`: The form field name
    /// - `label`: Base accessibility label
    /// - `aria`: Additional accessibility information (description, etc.)
    #[inline]
    pub fn input_with_aria<S1: Into<AzString>, S2: Into<AzString>, S3: Into<AzString>>(
        input_type: S1,
        name: S2,
        label: S3,
        aria: SmallAriaInfo,
    ) -> Self {
        let mut input = Self::create_input(input_type.into(), name.into(), label.into());
        input.root.set_accessibility_info(aria.to_full_info());
        input
    }

    /// Creates a textarea with name and accessibility information.
    ///
    /// **Parameters:**
    /// - `name`: The form field name
    /// - `label`: Base accessibility label
    /// - `aria`: Additional accessibility information (description, etc.)
    #[inline]
    pub fn textarea_with_aria<S1: Into<AzString>, S2: Into<AzString>>(
        name: S1,
        label: S2,
        aria: SmallAriaInfo,
    ) -> Self {
        let mut textarea = Self::create_textarea(name.into(), label.into());
        textarea.root.set_accessibility_info(aria.to_full_info());
        textarea
    }

    /// Creates a select dropdown with name and accessibility information.
    ///
    /// **Parameters:**
    /// - `name`: The form field name
    /// - `label`: Base accessibility label
    /// - `aria`: Additional accessibility information (description, etc.)
    #[inline]
    pub fn select_with_aria<S1: Into<AzString>, S2: Into<AzString>>(
        name: S1,
        label: S2,
        aria: SmallAriaInfo,
    ) -> Self {
        let mut select = Self::create_select(name.into(), label.into());
        select.root.set_accessibility_info(aria.to_full_info());
        select
    }

    /// Creates a table with caption and accessibility information.
    ///
    /// **Parameters:**
    /// - `caption`: Table caption (visible title)
    /// - `aria`: Accessibility information describing table purpose
    #[inline]
    pub fn table_with_aria<S: Into<AzString>>(caption: S, aria: SmallAriaInfo) -> Self {
        let mut table = Self::create_table()
            .with_child(Self::create_caption().with_child(Self::create_text(caption)));
        table.root.set_accessibility_info(aria.to_full_info());
        table
    }

    /// Creates a label for a form control with additional accessibility information.
    ///
    /// **Parameters:**
    /// - `for_id`: The ID of the associated form control
    /// - `text`: The visible label text
    /// - `aria`: Additional accessibility information (description, etc.)
    #[inline]
    pub fn label_with_aria<S1: Into<AzString>, S2: Into<AzString>>(
        for_id: S1,
        text: S2,
        aria: SmallAriaInfo,
    ) -> Self {
        let mut label = Self::create_label(for_id.into(), text.into());
        label.root.set_accessibility_info(aria.to_full_info());
        label
    }

    /// Parse XML/XHTML string into a DOM
    ///
    /// This is a simple wrapper that parses XML and converts it to a DOM.
    /// For now, it just creates a text node with the content since full XML parsing
    /// requires the xml feature and more complex parsing logic.
    #[cfg(feature = "xml")]
    pub fn from_xml<S: AsRef<str>>(xml_str: S) -> Self {
        // TODO: Implement full XML parsing
        // For now, just create a text node showing that XML was loaded
        Self::create_text(format!(
            "XML content loaded ({} bytes)",
            xml_str.as_ref().len()
        ))
    }

    /// Parse XML/XHTML string into a DOM (fallback without xml feature)
    #[cfg(not(feature = "xml"))]
    pub fn from_xml<S: AsRef<str>>(xml_str: S) -> Self {
        Self::create_text(format!(
            "XML parsing requires 'xml' feature ({} bytes)",
            xml_str.as_ref().len()
        ))
    }

    // Swaps `self` with a default DOM, necessary for builder methods
    #[inline(always)]
    pub fn swap_with_default(&mut self) -> Self {
        let mut s = Self {
            root: NodeData::create_div(),
            children: DomVec::from_const_slice(&[]),
            estimated_total_children: 0,
        };
        mem::swap(&mut s, self);
        s
    }

    #[inline]
    pub fn add_child(&mut self, child: Dom) {
        let estimated = child.estimated_total_children;
        let mut v: DomVec = Vec::new().into();
        mem::swap(&mut v, &mut self.children);
        let mut v = v.into_library_owned_vec();
        v.push(child);
        self.children = v.into();
        self.estimated_total_children += estimated + 1;
    }

    #[inline(always)]
    pub fn set_children(&mut self, children: DomVec) {
        let children_estimated = children
            .iter()
            .map(|s| s.estimated_total_children + 1)
            .sum();
        self.children = children;
        self.estimated_total_children = children_estimated;
    }

    pub fn copy_except_for_root(&mut self) -> Self {
        Self {
            root: self.root.copy_special(),
            children: self.children.clone(),
            estimated_total_children: self.estimated_total_children,
        }
    }
    pub fn node_count(&self) -> usize {
        self.estimated_total_children + 1
    }

    pub fn style(&mut self, css: azul_css::css::Css) -> StyledDom {
        StyledDom::create(self, css)
    }
    #[inline(always)]
    pub fn with_children(mut self, children: DomVec) -> Self {
        self.set_children(children);
        self
    }
    #[inline(always)]
    pub fn with_child(mut self, child: Self) -> Self {
        self.add_child(child);
        self
    }
    #[inline(always)]
    pub fn with_node_type(mut self, node_type: NodeType) -> Self {
        self.root.set_node_type(node_type);
        self
    }
    #[inline(always)]
    pub fn with_id(mut self, id: AzString) -> Self {
        self.root.add_id(id);
        self
    }
    #[inline(always)]
    pub fn with_class(mut self, class: AzString) -> Self {
        self.root.add_class(class);
        self
    }
    #[inline(always)]
    pub fn with_callback<C: Into<CoreCallback>>(
        mut self,
        event: EventFilter,
        data: RefAny,
        callback: C,
    ) -> Self {
        self.root.add_callback(event, data, callback);
        self
    }
    /// Add a CSS property with optional conditions (hover, focus, active, etc.)
    #[inline(always)]
    pub fn with_css_property(mut self, prop: CssPropertyWithConditions) -> Self {
        self.root.add_css_property(prop);
        self
    }
    /// Add a CSS property with optional conditions (hover, focus, active, etc.)
    #[inline(always)]
    pub fn add_css_property(&mut self, prop: CssPropertyWithConditions) {
        self.root.add_css_property(prop);
    }
    #[inline(always)]
    pub fn add_class(&mut self, class: AzString) {
        self.root.add_class(class);
    }
    #[inline(always)]
    pub fn add_callback<C: Into<CoreCallback>>(
        &mut self,
        event: EventFilter,
        data: RefAny,
        callback: C,
    ) {
        self.root.add_callback(event, data, callback);
    }
    #[inline(always)]
    pub fn set_tab_index(&mut self, tab_index: TabIndex) {
        self.root.set_tab_index(tab_index);
    }
    #[inline(always)]
    pub fn set_contenteditable(&mut self, contenteditable: bool) {
        self.root.set_contenteditable(contenteditable);
    }
    #[inline(always)]
    pub fn with_tab_index(mut self, tab_index: TabIndex) -> Self {
        self.root.set_tab_index(tab_index);
        self
    }
    #[inline(always)]
    pub fn with_contenteditable(mut self, contenteditable: bool) -> Self {
        self.root.set_contenteditable(contenteditable);
        self
    }
    #[inline(always)]
    pub fn with_dataset(mut self, data: OptionRefAny) -> Self {
        self.root.dataset = data;
        self
    }
    #[inline(always)]
    pub fn with_ids_and_classes(mut self, ids_and_classes: IdOrClassVec) -> Self {
        self.root.ids_and_classes = ids_and_classes;
        self
    }

    /// Adds an attribute to this DOM element.
    #[inline(always)]
    pub fn with_attribute(mut self, attr: AttributeType) -> Self {
        let mut attrs = self.root.attributes.clone();
        let mut v = attrs.into_library_owned_vec();
        v.push(attr);
        self.root.attributes = v.into();
        self
    }

    /// Adds multiple attributes to this DOM element.
    #[inline(always)]
    pub fn with_attributes(mut self, attributes: AttributeTypeVec) -> Self {
        self.root.attributes = attributes;
        self
    }

    #[inline(always)]
    pub fn with_callbacks(mut self, callbacks: CoreCallbackDataVec) -> Self {
        self.root.callbacks = callbacks;
        self
    }
    #[inline(always)]
    pub fn with_css_props(mut self, css_props: CssPropertyWithConditionsVec) -> Self {
        self.root.css_props = css_props;
        self
    }

    /// Assigns a stable key to the root node of this DOM for reconciliation.
    ///
    /// This is crucial for performance and correct state preservation when
    /// lists of items change order or items are inserted/removed.
    ///
    /// # Example
    /// ```rust
    /// Dom::create_div()
    ///     .with_key("user-avatar-123")
    /// ```
    #[inline]
    pub fn with_key<K: core::hash::Hash>(mut self, key: K) -> Self {
        self.root.set_key(key);
        self
    }

    /// Registers a callback to merge dataset state from the previous frame.
    ///
    /// This is used for components that maintain heavy internal state (video players,
    /// WebGL contexts, network connections) that should not be destroyed and recreated
    /// on every render frame.
    ///
    /// The callback receives both datasets as `RefAny` (cheap shallow clones) and
    /// returns the `RefAny` that should be used for the new node.
    #[inline]
    pub fn with_merge_callback<C: Into<DatasetMergeCallback>>(mut self, callback: C) -> Self {
        self.root.set_merge_callback(callback);
        self
    }

    pub fn set_inline_style(&mut self, style: &str) {
        self.root.set_inline_style(style);
    }

    pub fn with_inline_style(mut self, style: &str) -> Self {
        self.set_inline_style(style);
        self
    }
    
    /// Parse and set CSS styles with full selector support.
    /// 
    /// This is the unified API for setting inline CSS on a DOM node. It supports:
    /// - Simple properties: `color: red; font-size: 14px;`
    /// - Pseudo-selectors: `:hover { background: blue; }`
    /// - @-rules: `@os linux { font-size: 14px; }`
    /// - Nesting: `@os linux { font-size: 14px; :hover { color: red; }}`
    /// 
    /// # Examples
    /// ```rust
    /// // Simple inline styles
    /// Dom::create_div().with_css("color: red; font-size: 14px;")
    /// 
    /// // With hover and active states
    /// Dom::create_div().with_css("
    ///     color: blue;
    ///     :hover { color: red; }
    ///     :active { color: green; }
    /// ")
    /// 
    /// // OS-specific with nested hover
    /// Dom::create_div().with_css("
    ///     font-size: 12px;
    ///     @os linux { font-size: 14px; :hover { color: red; }}
    ///     @os windows { font-size: 13px; }
    /// ")
    /// ```
    pub fn set_css(&mut self, style: &str) {
        let parsed = CssPropertyWithConditionsVec::parse(style);
        let mut current = Vec::new().into();
        mem::swap(&mut current, &mut self.root.css_props);
        let mut v = current.into_library_owned_vec();
        v.extend(parsed.into_library_owned_vec());
        self.root.css_props = v.into();
    }
    
    /// Builder method for `set_css`
    pub fn with_css(mut self, style: &str) -> Self {
        self.set_css(style);
        self
    }

    /// Sets inline CSS styles for the hover state on the root node
    /// 
    /// Deprecated: Use `with_css(":hover { ... }")` instead
    pub fn set_inline_hover_style(&mut self, style: &str) {
        self.root.set_inline_hover_style(style);
    }

    /// Builder method for setting inline CSS styles for the hover state
    pub fn with_inline_hover_style(mut self, style: &str) -> Self {
        self.set_inline_hover_style(style);
        self
    }

    /// Sets inline CSS styles for the active state on the root node
    pub fn set_inline_active_style(&mut self, style: &str) {
        self.root.set_inline_active_style(style);
    }

    /// Builder method for setting inline CSS styles for the active state
    pub fn with_inline_active_style(mut self, style: &str) -> Self {
        self.set_inline_active_style(style);
        self
    }

    /// Sets inline CSS styles for the focus state on the root node
    pub fn set_inline_focus_style(&mut self, style: &str) {
        self.root.set_inline_focus_style(style);
    }

    /// Builder method for setting inline CSS styles for the focus state
    pub fn with_inline_focus_style(mut self, style: &str) -> Self {
        self.set_inline_focus_style(style);
        self
    }

    /// Sets the context menu for the root node
    #[inline]
    pub fn set_context_menu(&mut self, context_menu: Menu) {
        self.root.set_context_menu(context_menu);
    }

    #[inline]
    pub fn with_context_menu(mut self, context_menu: Menu) -> Self {
        self.set_context_menu(context_menu);
        self
    }

    /// Sets the menu bar for the root node
    #[inline]
    pub fn set_menu_bar(&mut self, menu_bar: Menu) {
        self.root.set_menu_bar(menu_bar);
    }

    #[inline]
    pub fn with_menu_bar(mut self, menu_bar: Menu) -> Self {
        self.set_menu_bar(menu_bar);
        self
    }

    #[inline]
    pub fn with_clip_mask(mut self, clip_mask: ImageMask) -> Self {
        self.root.set_clip_mask(clip_mask);
        self
    }

    #[inline]
    pub fn with_accessibility_info(mut self, accessibility_info: AccessibilityInfo) -> Self {
        self.root.set_accessibility_info(accessibility_info);
        self
    }

    pub fn fixup_children_estimated(&mut self) -> usize {
        if self.children.is_empty() {
            self.estimated_total_children = 0;
        } else {
            self.estimated_total_children = self
                .children
                .iter_mut()
                .map(|s| s.fixup_children_estimated() + 1)
                .sum();
        }
        return self.estimated_total_children;
    }
}

impl core::iter::FromIterator<Dom> for Dom {
    fn from_iter<I: IntoIterator<Item = Dom>>(iter: I) -> Self {
        let mut estimated_total_children = 0;
        let children = iter
            .into_iter()
            .map(|c| {
                estimated_total_children += c.estimated_total_children + 1;
                c
            })
            .collect::<Vec<Dom>>();

        Dom {
            root: NodeData::create_div(),
            children: children.into(),
            estimated_total_children,
        }
    }
}

impl fmt::Debug for Dom {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fn print_dom(d: &Dom, f: &mut fmt::Formatter) -> fmt::Result {
            write!(f, "Dom {{\r\n")?;
            write!(f, "\troot: {:#?}\r\n", d.root)?;
            write!(
                f,
                "\testimated_total_children: {:#?}\r\n",
                d.estimated_total_children
            )?;
            write!(f, "\tchildren: [\r\n")?;
            for c in d.children.iter() {
                print_dom(c, f)?;
            }
            write!(f, "\t]\r\n")?;
            write!(f, "}}\r\n")?;
            Ok(())
        }

        print_dom(self, f)
    }
}