accesskit 0.25.1

UI accessibility infrastructure across platforms
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
// Copyright 2021 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.

// Derived from Chromium's accessibility abstraction.
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE.chromium file.

#![cfg_attr(not(any(feature = "pyo3", feature = "schemars")), no_std)]

extern crate alloc;

#[cfg(feature = "schemars")]
use alloc::borrow::Cow;
use alloc::{borrow::ToOwned, boxed::Box, string::String, vec::Vec};
use core::fmt;
#[cfg(feature = "pyo3")]
use pyo3::pyclass;
#[cfg(feature = "schemars")]
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
#[cfg(feature = "serde")]
use serde::{
    Deserialize, Serialize,
    de::{Deserializer, IgnoredAny, MapAccess, Visitor},
    ser::{SerializeMap, Serializer},
};
#[cfg(feature = "schemars")]
use serde_json::{Map as SchemaMap, Value as SchemaValue};

pub use uuid::Uuid;

mod geometry;
pub use geometry::{Affine, Point, Rect, Size, Vec2};

/// The type of an accessibility node.
///
/// The majority of these roles come from the ARIA specification. Reference
/// the latest draft for proper usage.
///
/// Like the AccessKit schema as a whole, this list is largely taken
/// from Chromium. However, unlike Chromium's alphabetized list, this list
/// is ordered roughly by expected usage frequency (with the notable exception
/// of [`Role::Unknown`]). This is more efficient in serialization formats
/// where integers use a variable-length encoding.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "enumn", derive(enumn::N))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
#[cfg_attr(
    feature = "pyo3",
    pyclass(
        module = "accesskit",
        rename_all = "SCREAMING_SNAKE_CASE",
        eq,
        from_py_object
    )
)]
#[repr(u8)]
pub enum Role {
    #[default]
    Unknown,
    TextRun,
    Cell,
    Label,
    Image,
    Link,
    Row,
    ListItem,

    /// Contains the bullet, number, or other marker for a list item.
    ListMarker,

    TreeItem,
    ListBoxOption,
    MenuItem,
    MenuListOption,
    Paragraph,

    /// A generic container that should be ignored by assistive technologies
    /// and filtered out of platform accessibility trees. Equivalent to the ARIA
    /// `none` or `presentation` role, or to an HTML `div` with no role.
    GenericContainer,

    CheckBox,
    RadioButton,
    TextInput,
    Button,
    DefaultButton,
    Pane,
    RowHeader,
    ColumnHeader,
    RowGroup,
    List,
    Table,
    LayoutTableCell,
    LayoutTableRow,
    LayoutTable,
    Switch,
    Menu,

    MultilineTextInput,
    SearchInput,
    DateInput,
    DateTimeInput,
    WeekInput,
    MonthInput,
    TimeInput,
    EmailInput,
    NumberInput,
    PasswordInput,
    PhoneNumberInput,
    UrlInput,

    Abbr,
    Alert,
    AlertDialog,
    Application,
    Article,
    Audio,
    Banner,
    Blockquote,
    Canvas,
    Caption,
    Caret,
    Code,
    ColorWell,
    ComboBox,
    EditableComboBox,
    Complementary,
    Comment,
    ContentDeletion,
    ContentInsertion,
    ContentInfo,
    Definition,
    DescriptionList,
    Details,
    Dialog,
    DisclosureTriangle,
    Document,
    EmbeddedObject,
    Emphasis,
    Feed,
    FigureCaption,
    Figure,
    Footer,
    Form,
    Grid,
    GridCell,
    Group,
    Header,
    Heading,
    Iframe,
    IframePresentational,
    ImeCandidate,
    Keyboard,
    Legend,
    LineBreak,
    ListBox,
    Log,
    Main,
    Mark,
    Marquee,
    Math,
    MenuBar,
    MenuItemCheckBox,
    MenuItemRadio,
    MenuListPopup,
    Meter,
    Navigation,
    Note,
    PluginObject,
    ProgressIndicator,
    RadioGroup,
    Region,
    RootWebArea,
    Ruby,
    RubyAnnotation,
    ScrollBar,
    ScrollView,
    Search,
    Section,
    SectionFooter,
    SectionHeader,
    Slider,
    SpinButton,
    Splitter,
    Status,
    Strong,
    Suggestion,
    SvgRoot,
    Tab,
    TabList,
    TabPanel,
    Term,
    Time,
    Timer,
    TitleBar,
    Toolbar,
    Tooltip,
    Tree,
    TreeGrid,
    Video,
    WebView,
    Window,

    PdfActionableHighlight,
    PdfRoot,

    // ARIA Graphics module roles:
    // https://rawgit.com/w3c/graphics-aam/master/#mapping_role_table
    GraphicsDocument,
    GraphicsObject,
    GraphicsSymbol,

    // DPub Roles:
    // https://www.w3.org/TR/dpub-aam-1.0/#mapping_role_table
    DocAbstract,
    DocAcknowledgements,
    DocAfterword,
    DocAppendix,
    DocBackLink,
    DocBiblioEntry,
    DocBibliography,
    DocBiblioRef,
    DocChapter,
    DocColophon,
    DocConclusion,
    DocCover,
    DocCredit,
    DocCredits,
    DocDedication,
    DocEndnote,
    DocEndnotes,
    DocEpigraph,
    DocEpilogue,
    DocErrata,
    DocExample,
    DocFootnote,
    DocForeword,
    DocGlossary,
    DocGlossRef,
    DocIndex,
    DocIntroduction,
    DocNoteRef,
    DocNotice,
    DocPageBreak,
    DocPageFooter,
    DocPageHeader,
    DocPageList,
    DocPart,
    DocPreface,
    DocPrologue,
    DocPullquote,
    DocQna,
    DocSubtitle,
    DocTip,
    DocToc,

    /// Behaves similar to an ARIA grid but is primarily used by Chromium's
    /// `TableView` and its subclasses, so they can be exposed correctly
    /// on certain platforms.
    ListGrid,

    /// This is just like a multi-line document, but signals that assistive
    /// technologies should implement behavior specific to a VT-100-style
    /// terminal.
    Terminal,
}

/// An action to be taken on an accessibility node.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "enumn", derive(enumn::N))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
#[cfg_attr(
    feature = "pyo3",
    pyclass(
        module = "accesskit",
        rename_all = "SCREAMING_SNAKE_CASE",
        eq,
        from_py_object
    )
)]
#[repr(u8)]
pub enum Action {
    /// Do the equivalent of a single click or tap.
    Click,

    Focus,
    Blur,

    Collapse,
    Expand,

    /// Requires [`ActionRequest::data`] to be set to [`ActionData::CustomAction`].
    CustomAction,

    /// Decrement a numeric value by one step.
    Decrement,
    /// Increment a numeric value by one step.
    Increment,

    HideTooltip,
    ShowTooltip,

    /// Delete any selected text in the control's text value and
    /// insert the specified value in its place, like when typing or pasting.
    /// Requires [`ActionRequest::data`] to be set to [`ActionData::Value`].
    ReplaceSelectedText,

    /// Scroll down by the specified unit.
    ScrollDown,
    /// Scroll left by the specified unit.
    ScrollLeft,
    /// Scroll right by the specified unit.
    ScrollRight,
    /// Scroll up by the specified unit.
    ScrollUp,

    /// Scroll any scrollable containers to make the target node visible.
    /// Optionally set [`ActionRequest::data`] to [`ActionData::ScrollHint`].
    ScrollIntoView,

    /// Scroll the given object to a specified point in the tree's container
    /// (e.g. window). Requires [`ActionRequest::data`] to be set to
    /// [`ActionData::ScrollToPoint`].
    ScrollToPoint,

    /// Requires [`ActionRequest::data`] to be set to [`ActionData::SetScrollOffset`].
    SetScrollOffset,

    /// Requires [`ActionRequest::data`] to be set to [`ActionData::SetTextSelection`].
    SetTextSelection,

    /// Don't focus this node, but set it as the sequential focus navigation
    /// starting point, so that pressing Tab moves to the next element
    /// following this one, for example.
    SetSequentialFocusNavigationStartingPoint,

    /// Replace the value of the control with the specified value and
    /// reset the selection, if applicable. Requires [`ActionRequest::data`]
    /// to be set to [`ActionData::Value`] or [`ActionData::NumericValue`].
    SetValue,

    ShowContextMenu,
}

impl Action {
    fn mask(self) -> u32 {
        1 << (self as u8)
    }

    #[cfg(not(feature = "enumn"))]
    fn n(value: u8) -> Option<Self> {
        // Manually implement something similar to the enumn crate. We don't
        // want to bring this crate by default though and we can't use a
        // macro as it would break C bindings header file generation.
        match value {
            0 => Some(Action::Click),
            1 => Some(Action::Focus),
            2 => Some(Action::Blur),
            3 => Some(Action::Collapse),
            4 => Some(Action::Expand),
            5 => Some(Action::CustomAction),
            6 => Some(Action::Decrement),
            7 => Some(Action::Increment),
            8 => Some(Action::HideTooltip),
            9 => Some(Action::ShowTooltip),
            10 => Some(Action::ReplaceSelectedText),
            11 => Some(Action::ScrollDown),
            12 => Some(Action::ScrollLeft),
            13 => Some(Action::ScrollRight),
            14 => Some(Action::ScrollUp),
            15 => Some(Action::ScrollIntoView),
            16 => Some(Action::ScrollToPoint),
            17 => Some(Action::SetScrollOffset),
            18 => Some(Action::SetTextSelection),
            19 => Some(Action::SetSequentialFocusNavigationStartingPoint),
            20 => Some(Action::SetValue),
            21 => Some(Action::ShowContextMenu),
            _ => None,
        }
    }
}

fn action_mask_to_action_vec(mask: u32) -> Vec<Action> {
    let mut actions = Vec::new();
    let mut i = 0;
    while let Some(variant) = Action::n(i) {
        if mask & variant.mask() != 0 {
            actions.push(variant);
        }
        i += 1;
    }
    actions
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "enumn", derive(enumn::N))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
#[cfg_attr(
    feature = "pyo3",
    pyclass(
        module = "accesskit",
        rename_all = "SCREAMING_SNAKE_CASE",
        eq,
        from_py_object
    )
)]
#[repr(u8)]
pub enum Orientation {
    /// E.g. most toolbars and separators.
    Horizontal,
    /// E.g. menu or combo box.
    Vertical,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "enumn", derive(enumn::N))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
#[cfg_attr(
    feature = "pyo3",
    pyclass(
        module = "accesskit",
        rename_all = "SCREAMING_SNAKE_CASE",
        eq,
        from_py_object
    )
)]
#[repr(u8)]
pub enum TextDirection {
    LeftToRight,
    RightToLeft,
    TopToBottom,
    BottomToTop,
}

/// Indicates if a form control has invalid input or if a web DOM element has an
/// [`aria-invalid`] attribute.
///
/// [`aria-invalid`]: https://www.w3.org/TR/wai-aria-1.1/#aria-invalid
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "enumn", derive(enumn::N))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
#[cfg_attr(
    feature = "pyo3",
    pyclass(
        module = "accesskit",
        rename_all = "SCREAMING_SNAKE_CASE",
        eq,
        from_py_object
    )
)]
#[repr(u8)]
pub enum Invalid {
    True,
    Grammar,
    Spelling,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "enumn", derive(enumn::N))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
#[cfg_attr(
    feature = "pyo3",
    pyclass(
        module = "accesskit",
        rename_all = "SCREAMING_SNAKE_CASE",
        eq,
        from_py_object
    )
)]
#[repr(u8)]
pub enum Toggled {
    False,
    True,
    Mixed,
}

impl From<bool> for Toggled {
    #[inline]
    fn from(b: bool) -> Self {
        match b {
            false => Self::False,
            true => Self::True,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "enumn", derive(enumn::N))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
#[cfg_attr(
    feature = "pyo3",
    pyclass(
        module = "accesskit",
        rename_all = "SCREAMING_SNAKE_CASE",
        eq,
        from_py_object
    )
)]
#[repr(u8)]
pub enum SortDirection {
    Ascending,
    Descending,
    Other,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "enumn", derive(enumn::N))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
#[cfg_attr(
    feature = "pyo3",
    pyclass(
        module = "accesskit",
        rename_all = "SCREAMING_SNAKE_CASE",
        eq,
        from_py_object
    )
)]
#[repr(u8)]
pub enum AriaCurrent {
    False,
    True,
    Page,
    Step,
    Location,
    Date,
    Time,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "enumn", derive(enumn::N))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
#[cfg_attr(
    feature = "pyo3",
    pyclass(
        module = "accesskit",
        rename_all = "SCREAMING_SNAKE_CASE",
        eq,
        from_py_object
    )
)]
#[repr(u8)]
pub enum AutoComplete {
    Inline,
    List,
    Both,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "enumn", derive(enumn::N))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
#[cfg_attr(
    feature = "pyo3",
    pyclass(
        module = "accesskit",
        rename_all = "SCREAMING_SNAKE_CASE",
        eq,
        from_py_object
    )
)]
#[repr(u8)]
pub enum Live {
    Off,
    Polite,
    Assertive,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "enumn", derive(enumn::N))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
#[cfg_attr(
    feature = "pyo3",
    pyclass(
        module = "accesskit",
        rename_all = "SCREAMING_SNAKE_CASE",
        eq,
        from_py_object
    )
)]
#[repr(u8)]
pub enum HasPopup {
    Menu,
    Listbox,
    Tree,
    Grid,
    Dialog,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "enumn", derive(enumn::N))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
#[cfg_attr(
    feature = "pyo3",
    pyclass(
        module = "accesskit",
        rename_all = "SCREAMING_SNAKE_CASE",
        eq,
        from_py_object
    )
)]
#[repr(u8)]
pub enum ListStyle {
    Circle,
    Disc,
    Image,
    Numeric,
    Square,
    /// Language specific ordering (alpha, roman, cjk-ideographic, etc...)
    Other,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "enumn", derive(enumn::N))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
#[cfg_attr(
    feature = "pyo3",
    pyclass(
        module = "accesskit",
        rename_all = "SCREAMING_SNAKE_CASE",
        eq,
        from_py_object
    )
)]
#[repr(u8)]
pub enum TextAlign {
    Left,
    Right,
    Center,
    Justify,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "enumn", derive(enumn::N))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
#[cfg_attr(
    feature = "pyo3",
    pyclass(
        module = "accesskit",
        rename_all = "SCREAMING_SNAKE_CASE",
        eq,
        from_py_object
    )
)]
#[repr(u8)]
pub enum VerticalOffset {
    Subscript,
    Superscript,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "enumn", derive(enumn::N))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
#[cfg_attr(
    feature = "pyo3",
    pyclass(
        module = "accesskit",
        rename_all = "SCREAMING_SNAKE_CASE",
        eq,
        from_py_object
    )
)]
#[repr(u8)]
pub enum TextDecorationStyle {
    Solid,
    Dotted,
    Dashed,
    Double,
    Wavy,
}

pub type NodeIdContent = u64;

/// The stable identity of a [`Node`], unique within the node's tree.
///
/// Each tree (root or subtree) has its own independent ID space. The same
/// `NodeId` value can exist in different trees without conflict. When working
/// with multiple trees, the combination of `NodeId` and [`TreeId`] uniquely
/// identifies a node.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[repr(transparent)]
pub struct NodeId(pub NodeIdContent);

impl From<NodeIdContent> for NodeId {
    #[inline]
    fn from(inner: NodeIdContent) -> Self {
        Self(inner)
    }
}

impl From<NodeId> for NodeIdContent {
    #[inline]
    fn from(outer: NodeId) -> Self {
        outer.0
    }
}

impl fmt::Debug for NodeId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "#{}", self.0)
    }
}

/// The stable identity of a tree.
///
/// Use [`TreeId::ROOT`] for the main/root tree. For subtrees, use a random
/// UUID (version 4) to avoid collisions between independently created trees.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[repr(transparent)]
pub struct TreeId(pub Uuid);

impl TreeId {
    /// A reserved tree ID for the root tree. This uses a nil UUID.
    pub const ROOT: Self = Self(Uuid::nil());
}

/// Defines a custom action for a UI element.
///
/// For example, a list UI can allow a user to reorder items in the list by dragging the
/// items.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct CustomAction {
    pub id: i32,
    pub description: String,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct TextPosition {
    /// The node's role must be [`Role::TextRun`].
    pub node: NodeId,
    /// The index of an item in [`Node::character_lengths`], or the length
    /// of that slice if the position is at the end of the line.
    pub character_index: usize,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct TextSelection {
    /// The position where the selection started, and which does not change
    /// as the selection is expanded or contracted. If there is no selection
    /// but only a caret, this must be equal to the value of [`TextSelection::focus`].
    /// This is also known as a degenerate selection.
    pub anchor: TextPosition,
    /// The active end of the selection, which changes as the selection
    /// is expanded or contracted, or the position of the caret if there is
    /// no selection.
    pub focus: TextPosition,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize, enumn::N))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
#[repr(u8)]
enum Flag {
    Hidden,
    Multiselectable,
    Required,
    Visited,
    Busy,
    LiveAtomic,
    Modal,
    TouchTransparent,
    ReadOnly,
    Disabled,
    Italic,
    ClipsChildren,
    IsLineBreakingObject,
    IsPageBreakingObject,
    IsSpellingError,
    IsGrammarError,
    IsSearchMatch,
    IsSuggestion,
}

impl Flag {
    fn mask(self) -> u32 {
        1 << (self as u8)
    }
}

/// A color represented in 8-bit sRGB plus alpha.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
#[repr(C)]
pub struct Color {
    pub red: u8,
    pub green: u8,
    pub blue: u8,
    pub alpha: u8,
}

/// The style and color for a type of text decoration.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
#[repr(C)]
pub struct TextDecoration {
    pub style: TextDecorationStyle,
    pub color: Color,
}

// The following is based on the technique described here:
// https://viruta.org/reducing-memory-consumption-in-librsvg-2.html

#[derive(Debug, PartialEq)]
enum PropertyValue {
    None,
    NodeIdVec(Vec<NodeId>),
    NodeId(NodeId),
    String(String),
    F64(f64),
    F32(f32),
    Usize(usize),
    Color(Color),
    TextDecoration(TextDecoration),
    LengthVec(Vec<u8>),
    CoordVec(Vec<f32>),
    Bool(bool),
    Invalid(Invalid),
    Toggled(Toggled),
    Live(Live),
    TextDirection(TextDirection),
    Orientation(Orientation),
    SortDirection(SortDirection),
    AriaCurrent(AriaCurrent),
    AutoComplete(AutoComplete),
    HasPopup(HasPopup),
    ListStyle(ListStyle),
    TextAlign(TextAlign),
    VerticalOffset(VerticalOffset),
    Affine(Box<Affine>),
    Rect(Rect),
    TextSelection(Box<TextSelection>),
    CustomActionVec(Vec<CustomAction>),
    TreeId(TreeId),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize, enumn::N))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
#[repr(u8)]
enum PropertyId {
    // NodeIdVec
    Children,
    Controls,
    Details,
    DescribedBy,
    FlowTo,
    LabelledBy,
    Owns,
    RadioGroup,

    // NodeId
    ActiveDescendant,
    ErrorMessage,
    InPageLinkTarget,
    MemberOf,
    NextOnLine,
    PreviousOnLine,
    PopupFor,

    // String
    Label,
    Description,
    Value,
    AccessKey,
    AuthorId,
    ClassName,
    FontFamily,
    HtmlId,
    HtmlTag,
    InnerHtml,
    KeyboardShortcut,
    Language,
    Placeholder,
    RoleDescription,
    StateDescription,
    Tooltip,
    Url,
    RowIndexText,
    ColumnIndexText,
    BrailleLabel,
    BrailleRoleDescription,

    // f64
    ScrollX,
    ScrollXMin,
    ScrollXMax,
    ScrollY,
    ScrollYMin,
    ScrollYMax,
    NumericValue,
    MinNumericValue,
    MaxNumericValue,
    NumericValueStep,
    NumericValueJump,

    // f32
    FontSize,
    FontWeight,

    // usize
    RowCount,
    ColumnCount,
    RowIndex,
    ColumnIndex,
    RowSpan,
    ColumnSpan,
    Level,
    SizeOfSet,
    PositionInSet,

    // Color
    ColorValue,
    BackgroundColor,
    ForegroundColor,

    // TextDecoration
    Overline,
    Strikethrough,
    Underline,

    // LengthVec
    CharacterLengths,
    WordStarts,

    // CoordVec
    CharacterPositions,
    CharacterWidths,

    // bool
    Expanded,
    Selected,

    // Unique enums
    Invalid,
    Toggled,
    Live,
    TextDirection,
    Orientation,
    SortDirection,
    AriaCurrent,
    AutoComplete,
    HasPopup,
    ListStyle,
    TextAlign,
    VerticalOffset,

    // Other
    Transform,
    Bounds,
    TextSelection,
    CustomActions,
    TreeId,

    // This MUST be last.
    Unset,
}

impl Clone for PropertyValue {
    fn clone(&self) -> Self {
        match self {
            Self::None => Self::None,
            Self::NodeIdVec(v) => Self::NodeIdVec(v.clone()),
            Self::NodeId(v) => Self::NodeId(*v),
            Self::String(v) => Self::String(v.clone()),
            Self::F64(v) => Self::F64(*v),
            Self::F32(v) => Self::F32(*v),
            Self::Usize(v) => Self::Usize(*v),
            Self::Color(v) => Self::Color(*v),
            Self::TextDecoration(v) => Self::TextDecoration(*v),
            Self::LengthVec(v) => Self::LengthVec(v.clone()),
            Self::CoordVec(v) => Self::CoordVec(v.clone()),
            Self::Bool(v) => Self::Bool(*v),
            Self::Invalid(v) => Self::Invalid(*v),
            Self::Toggled(v) => Self::Toggled(*v),
            Self::Live(v) => Self::Live(*v),
            Self::TextDirection(v) => Self::TextDirection(*v),
            Self::Orientation(v) => Self::Orientation(*v),
            Self::SortDirection(v) => Self::SortDirection(*v),
            Self::AriaCurrent(v) => Self::AriaCurrent(*v),
            Self::AutoComplete(v) => Self::AutoComplete(*v),
            Self::HasPopup(v) => Self::HasPopup(*v),
            Self::ListStyle(v) => Self::ListStyle(*v),
            Self::TextAlign(v) => Self::TextAlign(*v),
            Self::VerticalOffset(v) => Self::VerticalOffset(*v),
            Self::Affine(v) => Self::Affine(v.clone()),
            Self::Rect(v) => Self::Rect(*v),
            Self::TextSelection(v) => Self::TextSelection(v.clone()),
            Self::CustomActionVec(v) => Self::CustomActionVec(v.clone()),
            Self::TreeId(v) => Self::TreeId(*v),
        }
    }

    fn clone_from(&mut self, source: &Self) {
        match (self, source) {
            (Self::NodeIdVec(dest), Self::NodeIdVec(source)) => dest.clone_from(source),
            (Self::String(dest), Self::String(source)) => dest.clone_from(source),
            (Self::LengthVec(dest), Self::LengthVec(source)) => dest.clone_from(source),
            (Self::CoordVec(dest), Self::CoordVec(source)) => dest.clone_from(source),
            (Self::CustomActionVec(dest), Self::CustomActionVec(source)) => dest.clone_from(source),
            (Self::Affine(dest), Self::Affine(source)) => dest.clone_from(source),
            (Self::TextSelection(dest), Self::TextSelection(source)) => dest.clone_from(source),
            (dest, source) => *dest = source.clone(),
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(transparent)]
struct PropertyIndices([u8; PropertyId::Unset as usize]);

impl Default for PropertyIndices {
    fn default() -> Self {
        Self([PropertyId::Unset as u8; PropertyId::Unset as usize])
    }
}

#[derive(Debug, Default)]
struct Properties {
    indices: PropertyIndices,
    values: Vec<PropertyValue>,
}

fn value_at(values: &[PropertyValue], index: u8) -> &PropertyValue {
    if index == PropertyId::Unset as u8 {
        &PropertyValue::None
    } else {
        &values[index as usize]
    }
}

impl PartialEq for Properties {
    fn eq(&self, other: &Self) -> bool {
        self.indices
            .0
            .iter()
            .zip(other.indices.0.iter())
            .all(|(&own, &other_index)| {
                value_at(&self.values, own) == value_at(&other.values, other_index)
            })
    }
}

/// A single accessible object. A complete UI is represented as a tree of these.
///
/// For brevity, and to make more of the documentation usable in bindings
/// to other languages, documentation of getter methods is written as if
/// documenting fields in a struct, and such methods are referred to
/// as properties.
#[derive(Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct Node {
    role: Role,
    actions: u32,
    child_actions: u32,
    flags: u32,
    properties: Properties,
}

impl PropertyIndices {
    fn get<'a>(&self, values: &'a [PropertyValue], id: PropertyId) -> &'a PropertyValue {
        value_at(values, self.0[id as usize])
    }
}

impl Properties {
    fn get_mut(&mut self, id: PropertyId, default: PropertyValue) -> &mut PropertyValue {
        let index = self.indices.0[id as usize] as usize;
        if index == PropertyId::Unset as usize {
            self.values.push(default);
            let index = self.values.len() - 1;
            self.indices.0[id as usize] = index as u8;
            &mut self.values[index]
        } else {
            let value = &mut self.values[index];
            if matches!(value, PropertyValue::None) {
                *value = default;
            }
            value
        }
    }

    fn set(&mut self, id: PropertyId, value: PropertyValue) {
        let index = self.indices.0[id as usize];
        if index == PropertyId::Unset as u8 {
            self.values.push(value);
            self.indices.0[id as usize] = (self.values.len() - 1) as u8;
        } else {
            self.values[index as usize] = value;
        }
    }

    fn clear(&mut self, id: PropertyId) {
        let index = self.indices.0[id as usize];
        if index != PropertyId::Unset as u8 {
            self.values[index as usize] = PropertyValue::None;
        }
    }
}

impl Clone for Properties {
    fn clone(&self) -> Self {
        Self {
            indices: self.indices,
            values: self.values.clone(),
        }
    }

    fn clone_from(&mut self, source: &Self) {
        self.indices = source.indices;
        source.values.clone_into(&mut self.values);
    }
}

macro_rules! flag_methods {
    ($($(#[$doc:meta])* ($id:ident, $getter:ident, $setter:ident, $clearer:ident)),+) => {
        impl Node {
            $($(#[$doc])*
            #[inline]
            pub fn $getter(&self) -> bool {
                (self.flags & (Flag::$id).mask()) != 0
            }
            #[inline]
            pub fn $setter(&mut self) {
                self.flags |= (Flag::$id).mask();
            }
            #[inline]
            pub fn $clearer(&mut self) {
                self.flags &= !((Flag::$id).mask());
            })*
            fn debug_flag_properties(&self, fmt: &mut fmt::DebugStruct) {
                $(
                    if self.$getter() {
                        fmt.field(stringify!($getter), &true);
                    }
                )*
            }
        }
        $(#[cfg(test)]
        mod $getter {
            use super::{Node, Role};

            #[test]
            fn getter_should_return_default_value() {
                let node = Node::new(Role::Unknown);
                assert!(!node.$getter());
            }

            #[test]
            fn setter_should_update_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$setter();
                assert!(node.$getter());
            }

            #[test]
            fn clearer_should_reset_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$setter();
                node.$clearer();
                assert!(!node.$getter());
            }
        })*
    }
}

macro_rules! option_ref_type_getters {
    ($(($method:ident, $type:ty, $variant:ident)),+) => {
        impl PropertyIndices {
            $(fn $method<'a>(&self, values: &'a [PropertyValue], id: PropertyId) -> Option<&'a $type> {
                match self.get(values, id) {
                    PropertyValue::$variant(value) => Some(value),
                    _ => None,
                }
            })*
        }
    }
}

macro_rules! slice_type_getters {
    ($(($method:ident, $type:ty, $variant:ident)),+) => {
        impl PropertyIndices {
            $(fn $method<'a>(&self, values: &'a [PropertyValue], id: PropertyId) -> &'a [$type] {
                match self.get(values, id) {
                    PropertyValue::$variant(value) => value,
                    _ => &[],
                }
            })*
        }
    }
}

macro_rules! copy_type_getters {
    ($(($method:ident, $type:ty, $variant:ident)),+) => {
        impl PropertyIndices {
            $(fn $method(&self, values: &[PropertyValue], id: PropertyId) -> Option<$type> {
                match self.get(values, id) {
                    PropertyValue::$variant(value) => Some(*value),
                    _ => None,
                }
            })*
        }
    }
}

macro_rules! owned_type_setters {
    ($(($method:ident, $type:ty, $variant:ident)),+) => {
        impl Node {
            $(fn $method(&mut self, id: PropertyId, value: impl Into<$type>) {
                self.properties.set(id, PropertyValue::$variant(value.into()));
            })*
        }
    }
}

macro_rules! copy_type_setters {
    ($(($method:ident, $type:ty, $variant:ident)),+) => {
        impl Node {
            $(fn $method(&mut self, id: PropertyId, value: $type) {
                self.properties.set(id, PropertyValue::$variant(value));
            })*
        }
    }
}

macro_rules! vec_type_methods {
    ($(($type:ty, $variant:ident, $getter:ident, $setter:ident, $pusher:ident)),+) => {
        $(slice_type_getters! {
            ($getter, $type, $variant)
        })*
        impl Node {
            $(fn $setter(&mut self, id: PropertyId, value: impl Into<Vec<$type>>) {
                self.properties.set(id, PropertyValue::$variant(value.into()));
            }
            fn $pusher(&mut self, id: PropertyId, item: $type) {
                if let PropertyValue::$variant(v) = self.properties.get_mut(id, PropertyValue::$variant(Vec::new())) {
                    v.push(item);
                }
            })*
        }
    }
}

macro_rules! property_methods {
    ($($(#[$doc:meta])* ($id:ident, $getter:ident, $type_getter:ident, $getter_result:ty, $setter:ident, $type_setter:ident, $setter_param:ty, $clearer:ident)),+) => {
        impl Node {
            $($(#[$doc])*
            #[inline]
            pub fn $getter(&self) -> $getter_result {
                self.properties.indices.$type_getter(&self.properties.values, PropertyId::$id)
            }
            #[inline]
            pub fn $setter(&mut self, value: $setter_param) {
                self.$type_setter(PropertyId::$id, value);
            }
            #[inline]
            pub fn $clearer(&mut self) {
                self.properties.clear(PropertyId::$id);
            })*
        }
    }
}

macro_rules! vec_property_methods {
    ($($(#[$doc:meta])* ($id:ident, $item_type:ty, $getter:ident, $type_getter:ident, $setter:ident, $type_setter:ident, $pusher:ident, $type_pusher:ident, $clearer:ident)),+) => {
        $(property_methods! {
            $(#[$doc])*
            ($id, $getter, $type_getter, &[$item_type], $setter, $type_setter, impl Into<Vec<$item_type>>, $clearer)
        }
        impl Node {
            #[inline]
            pub fn $pusher(&mut self, item: $item_type) {
                self.$type_pusher(PropertyId::$id, item);
            }
        })*
    }
}

macro_rules! vec_properties_debug_method {
    ($name:ident, [$($getter:ident,)*]) => {
        fn $name(&self, fmt: &mut fmt::DebugStruct) {
            $(
                let value = self.$getter();
                if !value.is_empty() {
                    fmt.field(stringify!($getter), &value);
                }
            )*
        }
    }
}

macro_rules! node_id_vec_property_methods {
    ($($(#[$doc:meta])* ($id:ident, $getter:ident, $setter:ident, $pusher:ident, $clearer:ident)),+) => {
        $(vec_property_methods! {
            $(#[$doc])*
            ($id, NodeId, $getter, get_node_id_vec, $setter, set_node_id_vec, $pusher, push_to_node_id_vec, $clearer)
        })*
        impl Node {
            vec_properties_debug_method! { debug_node_id_vec_properties, [$($getter,)*] }
        }
        $(#[cfg(test)]
        mod $getter {
            use super::{Node, NodeId, Role};

            #[test]
            fn getter_should_return_default_value() {
                let node = Node::new(Role::Unknown);
                assert!(node.$getter().is_empty());
            }
            #[test]
            fn setter_should_update_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$setter([]);
                assert!(node.$getter().is_empty());
                node.$setter([NodeId(0), NodeId(1)]);
                assert_eq!(node.$getter(), &[NodeId(0), NodeId(1)]);
            }
            #[test]
            fn pusher_should_update_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$pusher(NodeId(0));
                assert_eq!(node.$getter(), &[NodeId(0)]);
                node.$pusher(NodeId(1));
                assert_eq!(node.$getter(), &[NodeId(0), NodeId(1)]);
            }
            #[test]
            fn pusher_should_start_a_new_list_after_the_clearer() {
                let mut node = Node::new(Role::Unknown);
                node.$setter([NodeId(0)]);
                node.$clearer();
                node.$pusher(NodeId(1));
                assert_eq!(node.$getter(), &[NodeId(1)]);
            }
            #[test]
            fn clearer_should_reset_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$setter([NodeId(0)]);
                node.$clearer();
                assert!(node.$getter().is_empty());
            }
        })*
    }
}

macro_rules! option_properties_debug_method {
    ($name:ident, [$($getter:ident,)*]) => {
        fn $name(&self, fmt: &mut fmt::DebugStruct) {
            $(
                if let Some(value) = self.$getter() {
                    fmt.field(stringify!($getter), &value);
                }
            )*
        }
    }
}

macro_rules! node_id_property_methods {
    ($($(#[$doc:meta])* ($id:ident, $getter:ident, $setter:ident, $clearer:ident)),+) => {
        $(property_methods! {
            $(#[$doc])*
            ($id, $getter, get_node_id_property, Option<NodeId>, $setter, set_node_id_property, NodeId, $clearer)
        })*
        impl Node {
            option_properties_debug_method! { debug_node_id_properties, [$($getter,)*] }
        }
        $(#[cfg(test)]
        mod $getter {
            use super::{Node, NodeId, Role};

            #[test]
            fn getter_should_return_default_value() {
                let node = Node::new(Role::Unknown);
                assert!(node.$getter().is_none());
            }
            #[test]
            fn setter_should_update_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$setter(NodeId(1));
                assert_eq!(node.$getter(), Some(NodeId(1)));
            }
            #[test]
            fn clearer_should_reset_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$setter(NodeId(1));
                node.$clearer();
                assert!(node.$getter().is_none());
            }
        })*
    }
}

macro_rules! string_property_methods {
    ($($(#[$doc:meta])* ($id:ident, $getter:ident, $setter:ident, $clearer:ident)),+) => {
        $(property_methods! {
            $(#[$doc])*
            ($id, $getter, get_string_property, Option<&str>, $setter, set_string_property, impl Into<String>, $clearer)
        })*
        impl Node {
            option_properties_debug_method! { debug_string_properties, [$($getter,)*] }
        }
        $(#[cfg(test)]
        mod $getter {
            use super::{Node, Role};

            #[test]
            fn getter_should_return_default_value() {
                let node = Node::new(Role::Unknown);
                assert!(node.$getter().is_none());
            }
            #[test]
            fn setter_should_update_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$setter("test");
                assert_eq!(node.$getter(), Some("test"));
            }
            #[test]
            fn clearer_should_reset_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$setter("test");
                node.$clearer();
                assert!(node.$getter().is_none());
            }
        })*
    }
}

macro_rules! f64_property_methods {
    ($($(#[$doc:meta])* ($id:ident, $getter:ident, $setter:ident, $clearer:ident)),+) => {
        $(property_methods! {
            $(#[$doc])*
            ($id, $getter, get_f64_property, Option<f64>, $setter, set_f64_property, f64, $clearer)
        })*
        impl Node {
            option_properties_debug_method! { debug_f64_properties, [$($getter,)*] }
        }
        $(#[cfg(test)]
        mod $getter {
            use super::{Node, Role};

            #[test]
            fn getter_should_return_default_value() {
                let node = Node::new(Role::Unknown);
                assert!(node.$getter().is_none());
            }
            #[test]
            fn setter_should_update_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$setter(1.0);
                assert_eq!(node.$getter(), Some(1.0));
            }
            #[test]
            fn clearer_should_reset_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$setter(1.0);
                node.$clearer();
                assert!(node.$getter().is_none());
            }
        })*
    }
}

macro_rules! f32_property_methods {
    ($($(#[$doc:meta])* ($id:ident, $getter:ident, $setter:ident, $clearer:ident)),+) => {
        $(property_methods! {
            $(#[$doc])*
            ($id, $getter, get_f32_property, Option<f32>, $setter, set_f32_property, f32, $clearer)
        })*
        impl Node {
            option_properties_debug_method! { debug_f32_properties, [$($getter,)*] }
        }
        $(#[cfg(test)]
        mod $getter {
            use super::{Node, Role};

            #[test]
            fn getter_should_return_default_value() {
                let node = Node::new(Role::Unknown);
                assert!(node.$getter().is_none());
            }
            #[test]
            fn setter_should_update_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$setter(1.0);
                assert_eq!(node.$getter(), Some(1.0));
            }
            #[test]
            fn clearer_should_reset_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$setter(1.0);
                node.$clearer();
                assert!(node.$getter().is_none());
            }
        })*
    }
}

macro_rules! usize_property_methods {
    ($($(#[$doc:meta])* ($id:ident, $getter:ident, $setter:ident, $clearer:ident)),+) => {
        $(property_methods! {
            $(#[$doc])*
            ($id, $getter, get_usize_property, Option<usize>, $setter, set_usize_property, usize, $clearer)
        })*
        impl Node {
            option_properties_debug_method! { debug_usize_properties, [$($getter,)*] }
        }
        $(#[cfg(test)]
        mod $getter {
            use super::{Node, Role};

            #[test]
            fn getter_should_return_default_value() {
                let node = Node::new(Role::Unknown);
                assert!(node.$getter().is_none());
            }
            #[test]
            fn setter_should_update_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$setter(1);
                assert_eq!(node.$getter(), Some(1));
            }
            #[test]
            fn clearer_should_reset_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$setter(1);
                node.$clearer();
                assert!(node.$getter().is_none());
            }
        })*
    }
}

macro_rules! color_property_methods {
    ($($(#[$doc:meta])* ($id:ident, $getter:ident, $setter:ident, $clearer:ident)),+) => {
        $(property_methods! {
            $(#[$doc])*
            ($id, $getter, get_color_property, Option<Color>, $setter, set_color_property, Color, $clearer)
        })*
        impl Node {
            option_properties_debug_method! { debug_color_properties, [$($getter,)*] }
        }
        $(#[cfg(test)]
        mod $getter {
            use super::{Color, Node, Role};

            #[test]
            fn getter_should_return_default_value() {
                let node = Node::new(Role::Unknown);
                assert!(node.$getter().is_none());
            }
            #[test]
            fn setter_should_update_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$setter(Color { red: 255, green: 255, blue: 255, alpha: 255 });
                assert_eq!(node.$getter(), Some(Color { red: 255, green: 255, blue: 255, alpha: 255 }));
            }
            #[test]
            fn clearer_should_reset_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$setter(Color { red: 255, green: 255, blue: 255, alpha: 255 });
                node.$clearer();
                assert!(node.$getter().is_none());
            }
        })*
    }
}

macro_rules! text_decoration_property_methods {
    ($($(#[$doc:meta])* ($id:ident, $getter:ident, $setter:ident, $clearer:ident)),+) => {
        $(property_methods! {
            $(#[$doc])*
            ($id, $getter, get_text_decoration_property, Option<TextDecoration>, $setter, set_text_decoration_property, TextDecoration, $clearer)
        })*
        impl Node {
            option_properties_debug_method! { debug_text_decoration_properties, [$($getter,)*] }
        }
        $(#[cfg(test)]
        mod $getter {
            use super::{Color, Node, Role, TextDecoration, TextDecorationStyle};

            const TEST_TEXT_DECORATION: TextDecoration = TextDecoration {
                style: TextDecorationStyle::Dotted,
                color: Color {
                    red: 0,
                    green: 0,
                    blue: 0,
                    alpha: 255,
                },
            };

            #[test]
            fn getter_should_return_default_value() {
                let node = Node::new(Role::Unknown);
                assert!(node.$getter().is_none());
            }
            #[test]
            fn setter_should_update_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$setter(TEST_TEXT_DECORATION);
                assert_eq!(node.$getter(), Some(TEST_TEXT_DECORATION));
            }
            #[test]
            fn clearer_should_reset_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$setter(TEST_TEXT_DECORATION);
                node.$clearer();
                assert!(node.$getter().is_none());
            }
        })*
    }
}

macro_rules! length_vec_property_methods {
    ($($(#[$doc:meta])* ($id:ident, $getter:ident, $setter:ident, $clearer:ident)),+) => {
        $(property_methods! {
            $(#[$doc])*
            ($id, $getter, get_length_vec_property, &[u8], $setter, set_length_vec_property, impl Into<Vec<u8>>, $clearer)
        })*
        impl Node {
            vec_properties_debug_method! { debug_length_vec_properties, [$($getter,)*] }
        }
        $(#[cfg(test)]
        mod $getter {
            use super::{Node, Role};

            #[test]
            fn getter_should_return_default_value() {
                let node = Node::new(Role::Unknown);
                assert!(node.$getter().is_empty());
            }
            #[test]
            fn setter_should_update_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$setter([]);
                assert!(node.$getter().is_empty());
                node.$setter([1, 2]);
                assert_eq!(node.$getter(), &[1, 2]);
            }
            #[test]
            fn clearer_should_reset_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$setter([1, 2]);
                node.$clearer();
                assert!(node.$getter().is_empty());
            }
        })*
    }
}

macro_rules! coord_vec_property_methods {
    ($($(#[$doc:meta])* ($id:ident, $getter:ident, $setter:ident, $clearer:ident)),+) => {
        $(property_methods! {
            $(#[$doc])*
            ($id, $getter, get_coord_vec_property, Option<&[f32]>, $setter, set_coord_vec_property, impl Into<Vec<f32>>, $clearer)
        })*
        impl Node {
            option_properties_debug_method! { debug_coord_vec_properties, [$($getter,)*] }
        }
        $(#[cfg(test)]
        mod $getter {
            use super::{Node, Role};

            #[test]
            fn getter_should_return_default_value() {
                let node = Node::new(Role::Unknown);
                assert!(node.$getter().is_none());
            }
            #[test]
            fn setter_should_update_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$setter([]);
                let expected: Option<&[f32]> = Some(&[]);
                assert_eq!(node.$getter(), expected);
                node.$setter([1.0, 2.0]);
                let expected: Option<&[f32]> = Some(&[1.0, 2.0]);
                assert_eq!(node.$getter(), expected);
            }
            #[test]
            fn clearer_should_reset_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$setter([1.0, 2.0]);
                node.$clearer();
                assert!(node.$getter().is_none());
            }
        })*
    }
}

macro_rules! bool_property_methods {
    ($($(#[$doc:meta])* ($id:ident, $getter:ident, $setter:ident, $clearer:ident)),+) => {
        $(property_methods! {
            $(#[$doc])*
            ($id, $getter, get_bool_property, Option<bool>, $setter, set_bool_property, bool, $clearer)
        })*
        impl Node {
            option_properties_debug_method! { debug_bool_properties, [$($getter,)*] }
        }
        $(#[cfg(test)]
        mod $getter {
            use super::{Node, Role};

            #[test]
            fn getter_should_return_default_value() {
                let node = Node::new(Role::Unknown);
                assert!(node.$getter().is_none());
            }
            #[test]
            fn setter_should_update_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$setter(true);
                assert_eq!(node.$getter(), Some(true));
            }
            #[test]
            fn clearer_should_reset_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$setter(true);
                node.$clearer();
                assert!(node.$getter().is_none());
            }
        })*
    }
}

macro_rules! unique_enum_property_methods {
    ($($(#[$doc:meta])* ($id:ident, $getter:ident, $setter:ident, $clearer:ident, $variant:ident)),+) => {
        impl Node {
            $($(#[$doc])*
            #[inline]
            pub fn $getter(&self) -> Option<$id> {
                match self.properties.indices.get(&self.properties.values, PropertyId::$id) {
                    PropertyValue::$id(value) => Some(*value),
                    _ => None,
                }
            }
            #[inline]
            pub fn $setter(&mut self, value: $id) {
                self.properties.set(PropertyId::$id, PropertyValue::$id(value));
            }
            #[inline]
            pub fn $clearer(&mut self) {
                self.properties.clear(PropertyId::$id);
            })*
            option_properties_debug_method! { debug_unique_enum_properties, [$($getter,)*] }
        }
        $(#[cfg(test)]
        mod $getter {
            use super::{Node, Role};

            #[test]
            fn getter_should_return_default_value() {
                let node = Node::new(Role::Unknown);
                assert!(node.$getter().is_none());
            }
            #[test]
            fn setter_should_update_the_property() {
                let mut node = Node::new(Role::Unknown);
                let variant = super::$id::$variant;
                node.$setter(variant);
                assert_eq!(node.$getter(), Some(variant));
            }
            #[test]
            fn clearer_should_reset_the_property() {
                let mut node = Node::new(Role::Unknown);
                node.$setter(super::$id::$variant);
                node.$clearer();
                assert!(node.$getter().is_none());
            }
        })*
    }
}

impl Node {
    #[inline]
    pub fn new(role: Role) -> Self {
        Self {
            role,
            ..Default::default()
        }
    }
}

impl Clone for Node {
    fn clone(&self) -> Self {
        Self {
            role: self.role,
            actions: self.actions,
            child_actions: self.child_actions,
            flags: self.flags,
            properties: self.properties.clone(),
        }
    }

    fn clone_from(&mut self, source: &Self) {
        self.role = source.role;
        self.actions = source.actions;
        self.child_actions = source.child_actions;
        self.flags = source.flags;
        self.properties.clone_from(&source.properties);
    }
}

impl Node {
    #[inline]
    pub fn role(&self) -> Role {
        self.role
    }
    #[inline]
    pub fn set_role(&mut self, value: Role) {
        self.role = value;
    }

    #[inline]
    pub fn supports_action(&self, action: Action) -> bool {
        (self.actions & action.mask()) != 0
    }
    #[inline]
    pub fn add_action(&mut self, action: Action) {
        self.actions |= action.mask();
    }
    #[inline]
    pub fn remove_action(&mut self, action: Action) {
        self.actions &= !(action.mask());
    }
    #[inline]
    pub fn clear_actions(&mut self) {
        self.actions = 0;
    }

    /// Return whether the specified action is in the set supported on this node's
    /// direct children in the filtered tree.
    #[inline]
    pub fn child_supports_action(&self, action: Action) -> bool {
        (self.child_actions & action.mask()) != 0
    }
    /// Add the specified action to the set supported on this node's direct
    /// children in the filtered tree.
    #[inline]
    pub fn add_child_action(&mut self, action: Action) {
        self.child_actions |= action.mask();
    }
    /// Remove the specified action from the set supported on this node's direct
    /// children in the filtered tree.
    #[inline]
    pub fn remove_child_action(&mut self, action: Action) {
        self.child_actions &= !(action.mask());
    }
    /// Clear the set of actions supported on this node's direct children in the
    /// filtered tree.
    #[inline]
    pub fn clear_child_actions(&mut self) {
        self.child_actions = 0;
    }
}

flag_methods! {
    /// Whether this node and its descendants are excluded from the tree
    /// presented to assistive technologies and from hit testing. ARIA
    /// equivalent: [`aria-hidden`].
    ///
    /// **Difference with ARIA:** `aria-hidden` controls exposure to assistive
    /// technologies, while this property also excludes the node from hit
    /// testing.
    ///
    /// [`aria-hidden`]: https://www.w3.org/TR/wai-aria-1.2/#aria-hidden
    (Hidden, is_hidden, set_hidden, clear_hidden),
    /// Whether users may select more than one selectable descendant. ARIA
    /// equivalent: [`aria-multiselectable`].
    ///
    /// [`aria-multiselectable`]: https://www.w3.org/TR/wai-aria-1.2/#aria-multiselectable
    (Multiselectable, is_multiselectable, set_multiselectable, clear_multiselectable),
    /// Whether user input or selection is required on this node. ARIA
    /// equivalent: [`aria-required`].
    ///
    /// [`aria-required`]: https://www.w3.org/TR/wai-aria-1.2/#aria-required
    (Required, is_required, set_required, clear_required),
    /// Whether this node represents a link that has been visited.
    (Visited, is_visited, set_visited, clear_visited),
    /// Whether this node is being modified and updates should be withheld until
    /// it is ready. ARIA equivalent: [`aria-busy`].
    ///
    /// [`aria-busy`]: https://www.w3.org/TR/wai-aria-1.2/#aria-busy
    (Busy, is_busy, set_busy, clear_busy),
    /// Whether updates to this live region should be presented as a whole. ARIA
    /// equivalent: [`aria-atomic`].
    ///
    /// [`aria-atomic`]: https://www.w3.org/TR/wai-aria-1.2/#aria-atomic
    (LiveAtomic, is_live_atomic, set_live_atomic, clear_live_atomic),
    /// Whether this dialog is modal. ARIA equivalent: [`aria-modal`].
    ///
    /// [`aria-modal`]: https://www.w3.org/TR/wai-aria-1.2/#aria-modal
    (Modal, is_modal, set_modal, clear_modal),
    /// Whether touches pass through this node when a screen reader is in touch
    /// exploration mode, as they normally do on a virtual keyboard.
    (TouchTransparent, is_touch_transparent, set_touch_transparent, clear_touch_transparent),
    /// Whether this text widget permits focus and selection but not editing.
    /// ARIA equivalent: [`aria-readonly`].
    ///
    /// [`aria-readonly`]: https://www.w3.org/TR/wai-aria-1.2/#aria-readonly
    (ReadOnly, is_read_only, set_read_only, clear_read_only),
    /// Whether this control or group of controls is unavailable for interaction.
    /// ARIA equivalent: [`aria-disabled`].
    ///
    /// [`aria-disabled`]: https://www.w3.org/TR/wai-aria-1.2/#aria-disabled
    (Disabled, is_disabled, set_disabled, clear_disabled),
    /// Whether this node's text is italic.
    (Italic, is_italic, set_italic, clear_italic),
    /// Whether this node clips child content outside its bounds.
    (ClipsChildren, clips_children, set_clips_children, clear_clips_children),
    /// Whether this node causes a hard line break.
    (IsLineBreakingObject, is_line_breaking_object, set_is_line_breaking_object, clear_is_line_breaking_object),
    /// Whether this node causes a page break.
    (IsPageBreakingObject, is_page_breaking_object, set_is_page_breaking_object, clear_is_page_breaking_object),
    /// Whether this node's text is marked as a spelling error.
    (IsSpellingError, is_spelling_error, set_is_spelling_error, clear_is_spelling_error),
    /// Whether this node's text is marked as a grammar error.
    (IsGrammarError, is_grammar_error, set_is_grammar_error, clear_is_grammar_error),
    /// Whether this node represents text matching the current search.
    (IsSearchMatch, is_search_match, set_is_search_match, clear_is_search_match),
    /// Whether this node's text is a suggested replacement.
    (IsSuggestion, is_suggestion, set_is_suggestion, clear_is_suggestion)
}

option_ref_type_getters! {
    (get_affine_property, Affine, Affine),
    (get_string_property, str, String),
    (get_coord_vec_property, [f32], CoordVec),
    (get_text_selection_property, TextSelection, TextSelection)
}

slice_type_getters! {
    (get_length_vec_property, u8, LengthVec)
}

copy_type_getters! {
    (get_rect_property, Rect, Rect),
    (get_node_id_property, NodeId, NodeId),
    (get_f64_property, f64, F64),
    (get_f32_property, f32, F32),
    (get_usize_property, usize, Usize),
    (get_color_property, Color, Color),
    (get_text_decoration_property, TextDecoration, TextDecoration),
    (get_bool_property, bool, Bool),
    (get_tree_id_property, TreeId, TreeId)
}

owned_type_setters! {
    (set_affine_property, Box<Affine>, Affine),
    (set_string_property, String, String),
    (set_length_vec_property, Vec<u8>, LengthVec),
    (set_coord_vec_property, Vec<f32>, CoordVec),
    (set_text_selection_property, Box<TextSelection>, TextSelection)
}

copy_type_setters! {
    (set_rect_property, Rect, Rect),
    (set_node_id_property, NodeId, NodeId),
    (set_f64_property, f64, F64),
    (set_f32_property, f32, F32),
    (set_usize_property, usize, Usize),
    (set_color_property, Color, Color),
    (set_text_decoration_property, TextDecoration, TextDecoration),
    (set_bool_property, bool, Bool),
    (set_tree_id_property, TreeId, TreeId)
}

vec_type_methods! {
    (NodeId, NodeIdVec, get_node_id_vec, set_node_id_vec, push_to_node_id_vec),
    (CustomAction, CustomActionVec, get_custom_action_vec, set_custom_action_vec, push_to_custom_action_vec)
}

node_id_vec_property_methods! {
    /// The ordered list of this node's direct children in the tree. The order
    /// should match the intended reading and navigation order.
    (Children, children, set_children, push_child, clear_children),
    /// The nodes whose contents or presence are controlled by this node. ARIA
    /// equivalent: [`aria-controls`].
    ///
    /// [`aria-controls`]: https://www.w3.org/TR/wai-aria-1.2/#aria-controls
    (Controls, controls, set_controls, push_controlled, clear_controls),
    /// The nodes that provide detailed, structured descriptions for this node
    /// and that users may navigate to. Use [`Node::described_by`] when a
    /// plain-text description is sufficient. ARIA equivalent: [`aria-details`].
    ///
    /// **Difference with ARIA:** `aria-details` references a single element,
    /// while this property may reference multiple nodes.
    ///
    /// [`aria-details`]: https://www.w3.org/TR/wai-aria-1.2/#aria-details
    (Details, details, set_details, push_detail, clear_details),
    /// The nodes whose contents provide a plain-text description for this node.
    /// Use [`Node::details`] for structured content that users may need to
    /// navigate. ARIA equivalent: [`aria-describedby`].
    ///
    /// [`aria-describedby`]: https://www.w3.org/TR/wai-aria-1.2/#aria-describedby
    (DescribedBy, described_by, set_described_by, push_described_by, clear_described_by),
    /// The nodes that follow this node in an alternate reading order. ARIA
    /// equivalent: [`aria-flowto`].
    ///
    /// [`aria-flowto`]: https://www.w3.org/TR/wai-aria-1.2/#aria-flowto
    (FlowTo, flow_to, set_flow_to, push_flow_to, clear_flow_to),
    /// The nodes that label this node. ARIA equivalent: [`aria-labelledby`].
    ///
    /// [`aria-labelledby`]: https://www.w3.org/TR/wai-aria-1.2/#aria-labelledby
    (LabelledBy, labelled_by, set_labelled_by, push_labelled_by, clear_labelled_by),
    /// Nodes owned by this node that are not already its descendants in the
    /// tree. This property is unnecessary for direct children or other
    /// descendants. ARIA equivalent: [`aria-owns`].
    ///
    /// [`aria-owns`]: https://www.w3.org/TR/wai-aria-1.2/#aria-owns
    (Owns, owns, set_owns, push_owned, clear_owns),
    /// For a radio button, the list of all radio buttons in the same group,
    /// including this node.
    (RadioGroup, radio_group, set_radio_group, push_to_radio_group, clear_radio_group)
}

node_id_property_methods! {
    /// For a composite widget such as a listbox, tree, or grid, identifies
    /// the currently active descendant. Used when focus remains on the container
    /// while the active item changes. ARIA equivalent: [`aria-activedescendant`].
    ///
    /// [`aria-activedescendant`]: https://www.w3.org/TR/wai-aria-1.2/#aria-activedescendant
    (ActiveDescendant, active_descendant, set_active_descendant, clear_active_descendant),
    /// The node that provides an error message for this node. This should
    /// normally be used with [`Node::invalid`]. ARIA equivalent:
    /// [`aria-errormessage`].
    ///
    /// [`aria-errormessage`]: https://www.w3.org/TR/wai-aria-1.2/#aria-errormessage
    (ErrorMessage, error_message, set_error_message, clear_error_message),
    /// The target of this link when it points to another location in the same
    /// document.
    (InPageLinkTarget, in_page_link_target, set_in_page_link_target, clear_in_page_link_target),
    /// The group to which this node belongs.
    (MemberOf, member_of, set_member_of, clear_member_of),
    /// The next text run on the same visual line. The target's
    /// [`Node::previous_on_line`] should point back to this node.
    (NextOnLine, next_on_line, set_next_on_line, clear_next_on_line),
    /// The previous text run on the same visual line. The target's
    /// [`Node::next_on_line`] should point back to this node.
    (PreviousOnLine, previous_on_line, set_previous_on_line, clear_previous_on_line),
    /// The node for which this node is a popup.
    (PopupFor, popup_for, set_popup_for, clear_popup_for)
}

string_property_methods! {
    /// The label of this node. If the label is specified via the
    /// [`Node::labelled_by`] relation, this doesn't need to be set. The text
    /// content of a node with the [`Role::Label`] role should be provided via
    /// [`Node::value`], not this property. ARIA equivalent: [`aria-label`].
    ///
    /// [`aria-label`]: https://www.w3.org/TR/wai-aria-1.2/#aria-label
    (Label, label, set_label, clear_label),
    /// Additional information that supplements this node's label. ARIA 1.3
    /// draft equivalent: [`aria-description`].
    ///
    /// [`aria-description`]: https://www.w3.org/TR/wai-aria-1.3/#aria-description
    (Description, description, set_description, clear_description),
    /// The text content or string value of this node. ARIA equivalent:
    /// [`aria-valuetext`] for range widgets.
    ///
    /// **Difference with ARIA:** Unlike `aria-valuetext`, this property is also
    /// used for text controls and the text content of nodes such as [`Role::Label`]
    /// and [`Role::TextRun`].
    ///
    /// [`aria-valuetext`]: https://www.w3.org/TR/wai-aria-1.2/#aria-valuetext
    (Value, value, set_value, clear_value),
    /// A single character, usually part of this node's name, that can be pressed,
    /// possibly along with a platform-specific modifier, to perform
    /// this node's default action. For menu items, the access key is only active
    /// while the menu is active, in contrast with [`keyboard_shortcut`];
    /// a single menu item may in fact have both properties.
    ///
    /// [`keyboard_shortcut`]: Node::keyboard_shortcut
    (AccessKey, access_key, set_access_key, clear_access_key),
    /// A way for application authors to identify this node for automated
    /// testing purposes. The value must be unique among this node's siblings.
    (AuthorId, author_id, set_author_id, clear_author_id),
    /// The platform control class name for this node.
    (ClassName, class_name, set_class_name, clear_class_name),
    /// The font family used for this node's text. Only set this when it differs
    /// from the parent.
    (FontFamily, font_family, set_font_family, clear_font_family),
    /// The ID of the HTML element represented by this node. On platforms
    /// where both are mapped to the same platform property, this takes
    /// precedence over [`author_id`].
    ///
    /// [`author_id`]: Node::author_id
    (HtmlId, html_id, set_html_id, clear_html_id),
    /// The name of the HTML element represented by this node.
    (HtmlTag, html_tag, set_html_tag, clear_html_tag),
    /// Inner HTML of an element. Only used for a top-level math element,
    /// to support third-party math accessibility products that parse MathML.
    (InnerHtml, inner_html, set_inner_html, clear_inner_html),
    /// A keystroke or sequence of keystrokes, complete with any required
    /// modifiers(s), that will perform this node's default action.
    /// The value of this property should be in a human-friendly format. ARIA
    /// equivalent: [`aria-keyshortcuts`].
    ///
    /// [`aria-keyshortcuts`]: https://www.w3.org/TR/wai-aria-1.2/#aria-keyshortcuts
    (KeyboardShortcut, keyboard_shortcut, set_keyboard_shortcut, clear_keyboard_shortcut),
    /// An [IETF language tag](https://www.rfc-editor.org/info/bcp47).
    /// Only set this when it differs from the parent.
    (Language, language, set_language, clear_language),
    /// A short hint that helps the user with data entry when the node has no
    /// [`Node::value`]. This property should not be used instead of
    /// [`Node::label`]. ARIA equivalent: [`aria-placeholder`].
    ///
    /// [`aria-placeholder`]: https://www.w3.org/TR/wai-aria-1.2/#aria-placeholder
    (Placeholder, placeholder, set_placeholder, clear_placeholder),
    /// An optional string that may override an assistive technology's
    /// description of the node's role. Only provide this for custom control types.
    /// The value should be human-friendly and localized. ARIA equivalent:
    /// [`aria-roledescription`].
    ///
    /// [`aria-roledescription`]: https://www.w3.org/TR/wai-aria-1.2/#aria-roledescription
    (RoleDescription, role_description, set_role_description, clear_role_description),
    /// An optional string that may override an assistive technology's
    /// description of the node's state, replacing default strings such as
    /// "checked" or "selected". Note that most platform accessibility APIs
    /// and assistive technologies do not support this feature.
    (StateDescription, state_description, set_state_description, clear_state_description),
    /// If a node's only label comes from a tooltip, it should be exposed through
    /// this property rather than [`label`].
    ///
    /// [`label`]: Node::label
    (Tooltip, tooltip, set_tooltip, clear_tooltip),
    /// The target URL of a link.
    (Url, url, set_url, clear_url),
    /// A human-readable alternative to the numeric row index. ARIA 1.3 draft
    /// equivalent: [`aria-rowindextext`].
    ///
    /// [`aria-rowindextext`]: https://www.w3.org/TR/wai-aria-1.3/#aria-rowindextext
    (RowIndexText, row_index_text, set_row_index_text, clear_row_index_text),
    /// A human-readable alternative to the numeric column index. ARIA 1.3 draft
    /// equivalent: [`aria-colindextext`].
    ///
    /// [`aria-colindextext`]: https://www.w3.org/TR/wai-aria-1.3/#aria-colindextext
    (ColumnIndexText, column_index_text, set_column_index_text, clear_column_index_text),
    /// An alternative to [`Node::label`] that assistive technologies may present
    /// on a Braille display instead of speaking it. The value is ordinary text,
    /// not Unicode Braille characters. ARIA 1.3 draft equivalent:
    /// [`aria-braillelabel`].
    ///
    /// [`aria-braillelabel`]: https://www.w3.org/TR/wai-aria-1.3/#aria-braillelabel
    (BrailleLabel, braille_label, set_braille_label, clear_braille_label),
    /// An alternative to [`Node::role_description`] that assistive technologies
    /// may present on a Braille display instead of speaking it. The value is
    /// ordinary text, not Unicode Braille characters. ARIA 1.3 draft equivalent:
    /// [`aria-brailleroledescription`].
    ///
    /// [`aria-brailleroledescription`]: https://www.w3.org/TR/wai-aria-1.3/#aria-brailleroledescription
    (BrailleRoleDescription, braille_role_description, set_braille_role_description, clear_braille_role_description)
}

f64_property_methods! {
    /// The current horizontal scroll position of this scrollable container.
    (ScrollX, scroll_x, set_scroll_x, clear_scroll_x),
    /// The minimum horizontal scroll position of this scrollable container.
    (ScrollXMin, scroll_x_min, set_scroll_x_min, clear_scroll_x_min),
    /// The maximum horizontal scroll position of this scrollable container.
    (ScrollXMax, scroll_x_max, set_scroll_x_max, clear_scroll_x_max),
    /// The current vertical scroll position of this scrollable container.
    (ScrollY, scroll_y, set_scroll_y, clear_scroll_y),
    /// The minimum vertical scroll position of this scrollable container.
    (ScrollYMin, scroll_y_min, set_scroll_y_min, clear_scroll_y_min),
    /// The maximum vertical scroll position of this scrollable container.
    (ScrollYMax, scroll_y_max, set_scroll_y_max, clear_scroll_y_max),
    /// The current numeric value of this range widget. ARIA equivalent:
    /// [`aria-valuenow`].
    ///
    /// [`aria-valuenow`]: https://www.w3.org/TR/wai-aria-1.2/#aria-valuenow
    (NumericValue, numeric_value, set_numeric_value, clear_numeric_value),
    /// The minimum allowed numeric value of this range widget. ARIA equivalent:
    /// [`aria-valuemin`].
    ///
    /// [`aria-valuemin`]: https://www.w3.org/TR/wai-aria-1.2/#aria-valuemin
    (MinNumericValue, min_numeric_value, set_min_numeric_value, clear_min_numeric_value),
    /// The maximum allowed numeric value of this range widget. ARIA equivalent:
    /// [`aria-valuemax`].
    ///
    /// [`aria-valuemax`]: https://www.w3.org/TR/wai-aria-1.2/#aria-valuemax
    (MaxNumericValue, max_numeric_value, set_max_numeric_value, clear_max_numeric_value),
    /// The amount by which the numeric value changes when incremented or
    /// decremented by one step.
    (NumericValueStep, numeric_value_step, set_numeric_value_step, clear_numeric_value_step),
    /// The amount by which the numeric value changes for a large increment or
    /// decrement.
    (NumericValueJump, numeric_value_jump, set_numeric_value_jump, clear_numeric_value_jump)
}

f32_property_methods! {
    /// Font size is in pixels.
    (FontSize, font_size, set_font_size, clear_font_size),
    /// Font weight can take on any arbitrary numeric value. Increments of 100 in
    /// range `[0, 900]` represent keywords such as light, normal, bold, etc.
    (FontWeight, font_weight, set_font_weight, clear_font_weight)
}

usize_property_methods! {
    /// The total number of rows in a table, grid, or tree grid. ARIA equivalent:
    /// [`aria-rowcount`].
    ///
    /// [`aria-rowcount`]: https://www.w3.org/TR/wai-aria-1.2/#aria-rowcount
    (RowCount, row_count, set_row_count, clear_row_count),
    /// The total number of columns in a table, grid, or tree grid. ARIA
    /// equivalent: [`aria-colcount`].
    ///
    /// [`aria-colcount`]: https://www.w3.org/TR/wai-aria-1.2/#aria-colcount
    (ColumnCount, column_count, set_column_count, clear_column_count),
    /// The row index of this node within a table, grid, or tree grid. ARIA
    /// equivalent: [`aria-rowindex`].
    ///
    /// **Difference with ARIA:** `aria-rowindex` is one-based, while this
    /// property is zero-based.
    ///
    /// [`aria-rowindex`]: https://www.w3.org/TR/wai-aria-1.2/#aria-rowindex
    (RowIndex, row_index, set_row_index, clear_row_index),
    /// The column index of this node within a table, grid, or tree grid. ARIA
    /// equivalent: [`aria-colindex`].
    ///
    /// **Difference with ARIA:** `aria-colindex` is one-based, while this
    /// property is zero-based.
    ///
    /// [`aria-colindex`]: https://www.w3.org/TR/wai-aria-1.2/#aria-colindex
    (ColumnIndex, column_index, set_column_index, clear_column_index),
    /// The number of rows spanned by a cell or grid cell. ARIA equivalent:
    /// [`aria-rowspan`].
    ///
    /// [`aria-rowspan`]: https://www.w3.org/TR/wai-aria-1.2/#aria-rowspan
    (RowSpan, row_span, set_row_span, clear_row_span),
    /// The number of columns spanned by a cell or grid cell. ARIA equivalent:
    /// [`aria-colspan`].
    ///
    /// [`aria-colspan`]: https://www.w3.org/TR/wai-aria-1.2/#aria-colspan
    (ColumnSpan, column_span, set_column_span, clear_column_span),
    /// The hierarchical level of this node within a structure. ARIA equivalent:
    /// [`aria-level`].
    ///
    /// **Difference with ARIA:** `aria-level` is one-based, while this property
    /// is zero-based.
    ///
    /// [`aria-level`]: https://www.w3.org/TR/wai-aria-1.2/#aria-level
    (Level, level, set_level, clear_level),
    /// For containers like [`Role::ListBox`], specifies the total number of items.
    /// ARIA equivalent: [`aria-setsize`].
    ///
    /// **Difference with ARIA:** `aria-setsize` is set on each item, while this
    /// property is set on the container.
    ///
    /// [`aria-setsize`]: https://www.w3.org/TR/wai-aria-1.2/#aria-setsize
    (SizeOfSet, size_of_set, set_size_of_set, clear_size_of_set),
    /// For items like [`Role::ListBoxOption`], specifies their index in the item list.
    /// This must be less than the value of [`size_of_set`] as set on the container.
    /// ARIA equivalent: [`aria-posinset`].
    ///
    /// **Difference with ARIA:** `aria-posinset` is one-based, while this
    /// property is zero-based.
    ///
    /// [`size_of_set`]: Node::size_of_set
    /// [`aria-posinset`]: https://www.w3.org/TR/wai-aria-1.2/#aria-posinset
    (PositionInSet, position_in_set, set_position_in_set, clear_position_in_set)
}

color_property_methods! {
    /// For [`Role::ColorWell`], specifies the selected color.
    (ColorValue, color_value, set_color_value, clear_color_value),
    /// Background color.
    (BackgroundColor, background_color, set_background_color, clear_background_color),
    /// Foreground color.
    (ForegroundColor, foreground_color, set_foreground_color, clear_foreground_color)
}

text_decoration_property_methods! {
    /// The style and color of the overline applied to this node's text.
    (Overline, overline, set_overline, clear_overline),
    /// The style and color of the strikethrough applied to this node's text.
    (Strikethrough, strikethrough, set_strikethrough, clear_strikethrough),
    /// The style and color of the underline applied to this node's text.
    (Underline, underline, set_underline, clear_underline)
}

length_vec_property_methods! {
    /// For text runs, the length (non-inclusive) of each character
    /// in UTF-8 code units (bytes). The sum of these lengths must equal
    /// the length of [`value`], also in bytes.
    ///
    /// A character is defined as the smallest unit of text that
    /// can be selected. This isn't necessarily a single Unicode
    /// scalar value (code point). This is why AccessKit can't compute
    /// the lengths of the characters from the text itself; this information
    /// must be provided by the text editing implementation.
    ///
    /// If this node is the last text run in a line that ends with a hard
    /// line break, that line break should be included at the end of this
    /// node's value as either a CRLF or LF; in both cases, the line break
    /// should be counted as a single character for the sake of this slice.
    /// When the caret is at the end of such a line, the focus of the text
    /// selection should be on the line break, not after it.
    ///
    /// [`value`]: Node::value
    (CharacterLengths, character_lengths, set_character_lengths, clear_character_lengths),

    /// For text runs, the start index of each word in characters, as defined
    /// in [`character_lengths`]. This list must be sorted.
    ///
    /// If this text run doesn't contain the start of any words, but only
    /// the middle or end of a word, this list must be empty.
    ///
    /// If this text run is the first in the document or the first in a paragraph
    /// (that is, the previous run ends with a newline character), then the first
    /// character of the run is implicitly the start of a word. In this case,
    /// beginning this list with `0` is permitted but not necessary.
    ///
    /// The end of each word is the beginning of the next word; there are no
    /// characters that are not considered part of a word. Trailing whitespace
    /// is typically considered part of the word that precedes it, while
    /// a line's leading whitespace is considered its own word. Whether
    /// punctuation is considered a separate word or part of the preceding
    /// word depends on the particular text editing implementation.
    /// Some editors may have their own definition of a word; for example,
    /// in an IDE, words may correspond to programming language tokens.
    ///
    /// Not all assistive technologies require information about word
    /// boundaries, and not all platform accessibility APIs even expose
    /// this information, but for assistive technologies that do use
    /// this information, users will get unpredictable results if the word
    /// boundaries exposed by the accessibility tree don't match
    /// the editor's behavior. This is why AccessKit does not determine
    /// word boundaries itself.
    ///
    /// [`character_lengths`]: Node::character_lengths
    (WordStarts, word_starts, set_word_starts, clear_word_starts)
}

coord_vec_property_methods! {
    /// For text runs, this is the position of each character within
    /// the node's bounding box, in the direction given by
    /// [`text_direction`], in the coordinate space of this node.
    ///
    /// When present, the length of this slice should be the same as the length
    /// of [`character_lengths`], including for lines that end
    /// with a hard line break. The position of such a line break should
    /// be the position where an end-of-paragraph marker would be rendered.
    ///
    /// This property is optional. Without it, AccessKit can't support some
    /// use cases, such as screen magnifiers that track the caret position
    /// or screen readers that display a highlight cursor. However,
    /// most text functionality still works without this information.
    ///
    /// [`text_direction`]: Node::text_direction
    /// [`character_lengths`]: Node::character_lengths
    (CharacterPositions, character_positions, set_character_positions, clear_character_positions),

    /// For text runs, this is the advance width of each character,
    /// in the direction given by [`text_direction`], in the coordinate
    /// space of this node.
    ///
    /// When present, the length of this slice should be the same as the length
    /// of [`character_lengths`], including for lines that end
    /// with a hard line break. The width of such a line break should
    /// be non-zero if selecting the line break by itself results in
    /// a visible highlight (as in Microsoft Word), or zero if not
    /// (as in Windows Notepad).
    ///
    /// This property is optional. Without it, AccessKit can't support some
    /// use cases, such as screen magnifiers that track the caret position
    /// or screen readers that display a highlight cursor. However,
    /// most text functionality still works without this information.
    ///
    /// [`text_direction`]: Node::text_direction
    /// [`character_lengths`]: Node::character_lengths
    (CharacterWidths, character_widths, set_character_widths, clear_character_widths)
}

bool_property_methods! {
    /// Whether this node is expanded, collapsed, or neither. ARIA equivalent:
    /// [`aria-expanded`].
    ///
    /// Setting this to `false` means the node is collapsed; omitting it means this state
    /// isn't applicable.
    ///
    /// [`aria-expanded`]: https://www.w3.org/TR/wai-aria-1.2/#aria-expanded
    (Expanded, is_expanded, set_expanded, clear_expanded),

    /// Indicates whether this node is selected or unselected. ARIA equivalent:
    /// [`aria-selected`].
    ///
    /// The absence of this flag (as opposed to a `false` setting)
    /// means that the concept of "selected" doesn't apply.
    /// When deciding whether to set the flag to false or omit it,
    /// consider whether it would be appropriate for a screen reader
    /// to announce "not selected". The ambiguity of this flag
    /// in platform accessibility APIs has made extraneous
    /// "not selected" announcements a common annoyance.
    ///
    /// [`aria-selected`]: https://www.w3.org/TR/wai-aria-1.2/#aria-selected
    (Selected, is_selected, set_selected, clear_selected)
}

unique_enum_property_methods! {
    /// Whether this node's input is invalid, and whether the error is related
    /// to spelling or grammar. ARIA equivalent: [`aria-invalid`].
    ///
    /// [`aria-invalid`]: https://www.w3.org/TR/wai-aria-1.2/#aria-invalid
    (Invalid, invalid, set_invalid, clear_invalid, Grammar),
    /// The checked or pressed state of a toggle control. ARIA equivalents:
    /// [`aria-checked`] and [`aria-pressed`].
    ///
    /// **Difference with ARIA:** ARIA uses separate states for checked and
    /// pressed controls, while this property is interpreted based on the
    /// node's role.
    ///
    /// [`aria-checked`]: https://www.w3.org/TR/wai-aria-1.2/#aria-checked
    /// [`aria-pressed`]: https://www.w3.org/TR/wai-aria-1.2/#aria-pressed
    (Toggled, toggled, set_toggled, clear_toggled, True),
    /// The priority with which updates to this live region should be announced.
    /// ARIA equivalent: [`aria-live`].
    ///
    /// [`aria-live`]: https://www.w3.org/TR/wai-aria-1.2/#aria-live
    (Live, live, set_live, clear_live, Polite),
    /// The direction in which this node's text is laid out.
    (TextDirection, text_direction, set_text_direction, clear_text_direction, RightToLeft),
    /// Whether this node is oriented horizontally or vertically. ARIA
    /// equivalent: [`aria-orientation`].
    ///
    /// [`aria-orientation`]: https://www.w3.org/TR/wai-aria-1.2/#aria-orientation
    (Orientation, orientation, set_orientation, clear_orientation, Vertical),
    /// The direction in which items are sorted by this row or column header.
    /// ARIA equivalent: [`aria-sort`].
    ///
    /// [`aria-sort`]: https://www.w3.org/TR/wai-aria-1.2/#aria-sort
    (SortDirection, sort_direction, set_sort_direction, clear_sort_direction, Descending),
    /// Whether and how this node represents the current item within a set. ARIA
    /// equivalent: [`aria-current`].
    ///
    /// [`aria-current`]: https://www.w3.org/TR/wai-aria-1.2/#aria-current
    (AriaCurrent, aria_current, set_aria_current, clear_aria_current, True),
    /// How predictions are presented while the user enters text. ARIA
    /// equivalent: [`aria-autocomplete`].
    ///
    /// [`aria-autocomplete`]: https://www.w3.org/TR/wai-aria-1.2/#aria-autocomplete
    (AutoComplete, auto_complete, set_auto_complete, clear_auto_complete, List),
    /// The type of interactive popup that can be triggered by this node. ARIA
    /// equivalent: [`aria-haspopup`].
    ///
    /// [`aria-haspopup`]: https://www.w3.org/TR/wai-aria-1.2/#aria-haspopup
    (HasPopup, has_popup, set_has_popup, clear_has_popup, Menu),
    /// The list marker style. Only available on list items.
    (ListStyle, list_style, set_list_style, clear_list_style, Disc),
    /// How this node's text is aligned horizontally.
    (TextAlign, text_align, set_text_align, clear_text_align, Right),
    /// Whether this node's text is rendered as subscript or superscript.
    (VerticalOffset, vertical_offset, set_vertical_offset, clear_vertical_offset, Superscript)
}

property_methods! {
    /// An affine transform to apply to any coordinates within this node
    /// and its descendants, including the [`bounds`] property of this node.
    /// The combined transforms of this node and its ancestors define
    /// the coordinate space of this node. /// This should be `None` if
    /// it would be set to the identity transform, which should be the case
    /// for most nodes.
    ///
    /// AccessKit expects the final transformed coordinates to be relative
    /// to the origin of the tree's container (e.g. window), in physical
    /// pixels, with the y coordinate being top-down.
    ///
    /// [`bounds`]: Node::bounds
    (Transform, transform, get_affine_property, Option<&Affine>, set_transform, set_affine_property, impl Into<Box<Affine>>, clear_transform),

    /// The bounding box of this node, in the node's coordinate space.
    /// This property does not affect the coordinate space of either this node
    /// or its descendants; only the [`transform`] property affects that.
    /// This, along with the recommendation that most nodes should have
    /// a [`transform`] of `None`, implies that the `bounds` property
    /// of most nodes should be in the coordinate space of the nearest ancestor
    /// with a non-`None` [`transform`], or if there is no such ancestor,
    /// the tree's container (e.g. window).
    ///
    /// [`transform`]: Node::transform
    (Bounds, bounds, get_rect_property, Option<Rect>, set_bounds, set_rect_property, Rect, clear_bounds),

    /// The current text selection or caret position within this node's text.
    (TextSelection, text_selection, get_text_selection_property, Option<&TextSelection>, set_text_selection, set_text_selection_property, impl Into<Box<TextSelection>>, clear_text_selection),

    /// The tree that this node grafts. When set, this node acts as a graft
    /// point, and its child is the root of the specified subtree.
    ///
    /// A graft node must be created before its subtree is pushed.
    ///
    /// Removing a graft node or clearing this property removes its subtree,
    /// unless a new graft node is provided in the same update.
    (TreeId, tree_id, get_tree_id_property, Option<TreeId>, set_tree_id, set_tree_id_property, TreeId, clear_tree_id)
}

impl Node {
    option_properties_debug_method! { debug_option_properties, [transform, bounds, text_selection, tree_id,] }
}

#[cfg(test)]
mod transform {
    use super::{Affine, Node, Role};

    #[test]
    fn getter_should_return_default_value() {
        let node = Node::new(Role::Unknown);
        assert!(node.transform().is_none());
    }
    #[test]
    fn setter_should_update_the_property() {
        let mut node = Node::new(Role::Unknown);
        node.set_transform(Affine::IDENTITY);
        assert_eq!(node.transform(), Some(&Affine::IDENTITY));
    }
    #[test]
    fn clearer_should_reset_the_property() {
        let mut node = Node::new(Role::Unknown);
        node.set_transform(Affine::IDENTITY);
        node.clear_transform();
        assert!(node.transform().is_none());
    }
}

#[cfg(test)]
mod bounds {
    use super::{Node, Rect, Role};

    #[test]
    fn getter_should_return_default_value() {
        let node = Node::new(Role::Unknown);
        assert!(node.bounds().is_none());
    }
    #[test]
    fn setter_should_update_the_property() {
        let mut node = Node::new(Role::Unknown);
        let value = Rect {
            x0: 0.0,
            y0: 1.0,
            x1: 2.0,
            y1: 3.0,
        };
        node.set_bounds(value);
        assert_eq!(node.bounds(), Some(value));
    }
    #[test]
    fn clearer_should_reset_the_property() {
        let mut node = Node::new(Role::Unknown);
        node.set_bounds(Rect {
            x0: 0.0,
            y0: 1.0,
            x1: 2.0,
            y1: 3.0,
        });
        node.clear_bounds();
        assert!(node.bounds().is_none());
    }
}

#[cfg(test)]
mod text_selection {
    use super::{Node, NodeId, Role, TextPosition, TextSelection};

    #[test]
    fn getter_should_return_default_value() {
        let node = Node::new(Role::Unknown);
        assert!(node.text_selection().is_none());
    }
    #[test]
    fn setter_should_update_the_property() {
        let mut node = Node::new(Role::Unknown);
        let value = TextSelection {
            anchor: TextPosition {
                node: NodeId(0),
                character_index: 0,
            },
            focus: TextPosition {
                node: NodeId(0),
                character_index: 2,
            },
        };
        node.set_text_selection(value);
        assert_eq!(node.text_selection(), Some(&value));
    }
    #[test]
    fn clearer_should_reset_the_property() {
        let mut node = Node::new(Role::Unknown);
        node.set_text_selection(TextSelection {
            anchor: TextPosition {
                node: NodeId(0),
                character_index: 0,
            },
            focus: TextPosition {
                node: NodeId(0),
                character_index: 2,
            },
        });
        node.clear_text_selection();
        assert!(node.text_selection().is_none());
    }
}

#[cfg(test)]
mod tree_id {
    use super::{Node, Role, TreeId, Uuid};

    #[test]
    fn getter_should_return_default_value() {
        let node = Node::new(Role::GenericContainer);
        assert!(node.tree_id().is_none());
    }
    #[test]
    fn setter_should_update_the_property() {
        let mut node = Node::new(Role::GenericContainer);
        let value = TreeId(Uuid::nil());
        node.set_tree_id(value);
        assert_eq!(node.tree_id(), Some(value));
    }
    #[test]
    fn clearer_should_reset_the_property() {
        let mut node = Node::new(Role::GenericContainer);
        node.set_tree_id(TreeId(Uuid::nil()));
        node.clear_tree_id();
        assert!(node.tree_id().is_none());
    }
}

vec_property_methods! {
    /// The application-defined actions supported by this node.
    (CustomActions, CustomAction, custom_actions, get_custom_action_vec, set_custom_actions, set_custom_action_vec, push_custom_action, push_to_custom_action_vec, clear_custom_actions)
}

#[cfg(test)]
mod custom_actions {
    use super::{CustomAction, Node, Role};
    use core::slice;

    #[test]
    fn getter_should_return_default_value() {
        let node = Node::new(Role::Unknown);
        assert!(node.custom_actions().is_empty());
    }
    #[test]
    fn setter_should_update_the_property() {
        let mut node = Node::new(Role::Unknown);
        let value = alloc::vec![
            CustomAction {
                id: 0,
                description: "first test action".into(),
            },
            CustomAction {
                id: 1,
                description: "second test action".into(),
            },
        ];
        node.set_custom_actions(value.clone());
        assert_eq!(node.custom_actions(), value);
    }
    #[test]
    fn pusher_should_update_the_property() {
        let mut node = Node::new(Role::Unknown);
        let first_action = CustomAction {
            id: 0,
            description: "first test action".into(),
        };
        let second_action = CustomAction {
            id: 1,
            description: "second test action".into(),
        };
        node.push_custom_action(first_action.clone());
        assert_eq!(node.custom_actions(), slice::from_ref(&first_action));
        node.push_custom_action(second_action.clone());
        assert_eq!(node.custom_actions(), &[first_action, second_action]);
    }
    #[test]
    fn pusher_should_start_a_new_list_after_the_clearer() {
        let mut node = Node::new(Role::Unknown);
        node.set_custom_actions([CustomAction {
            id: 0,
            description: "first test action".into(),
        }]);
        node.clear_custom_actions();
        let second_action = CustomAction {
            id: 1,
            description: "second test action".into(),
        };
        node.push_custom_action(second_action.clone());
        assert_eq!(node.custom_actions(), slice::from_ref(&second_action));
    }
    #[test]
    fn clearer_should_reset_the_property() {
        let mut node = Node::new(Role::Unknown);
        node.set_custom_actions([CustomAction {
            id: 0,
            description: "test action".into(),
        }]);
        node.clear_custom_actions();
        assert!(node.custom_actions().is_empty());
    }
}

impl fmt::Debug for Node {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut fmt = f.debug_struct("Node");

        fmt.field("role", &self.role());

        let supported_actions = action_mask_to_action_vec(self.actions);
        if !supported_actions.is_empty() {
            fmt.field("actions", &supported_actions);
        }

        let child_supported_actions = action_mask_to_action_vec(self.child_actions);
        if !child_supported_actions.is_empty() {
            fmt.field("child_actions", &child_supported_actions);
        }

        self.debug_flag_properties(&mut fmt);
        self.debug_node_id_vec_properties(&mut fmt);
        self.debug_node_id_properties(&mut fmt);
        self.debug_string_properties(&mut fmt);
        self.debug_f64_properties(&mut fmt);
        self.debug_f32_properties(&mut fmt);
        self.debug_usize_properties(&mut fmt);
        self.debug_color_properties(&mut fmt);
        self.debug_text_decoration_properties(&mut fmt);
        self.debug_length_vec_properties(&mut fmt);
        self.debug_coord_vec_properties(&mut fmt);
        self.debug_bool_properties(&mut fmt);
        self.debug_unique_enum_properties(&mut fmt);
        self.debug_option_properties(&mut fmt);

        let custom_actions = self.custom_actions();
        if !custom_actions.is_empty() {
            fmt.field("custom_actions", &custom_actions);
        }

        fmt.finish()
    }
}

#[cfg(feature = "serde")]
macro_rules! serialize_property {
    ($self:ident, $map:ident, $index:ident, $id:ident, { $($variant:ident),+ }) => {
        match &$self.values[$index as usize] {
            PropertyValue::None => (),
            $(PropertyValue::$variant(value) => {
                $map.serialize_entry(&$id, &value)?;
            })*
        }
    }
}

#[cfg(feature = "serde")]
macro_rules! deserialize_property {
    ($props:ident, $map:ident, $key:ident, { $($type:ident { $($id:ident),+ }),+ }) => {
        match $key {
            $($(PropertyId::$id => {
                let value = $map.next_value()?;
                $props.set(PropertyId::$id, PropertyValue::$type(value));
            })*)*
            PropertyId::Unset => {
                let _ = $map.next_value::<IgnoredAny>()?;
            }
        }
    }
}

#[cfg(feature = "serde")]
impl Serialize for Properties {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut len = 0;
        for value in &*self.values {
            if !matches!(*value, PropertyValue::None) {
                len += 1;
            }
        }
        let mut map = serializer.serialize_map(Some(len))?;
        for (id, index) in self.indices.0.iter().copied().enumerate() {
            if index == PropertyId::Unset as u8 {
                continue;
            }
            let id = PropertyId::n(id as _).unwrap();
            serialize_property!(self, map, index, id, {
                NodeIdVec,
                NodeId,
                String,
                F64,
                F32,
                Usize,
                Color,
                TextDecoration,
                LengthVec,
                CoordVec,
                Bool,
                Invalid,
                Toggled,
                Live,
                TextDirection,
                Orientation,
                SortDirection,
                AriaCurrent,
                AutoComplete,
                HasPopup,
                ListStyle,
                TextAlign,
                VerticalOffset,
                Affine,
                Rect,
                TextSelection,
                CustomActionVec,
                TreeId
            });
        }
        map.end()
    }
}

#[cfg(feature = "serde")]
struct PropertiesVisitor;

#[cfg(feature = "serde")]
impl<'de> Visitor<'de> for PropertiesVisitor {
    type Value = Properties;

    #[inline]
    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("property map")
    }

    fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
    where
        V: MapAccess<'de>,
    {
        let mut props = Properties::default();
        while let Some(id) = map.next_key()? {
            deserialize_property!(props, map, id, {
                NodeIdVec {
                    Children,
                    Controls,
                    Details,
                    DescribedBy,
                    FlowTo,
                    LabelledBy,
                    Owns,
                    RadioGroup
                },
                NodeId {
                    ActiveDescendant,
                    ErrorMessage,
                    InPageLinkTarget,
                    MemberOf,
                    NextOnLine,
                    PreviousOnLine,
                    PopupFor
                },
                String {
                    Label,
                    Description,
                    Value,
                    AccessKey,
                    AuthorId,
                    ClassName,
                    FontFamily,
                    HtmlId,
                    HtmlTag,
                    InnerHtml,
                    KeyboardShortcut,
                    Language,
                    Placeholder,
                    RoleDescription,
                    StateDescription,
                    Tooltip,
                    Url,
                    RowIndexText,
                    ColumnIndexText,
                    BrailleLabel,
                    BrailleRoleDescription
                },
                F64 {
                    ScrollX,
                    ScrollXMin,
                    ScrollXMax,
                    ScrollY,
                    ScrollYMin,
                    ScrollYMax,
                    NumericValue,
                    MinNumericValue,
                    MaxNumericValue,
                    NumericValueStep,
                    NumericValueJump
                },
                F32 {
                    FontSize,
                    FontWeight
                },
                Usize {
                    RowCount,
                    ColumnCount,
                    RowIndex,
                    ColumnIndex,
                    RowSpan,
                    ColumnSpan,
                    Level,
                    SizeOfSet,
                    PositionInSet
                },
                Color {
                    ColorValue,
                    BackgroundColor,
                    ForegroundColor
                },
                TextDecoration {
                    Overline,
                    Strikethrough,
                    Underline
                },
                LengthVec {
                    CharacterLengths,
                    WordStarts
                },
                CoordVec {
                    CharacterPositions,
                    CharacterWidths
                },
                Bool {
                    Expanded,
                    Selected
                },
                Invalid { Invalid },
                Toggled { Toggled },
                Live { Live },
                TextDirection { TextDirection },
                Orientation { Orientation },
                SortDirection { SortDirection },
                AriaCurrent { AriaCurrent },
                AutoComplete { AutoComplete },
                HasPopup { HasPopup },
                ListStyle { ListStyle },
                TextAlign { TextAlign },
                VerticalOffset { VerticalOffset },
                Affine { Transform },
                Rect { Bounds },
                TextSelection { TextSelection },
                CustomActionVec { CustomActions },
                TreeId { TreeId }
            });
        }

        Ok(props)
    }
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Properties {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_map(PropertiesVisitor)
    }
}

#[cfg(feature = "schemars")]
macro_rules! add_schema_property {
    ($gen:ident, $properties:ident, $enum_value:expr, $type:ty) => {{
        let name = format!("{:?}", $enum_value);
        let name = name[..1].to_ascii_lowercase() + &name[1..];
        let subschema = $gen.subschema_for::<$type>();
        $properties.insert(name, SchemaValue::from(subschema));
    }};
}

#[cfg(feature = "schemars")]
macro_rules! add_properties_to_schema {
    ($gen:ident, $properties:ident, { $($type:ty { $($id:ident),+ }),+ }) => {
        $($(add_schema_property!($gen, $properties, PropertyId::$id, $type);)*)*
    }
}

#[cfg(feature = "schemars")]
impl JsonSchema for Properties {
    #[inline]
    fn schema_name() -> Cow<'static, str> {
        "Properties".into()
    }

    fn json_schema(generator: &mut SchemaGenerator) -> Schema {
        let mut properties = SchemaMap::<String, SchemaValue>::new();
        add_properties_to_schema!(generator, properties, {
            Vec<NodeId> {
                Children,
                Controls,
                Details,
                DescribedBy,
                FlowTo,
                LabelledBy,
                Owns,
                RadioGroup
            },
            NodeId {
                ActiveDescendant,
                ErrorMessage,
                InPageLinkTarget,
                MemberOf,
                NextOnLine,
                PreviousOnLine,
                PopupFor
            },
            String {
                Label,
                Description,
                Value,
                AccessKey,
                AuthorId,
                ClassName,
                FontFamily,
                HtmlId,
                HtmlTag,
                InnerHtml,
                KeyboardShortcut,
                Language,
                Placeholder,
                RoleDescription,
                StateDescription,
                Tooltip,
                Url,
                RowIndexText,
                ColumnIndexText,
                BrailleLabel,
                BrailleRoleDescription
            },
            f64 {
                ScrollX,
                ScrollXMin,
                ScrollXMax,
                ScrollY,
                ScrollYMin,
                ScrollYMax,
                NumericValue,
                MinNumericValue,
                MaxNumericValue,
                NumericValueStep,
                NumericValueJump
            },
            f32 {
                FontSize,
                FontWeight
            },
            usize {
                RowCount,
                ColumnCount,
                RowIndex,
                ColumnIndex,
                RowSpan,
                ColumnSpan,
                Level,
                SizeOfSet,
                PositionInSet
            },
            Color {
                ColorValue,
                BackgroundColor,
                ForegroundColor
            },
            TextDecoration {
                Overline,
                Strikethrough,
                Underline
            },
            Vec<u8> {
                CharacterLengths,
                WordStarts
            },
            Vec<f32> {
                CharacterPositions,
                CharacterWidths
            },
            bool {
                Expanded,
                Selected
            },
            Invalid { Invalid },
            Toggled { Toggled },
            Live { Live },
            TextDirection { TextDirection },
            Orientation { Orientation },
            SortDirection { SortDirection },
            AriaCurrent { AriaCurrent },
            AutoComplete { AutoComplete },
            HasPopup { HasPopup },
            ListStyle { ListStyle },
            TextAlign { TextAlign },
            VerticalOffset { VerticalOffset },
            Affine { Transform },
            Rect { Bounds },
            TextSelection { TextSelection },
            Vec<CustomAction> { CustomActions },
            TreeId { TreeId }
        });
        json_schema!({
            "type": "object",
            "properties": properties
        })
    }
}

/// The data associated with an accessibility tree that's global to the
/// tree and not associated with any particular node.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct TreeInfo {
    /// The identifier of the tree's root node.
    pub root: NodeId,
    /// The name of the UI toolkit in use.
    pub toolkit_name: Option<String>,
    /// The version of the UI toolkit.
    pub toolkit_version: Option<String>,
}

#[deprecated(note = "Use TreeInfo instead")]
pub type Tree = TreeInfo;

impl TreeInfo {
    #[inline]
    pub fn new(root: NodeId) -> TreeInfo {
        TreeInfo {
            root,
            toolkit_name: None,
            toolkit_version: None,
        }
    }
}

/// A serializable representation of an atomic change to a tree.
///
/// The sender and receiver must be in sync; the update is only meant
/// to bring the tree from a specific previous state into its next state.
/// Trying to apply it to the wrong tree should immediately panic.
///
/// Note that for performance, an update should only include nodes that are
/// new or changed. AccessKit platform adapters will avoid raising extraneous
/// events for nodes that have not changed since the previous update,
/// but there is still a cost in processing these nodes and replacing
/// the previous instances.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct TreeUpdate {
    /// Zero or more new or updated nodes. Order doesn't matter.
    ///
    /// Each node in this list will overwrite any existing node with the same ID.
    /// This means that when updating a node, fields that are unchanged
    /// from the previous version must still be set to the same values
    /// as before.
    ///
    /// It is an error for any node in this list to not be either the root
    /// or a child of another node. For nodes other than the root, the parent
    /// must be either an unchanged node already in the tree, or another node
    /// in this list.
    ///
    /// To add a child to the tree, the list must include both the child
    /// and an updated version of the parent with the child's ID added to
    /// [`Node::children`].
    ///
    /// To remove a child and all of its descendants, this list must include
    /// an updated version of the parent node with the child's ID removed
    /// from [`Node::children`]. Neither the child nor any of its descendants
    /// may be included in this list.
    pub nodes: Vec<(NodeId, Node)>,

    /// Rarely updated information about the tree as a whole. This may be omitted
    /// if it has not changed since the previous update, but providing the same
    /// information again is also allowed. This is required when initializing
    /// a tree.
    pub tree: Option<TreeInfo>,

    /// The identifier of the tree that this update applies to.
    ///
    /// Use [`TreeId::ROOT`] for the main/root tree. For subtrees, use a unique
    /// [`TreeId`] that identifies the subtree.
    ///
    /// When updating a subtree (non-ROOT tree_id):
    /// - A graft node with [`Node::tree_id`] set to this tree's ID must already
    ///   exist in the parent tree before the first subtree update.
    /// - The first update for a subtree must include [`tree`](Self::tree) data.
    pub tree_id: TreeId,

    /// The node within this tree that has keyboard focus when the native
    /// host (e.g. window) has focus. If no specific node within the tree
    /// has keyboard focus, this must be set to the root. The latest focus state
    /// must be provided with every tree update, even if the focus state
    /// didn't change in a given update.
    ///
    /// For subtrees, this specifies which node has focus when the subtree
    /// itself is focused (i.e., when focus is on the graft node in the parent
    /// tree).
    pub focus: NodeId,
}

/// The amount by which to scroll in the direction specified by one of the
/// `Scroll` actions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
#[cfg_attr(
    feature = "pyo3",
    pyclass(module = "accesskit", rename_all = "SCREAMING_SNAKE_CASE", eq)
)]
#[repr(u8)]
pub enum ScrollUnit {
    /// A single item of a list, line of text (for vertical scrolling),
    /// character (for horizontal scrolling), or an approximation of
    /// one of these.
    Item,
    /// The amount of content that fits in the viewport.
    Page,
}

/// A suggestion about where the node being scrolled into view should be
/// positioned relative to the edges of the scrollable container.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
#[cfg_attr(
    feature = "pyo3",
    pyclass(module = "accesskit", rename_all = "SCREAMING_SNAKE_CASE", eq)
)]
#[repr(u8)]
pub enum ScrollHint {
    TopLeft,
    BottomRight,
    TopEdge,
    BottomEdge,
    LeftEdge,
    RightEdge,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
#[repr(C)]
pub enum ActionData {
    CustomAction(i32),
    Value(Box<str>),
    NumericValue(f64),
    ScrollUnit(ScrollUnit),
    /// Optional suggestion for [`Action::ScrollIntoView`], specifying
    /// the preferred position of the target node relative to the scrollable
    /// container's viewport.
    ScrollHint(ScrollHint),
    /// Target for [`Action::ScrollToPoint`], in platform-native coordinates
    /// relative to the origin of the tree's container (e.g. window).
    ScrollToPoint(Point),
    /// Target for [`Action::SetScrollOffset`], in the coordinate space
    /// of the action's target node.
    SetScrollOffset(Point),
    SetTextSelection(TextSelection),
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct ActionRequest {
    pub action: Action,
    pub target_tree: TreeId,
    pub target_node: NodeId,
    pub data: Option<ActionData>,
}

/// Handles activation of the application's accessibility implementation.
pub trait ActivationHandler {
    /// Requests a [`TreeUpdate`] with a full tree. If the application
    /// can generate the tree synchronously within this method call,
    /// it should do so and return the [`TreeUpdate`]. Otherwise,
    /// it must send the update to the platform adapter asynchronously,
    /// no later than the next display refresh, even if a frame would not
    /// normally be rendered due to user input or other activity.
    /// The application should not return or send a placeholder [`TreeUpdate`];
    /// the platform adapter will provide one if necessary until the real
    /// tree is sent.
    ///
    /// The primary purpose of this method is to allow the application
    /// to lazily initialize its accessibility implementation. However,
    /// this method may be called consecutively without any call to
    /// [`DeactivationHandler::deactivate_accessibility`]; this typically happens
    /// if the platform adapter merely forwards tree updates to assistive
    /// technologies without maintaining any state. A call to this method
    /// must always generate a [`TreeUpdate`] with a full tree, even if
    /// the application normally sends incremental updates.
    ///
    /// The thread on which this method is called is platform-dependent.
    /// Refer to the platform adapter documentation for more details.
    fn request_initial_tree(&mut self) -> Option<TreeUpdate>;
}

/// Handles requests from assistive technologies or other clients.
pub trait ActionHandler {
    /// Perform the requested action. If the requested action is not supported,
    /// this method must do nothing.
    ///
    /// The thread on which this method is called is platform-dependent.
    /// Refer to the platform adapter documentation for more details.
    ///
    /// This method may queue the request and handle it asynchronously.
    /// This behavior is preferred over blocking, e.g. when dispatching
    /// the request to another thread.
    fn do_action(&mut self, request: ActionRequest);
}

/// Handles deactivation of the application's accessibility implementation.
pub trait DeactivationHandler {
    /// Deactivate the application's accessibility implementation and drop any
    /// associated data that can be reconstructed later. After this method
    /// is called, if an accessibility tree is needed again, the platform
    /// adapter will call [`ActivationHandler::request_initial_tree`] again.
    ///
    /// The thread on which this method is called is platform-dependent.
    /// Refer to the platform adapter documentation for more details.
    fn deactivate_accessibility(&mut self);
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::format;

    #[test]
    fn nodes_should_be_equal_regardless_of_the_order_properties_were_set() {
        let mut node = Node::new(Role::Button);
        node.set_label("a label");
        node.set_children([NodeId(1)]);
        node.set_description("a description");

        let mut reordered = Node::new(Role::Button);
        reordered.set_description("a description");
        reordered.set_children([NodeId(1)]);
        reordered.set_label("a label");

        assert_eq!(node, reordered);
    }

    #[test]
    fn cleared_property_should_be_equal_to_one_that_was_never_set() {
        let mut node = Node::new(Role::Button);
        node.set_label("a label");
        node.clear_label();

        assert_eq!(node, Node::new(Role::Button));
    }

    #[test]
    fn clone_from_should_be_equivalent_to_clone() {
        let mut source = Node::new(Role::Button);
        source.add_action(Action::Click);
        source.add_child_action(Action::Focus);
        source.set_hidden();
        source.set_label("source");
        source.set_children([NodeId(1)]);

        let mut dest = Node::new(Role::CheckBox);
        dest.add_action(Action::Focus);
        dest.set_multiselectable();
        dest.set_description("dest");
        dest.set_children([NodeId(7), NodeId(8)]);
        dest.clone_from(&source);

        assert_eq!(dest, source.clone());
    }

    #[test]
    fn clone_from_should_reuse_the_destination_string_buffer() {
        let mut source = Node::new(Role::Button);
        source.set_label("new label");
        let mut dest = Node::new(Role::Button);
        dest.set_label("old label with room to spare");
        let buffer = dest.label().unwrap().as_ptr();

        dest.clone_from(&source);

        assert_eq!(dest.label(), Some("new label"));
        assert_eq!(dest.label().unwrap().as_ptr(), buffer);
    }

    #[test]
    fn clone_from_should_reuse_the_destination_slice_buffer() {
        let mut source = Node::new(Role::TextRun);
        source.set_character_lengths([1u8, 2, 3]);
        let mut dest = Node::new(Role::TextRun);
        dest.set_character_lengths([9u8; 16]);
        let buffer = dest.character_lengths().as_ptr();

        dest.clone_from(&source);

        assert_eq!(dest.character_lengths(), &[1, 2, 3]);
        assert_eq!(dest.character_lengths().as_ptr(), buffer);
    }

    #[test]
    fn u64_should_be_convertible_to_node_id() {
        assert_eq!(NodeId::from(0u64), NodeId(0));
        assert_eq!(NodeId::from(1u64), NodeId(1));
    }

    #[test]
    fn node_id_should_be_convertible_to_u64() {
        assert_eq!(u64::from(NodeId(0)), 0u64);
        assert_eq!(u64::from(NodeId(1)), 1u64);
    }

    #[test]
    fn node_id_should_have_debug_repr() {
        assert_eq!(&format!("{:?}", NodeId(0)), "#0");
        assert_eq!(&format!("{:?}", NodeId(1)), "#1");
    }

    #[test]
    fn action_n_should_return_the_corresponding_variant() {
        assert_eq!(Action::n(0), Some(Action::Click));
        assert_eq!(Action::n(1), Some(Action::Focus));
        assert_eq!(Action::n(2), Some(Action::Blur));
        assert_eq!(Action::n(3), Some(Action::Collapse));
        assert_eq!(Action::n(4), Some(Action::Expand));
        assert_eq!(Action::n(5), Some(Action::CustomAction));
        assert_eq!(Action::n(6), Some(Action::Decrement));
        assert_eq!(Action::n(7), Some(Action::Increment));
        assert_eq!(Action::n(8), Some(Action::HideTooltip));
        assert_eq!(Action::n(9), Some(Action::ShowTooltip));
        assert_eq!(Action::n(10), Some(Action::ReplaceSelectedText));
        assert_eq!(Action::n(11), Some(Action::ScrollDown));
        assert_eq!(Action::n(12), Some(Action::ScrollLeft));
        assert_eq!(Action::n(13), Some(Action::ScrollRight));
        assert_eq!(Action::n(14), Some(Action::ScrollUp));
        assert_eq!(Action::n(15), Some(Action::ScrollIntoView));
        assert_eq!(Action::n(16), Some(Action::ScrollToPoint));
        assert_eq!(Action::n(17), Some(Action::SetScrollOffset));
        assert_eq!(Action::n(18), Some(Action::SetTextSelection));
        assert_eq!(
            Action::n(19),
            Some(Action::SetSequentialFocusNavigationStartingPoint)
        );
        assert_eq!(Action::n(20), Some(Action::SetValue));
        assert_eq!(Action::n(21), Some(Action::ShowContextMenu));
        assert_eq!(Action::n(22), None);
    }

    #[test]
    fn empty_action_mask_should_be_converted_to_empty_vec() {
        assert_eq!(
            Vec::<Action>::new(),
            action_mask_to_action_vec(Node::new(Role::Unknown).actions)
        );
    }

    #[test]
    fn action_mask_should_be_convertible_to_vec() {
        let mut node = Node::new(Role::Unknown);
        node.add_action(Action::Click);
        assert_eq!(
            &[Action::Click],
            action_mask_to_action_vec(node.actions).as_slice()
        );

        let mut node = Node::new(Role::Unknown);
        node.add_action(Action::ShowContextMenu);
        assert_eq!(
            &[Action::ShowContextMenu],
            action_mask_to_action_vec(node.actions).as_slice()
        );

        let mut node = Node::new(Role::Unknown);
        node.add_action(Action::Click);
        node.add_action(Action::ShowContextMenu);
        assert_eq!(
            &[Action::Click, Action::ShowContextMenu],
            action_mask_to_action_vec(node.actions).as_slice()
        );

        let mut node = Node::new(Role::Unknown);
        node.add_action(Action::Focus);
        node.add_action(Action::Blur);
        node.add_action(Action::Collapse);
        assert_eq!(
            &[Action::Focus, Action::Blur, Action::Collapse],
            action_mask_to_action_vec(node.actions).as_slice()
        );
    }

    #[test]
    fn new_node_should_have_user_provided_role() {
        let node = Node::new(Role::Button);
        assert_eq!(node.role(), Role::Button);
    }

    #[test]
    fn node_role_setter_should_update_the_role() {
        let mut node = Node::new(Role::Button);
        node.set_role(Role::CheckBox);
        assert_eq!(node.role(), Role::CheckBox);
    }

    macro_rules! assert_absent_action {
        ($node:ident, $action:ident) => {
            assert!(!$node.supports_action(Action::$action));
            assert!(!$node.child_supports_action(Action::$action));
        };
    }

    #[test]
    fn new_node_should_not_support_anyaction() {
        let node = Node::new(Role::Unknown);
        assert_absent_action!(node, Click);
        assert_absent_action!(node, Focus);
        assert_absent_action!(node, Blur);
        assert_absent_action!(node, Collapse);
        assert_absent_action!(node, Expand);
        assert_absent_action!(node, CustomAction);
        assert_absent_action!(node, Decrement);
        assert_absent_action!(node, Increment);
        assert_absent_action!(node, HideTooltip);
        assert_absent_action!(node, ShowTooltip);
        assert_absent_action!(node, ReplaceSelectedText);
        assert_absent_action!(node, ScrollDown);
        assert_absent_action!(node, ScrollLeft);
        assert_absent_action!(node, ScrollRight);
        assert_absent_action!(node, ScrollUp);
        assert_absent_action!(node, ScrollIntoView);
        assert_absent_action!(node, ScrollToPoint);
        assert_absent_action!(node, SetScrollOffset);
        assert_absent_action!(node, SetTextSelection);
        assert_absent_action!(node, SetSequentialFocusNavigationStartingPoint);
        assert_absent_action!(node, SetValue);
        assert_absent_action!(node, ShowContextMenu);
    }

    #[test]
    fn node_add_action_should_add_the_action() {
        let mut node = Node::new(Role::Unknown);
        node.add_action(Action::Focus);
        assert!(node.supports_action(Action::Focus));
        node.add_action(Action::Blur);
        assert!(node.supports_action(Action::Blur));
    }

    #[test]
    fn node_add_child_action_should_add_the_action() {
        let mut node = Node::new(Role::Unknown);
        node.add_child_action(Action::Focus);
        assert!(node.child_supports_action(Action::Focus));
        node.add_child_action(Action::Blur);
        assert!(node.child_supports_action(Action::Blur));
    }

    #[test]
    fn node_add_action_should_do_nothing_if_the_action_is_already_supported() {
        let mut node = Node::new(Role::Unknown);
        node.add_action(Action::Focus);
        node.add_action(Action::Focus);
        assert!(node.supports_action(Action::Focus));
    }

    #[test]
    fn node_add_child_action_should_do_nothing_if_the_action_is_already_supported() {
        let mut node = Node::new(Role::Unknown);
        node.add_child_action(Action::Focus);
        node.add_child_action(Action::Focus);
        assert!(node.child_supports_action(Action::Focus));
    }

    #[test]
    fn node_remove_action_should_remove_the_action() {
        let mut node = Node::new(Role::Unknown);
        node.add_action(Action::Blur);
        node.remove_action(Action::Blur);
        assert!(!node.supports_action(Action::Blur));
    }

    #[test]
    fn node_remove_child_action_should_remove_the_action() {
        let mut node = Node::new(Role::Unknown);
        node.add_child_action(Action::Blur);
        node.remove_child_action(Action::Blur);
        assert!(!node.child_supports_action(Action::Blur));
    }

    #[test]
    fn node_clear_actions_should_remove_all_actions() {
        let mut node = Node::new(Role::Unknown);
        node.add_action(Action::Focus);
        node.add_action(Action::Blur);
        node.clear_actions();
        assert!(!node.supports_action(Action::Focus));
        assert!(!node.supports_action(Action::Blur));
    }

    #[test]
    fn node_clear_child_actions_should_remove_all_actions() {
        let mut node = Node::new(Role::Unknown);
        node.add_child_action(Action::Focus);
        node.add_child_action(Action::Blur);
        node.clear_child_actions();
        assert!(!node.child_supports_action(Action::Focus));
        assert!(!node.child_supports_action(Action::Blur));
    }

    #[test]
    fn node_should_have_debug_repr() {
        let mut node = Node::new(Role::Unknown);
        node.add_action(Action::Click);
        node.add_action(Action::Focus);
        node.add_child_action(Action::ScrollIntoView);
        node.set_hidden();
        node.set_multiselectable();
        node.set_children([NodeId(0), NodeId(1)]);
        node.set_active_descendant(NodeId(2));
        node.push_custom_action(CustomAction {
            id: 0,
            description: "test action".into(),
        });

        assert_eq!(
            &format!("{node:?}"),
            r#"Node { role: Unknown, actions: [Click, Focus], child_actions: [ScrollIntoView], is_hidden: true, is_multiselectable: true, children: [#0, #1], active_descendant: #2, custom_actions: [CustomAction { id: 0, description: "test action" }] }"#
        );
    }

    #[test]
    fn new_tree_should_have_root_id() {
        let tree = TreeInfo::new(NodeId(1));
        assert_eq!(tree.root, NodeId(1));
        assert_eq!(tree.toolkit_name, None);
        assert_eq!(tree.toolkit_version, None);
    }
}