summary refs log tree commit diff stats
path: root/tinyc/win32/include/stdint.h
blob: cde32b6e399645191bd3969295875d2f1c503db4 (plain) (blame)
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
/**
 * This file has no copyright assigned and is placed in the Public Domain.
 * This file is part of the w64 mingw-runtime package.
 * No warranty is given; refer to the file DISCLAIMER within this package.
 */
/* ISO C9x  7.18  Integer types <stdint.h>
 * Based on ISO/IEC SC22/WG14 9899 Committee draft (SC22 N2794)
 *
 *  THIS SOFTWARE IS NOT COPYRIGHTED
 *
 *  Contributor: Danny Smith <danny_r_smith_2001@yahoo.co.nz>
 *
 *  This source code is offered for use in the public domain. You may
 *  use, modify or distribute it freely.
 *
 *  This code is distributed in the hope that it will be useful but
 *  WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY
 *  DISCLAIMED. This includes but is not limited to warranties of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 *  Date: 2000-12-02
 */


#ifndef _STDINT_H
#define _STDINT_H

#include <_mingw.h>

#define __need_wint_t
#define __need_wchar_t
#include "stddef.h"

#ifndef __int8_t_defined
#define __int8_t_defined
/* 7.18.1.1  Exact-width integer types */
typedef signed char int8_t;
typedef unsigned char   uint8_t;
typedef short  int16_t;
typedef unsigned short  uint16_t;
typedef int  int32_t;
typedef unsigned   uint32_t;
typedef long long  int64_t;
typedef unsigned long long   uint64_t;
#endif

/* 7.18.1.2  Minimum-width integer types */
typedef signed char int_least8_t;
typedef unsigned char   uint_least8_t;
typedef short  int_least16_t;
typedef unsigned short  uint_least16_t;
typedef int  int_least32_t;
typedef unsigned   uint_least32_t;
typedef long long  int_least64_t;
typedef unsigned long long   uint_least64_t;

/*  7.18.1.3  Fastest minimum-width integer types
 *  Not actually guaranteed to be fastest for all purposes
 *  Here we use the exact-width types for 8 and 16-bit ints.
 */
typedef char int_fast8_t;
typedef unsigned char uint_fast8_t;
typedef short  int_fast16_t;
typedef unsigned short  uint_fast16_t;
typedef int  int_fast32_t;
typedef unsigned  int  uint_fast32_t;
typedef long long  int_fast64_t;
typedef unsigned long long   uint_fast64_t;

/* 7.18.1.5  Greatest-width integer types */
typedef long long  intmax_t;
typedef unsigned long long   uintmax_t;

/* 7.18.2  Limits of specified-width integer types */
#if !defined ( __cplusplus) || defined (__STDC_LIMIT_MACROS)

/* 7.18.2.1  Limits of exact-width integer types */
#define INT8_MIN (-128)
#define INT16_MIN (-32768)
#define INT32_MIN (-2147483647 - 1)
#define INT64_MIN  (-9223372036854775807LL - 1)

#define INT8_MAX 127
#define INT16_MAX 32767
#define INT32_MAX 2147483647
#define INT64_MAX 9223372036854775807LL

#define UINT8_MAX 0xff /* 255U */
#define UINT16_MAX 0xffff /* 65535U */
#define UINT32_MAX 0xffffffff  /* 4294967295U */
#define UINT64_MAX 0xffffffffffffffffULL /* 18446744073709551615ULL */

/* 7.18.2.2  Limits of minimum-width integer types */
#define INT_LEAST8_MIN INT8_MIN
#define INT_LEAST16_MIN INT16_MIN
#define INT_LEAST32_MIN INT32_MIN
#define INT_LEAST64_MIN INT64_MIN

#define INT_LEAST8_MAX INT8_MAX
#define INT_LEAST16_MAX INT16_MAX
#define INT_LEAST32_MAX INT32_MAX
#define INT_LEAST64_MAX INT64_MAX

#define UINT_LEAST8_MAX UINT8_MAX
#define UINT_LEAST16_MAX UINT16_MAX
#define UINT_LEAST32_MAX UINT32_MAX
#define UINT_LEAST64_MAX UINT64_MAX

/* 7.18.2.3  Limits of fastest minimum-width integer types */
#define INT_FAST8_MIN INT8_MIN
#define INT_FAST16_MIN INT16_MIN
#define INT_FAST32_MIN INT32_MIN
#define INT_FAST64_MIN INT64_MIN

#define INT_FAST8_MAX INT8_MAX
#define INT_FAST16_MAX INT16_MAX
#define INT_FAST32_MAX INT32_MAX
#define INT_FAST64_MAX INT64_MAX

#define UINT_FAST8_MAX UINT8_MAX
#define UINT_FAST16_MAX UINT16_MAX
#define UINT_FAST32_MAX UINT32_MAX
#define UINT_FAST64_MAX UINT64_MAX

/* 7.18.2.4  Limits of integer types capable of holding
    object pointers */
#ifdef _WIN64
#define INTPTR_MIN INT64_MIN
#define INTPTR_MAX INT64_MAX
#define UINTPTR_MAX UINT64_MAX
#else
#define INTPTR_MIN INT32_MIN
#define INTPTR_MAX INT32_MAX
#define UINTPTR_MAX UINT32_MAX
#endif

/* 7.18.2.5  Limits of greatest-width integer types */
#define INTMAX_MIN INT64_MIN
#define INTMAX_MAX INT64_MAX
#define UINTMAX_MAX UINT64_MAX

/* 7.18.3  Limits of other integer types */
#ifdef _WIN64
#define PTRDIFF_MIN INT64_MIN
#define PTRDIFF_MAX INT64_MAX
#else
#define PTRDIFF_MIN INT32_MIN
#define PTRDIFF_MAX INT32_MAX
#endif

#define SIG_ATOMIC_MIN INT32_MIN
#define SIG_ATOMIC_MAX INT32_MAX

#ifndef SIZE_MAX
#ifdef _WIN64
#define SIZE_MAX UINT64_MAX
#else
#define SIZE_MAX UINT32_MAX
#endif
#endif

#ifndef WCHAR_MIN  /* also in wchar.h */
#define WCHAR_MIN 0
#define WCHAR_MAX ((wchar_t)-1) /* UINT16_MAX */
#endif

/*
 * wint_t is unsigned short for compatibility with MS runtime
 */
#define WINT_MIN 0
#define WINT_MAX ((wint_t)-1) /* UINT16_MAX */

#endif /* !defined ( __cplusplus) || defined __STDC_LIMIT_MACROS */


/* 7.18.4  Macros for integer constants */
#if !defined ( __cplusplus) || defined (__STDC_CONSTANT_MACROS)

/* 7.18.4.1  Macros for minimum-width integer constants

    According to Douglas Gwyn <gwyn@arl.mil>:
	"This spec was changed in ISO/IEC 9899:1999 TC1; in ISO/IEC
	9899:1999 as initially published, the expansion was required
	to be an integer constant of precisely matching type, which
	is impossible to accomplish for the shorter types on most
	platforms, because C99 provides no standard way to designate
	an integer constant with width less than that of type int.
	TC1 changed this to require just an integer constant
	*expression* with *promoted* type."

	The trick used here is from Clive D W Feather.
*/

#define INT8_C(val) (INT_LEAST8_MAX-INT_LEAST8_MAX+(val))
#define INT16_C(val) (INT_LEAST16_MAX-INT_LEAST16_MAX+(val))
#define INT32_C(val) (INT_LEAST32_MAX-INT_LEAST32_MAX+(val))
/*  The 'trick' doesn't work in C89 for long long because, without
    suffix, (val) will be evaluated as int, not intmax_t */
#define INT64_C(val) val##LL

#define UINT8_C(val) (UINT_LEAST8_MAX-UINT_LEAST8_MAX+(val))
#define UINT16_C(val) (UINT_LEAST16_MAX-UINT_LEAST16_MAX+(val))
#define UINT32_C(val) (UINT_LEAST32_MAX-UINT_LEAST32_MAX+(val))
#define UINT64_C(val) val##ULL

/* 7.18.4.2  Macros for greatest-width integer constants */
#define INTMAX_C(val) val##LL
#define UINTMAX_C(val) val##ULL

#endif  /* !defined ( __cplusplus) || defined __STDC_CONSTANT_MACROS */

#endif
>833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822
import std/algorithm
import std/deques
import std/math
import std/options
import std/posix
import std/sets
import std/strutils
import std/tables
import std/times

import chagashi/charset
import chagashi/decoder
import chame/tags
import css/cssparser
import css/cssvalues
import css/mediaquery
import css/sheet
import html/catom
import html/enums
import html/event
import html/script
import io/bufwriter
import io/dynstream
import io/promise
import js/console
import js/domexception
import js/timeout
import loader/headers
import loader/loaderiface
import loader/request
import loader/response
import monoucha/fromjs
import monoucha/javascript
import monoucha/jserror
import monoucha/jsopaque
import monoucha/jspropenumlist
import monoucha/jsutils
import monoucha/quickjs
import monoucha/tojs
import types/bitmap
import types/blob
import types/canvastypes
import types/color
import types/line
import types/matrix
import types/opt
import types/path
import types/referrer
import types/url
import types/vector
import types/winattrs
import utils/mimeguess
import utils/strwidth
import utils/twtstr

type
  FormMethod* = enum
    fmGet = "get"
    fmPost = "post"
    fmDialog = "dialog"

  FormEncodingType* = enum
    fetUrlencoded = "application/x-www-form-urlencoded",
    fetMultipart = "multipart/form-data",
    fetTextPlain = "text/plain"

  DocumentReadyState* = enum
    rsLoading = "loading"
    rsInteractive = "interactive"
    rsComplete = "complete"

type
  DependencyType* = enum
    dtHover, dtChecked, dtFocus

  Location = ref object
    window: Window

  CachedURLImage = ref object
    expiry: int64
    loading: bool
    shared: seq[HTMLImageElement]
    bmp: NetworkBitmap

  Window* = ref object of EventTarget
    attrs*: WindowAttributes
    internalConsole*: Console
    navigator* {.jsget.}: Navigator
    screen* {.jsget.}: Screen
    history* {.jsget.}: History
    localStorage* {.jsget.}: Storage
    sessionStorage* {.jsget.}: Storage
    settings*: EnvironmentSettings
    loader*: FileLoader
    location* {.jsget.}: Location
    jsrt*: JSRuntime
    jsctx*: JSContext
    document* {.jsufget.}: Document
    timeouts*: TimeoutState
    navigate*: proc(url: URL)
    importMapsAllowed*: bool
    factory*: CAtomFactory
    loadingResourcePromises*: seq[EmptyPromise]
    imageURLCache: Table[string, CachedURLImage]
    images*: bool
    styling*: bool
    # ID of the next image
    imageId: int
    # list of streams that must be closed for canvas rendering on load
    pendingCanvasCtls*: seq[CanvasRenderingContext2D]

  # Navigator stuff
  Navigator* = object
    plugins: PluginArray

  PluginArray* = object

  MimeTypeArray* = object

  Screen* = object

  History* = object

  Storage* = object
    map*: seq[tuple[key, value: string]]

  NamedNodeMap = ref object
    element: Element
    attrlist: seq[Attr]

  Collection = ref object of RootObj
    islive: bool
    childonly: bool
    root: Node
    match: proc(node: Node): bool {.noSideEffect.}
    snapshot: seq[Node]
    livelen: int

  NodeList = ref object of Collection

  HTMLCollection = ref object of Collection

  HTMLFormControlsCollection = ref object of HTMLCollection

  RadioNodeList = ref object of NodeList

  HTMLAllCollection = ref object of Collection

  DOMTokenList = ref object
    toks*: seq[CAtom]
    element: Element
    localName: CAtom

  DOMStringMap = object
    target {.cursor.}: HTMLElement

  Node* = ref object of EventTarget
    childList*: seq[Node]
    parentNode* {.jsget.}: Node
    index*: int # Index in parents children. -1 for nodes without a parent.
    # Live collection cache: pointers to live collections are saved in all
    # nodes they refer to. These are removed when the collection is destroyed,
    # and invalidated when the owner node's children or attributes change.
    liveCollections: HashSet[pointer]
    cachedChildNodes: NodeList
    internalDocument: Document # not nil

  Attr* = ref object of Node
    dataIdx: int
    ownerElement*: Element

  DOMImplementation = object
    document: Document

  DocumentWriteBuffer* = ref object
    data*: string
    i*: int

  Document* = ref object of Node
    factory*: CAtomFactory
    charset*: Charset
    window* {.jsget: "defaultView".}: Window
    url* {.jsget: "URL".}: URL
    mode*: QuirksMode
    currentScript: HTMLScriptElement
    isxml*: bool
    implementation {.jsget.}: DOMImplementation
    origin: Origin
    readyState* {.jsget.}: DocumentReadyState
    # document.write
    ignoreDestructiveWrites: int
    throwOnDynamicMarkupInsertion: int
    activeParserWasAborted: bool
    writeBuffers*: seq[DocumentWriteBuffer]

    scriptsToExecSoon*: seq[HTMLScriptElement]
    scriptsToExecInOrder*: Deque[HTMLScriptElement]
    scriptsToExecOnLoad*: Deque[HTMLScriptElement]
    parserBlockingScript*: HTMLScriptElement

    parserCannotChangeModeFlag*: bool
    internalFocus: Element
    contentType* {.jsget.}: string
    renderBlockingElements: seq[Element]

    invalidCollections: HashSet[pointer] # pointers to Collection objects
    invalid*: bool # whether the document must be rendered again

    cachedAll: HTMLAllCollection
    cachedSheets: seq[CSSStylesheet]
    cachedSheetsInvalid*: bool
    cachedChildren: HTMLCollection
    cachedForms: HTMLCollection
    #TODO I hate this but I really don't want to put chadombuilder into dom too
    parser*: pointer

  CharacterData* = ref object of Node
    data* {.jsget.}: string

  Text* = ref object of CharacterData

  Comment* = ref object of CharacterData

  CDATASection = ref object of CharacterData

  ProcessingInstruction = ref object of CharacterData
    target {.jsget.}: string

  DocumentFragment* = ref object of Node
    host*: Element
    cachedChildren*: HTMLCollection

  DocumentType* = ref object of Node
    name*: string
    publicId*: string
    systemId*: string

  AttrData* = object
    qualifiedName*: CAtom
    localName*: CAtom
    prefix*: CAtom
    namespace*: CAtom
    value*: string

  Element* = ref object of Node
    namespace*: Namespace
    namespacePrefix*: NamespacePrefix
    prefix*: string
    localName*: CAtom

    id* {.jsget.}: CAtom
    name* {.jsget.}: CAtom
    classList* {.jsget.}: DOMTokenList
    attrs*: seq[AttrData] # sorted by int(qualifiedName)
    internalAttributes: NamedNodeMap
    internalHover: bool
    invalid*: bool
    cachedStyle*: CSSStyleDeclaration
    cachedChildren: HTMLCollection
    # The owner StyledNode is marked as invalid when one of these no longer
    # matches the DOM value.
    invalidDeps*: set[DependencyType]

  AttrDummyElement = ref object of Element

  CSSStyleDeclaration* = ref object
    decls*: seq[CSSDeclaration]
    element: Element

  HTMLElement* = ref object of Element
    dataset {.jsget.}: DOMStringMap

  FormAssociatedElement* = ref object of HTMLElement
    form*: HTMLFormElement
    parserInserted*: bool

  HTMLInputElement* = ref object of FormAssociatedElement
    inputType*: InputType
    value* {.jsget.}: string
    internalChecked {.jsget: "checked".}: bool
    xcoord*: int
    ycoord*: int
    file*: WebFile

  HTMLAnchorElement* = ref object of HTMLElement
    relList {.jsget.}: DOMTokenList

  HTMLSelectElement* = ref object of FormAssociatedElement

  HTMLSpanElement* = ref object of HTMLElement

  HTMLOptGroupElement* = ref object of HTMLElement

  HTMLOptionElement* = ref object of HTMLElement
    selected*: bool

  HTMLHeadingElement* = ref object of HTMLElement

  HTMLBRElement* = ref object of HTMLElement

  HTMLMenuElement* = ref object of HTMLElement

  HTMLUListElement* = ref object of HTMLElement

  HTMLOListElement* = ref object of HTMLElement

  HTMLLIElement* = ref object of HTMLElement
    value* {.jsget.}: Option[int32]

  HTMLStyleElement* = ref object of HTMLElement
    sheet: CSSStylesheet

  HTMLLinkElement* = ref object of HTMLElement
    sheet*: CSSStylesheet
    relList {.jsget.}: DOMTokenList
    fetchStarted: bool

  HTMLFormElement* = ref object of HTMLElement
    constructingEntryList*: bool
    controls*: seq[FormAssociatedElement]
    cachedElements: HTMLFormControlsCollection
    relList {.jsget.}: DOMTokenList

  HTMLTemplateElement* = ref object of HTMLElement
    content*: DocumentFragment

  HTMLUnknownElement* = ref object of HTMLElement

  HTMLScriptElement* = ref object of HTMLElement
    parserDocument*: Document
    preparationTimeDocument*: Document
    forceAsync*: bool
    external*: bool
    readyForParserExec*: bool
    alreadyStarted*: bool
    delayingTheLoadEvent: bool
    ctype: ScriptType
    internalNonce: string
    scriptResult*: ScriptResult
    onReady: (proc())

  HTMLBaseElement* = ref object of HTMLElement

  HTMLAreaElement* = ref object of HTMLElement
    relList {.jsget.}: DOMTokenList

  HTMLButtonElement* = ref object of FormAssociatedElement
    ctype*: ButtonType
    value* {.jsget, jsset.}: string

  HTMLTextAreaElement* = ref object of FormAssociatedElement
    value* {.jsget.}: string

  HTMLLabelElement* = ref object of HTMLElement

  HTMLCanvasElement* = ref object of HTMLElement
    ctx2d*: CanvasRenderingContext2D
    bitmap*: NetworkBitmap

  DrawingState = object
    # CanvasTransform
    transformMatrix: Matrix
    # CanvasFillStrokeStyles
    fillStyle: ARGBColor
    strokeStyle: ARGBColor
    # CanvasPathDrawingStyles
    lineWidth: float64
    # CanvasTextDrawingStyles
    textAlign: CanvasTextAlign
    # CanvasPath
    path: Path

  RenderingContext = ref object of RootObj

  CanvasRenderingContext2D = ref object of RenderingContext
    canvas {.jsget.}: HTMLCanvasElement
    bitmap: NetworkBitmap
    state: DrawingState
    stateStack: seq[DrawingState]
    ps*: PosixStream

  TextMetrics = ref object
    # x-direction
    width {.jsget.}: float64
    actualBoundingBoxLeft {.jsget.}: float64
    actualBoundingBoxRight {.jsget.}: float64
    # y-direction
    fontBoundingBoxAscent {.jsget.}: float64
    fontBoundingBoxDescent {.jsget.}: float64
    actualBoundingBoxAscent {.jsget.}: float64
    actualBoundingBoxDescent {.jsget.}: float64
    emHeightAscent {.jsget.}: float64
    emHeightDescent {.jsget.}: float64
    hangingBaseline {.jsget.}: float64
    alphabeticBaseline {.jsget.}: float64
    ideographicBaseline {.jsget.}: float64

  HTMLImageElement* = ref object of HTMLElement
    bitmap*: NetworkBitmap
    fetchStarted: bool

  HTMLVideoElement* = ref object of HTMLElement

  HTMLAudioElement* = ref object of HTMLElement

jsDestructor(Navigator)
jsDestructor(PluginArray)
jsDestructor(MimeTypeArray)
jsDestructor(Screen)
jsDestructor(History)
jsDestructor(Storage)

jsDestructor(Element)
jsDestructor(HTMLElement)
jsDestructor(HTMLInputElement)
jsDestructor(HTMLAnchorElement)
jsDestructor(HTMLSelectElement)
jsDestructor(HTMLSpanElement)
jsDestructor(HTMLOptGroupElement)
jsDestructor(HTMLOptionElement)
jsDestructor(HTMLHeadingElement)
jsDestructor(HTMLBRElement)
jsDestructor(HTMLMenuElement)
jsDestructor(HTMLUListElement)
jsDestructor(HTMLOListElement)
jsDestructor(HTMLLIElement)
jsDestructor(HTMLStyleElement)
jsDestructor(HTMLLinkElement)
jsDestructor(HTMLFormElement)
jsDestructor(HTMLTemplateElement)
jsDestructor(HTMLUnknownElement)
jsDestructor(HTMLScriptElement)
jsDestructor(HTMLBaseElement)
jsDestructor(HTMLAreaElement)
jsDestructor(HTMLButtonElement)
jsDestructor(HTMLTextAreaElement)
jsDestructor(HTMLLabelElement)
jsDestructor(HTMLCanvasElement)
jsDestructor(HTMLImageElement)
jsDestructor(HTMLVideoElement)
jsDestructor(HTMLAudioElement)
jsDestructor(Node)
jsDestructor(NodeList)
jsDestructor(HTMLCollection)
jsDestructor(HTMLFormControlsCollection)
jsDestructor(RadioNodeList)
jsDestructor(HTMLAllCollection)
jsDestructor(Location)
jsDestructor(Document)
jsDestructor(DOMImplementation)
jsDestructor(DOMTokenList)
jsDestructor(DOMStringMap)
jsDestructor(Comment)
jsDestructor(CDATASection)
jsDestructor(DocumentFragment)
jsDestructor(ProcessingInstruction)
jsDestructor(CharacterData)
jsDestructor(Text)
jsDestructor(DocumentType)
jsDestructor(Attr)
jsDestructor(NamedNodeMap)
jsDestructor(CanvasRenderingContext2D)
jsDestructor(TextMetrics)
jsDestructor(CSSStyleDeclaration)

# Forward declarations
func attr*(element: Element; s: StaticAtom): string
func attrb*(element: Element; s: CAtom): bool
func baseURL*(document: Document): URL
proc attr*(element: Element; name: CAtom; value: string)
proc attr*(element: Element; name: StaticAtom; value: string)
proc delAttr(element: Element; i: int; keep = false)
proc getImageId(window: Window): int
proc parseColor(element: Element; s: string): ARGBColor
proc reflectAttr(element: Element; name: CAtom; value: Option[string])
proc setInvalid*(element: Element)

# Forward declaration hacks
# set in css/cascade
var appliesFwdDecl*: proc(mqlist: MediaQueryList; window: Window): bool
  {.nimcall, noSideEffect.}
# set in css/match
var doqsa*: proc (node: Node; q: string): seq[Element] {.nimcall.} = nil
var doqs*: proc (node: Node; q: string): Element {.nimcall.} = nil
# set in html/chadombuilder
var domParseHTMLFragment*: proc(element: Element; s: string): seq[Node]
  {.nimcall.}
# set in html/env
var windowFetch*: proc(window: Window; input: JSValue;
  init = RequestInit(window: JS_UNDEFINED)): JSResult[FetchPromise]
  {.nimcall.} = nil

# For now, these are the same; on an API level however, getGlobal is guaranteed
# to be non-null, while getWindow may return null in the future. (This is in
# preparation for Worker support.)
func getGlobal*(ctx: JSContext): Window =
  let global = JS_GetGlobalObject(ctx)
  var window: Window
  assert ctx.fromJS(global, window).isSome
  JS_FreeValue(ctx, global)
  return window

func getWindow*(ctx: JSContext): Window =
  let global = JS_GetGlobalObject(ctx)
  var window: Window
  assert ctx.fromJS(global, window).isSome
  JS_FreeValue(ctx, global)
  return window

func console(window: Window): Console =
  return window.internalConsole

proc resetTransform(state: var DrawingState) =
  state.transformMatrix = newIdentityMatrix(3)

proc reset(state: var DrawingState) =
  state.resetTransform()
  state.fillStyle = rgba(0, 0, 0, 255)
  state.strokeStyle = rgba(0, 0, 0, 255)
  state.path = newPath()

proc create2DContext*(jctx: JSContext; target: HTMLCanvasElement;
    options = JS_UNDEFINED) =
  var pipefd: array[2, cint]
  if pipe(pipefd) == -1:
    return
  let window = jctx.getWindow()
  let imageId = target.bitmap.imageId
  let loader = window.loader
  loader.passFd("canvas-ctl-" & $imageId, FileHandle(pipefd[0]))
  discard close(pipefd[0])
  let ps = newPosixStream(FileHandle(pipefd[1]))
  let ctlreq = newRequest(newURL("stream:canvas-ctl-" & $imageId).get)
  let ctlres = loader.doRequest(ctlreq)
  doAssert ctlres.res == 0
  let cacheId = loader.addCacheFile(ctlres.outputId, loader.clientPid)
  target.bitmap.cacheId = cacheId
  let request = newRequest(
    newURL("img-codec+x-cha-canvas:decode").get,
    httpMethod = hmPost,
    headers = newHeaders({"Cha-Image-Info-Only": "1"}),
    body = RequestBody(t: rbtOutput, outputId: ctlres.outputId)
  )
  let response = loader.doRequest(request)
  if response.res != 0:
    # no canvas module; give up
    ps.sclose()
    ctlres.resume()
    ctlres.close()
    return
  ctlres.resume()
  ctlres.close()
  response.resume()
  target.ctx2d = CanvasRenderingContext2D(
    bitmap: target.bitmap,
    canvas: target,
    ps: ps
  )
  window.pendingCanvasCtls.add(target.ctx2d)
  ps.withPacketWriter w:
    w.swrite(pcSetDimensions)
    w.swrite(target.bitmap.width)
    w.swrite(target.bitmap.height)
  target.ctx2d.state.reset()

proc fillRect(ctx: CanvasRenderingContext2D; x1, y1, x2, y2: int;
    color: ARGBColor) =
  if ctx.ps != nil:
    ctx.ps.withPacketWriter w:
      w.swrite(pcFillRect)
      w.swrite(x1)
      w.swrite(y1)
      w.swrite(x2)
      w.swrite(y2)
      w.swrite(color)

proc strokeRect(ctx: CanvasRenderingContext2D; x1, y1, x2, y2: int;
    color: ARGBColor) =
  if ctx.ps != nil:
    ctx.ps.withPacketWriter w:
      w.swrite(pcStrokeRect)
      w.swrite(x1)
      w.swrite(y1)
      w.swrite(x2)
      w.swrite(y2)
      w.swrite(color)

proc fillPath(ctx: CanvasRenderingContext2D; path: Path; color: ARGBColor;
    fillRule: CanvasFillRule) =
  if ctx.ps != nil:
    let lines = path.getLineSegments()
    ctx.ps.withPacketWriter w:
      w.swrite(pcFillPath)
      w.swrite(lines)
      w.swrite(color)
      w.swrite(fillRule)

proc strokePath(ctx: CanvasRenderingContext2D; path: Path; color: ARGBColor) =
  if ctx.ps != nil:
    let lines = path.getLines()
    ctx.ps.withPacketWriter w:
      w.swrite(pcStrokePath)
      w.swrite(lines)
      w.swrite(color)

proc fillText(ctx: CanvasRenderingContext2D; text: string; x, y: float64;
    color: ARGBColor; align: CanvasTextAlign) =
  if ctx.ps != nil:
    ctx.ps.withPacketWriter w:
      w.swrite(pcFillText)
      w.swrite(text)
      w.swrite(x)
      w.swrite(y)
      w.swrite(color)
      w.swrite(align)

proc strokeText(ctx: CanvasRenderingContext2D; text: string; x, y: float64;
    color: ARGBColor; align: CanvasTextAlign) =
  if ctx.ps != nil:
    ctx.ps.withPacketWriter w:
      w.swrite(pcStrokeText)
      w.swrite(text)
      w.swrite(x)
      w.swrite(y)
      w.swrite(color)
      w.swrite(align)

proc clearRect(ctx: CanvasRenderingContext2D; x1, y1, x2, y2: int) =
  ctx.fillRect(0, 0, ctx.bitmap.width, ctx.bitmap.height, rgba(0, 0, 0, 0))

proc clear(ctx: CanvasRenderingContext2D) =
  ctx.clearRect(0, 0, ctx.bitmap.width, ctx.bitmap.height)

# CanvasState
proc save(ctx: CanvasRenderingContext2D) {.jsfunc.} =
  ctx.stateStack.add(ctx.state)

proc restore(ctx: CanvasRenderingContext2D) {.jsfunc.} =
  if ctx.stateStack.len > 0:
    ctx.state = ctx.stateStack.pop()

proc reset(ctx: CanvasRenderingContext2D) {.jsfunc.} =
  ctx.clear()
  ctx.stateStack.setLen(0)
  ctx.state.reset()

# CanvasTransform
#TODO scale
proc rotate(ctx: CanvasRenderingContext2D; angle: float64) {.jsfunc.} =
  if classify(angle) in {fcInf, fcNegInf, fcNan}:
    return
  ctx.state.transformMatrix *= newMatrix(
    me = @[
      cos(angle), -sin(angle), 0,
      sin(angle), cos(angle), 0,
      0, 0, 1
    ],
    w = 3,
    h = 3
  )

proc translate(ctx: CanvasRenderingContext2D; x, y: float64) {.jsfunc.} =
  for v in [x, y]:
    if classify(v) in {fcInf, fcNegInf, fcNan}:
      return
  ctx.state.transformMatrix *= newMatrix(
    me = @[
      1f64, 0, x,
      0, 1, y,
      0, 0, 1
    ],
    w = 3,
    h = 3
  )

proc transform(ctx: CanvasRenderingContext2D; a, b, c, d, e, f: float64)
    {.jsfunc.} =
  for v in [a, b, c, d, e, f]:
    if classify(v) in {fcInf, fcNegInf, fcNan}:
      return
  ctx.state.transformMatrix *= newMatrix(
    me = @[
      a, c, e,
      b, d, f,
      0, 0, 1
    ],
    w = 3,
    h = 3
  )

#TODO getTransform, setTransform with DOMMatrix (i.e. we're missing DOMMatrix)
proc setTransform(ctx: CanvasRenderingContext2D; a, b, c, d, e, f: float64)
    {.jsfunc.} =
  for v in [a, b, c, d, e, f]:
    if classify(v) in {fcInf, fcNegInf, fcNan}:
      return
  ctx.state.resetTransform()
  ctx.transform(a, b, c, d, e, f)

proc resetTransform(ctx: CanvasRenderingContext2D) {.jsfunc.} =
  ctx.state.resetTransform()

func transform(ctx: CanvasRenderingContext2D; v: Vector2D): Vector2D =
  let mul = ctx.state.transformMatrix * newMatrix(@[v.x, v.y, 1], 1, 3)
  return Vector2D(x: mul.me[0], y: mul.me[1])

# CanvasFillStrokeStyles
proc fillStyle(ctx: CanvasRenderingContext2D): string {.jsfget.} =
  return ctx.state.fillStyle.serialize()

proc fillStyle(ctx: CanvasRenderingContext2D; s: string) {.jsfset.} =
  #TODO gradient, pattern
  ctx.state.fillStyle = ctx.canvas.parseColor(s)

proc strokeStyle(ctx: CanvasRenderingContext2D): string {.jsfget.} =
  return ctx.state.strokeStyle.serialize()

proc strokeStyle(ctx: CanvasRenderingContext2D; s: string) {.jsfset.} =
  #TODO gradient, pattern
  ctx.state.strokeStyle = ctx.canvas.parseColor(s)

# CanvasRect
proc clearRect(ctx: CanvasRenderingContext2D; x, y, w, h: float64) {.jsfunc.} =
  for v in [x, y, w, h]:
    if classify(v) in {fcInf, fcNegInf, fcNan}:
      return
  #TODO clipping regions (right now we just clip to default)
  let bw = float64(ctx.bitmap.width)
  let bh = float64(ctx.bitmap.height)
  let x1 = int(min(max(x, 0), bw))
  let y1 = int(min(max(y, 0), bh))
  let x2 = int(min(max(x + w, 0), bw))
  let y2 = int(min(max(y + h, 0), bh))
  ctx.clearRect(x1, y1, x2, y2)

proc fillRect(ctx: CanvasRenderingContext2D; x, y, w, h: float64) {.jsfunc.} =
  for v in [x, y, w, h]:
    if classify(v) in {fcInf, fcNegInf, fcNan}:
      return
  #TODO do we have to clip here?
  if w == 0 or h == 0:
    return
  let bw = float64(ctx.bitmap.width)
  let bh = float64(ctx.bitmap.height)
  let x1 = int(min(max(x, 0), bw))
  let y1 = int(min(max(y, 0), bh))
  let x2 = int(min(max(x + w, 0), bw))
  let y2 = int(min(max(y + h, 0), bh))
  ctx.fillRect(x1, y1, x2, y2, ctx.state.fillStyle)

proc strokeRect(ctx: CanvasRenderingContext2D; x, y, w, h: float64) {.jsfunc.} =
  for v in [x, y, w, h]:
    if classify(v) in {fcInf, fcNegInf, fcNan}:
      return
  #TODO do we have to clip here?
  if w == 0 or h == 0:
    return
  let bw = float64(ctx.bitmap.width)
  let bh = float64(ctx.bitmap.height)
  let x1 = int(min(max(x, 0), bw))
  let y1 = int(min(max(y, 0), bh))
  let x2 = int(min(max(x + w, 0), bw))
  let y2 = int(min(max(y + h, 0), bh))
  ctx.strokeRect(x1, y1, x2, y2, ctx.state.strokeStyle)

# CanvasDrawPath
proc beginPath(ctx: CanvasRenderingContext2D) {.jsfunc.} =
  ctx.state.path.beginPath()

proc fill(ctx: CanvasRenderingContext2D; fillRule = cfrNonZero) {.jsfunc.} =
  #TODO path
  ctx.state.path.tempClosePath()
  ctx.fillPath(ctx.state.path, ctx.state.fillStyle, fillRule)
  ctx.state.path.tempOpenPath()

proc stroke(ctx: CanvasRenderingContext2D) {.jsfunc.} = #TODO path
  ctx.strokePath(ctx.state.path, ctx.state.strokeStyle)

proc clip(ctx: CanvasRenderingContext2D; fillRule = cfrNonZero) {.jsfunc.} =
  #TODO path
  discard #TODO implement

#TODO clip, ...

# CanvasUserInterface

# CanvasText
#TODO maxwidth
proc fillText(ctx: CanvasRenderingContext2D; text: string; x, y: float64)
    {.jsfunc.} =
  for v in [x, y]:
    if classify(v) in {fcInf, fcNegInf, fcNan}:
      return
  let vec = ctx.transform(Vector2D(x: x, y: y))
  ctx.fillText(text, vec.x, vec.y, ctx.state.fillStyle, ctx.state.textAlign)

#TODO maxwidth
proc strokeText(ctx: CanvasRenderingContext2D; text: string; x, y: float64)
    {.jsfunc.} =
  for v in [x, y]:
    if classify(v) in {fcInf, fcNegInf, fcNan}:
      return
  let vec = ctx.transform(Vector2D(x: x, y: y))
  ctx.strokeText(text, vec.x, vec.y, ctx.state.strokeStyle, ctx.state.textAlign)

proc measureText(ctx: CanvasRenderingContext2D; text: string): TextMetrics
    {.jsfunc.} =
  let tw = text.width()
  return TextMetrics(
    width: 8 * float64(tw),
    actualBoundingBoxLeft: 0,
    actualBoundingBoxRight: 8 * float64(tw),
    #TODO and the rest...
  )

# CanvasDrawImage

# CanvasImageData

# CanvasPathDrawingStyles
proc lineWidth(ctx: CanvasRenderingContext2D): float64 {.jsfget.} =
  return ctx.state.lineWidth

proc lineWidth(ctx: CanvasRenderingContext2D; f: float64) {.jsfset.} =
  if classify(f) in {fcZero, fcNegZero, fcInf, fcNegInf, fcNan}:
    return
  ctx.state.lineWidth = f

proc setLineDash(ctx: CanvasRenderingContext2D; segments: seq[float64])
    {.jsfunc.} =
  discard #TODO implement

proc getLineDash(ctx: CanvasRenderingContext2D): seq[float64] {.jsfunc.} =
  discard #TODO implement

# CanvasTextDrawingStyles
proc textAlign(ctx: CanvasRenderingContext2D): string {.jsfget.} =
  return $ctx.state.textAlign

proc textAlign(ctx: CanvasRenderingContext2D; s: string) {.jsfset.} =
  let x = parseEnumNoCase[CanvasTextAlign](s)
  if x.isSome:
    ctx.state.textAlign = x.get

# CanvasPath
proc closePath(ctx: CanvasRenderingContext2D) {.jsfunc.} =
  ctx.state.path.closePath()

proc moveTo(ctx: CanvasRenderingContext2D; x, y: float64) {.jsfunc.} =
  ctx.state.path.moveTo(x, y)

proc lineTo(ctx: CanvasRenderingContext2D; x, y: float64) {.jsfunc.} =
  ctx.state.path.lineTo(x, y)

proc quadraticCurveTo(ctx: CanvasRenderingContext2D; cpx, cpy, x,
    y: float64) {.jsfunc.} =
  ctx.state.path.quadraticCurveTo(cpx, cpy, x, y)

proc arcTo(ctx: CanvasRenderingContext2D; x1, y1, x2, y2, radius: float64):
    Err[DOMException] {.jsfunc.} =
  if radius < 0:
    return errDOMException("Expected positive radius, but got negative",
      "IndexSizeError")
  ctx.state.path.arcTo(x1, y1, x2, y2, radius)
  return ok()

proc arc(ctx: CanvasRenderingContext2D; x, y, radius, startAngle,
    endAngle: float64; counterclockwise = false): Err[DOMException]
    {.jsfunc.} =
  if radius < 0:
    return errDOMException("Expected positive radius, but got negative",
      "IndexSizeError")
  ctx.state.path.arc(x, y, radius, startAngle, endAngle, counterclockwise)
  return ok()

proc ellipse(ctx: CanvasRenderingContext2D; x, y, radiusX, radiusY, rotation,
    startAngle, endAngle: float64; counterclockwise = false): Err[DOMException]
    {.jsfunc.} =
  if radiusX < 0 or radiusY < 0:
    return errDOMException("Expected positive radius, but got negative",
      "IndexSizeError")
  ctx.state.path.ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle,
    counterclockwise)
  return ok()

proc rect(ctx: CanvasRenderingContext2D; x, y, w, h: float64) {.jsfunc.} =
  ctx.state.path.rect(x, y, w, h)

proc roundRect(ctx: CanvasRenderingContext2D; x, y, w, h, radii: float64)
    {.jsfunc.} =
  ctx.state.path.roundRect(x, y, w, h, radii)

# Reflected attributes.
type
  ReflectType = enum
    rtStr, rtBool, rtLong, rtUlongGz, rtUlong, rtFunction

  ReflectEntry = object
    attrname: StaticAtom
    funcname: string
    tags: set[TagType]
    case t: ReflectType
    of rtLong:
      i: int32
    of rtUlong, rtUlongGz:
      u: uint32
    of rtFunction:
      ctype: StaticAtom
    else: discard

func attrType0(s: static string): StaticAtom {.compileTime.} =
  return strictParseEnum[StaticAtom](s).get

template toset(ts: openArray[TagType]): set[TagType] =
  var tags: system.set[TagType]
  for tag in ts:
    tags.incl(tag)
  tags

func makes(name: static string; ts: set[TagType]): ReflectEntry =
  const attrname = attrType0(name)
  ReflectEntry(
    attrname: attrname,
    funcname: name,
    t: rtStr,
    tags: ts
  )

func makes(attrname, funcname: static string; ts: set[TagType]):
    ReflectEntry =
  const attrname = attrType0(attrname)
  ReflectEntry(
    attrname: attrname,
    funcname: funcname,
    t: rtStr,
    tags: ts
  )

func makes(name: static string; ts: varargs[TagType]): ReflectEntry =
  makes(name, toset(ts))

func makes(attrname, funcname: static string; ts: varargs[TagType]):
    ReflectEntry =
  makes(attrname, funcname, toset(ts))

func makeb(attrname, funcname: static string; ts: varargs[TagType]):
    ReflectEntry =
  const attrname = attrType0(attrname)
  ReflectEntry(
    attrname: attrname,
    funcname: funcname,
    t: rtBool,
    tags: toset(ts)
  )

func makeb(name: static string; ts: varargs[TagType]): ReflectEntry =
  makeb(name, name, ts)

func makeul(name: static string; ts: varargs[TagType]; default = 0u32):
    ReflectEntry =
  const attrname = attrType0(name)
  ReflectEntry(
    attrname: attrname,
    funcname: name,
    t: rtUlong,
    tags: toset(ts),
    u: default
  )

func makeulgz(name: static string; ts: varargs[TagType]; default = 0u32):
    ReflectEntry =
  const attrname = attrType0(name)
  ReflectEntry(
    attrname: attrname,
    funcname: name,
    t: rtUlongGz,
    tags: toset(ts),
    u: default
  )

func makef(name: static string; ts: set[TagType]; ctype: static string): ReflectEntry =
  const attrname = attrType0(name)
  ReflectEntry(
    attrname: attrname,
    funcname: name,
    t: rtFunction,
    tags: ts,
    ctype: attrType0(ctype)
  )

const ReflectTable0 = [
  # non-global attributes
  makes("target", TAG_A, TAG_AREA, TAG_LABEL, TAG_LINK),
  makes("href", TAG_LINK),
  makeb("required", TAG_INPUT, TAG_SELECT, TAG_TEXTAREA),
  makeb("novalidate", "noValidate", TAG_FORM),
  makes("rel", TAG_A, TAG_LINK, TAG_LABEL),
  makes("for", "htmlFor", TAG_LABEL),
  makeul("cols", TAG_TEXTAREA, 20u32),
  makeul("rows", TAG_TEXTAREA, 1u32),
# <SELECT>:
#> For historical reasons, the default value of the size IDL attribute does
#> not return the actual size used, which, in the absence of the size content
#> attribute, is either 1 or 4 depending on the presence of the multiple
#> attribute.
  makeulgz("size", TAG_SELECT, 0u32),
  makeulgz("size", TAG_INPUT, 20u32),
  makeul("width", TAG_CANVAS, 300u32),
  makeul("height", TAG_CANVAS, 150u32),
  makes("alt", TAG_IMG),
  makes("src", TAG_IMG, TAG_SCRIPT),
  makes("srcset", TAG_IMG),
  makes("sizes", TAG_IMG),
  #TODO can we add crossOrigin here?
  makes("usemap", "useMap", TAG_IMG),
  makeb("ismap", "isMap", TAG_IMG),
  # "super-global" attributes
  makes("slot", AllTagTypes),
  makes("class", "className", AllTagTypes),
  makef("onclick", AllTagTypes, "click"),
]

func document*(node: Node): Document =
  if node of Document:
    return Document(node)
  return node.internalDocument

proc toAtom*(window: Window; atom: StaticAtom): CAtom =
  return window.factory.toAtom(atom)

proc toAtom*(window: Window; s: string): CAtom =
  return window.factory.toAtom(s)

proc toStr*(window: Window; atom: CAtom): string =
  return window.factory.toStr(atom)

proc toAtom*(document: Document; s: string): CAtom =
  return document.factory.toAtom(s)

proc toAtom*(document: Document; at: StaticAtom): CAtom =
  return document.factory.toAtom(at)

proc toStr(document: Document; atom: CAtom): string =
  return document.factory.toStr(atom)

proc toTagType*(document: Document; atom: CAtom): TagType =
  return document.factory.toTagType(atom)

proc toStaticAtom(document: Document; atom: CAtom): StaticAtom =
  return document.factory.toStaticAtom(atom)

proc toAtom*(document: Document; tagType: TagType): CAtom =
  return document.factory.toAtom(tagType)

proc toAtom(document: Document; namespace: Namespace): CAtom =
  #TODO optimize
  assert namespace != NO_NAMESPACE
  return document.toAtom($namespace)

proc toAtom(document: Document; prefix: NamespacePrefix): CAtom =
  #TODO optimize
  assert prefix != NO_PREFIX
  return document.toAtom($prefix)

func tagTypeNoNS(element: Element): TagType =
  return element.document.toTagType(element.localName)

func tagType*(element: Element): TagType =
  if element.namespace != Namespace.HTML:
    return TAG_UNKNOWN
  return element.tagTypeNoNS

func localNameStr*(element: Element): string =
  return element.document.toStr(element.localName)

func findAttr(element: Element; qualifiedName: CAtom): int =
  for i, attr in element.attrs.mpairs:
    if attr.qualifiedName == qualifiedName:
      return i
  return -1

func findAttr(element: Element; qualifiedName: StaticAtom): int =
  return element.findAttr(element.document.toAtom(qualifiedName))

func findAttrNS(element: Element; namespace, qualifiedName: CAtom): int =
  for i, attr in element.attrs.mpairs:
    if attr.namespace == namespace and attr.qualifiedName == qualifiedName:
      return i
  return -1

func escapeText(s: string; attribute_mode = false): string =
  var nbsp_mode = false
  var nbsp_prev: char
  for c in s:
    if nbsp_mode:
      if c == char(0xA0):
        result &= "&nbsp;"
      else:
        result &= nbsp_prev & c
      nbsp_mode = false
    elif c == '&':
      result &= "&amp;"
    elif c == char(0xC2):
      nbsp_mode = true
      nbsp_prev = c
    elif attribute_mode and c == '"':
      result &= "&quot;"
    elif not attribute_mode and c == '<':
      result &= "&lt;"
    elif not attribute_mode and c == '>':
      result &= "&gt;"
    else:
      result &= c

func `$`*(node: Node): string =
  # Note: this function should only be used for debugging.
  if node == nil:
    return "null"
  if node of Element:
    let element = Element(node)
    result = "<" & element.localNameStr
    for attr in element.attrs:
      let k = element.document.toStr(attr.localName)
      result &= ' ' & k & "=\"" & attr.value.escapeText(true) & "\""
    result &= ">\n"
    for node in element.childList:
      for line in ($node).split('\n'):
        result &= "\t" & line & "\n"
    result &= "</" & element.localNameStr & ">"
  elif node of Text:
    let text = Text(node)
    result = text.data.escapeText()
  elif node of Comment:
    result = "<!-- " & Comment(node).data & "-->"
  elif node of ProcessingInstruction:
    result = "" #TODO
  elif node of DocumentType:
    result = "<!DOCTYPE" & ' ' & DocumentType(node).name & ">"
  elif node of Document:
    result = "Node of Document"
  elif node of DocumentFragment:
    result = "Node of DocumentFragment"
  else:
    result = "Unknown node"

func parentElement*(node: Node): Element {.jsfget.} =
  let p = node.parentNode
  if p != nil and p of Element:
    return Element(p)
  return nil

iterator elementList*(node: Node): Element {.inline.} =
  for child in node.childList:
    if child of Element:
      yield Element(child)

iterator elementList_rev*(node: Node): Element {.inline.} =
  for i in countdown(node.childList.high, 0):
    let child = node.childList[i]
    if child of Element:
      yield Element(child)

# Returns the node's ancestors
iterator ancestors*(node: Node): Element {.inline.} =
  var element = node.parentElement
  while element != nil:
    yield element
    element = element.parentElement

iterator nodeAncestors*(node: Node): Node {.inline.} =
  var node = node.parentNode
  while node != nil:
    yield node
    node = node.parentNode

# Returns the node itself and its ancestors
iterator branch*(node: Node): Node {.inline.} =
  var node = node
  while node != nil:
    yield node
    node = node.parentNode

# Returns the node's descendants
iterator descendants*(node: Node): Node {.inline.} =
  var stack: seq[Node]
  for i in countdown(node.childList.high, 0):
    stack.add(node.childList[i])
  while stack.len > 0:
    let node = stack.pop()
    yield node
    for i in countdown(node.childList.high, 0):
      stack.add(node.childList[i])

iterator elements*(node: Node): Element {.inline.} =
  for child in node.descendants:
    if child of Element:
      yield Element(child)

iterator elements*(node: Node; tag: TagType): Element {.inline.} =
  for desc in node.elements:
    if desc.tagType == tag:
      yield desc

iterator elements*(node: Node; tag: set[TagType]): Element {.inline.} =
  for desc in node.elements:
    if desc.tagType in tag:
      yield desc

iterator inputs(form: HTMLFormElement): HTMLInputElement {.inline.} =
  for control in form.controls:
    if control of HTMLInputElement:
      yield HTMLInputElement(control)

iterator radiogroup(form: HTMLFormElement): HTMLInputElement {.inline.} =
  for input in form.inputs:
    if input.inputType == itRadio:
      yield input

iterator radiogroup(document: Document): HTMLInputElement {.inline.} =
  for input in document.elements(TAG_INPUT):
    let input = HTMLInputElement(input)
    if input.form == nil and input.inputType == itRadio:
      yield input

iterator radiogroup*(input: HTMLInputElement): HTMLInputElement {.inline.} =
  if input.form != nil:
    for input in input.form.radiogroup:
      yield input
  else:
    for input in input.document.radiogroup:
      yield input

iterator textNodes*(node: Node): Text {.inline.} =
  for node in node.childList:
    if node of Text:
      yield Text(node)

iterator options*(select: HTMLSelectElement): HTMLOptionElement {.inline.} =
  for child in select.elementList:
    if child of HTMLOptionElement:
      yield HTMLOptionElement(child)
    elif child of HTMLOptGroupElement:
      for opt in child.elementList:
        if opt of HTMLOptionElement:
          yield HTMLOptionElement(opt)

func id(collection: Collection): pointer =
  return cast[pointer](collection)

proc populateCollection(collection: Collection) =
  if collection.childonly:
    for child in collection.root.childList:
      if collection.match == nil or collection.match(child):
        collection.snapshot.add(child)
  else:
    for desc in collection.root.descendants:
      if collection.match == nil or collection.match(desc):
        collection.snapshot.add(desc)
  if collection.islive:
    for child in collection.snapshot:
      child.liveCollections.incl(collection.id)
    collection.root.liveCollections.incl(collection.id)

proc refreshCollection(collection: Collection) =
  let document = collection.root.document
  if collection.id in document.invalidCollections:
    for child in collection.snapshot:
      assert collection.id in child.liveCollections
      child.liveCollections.excl(collection.id)
    collection.snapshot.setLen(0)
    collection.populateCollection()
    document.invalidCollections.excl(collection.id)

proc finalize0(collection: Collection) =
  if collection.islive:
    for child in collection.snapshot:
      assert collection.id in child.liveCollections
      child.liveCollections.excl(collection.id)
    collection.root.document.invalidCollections.excl(collection.id)

proc finalize(collection: HTMLCollection) {.jsfin.} =
  collection.finalize0()

proc finalize(collection: NodeList) {.jsfin.} =
  collection.finalize0()

proc finalize(collection: HTMLFormControlsCollection) {.jsfin.} =
  collection.finalize0()

proc finalize(collection: RadioNodeList) {.jsfin.} =
  collection.finalize0()

proc finalize(collection: HTMLAllCollection) {.jsfin.} =
  collection.finalize0()

func ownerDocument(node: Node): Document {.jsfget.} =
  if node of Document:
    return nil
  return node.document

func hasChildNodes(node: Node): bool {.jsfunc.} =
  return node.childList.len > 0

proc len(collection: Collection): int =
  collection.refreshCollection()
  return collection.snapshot.len

type CollectionMatchFun = proc(node: Node): bool {.noSideEffect.}

func newCollection[T: Collection](root: Node; match: CollectionMatchFun;
    islive, childonly: bool): T =
  result = T(
    islive: islive,
    childonly: childonly,
    match: match,
    root: root
  )
  result.populateCollection()

func jsNodeType0(node: Node): NodeType =
  if node of CharacterData:
    if node of Text:
      return TEXT_NODE
    elif node of Comment:
      return COMMENT_NODE
    elif node of CDATASection:
      return CDATA_SECTION_NODE
    elif node of ProcessingInstruction:
      return PROCESSING_INSTRUCTION_NODE
    assert false
  elif node of Element:
    return ELEMENT_NODE
  elif node of Document:
    return DOCUMENT_NODE
  elif node of DocumentType:
    return DOCUMENT_TYPE_NODE
  elif node of Attr:
    return ATTRIBUTE_NODE
  elif node of DocumentFragment:
    return DOCUMENT_FRAGMENT_NODE
  assert false

func jsNodeType(node: Node): uint16 {.jsfget: "nodeType".} =
  return uint16(node.jsNodeType0)

func isElement(node: Node): bool =
  return node of Element

template parentNodeChildrenImpl(parentNode: typed) =
  if parentNode.cachedChildren == nil:
    parentNode.cachedChildren = newCollection[HTMLCollection](
      root = parentNode,
      match = isElement,
      islive = true,
      childonly = true
    )
  return parentNode.cachedChildren

func children(parentNode: Document): HTMLCollection {.jsfget.} =
  parentNodeChildrenImpl(parentNode)

func children(parentNode: DocumentFragment): HTMLCollection {.jsfget.} =
  parentNodeChildrenImpl(parentNode)

func children(parentNode: Element): HTMLCollection {.jsfget.} =
  parentNodeChildrenImpl(parentNode)

func childNodes(node: Node): NodeList {.jsfget.} =
  if node.cachedChildNodes == nil:
    node.cachedChildNodes = newCollection[NodeList](
      root = node,
      match = nil,
      islive = true,
      childonly = true
    )
  return node.cachedChildNodes

func isForm(node: Node): bool =
  return node of HTMLFormElement

func forms(document: Document): HTMLCollection {.jsfget.} =
  if document.cachedForms == nil:
    document.cachedForms = newCollection[HTMLCollection](
      root = document,
      match = isForm,
      islive = true,
      childonly = false
    )
  return document.cachedForms

# DOMTokenList
func length(tokenList: DOMTokenList): uint32 {.jsfget.} =
  return uint32(tokenList.toks.len)

proc item(ctx: JSContext; tokenList: DOMTokenList; i: int): JSValue {.jsfunc.} =
  if i < tokenList.toks.len:
    return ctx.toJS(tokenList.toks[i])
  return JS_NULL

func contains*(tokenList: DOMTokenList; a: CAtom): bool =
  return a in tokenList.toks

func contains(tokenList: DOMTokenList; a: StaticAtom): bool =
  return tokenList.element.document.toAtom(a) in tokenList.toks

func jsContains(tokenList: DOMTokenList; s: string): bool
    {.jsfunc: "contains".} =
  return tokenList.element.document.toAtom(s) in tokenList

func `$`(tokenList: DOMTokenList): string {.jsfunc.} =
  var s = ""
  for i, tok in tokenList.toks:
    if i != 0:
      s &= ' '
    s &= tokenList.element.document.toStr(tok)
  return s

proc update(tokenList: DOMTokenList) =
  if not tokenList.element.attrb(tokenList.localName) and
      tokenList.toks.len == 0:
    return
  tokenList.element.attr(tokenList.localName, $tokenList)

func validateDOMToken(ctx: JSContext; document: Document; tok: JSValue):
    DOMResult[CAtom] =
  var res: string
  ?ctx.fromJS(tok, res)
  if res == "":
    return errDOMException("Got an empty string", "SyntaxError")
  if AsciiWhitespace in res:
    return errDOMException("Got a string containing whitespace",
      "InvalidCharacterError")
  return ok(document.toAtom(res))

proc add(ctx: JSContext; tokenList: DOMTokenList; tokens: varargs[JSValue]):
    Err[DOMException] {.jsfunc.} =
  var toks: seq[CAtom] = @[]
  for tok in tokens:
    toks.add(?ctx.validateDOMToken(tokenList.element.document, tok))
  tokenList.toks.add(toks)
  tokenList.update()
  return ok()

proc remove(ctx: JSContext; tokenList: DOMTokenList; tokens: varargs[JSValue]):
    Err[DOMException] {.jsfunc.} =
  var toks: seq[CAtom] = @[]
  for tok in tokens:
    toks.add(?ctx.validateDOMToken(tokenList.element.document, tok))
  for tok in toks:
    let i = tokenList.toks.find(tok)
    if i != -1:
      tokenList.toks.delete(i)
  tokenList.update()
  return ok()

proc toggle(ctx: JSContext; tokenList: DOMTokenList; token: JSValue;
    force = none(bool)): DOMResult[bool] {.jsfunc.} =
  let token = ?ctx.validateDOMToken(tokenList.element.document, token)
  let i = tokenList.toks.find(token)
  if i != -1:
    if not force.get(false):
      tokenList.toks.delete(i)
      tokenList.update()
      return ok(false)
    return ok(true)
  if force.get(true):
    tokenList.toks.add(token)
    tokenList.update()
    return ok(true)
  return ok(false)

proc replace(ctx: JSContext; tokenList: DOMTokenList; token, newToken: JSValue):
    DOMResult[bool] {.jsfunc.} =
  let token = ?ctx.validateDOMToken(tokenList.element.document, token)
  let newToken = ?ctx.validateDOMToken(tokenList.element.document, newToken)
  let i = tokenList.toks.find(token)
  if i == -1:
    return ok(false)
  tokenList.toks[i] = newToken
  tokenList.update()
  return ok(true)

const SupportedTokensMap = {
  satRel: @[
    "alternate", "dns-prefetch", "icon", "manifest", "modulepreload",
    "next", "pingback", "preconnect", "prefetch", "preload", "search",
    "stylesheet"
  ]
}

func supports(tokenList: DOMTokenList; token: string):
    JSResult[bool] {.jsfunc.} =
  let localName = tokenList.element.document.toStaticAtom(tokenList.localName)
  for it in SupportedTokensMap:
    if it[0] == localName:
      let lowercase = token.toLowerAscii()
      return ok(lowercase in it[1])
  return errTypeError("No supported tokens defined for attribute")

func value(tokenList: DOMTokenList): string {.jsfget.} =
  return $tokenList

proc getter(ctx: JSContext; this: DOMTokenList; atom: JSAtom): JSValue
    {.jsgetprop.} =
  var u: uint32
  if ctx.fromJS(atom, u).isSome:
    return ctx.item(this, int(u))
  return JS_NULL

# DOMStringMap
func validateAttributeName(name: string): Err[DOMException] =
  if name.matchNameProduction():
    return ok()
  return errDOMException("Invalid character in attribute name",
    "InvalidCharacterError")

func validateAttributeQName(name: string): Err[DOMException] =
  if name.matchQNameProduction():
    return ok()
  return errDOMException("Invalid character in attribute name",
    "InvalidCharacterError")

proc delete(map: var DOMStringMap; name: string): bool {.jsfunc.} =
  let name = map.target.document.toAtom("data-" & name.camelToKebabCase())
  let i = map.target.findAttr(name)
  if i != -1:
    map.target.delAttr(i)
  return i != -1

func getter(map: var DOMStringMap; name: string): Option[string]
    {.jsgetprop.} =
  let name = map.target.document.toAtom("data-" & name.camelToKebabCase())
  let i = map.target.findAttr(name)
  if i != -1:
    return some(map.target.attrs[i].value)
  return none(string)

proc setter(map: var DOMStringMap; name, value: string): Err[DOMException]
    {.jssetprop.} =
  var washy = false
  for c in name:
    if not washy or c notin AsciiLowerAlpha:
      washy = c == '-'
      continue
    return errDOMException("Lower case after hyphen is not allowed in dataset",
      "InvalidCharacterError")
  let name = "data-" & name.camelToKebabCase()
  ?name.validateAttributeName()
  let aname = map.target.document.toAtom(name)
  map.target.attr(aname, value)
  return ok()

func names(ctx: JSContext; map: var DOMStringMap): JSPropertyEnumList
    {.jspropnames.} =
  var list = newJSPropertyEnumList(ctx, uint32(map.target.attrs.len))
  for attr in map.target.attrs:
    let k = map.target.document.toStr(attr.localName)
    if k.startsWith("data-") and AsciiUpperAlpha notin k:
      list.add(k["data-".len .. ^1].kebabToCamelCase())
  return list

# NodeList
func length(this: NodeList): uint32 {.jsfget.} =
  return uint32(this.len)

func item(this: NodeList; u: uint32): Node {.jsfunc.} =
  let i = int(u)
  if i < this.len:
    return this.snapshot[i]
  return nil

func getter(ctx: JSContext; this: NodeList; atom: JSAtom): Node {.jsgetprop.} =
  var u: uint32
  if ctx.fromJS(atom, u).isSome:
    return this.item(u)
  return nil

func names(ctx: JSContext; this: NodeList): JSPropertyEnumList {.jspropnames.} =
  let L = this.length
  var list = newJSPropertyEnumList(ctx, L)
  for u in 0 ..< L:
    list.add(u)
  return list

# HTMLCollection
proc length(this: HTMLCollection): uint32 {.jsfget.} =
  return uint32(this.len)

func item(this: HTMLCollection; u: uint32): Element {.jsfunc.} =
  if u < this.length:
    return Element(this.snapshot[int(u)])
  return nil

func namedItem(this: HTMLCollection; atom: CAtom): Element {.jsfunc.} =
  for it in this.snapshot:
    let it = Element(it)
    if it.id == atom or it.namespace == Namespace.HTML and it.name == atom:
      return it
  return nil

proc getter(ctx: JSContext; this: HTMLCollection; atom: JSAtom): Element
    {.jsgetprop.} =
  var u: uint32
  if ctx.fromJS(atom, u).isSome:
    return this.item(u)
  var s: CAtom
  if ctx.fromJS(atom, s).isSome:
    return this.namedItem(s)
  return nil

func names(ctx: JSContext; collection: HTMLCollection): JSPropertyEnumList
    {.jspropnames.} =
  let L = collection.length
  var list = newJSPropertyEnumList(ctx, L)
  var ids = initOrderedSet[CAtom]()
  for u in 0 ..< L:
    list.add(u)
    let elem = collection.item(u)
    if elem.id != CAtomNull:
      ids.incl(elem.id)
    if elem.namespace == Namespace.HTML:
      ids.incl(elem.name)
  for id in ids:
    list.add(collection.root.document.toStr(id))
  return list

# HTMLFormControlsCollection
proc namedItem(ctx: JSContext; this: HTMLFormControlsCollection; name: CAtom):
    JSValue {.jsfunc.} =
  let nodes = newCollection[RadioNodeList](
    this.root,
    func(node: Node): bool =
      if not this.match(node):
        return false
      let element = Element(node)
      return element.id == name or
        element.namespace == Namespace.HTML and element.name == name,
    islive = true,
    childonly = false
  )
  if nodes.len == 0:
    return JS_NULL
  if nodes.len == 1:
    return ctx.toJS(nodes.snapshot[0])
  return ctx.toJS(nodes)

proc names(ctx: JSContext; this: HTMLFormControlsCollection): JSPropertyEnumList
    {.jspropnames.} =
  return ctx.names(HTMLCollection(this))

proc getter(ctx: JSContext; this: HTMLFormControlsCollection; atom: JSAtom):
    JSValue {.jsgetprop.} =
  var u: uint32
  if ctx.fromJS(atom, u).isSome:
    return ctx.toJS(this.item(u))
  var s: CAtom
  if ctx.fromJS(atom, s).isSome:
    return ctx.namedItem(this, s)
  return JS_NULL

# HTMLAllCollection
proc length(this: HTMLAllCollection): uint32 {.jsfget.} =
  return uint32(this.len)

func item(this: HTMLAllCollection; u: uint32): Element {.jsfunc.} =
  let i = int(u)
  if i < this.len:
    return Element(this.snapshot[i])
  return nil

func getter(ctx: JSContext; this: HTMLAllCollection; atom: JSAtom): Element
    {.jsgetprop.} =
  var u: uint32
  if ctx.fromJS(atom, u).isSome:
    return this.item(u)
  return nil

func names(ctx: JSContext; this: HTMLAllCollection): JSPropertyEnumList
    {.jspropnames.} =
  let L = this.length
  var list = newJSPropertyEnumList(ctx, L)
  for u in 0 ..< L:
    list.add(u)
  return list

proc all(document: Document): HTMLAllCollection {.jsfget.} =
  if document.cachedAll == nil:
    document.cachedAll = newCollection[HTMLAllCollection](
      root = document,
      match = isElement,
      islive = true,
      childonly = false
    )
  return document.cachedAll

# Location
proc newLocation*(window: Window): Location =
  let location = Location(window: window)
  let ctx = window.jsctx
  if ctx != nil:
    let val = toJS(ctx, location)
    let valueOf = ctx.getOpaque().valRefs[jsvObjectPrototypeValueOf]
    defineProperty(ctx, val, "valueOf", JS_DupValue(ctx, valueOf))
    defineProperty(ctx, val, "toPrimitive", JS_UNDEFINED)
    #TODO [[DefaultProperties]]
    JS_FreeValue(ctx, val)
  return location

func location(document: Document): Location {.jsfget.} =
  if document.window == nil:
    return nil
  return document.window.location

func document(location: Location): Document =
  return location.window.document

func url(location: Location): URL =
  let document = location.document
  if document != nil:
    return document.url
  return newURL("about:blank").get

proc setLocation*(document: Document; s: string): Err[JSError]
    {.jsfset: "location".} =
  if document.location == nil:
    return errTypeError("document.location is not an object")
  let url = parseURL(s)
  if url.isNone:
    return errDOMException("Invalid URL", "SyntaxError")
  document.window.navigate(url.get)
  return ok()

# Note: we do not implement security checks (as documents are in separate
# windows anyway).
func `$`(location: Location): string {.jsuffunc.} =
  return location.url.serialize()

func href(location: Location): string {.jsuffget.} =
  return $location

proc setHref(location: Location; s: string): Err[JSError]
    {.jsfset: "href".} =
  if location.document == nil:
    return ok()
  return location.document.setLocation(s)

proc assign(location: Location; s: string): Err[JSError] {.jsuffunc.} =
  location.setHref(s)

proc replace(location: Location; s: string): Err[JSError] {.jsuffunc.} =
  location.setHref(s)

proc reload(location: Location) {.jsuffunc.} =
  if location.document == nil:
    return
  location.document.window.navigate(location.url)

func origin(location: Location): string {.jsuffget.} =
  return location.url.jsOrigin

func protocol(location: Location): string {.jsuffget.} =
  return location.url.protocol

proc protocol(location: Location; s: string): Err[DOMException] {.jsfset.} =
  let document = location.document
  if document == nil:
    return
  let copyURL = newURL(location.url)
  copyURL.setProtocol(s)
  if copyURL.scheme != "http" and copyURL.scheme != "https":
    return errDOMException("Invalid URL", "SyntaxError")
  document.window.navigate(copyURL)
  return ok()

func host(location: Location): string {.jsuffget.} =
  return location.url.host

proc setHost(location: Location; s: string) {.jsfset: "host".} =
  let document = location.document
  if document == nil:
    return
  let copyURL = newURL(location.url)
  copyURL.setHost(s)
  document.window.navigate(copyURL)

proc hostname(location: Location): string {.jsuffget.} =
  return location.url.hostname

proc setHostname(location: Location; s: string) {.jsfset: "hostname".} =
  let document = location.document
  if document == nil:
    return
  let copyURL = newURL(location.url)
  copyURL.setHostname(s)
  document.window.navigate(copyURL)

proc port(location: Location): string {.jsuffget.} =
  return location.url.port

proc setPort(location: Location; s: string) {.jsfset: "port".} =
  let document = location.document
  if document == nil:
    return
  let copyURL = newURL(location.url)
  copyURL.setPort(s)
  document.window.navigate(copyURL)

proc pathname(location: Location): string {.jsuffget.} =
  return location.url.pathname

proc setPathname(location: Location; s: string) {.jsfset: "pathname".} =
  let document = location.document
  if document == nil:
    return
  let copyURL = newURL(location.url)
  copyURL.setPathname(s)
  document.window.navigate(copyURL)

proc search(location: Location): string {.jsuffget.} =
  return location.url.search

proc setSearch(location: Location; s: string) {.jsfset: "search".} =
  let document = location.document
  if document == nil:
    return
  let copyURL = newURL(location.url)
  copyURL.setSearch(s)
  document.window.navigate(copyURL)

proc hash(location: Location): string {.jsuffget.} =
  return location.url.hash

proc setHash(location: Location; s: string) {.jsfset: "hash".} =
  let document = location.document
  if document == nil:
    return
  let copyURL = newURL(location.url)
  copyURL.setHash(s)
  document.window.navigate(copyURL)

func jsOwnerElement(attr: Attr): Element {.jsfget: "ownerElement".} =
  if attr.ownerElement of AttrDummyElement:
    return nil
  return attr.ownerElement

func data(attr: Attr): lent AttrData =
  return attr.ownerElement.attrs[attr.dataIdx]

proc jsNamespaceURI(attr: Attr): string {.jsfget: "namespaceURI".} =
  return attr.ownerElement.document.toStr(attr.data.namespace)

proc jsPrefix(attr: Attr): string {.jsfget: "prefix".} =
  return attr.ownerElement.document.toStr(attr.data.prefix)

proc jsLocalName(attr: Attr): string {.jsfget: "localName".} =
  return attr.ownerElement.document.toStr(attr.data.localName)

proc jsValue(attr: Attr): string {.jsfget: "value".} =
  return attr.data.value

func jsName(attr: Attr): string {.jsfget: "name".} =
  return attr.ownerElement.document.toStr(attr.data.qualifiedName)

func findAttr(map: NamedNodeMap; dataIdx: int): int =
  for i, attr in map.attrlist:
    if attr.dataIdx == dataIdx:
      return i
  return -1

proc getAttr(map: NamedNodeMap; dataIdx: int): Attr =
  let i = map.findAttr(dataIdx)
  if i != -1:
    return map.attrlist[i]
  let attr = Attr(
    internalDocument: map.element.document,
    index: -1,
    dataIdx: dataIdx,
    ownerElement: map.element
  )
  map.attrlist.add(attr)
  return attr

func normalizeAttrQName(element: Element; qualifiedName: string): CAtom =
  if element.namespace == Namespace.HTML and not element.document.isxml:
    return element.document.toAtom(qualifiedName.toLowerAscii())
  return element.document.toAtom(qualifiedName)

func hasAttributes(element: Element): bool {.jsfunc.} =
  return element.attrs.len > 0

func attributes(element: Element): NamedNodeMap {.jsfget.} =
  if element.internalAttributes != nil:
    return element.internalAttributes
  element.internalAttributes = NamedNodeMap(element: element)
  for i, attr in element.attrs.mpairs:
    element.internalAttributes.attrlist.add(Attr(
      internalDocument: element.document,
      index: -1,
      dataIdx: i,
      ownerElement: element
    ))
  return element.internalAttributes

func findAttr(element: Element; qualifiedName: string): int =
  return element.findAttr(element.normalizeAttrQName(qualifiedName))

func findAttrNS(element: Element; namespace, localName: string): int =
  let namespace = element.document.toAtom(namespace)
  let localName = element.document.toAtom(localName)
  return element.findAttrNS(namespace, localName)

func hasAttribute(element: Element; qualifiedName: string): bool {.jsfunc.} =
  return element.findAttr(qualifiedName) != -1

func hasAttributeNS(element: Element; namespace, localName: string): bool
    {.jsfunc.} =
  return element.findAttrNS(namespace, localName) != -1

func getAttribute(element: Element; qualifiedName: string): Option[string]
    {.jsfunc.} =
  let i = element.findAttr(qualifiedName)
  if i != -1:
    return some(element.attrs[i].value)
  return none(string)

func getAttributeNS(element: Element; namespace, localName: string):
    Option[string] {.jsfunc.} =
  let i = element.findAttrNS(namespace, localName)
  if i != -1:
    return some(element.attrs[i].value)
  return none(string)

proc getNamedItem(map: NamedNodeMap; qualifiedName: string): Attr
    {.jsfunc.} =
  let i = map.element.findAttr(qualifiedName)
  if i != -1:
    return map.getAttr(i)
  return nil

proc getNamedItemNS(map: NamedNodeMap; namespace, localName: string):
    Attr {.jsfunc.} =
  let i = map.element.findAttrNS(namespace, localName)
  if i != -1:
    return map.getAttr(i)
  return nil

func length(map: NamedNodeMap): uint32 {.jsfget.} =
  return uint32(map.element.attrs.len)

proc item(map: NamedNodeMap; i: uint32): Attr {.jsfunc.} =
  if int(i) < map.element.attrs.len:
    return map.getAttr(int(i))
  return nil

func getter(ctx: JSContext; map: NamedNodeMap; atom: JSAtom): Opt[Attr]
    {.jsgetprop.} =
  var u: uint32
  if ctx.fromJS(atom, u).isSome:
    return ok(map.item(u))
  var s: string
  ?ctx.fromJS(atom, s)
  return ok(map.getNamedItem(s))

func names(ctx: JSContext; map: NamedNodeMap): JSPropertyEnumList
    {.jspropnames.} =
  let len = if map.element.namespace == Namespace.HTML:
    uint32(map.attrlist.len + map.element.attrs.len)
  else:
    uint32(map.attrlist.len)
  var list = newJSPropertyEnumList(ctx, len)
  for u in 0 ..< len:
    list.add(u)
  var names: HashSet[string]
  let element = map.element
  for attr in element.attrs:
    let name = element.document.toStr(attr.qualifiedName)
    if element.namespace == Namespace.HTML and AsciiUpperAlpha in name:
      continue
    if name in names:
      continue
    names.incl(name)
    list.add(name)
  return list

func length(characterData: CharacterData): uint32 {.jsfget.} =
  return uint32(characterData.data.utf16Len)

func tagName(element: Element): string {.jsfget.} =
  if element.namespace == Namespace.HTML:
    return element.document.toStr(element.localName).toUpperAscii()
  return element.document.toStr(element.localName)

func nodeName(node: Node): string {.jsfget.} =
  if node of Element:
    return Element(node).tagName
  if node of Attr:
    let attr = Attr(node)
    return attr.ownerElement.document.toStr(attr.data.qualifiedName)
  if node of DocumentType:
    return DocumentType(node).name
  if node of CDATASection:
    return "#cdata-section"
  if node of Comment:
    return "#comment"
  if node of Document:
    return "#document"
  if node of DocumentFragment:
    return "#document-fragment"
  if node of ProcessingInstruction:
    return ProcessingInstruction(node).target
  assert node of Text
  return "#text"

func scriptingEnabled*(document: Document): bool =
  if document.window == nil:
    return false
  return document.window.settings.scripting

func scriptingEnabled*(element: Element): bool =
  return element.document.scriptingEnabled

func isSubmitButton*(element: Element): bool =
  if element of HTMLButtonElement:
    return element.attr(satType) == "submit"
  elif element of HTMLInputElement:
    let element = HTMLInputElement(element)
    return element.inputType in {itSubmit, itImage}
  return false

func canSubmitImplicitly*(form: HTMLFormElement): bool =
  const BlocksImplicitSubmission = {
    itText, itSearch, itURL, itTel, itEmail, itPassword, itDate, itMonth,
    itWeek, itTime, itDatetimeLocal, itNumber
  }
  var found = false
  for control in form.controls:
    if control of HTMLInputElement:
      let input = HTMLInputElement(control)
      if input.inputType in BlocksImplicitSubmission:
        if found:
          return false
        else:
          found = true
    elif control.isSubmitButton():
      return false
  return true

func qualifiedName*(element: Element): string =
  if element.namespacePrefix != NO_PREFIX:
    $element.namespacePrefix & ':' & element.localNameStr
  else:
    element.localNameStr

template toOA*(writeBuffer: DocumentWriteBuffer): openArray[char] =
  writeBuffer.data.toOpenArray(writeBuffer.i, writeBuffer.data.high)

#TODO :(
proc CDB_parseDocumentWriteChunk(wrapper: pointer) {.importc.}

# https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#document-write-steps
proc write(ctx: JSContext; document: Document; args: varargs[JSValue]):
    Err[DOMException] {.jsfunc.} =
  if document.isxml:
    return errDOMException("document.write not supported in XML documents",
      "InvalidStateError")
  if document.throwOnDynamicMarkupInsertion > 0:
    return errDOMException("throw-on-dynamic-markup-insertion counter > 0",
      "InvalidStateError")
  if document.activeParserWasAborted:
    return ok()
  assert document.parser != nil
  #TODO if insertion point is undefined... (open document)
  if document.writeBuffers.len == 0:
    return ok() #TODO (probably covered by open above)
  let buffer = document.writeBuffers[^1]
  var text = ""
  for arg in args:
    var s: string
    ?ctx.fromJS(arg, s)
    text &= s
  buffer.data &= text
  if document.parserBlockingScript == nil:
    CDB_parseDocumentWriteChunk(document.parser)
  return ok()

func findFirst*(document: Document; tagType: TagType): HTMLElement =
  for element in document.elements(tagType):
    return HTMLElement(element)
  nil

func html*(document: Document): HTMLElement =
  return document.findFirst(TAG_HTML)

func head*(document: Document): HTMLElement {.jsfget.} =
  return document.findFirst(TAG_HEAD)

func body*(document: Document): HTMLElement {.jsfget.} =
  return document.findFirst(TAG_BODY)

func select*(option: HTMLOptionElement): HTMLSelectElement =
  for anc in option.ancestors:
    if anc of HTMLSelectElement:
      return HTMLSelectElement(anc)
  return nil

func countChildren(node: Node; nodeType: type): int =
  for child in node.childList:
    if child of nodeType:
      inc result

func hasChild(node: Node; nodeType: type): bool =
  for child in node.childList:
    if child of nodeType:
      return true

func hasChildExcept(node: Node; nodeType: type; ex: Node): bool =
  for child in node.childList:
    if child == ex:
      continue
    if child of nodeType:
      return true
  return false

func previousSibling*(node: Node): Node {.jsfget.} =
  let i = node.index - 1
  if node.parentNode == nil or i < 0:
    return nil
  return node.parentNode.childList[i]

func nextSibling*(node: Node): Node {.jsfget.} =
  let i = node.index + 1
  if node.parentNode == nil or i >= node.parentNode.childList.len:
    return nil
  return node.parentNode.childList[i]

func hasNextSibling(node: Node; nodeType: type): bool =
  var node = node.nextSibling
  while node != nil:
    if node of nodeType:
      return true
    node = node.nextSibling
  return false

func hasPreviousSibling(node: Node; nodeType: type): bool =
  var node = node.previousSibling
  while node != nil:
    if node of nodeType:
      return true
    node = node.previousSibling
  return false

func nodeValue(node: Node): Option[string] {.jsfget.} =
  if node of CharacterData:
    return some(CharacterData(node).data)
  elif node of Attr:
    return some(Attr(node).data.value)
  return none(string)

func textContent*(node: Node): string =
  if node of CharacterData:
    result = CharacterData(node).data
  else:
    result = ""
    for child in node.childList:
      if not (child of Comment):
        result &= child.textContent

func jsTextContent(node: Node): Option[string] {.jsfget: "textContent".} =
  if node of Document or node of DocumentType:
    return none(string) # null
  return some(node.textContent)

func childTextContent*(node: Node): string =
  for child in node.childList:
    if child of Text:
      result &= Text(child).data

func rootNode(node: Node): Node =
  var node = node
  while node.parentNode != nil:
    node = node.parentNode
  return node

func isConnected(node: Node): bool {.jsfget.} =
  return node.rootNode of Document #TODO shadow root

func inSameTree*(a, b: Node): bool =
  a.rootNode == b.rootNode

# a == b or a in b's ancestors
func contains*(a, b: Node): bool {.jsfunc.} =
  if b != nil:
    for node in b.branch:
      if node == a:
        return true
  return false

func firstChild*(node: Node): Node {.jsfget.} =
  if node.childList.len == 0:
    return nil
  return node.childList[0]

func lastChild*(node: Node): Node {.jsfget.} =
  if node.childList.len == 0:
    return nil
  return node.childList[^1]

func firstElementChild*(node: Node): Element {.jsfget.} =
  for child in node.elementList:
    return child
  return nil

func lastElementChild*(node: Node): Element {.jsfget.} =
  for child in node.elementList_rev:
    return child
  return nil

func findAncestor*(node: Node; tagTypes: set[TagType]): Element =
  for element in node.ancestors:
    if element.tagType in tagTypes:
      return element
  return nil

func getElementById(document: Document; id: string): Element {.jsfunc.} =
  if id.len == 0:
    return nil
  let id = document.toAtom(id)
  for child in document.elements:
    if child.id == id:
      return child
  return nil

func getElementsByTagName0(root: Node; tagName: string): HTMLCollection =
  if tagName == "*":
    return newCollection[HTMLCollection](
      root,
      isElement,
      islive = true,
      childonly = false
    )
  let localName = root.document.toAtom(tagName)
  let localNameLower = root.document.toAtom(tagName.toLowerAscii())
  return newCollection[HTMLCollection](
    root,
    func(node: Node): bool =
      if node of Element:
        let element = Element(node)
        if element.namespace == Namespace.HTML:
          return element.localName == localNameLower
        return element.localName == localName
      return false,
    islive = true,
    childonly = false
  )

func getElementsByTagName(document: Document; tagName: string): HTMLCollection
    {.jsfunc.} =
  return document.getElementsByTagName0(tagName)

func getElementsByTagName(element: Element; tagName: string): HTMLCollection
    {.jsfunc.} =
  return element.getElementsByTagName0(tagName)

func getElementsByClassName0(node: Node; classNames: string): HTMLCollection =
  var classAtoms = newSeq[CAtom]()
  let document = node.document
  let isquirks = document.mode == QUIRKS
  if isquirks:
    for class in classNames.split(AsciiWhitespace):
      classAtoms.add(document.toAtom(class.toLowerAscii()))
  else:
    for class in classNames.split(AsciiWhitespace):
      classAtoms.add(document.toAtom(class))
  return newCollection[HTMLCollection](node,
    func(node: Node): bool =
      if node of Element:
        let element = Element(node)
        if isquirks:
          var cl = newSeq[CAtom]()
          for tok in element.classList.toks:
            let s = document.toStr(tok)
            cl.add(document.toAtom(s.toLowerAscii()))
          for class in classAtoms:
            if class notin cl:
              return false
        else:
          for class in classAtoms:
            if class notin element.classList.toks:
              return false
        return true,
    islive = true,
    childonly = false
  )

func getElementsByClassName(document: Document; classNames: string):
    HTMLCollection {.jsfunc.} =
  return document.getElementsByClassName0(classNames)

func getElementsByClassName(element: Element; classNames: string):
    HTMLCollection {.jsfunc.} =
  return element.getElementsByClassName0(classNames)

func previousElementSibling*(elem: Element): Element {.jsfget.} =
  let p = elem.parentNode
  if p == nil: return nil
  for i in countdown(elem.index - 1, 0):
    let node = p.childList[i]
    if node of Element:
      return Element(node)
  return nil

func nextElementSibling*(elem: Element): Element {.jsfget.} =
  let p = elem.parentNode
  if p == nil: return nil
  for i in elem.index + 1 .. p.childList.high:
    let node = p.childList[i]
    if node of Element:
      return Element(node)
  return nil

func documentElement(document: Document): Element {.jsfget.} =
  document.firstElementChild()

func attr*(element: Element; s: CAtom): string =
  let i = element.findAttr(s)
  if i != -1:
    return element.attrs[i].value
  return ""

func attr*(element: Element; s: StaticAtom): string =
  return element.attr(element.document.toAtom(s))

func attrl*(element: Element; s: StaticAtom): Option[int32] =
  return parseInt32(element.attr(s))

func attrulgz*(element: Element; s: StaticAtom): Option[uint32] =
  let x = parseUInt32(element.attr(s), allowSign = true)
  if x.isSome and x.get > 0:
    return x
  return none(uint32)

func attrul*(element: Element; s: StaticAtom): Option[uint32] =
  let x = parseUInt32(element.attr(s), allowSign = true)
  if x.isSome and x.get >= 0:
    return x
  return none(uint32)

func attrb*(element: Element; s: CAtom): bool =
  return element.findAttr(s) != -1

func attrb*(element: Element; at: StaticAtom): bool =
  let atom = element.document.toAtom(at)
  return element.attrb(atom)

# https://html.spec.whatwg.org/multipage/parsing.html#serialising-html-fragments
func serializesAsVoid(element: Element): bool =
  const Extra = {TAG_BASEFONT, TAG_BGSOUND, TAG_FRAME, TAG_KEYGEN, TAG_PARAM}
  return element.tagType in VoidElements + Extra

func serializeFragment*(node: Node): string

func serializeFragmentInner(child: Node; parentType: TagType): string =
  result = ""
  if child of Element:
    let element = Element(child)
    let tags = element.localNameStr
    result &= '<'
    #TODO qualified name if not HTML, SVG or MathML
    result &= tags
    #TODO custom elements
    for attr in element.attrs:
      #TODO namespaced attrs
      let k = element.document.toStr(attr.localName)
      result &= ' ' & k & "=\"" & attr.value.escapeText(true) & "\""
    result &= '>'
    result &= element.serializeFragment()
    result &= "</"
    result &= tags
    result &= '>'
  elif child of Text:
    let text = Text(child)
    const LiteralTags = {
      TAG_STYLE, TAG_SCRIPT, TAG_XMP, TAG_IFRAME, TAG_NOEMBED, TAG_NOFRAMES,
      TAG_PLAINTEXT, TAG_NOSCRIPT
    }
    result = if parentType in LiteralTags:
      text.data
    else:
      text.data.escapeText()
  elif child of Comment:
    result &= "<!--" & Comment(child).data & "-->"
  elif child of ProcessingInstruction:
    let inst = ProcessingInstruction(child)
    result &= "<?" & inst.target & " " & inst.data & '>'
  elif child of DocumentType:
    result &= "<!DOCTYPE " & DocumentType(child).name & '>'

func serializeFragment*(node: Node): string =
  var node = node
  var parentType = TAG_UNKNOWN
  if node of Element:
    let element = Element(node)
    if element.serializesAsVoid():
      return ""
    if element of HTMLTemplateElement:
      node = HTMLTemplateElement(element).content
    else:
      parentType = element.tagType
      if parentType == TAG_NOSCRIPT and not element.scriptingEnabled:
        # Pretend parentType is not noscript, so we do not append literally
        # in serializeFragmentInner.
        parentType = TAG_UNKNOWN
  var s = ""
  for child in node.childList:
    s &= child.serializeFragmentInner(parentType)
  return s

# Element attribute reflection (getters)
func innerHTML(element: Element): string {.jsfget.} =
  #TODO xml
  return element.serializeFragment()

func outerHTML(element: Element): string {.jsfget.} =
  #TODO xml
  return element.serializeFragmentInner(TAG_UNKNOWN)

func crossOrigin0(element: HTMLElement): CORSAttribute =
  if not element.attrb(satCrossorigin):
    return caNoCors
  case element.attr(satCrossorigin)
  of "anonymous", "":
    return caAnonymous
  of "use-credentials":
    return caUseCredentials
  else:
    return caAnonymous

func crossOrigin(element: HTMLScriptElement): CORSAttribute {.jsfget.} =
  return element.crossOrigin0

func crossOrigin(element: HTMLImageElement): CORSAttribute {.jsfget.} =
  return element.crossOrigin0

func referrerpolicy(element: HTMLScriptElement): Option[ReferrerPolicy] =
  return strictParseEnum[ReferrerPolicy](element.attr(satReferrerpolicy))

proc sheets*(document: Document): seq[CSSStylesheet] =
  if document.cachedSheetsInvalid and document.window.styling:
    document.cachedSheets.setLen(0)
    for elem in document.html.descendants:
      if elem of HTMLStyleElement:
        let style = HTMLStyleElement(elem)
        style.sheet = parseStylesheet(style.textContent, document.factory)
        if style.sheet != nil:
          document.cachedSheets.add(style.sheet)
      elif elem of HTMLLinkElement:
        let link = HTMLLinkElement(elem)
        if link.sheet != nil:
          document.cachedSheets.add(link.sheet)
      else: discard
    document.cachedSheetsInvalid = false
  return document.cachedSheets

func checked*(input: HTMLInputElement): bool {.inline.} =
  return input.internalChecked

proc setChecked*(input: HTMLInputElement; b: bool) {.inline.} =
  input.invalidDeps.incl(dtChecked)
  input.internalChecked = b

func inputString*(input: HTMLInputElement): string =
  case input.inputType
  of itCheckbox, itRadio:
    if input.checked:
      "*"
    else:
      " "
  of itSearch, itText, itEmail, itURL, itTel:
    input.value.padToWidth(int(input.attrulgz(satSize).get(20)))
  of itPassword:
    '*'.repeat(input.value.len).padToWidth(int(input.attrulgz(satSize).get(20)))
  of itReset:
    if input.value != "":
      input.value
    else:
      "RESET"
  of itSubmit, itButton:
    if input.value != "":
      input.value
    else:
      "SUBMIT"
  of itFile:
    let s = if input.file != nil: input.file.name else: ""
    s.padToWidth(int(input.attrulgz(satSize).get(20)))
  else: input.value

func textAreaString*(textarea: HTMLTextAreaElement): string =
  let split = textarea.value.split('\n')
  let rows = int(textarea.attrul(satRows).get(1))
  for i in 0 ..< rows:
    let cols = int(textarea.attrul(satCols).get(20))
    if cols > 2:
      if i < split.len:
        result &= '[' & split[i].padToWidth(cols - 2) & "]\n"
      else:
        result &= '[' & ' '.repeat(cols - 2) & "]\n"
    else:
      result &= "[]\n"

func isButton*(element: Element): bool =
  if element of HTMLButtonElement:
    return true
  if element of HTMLInputElement:
    let element = HTMLInputElement(element)
    return element.inputType in {itSubmit, itButton, itReset, itImage}
  return false

func action*(element: Element): string =
  if element.isSubmitButton():
    if element.attrb(satFormaction):
      return element.attr(satFormaction)
  if element of FormAssociatedElement:
    let element = FormAssociatedElement(element)
    if element.form != nil:
      if element.form.attrb(satAction):
        return element.form.attr(satAction)
  if element of HTMLFormElement:
    return element.attr(satAction)
  return ""

func enctype*(element: Element): FormEncodingType =
  if element of HTMLFormElement:
    # Note: see below, this is not in the standard.
    if element.attrb(satEnctype):
      let s = element.attr(satEnctype)
      return parseEnumNoCase[FormEncodingType](s).get(fetUrlencoded)
  if element.isSubmitButton():
    if element.attrb(satFormenctype):
      let s = element.attr(satFormenctype)
      return parseEnumNoCase[FormEncodingType](s).get(fetUrlencoded)
  if element of FormAssociatedElement:
    let element = FormAssociatedElement(element)
    if (let form = element.form; form != nil):
      if form.attrb(satEnctype):
        let s = form.attr(satEnctype)
        return parseEnumNoCase[FormEncodingType](s).get(fetUrlencoded)
  return fetUrlencoded

func parseFormMethod(s: string): FormMethod =
  return parseEnumNoCase[FormMethod](s).get(fmGet)

func formmethod*(element: Element): FormMethod =
  if element of HTMLFormElement:
    # The standard says nothing about this, but this code path is reached
    # on implicit form submission and other browsers seem to agree on this
    # behavior.
    return parseFormMethod(element.attr(satMethod))
  if element.isSubmitButton():
    if element.attrb(satFormmethod):
      return parseFormMethod(element.attr(satFormmethod))
  if element of FormAssociatedElement:
    let element = FormAssociatedElement(element)
    if element.form != nil:
      if element.form.attrb(satMethod):
        return parseFormMethod(element.form.attr(satMethod))
  return fmGet

func findAnchor*(document: Document; id: string): Element =
  if id.len == 0:
    return nil
  let id = document.toAtom(id)
  for child in document.elements:
    if child.id == id:
      return child
    if child of HTMLAnchorElement and child.name == id:
      return child
  return nil

proc findMetaRefresh*(document: Document): Element =
  for child in document.elements(TAG_META):
    if child.attr(satHttpEquiv) == "refresh":
      return child
  return nil

func focus*(document: Document): Element =
  return document.internalFocus

proc setFocus*(document: Document; element: Element) =
  if document.focus != nil:
    document.focus.invalidDeps.incl(dtFocus)
  document.internalFocus = element
  if element != nil:
    element.invalidDeps.incl(dtFocus)

func hover*(element: Element): bool =
  return element.internalHover

proc setHover*(element: Element; hover: bool) =
  element.invalidDeps.incl(dtHover)
  element.internalHover = hover

func findAutoFocus*(document: Document): Element =
  for child in document.elements:
    if child.attrb(satAutofocus):
      return child
  return nil

# Forward declaration hack
isDefaultPassive = func(target: EventTarget): bool =
  if target of Window:
    return true
  if not (target of Node):
    return false
  let node = Node(target)
  return EventTarget(node.document) == target or
    EventTarget(node.document.html) == target or
    EventTarget(node.document.body) == target

getParent = proc(ctx: JSContext; eventTarget: EventTarget; event: Event):
    EventTarget =
  if eventTarget of Node:
    if eventTarget of Document:
      if event.ctype == ctx.toAtom(satLoad):
        return nil
      # if no browsing context, then window will be nil anyway
      return Document(eventTarget).window
    return Node(eventTarget).parentNode
  return nil

getFactory = proc(ctx: JSContext): CAtomFactory =
  return ctx.getGlobal().factory

windowConsoleError = proc(ctx: JSContext; ss: varargs[string]) =
  ctx.getGlobal().console.error(ss)

getAPIBaseURLImpl = func(ctx: JSContext): URL =
  let window = ctx.getWindow()
  if window == nil or window.document == nil:
    return nil
  return window.document.baseURL

proc fireEvent*(window: Window; name: StaticAtom; target: EventTarget) =
  let event = newEvent(window.toAtom(name), target)
  discard window.jsctx.dispatch(target, event)

proc parseColor(element: Element; s: string): ARGBColor =
  let cval = parseComponentValue(s)
  #TODO return element style
  # For now we just use white.
  let ec = rgb(255, 255, 255)
  if cval.isNone:
    return ec
  let color0 = cssColor(cval.get)
  if color0.isNone:
    return ec
  let color = color0.get
  if color.t != ctRGB:
    return ec
  return color.argbcolor

#TODO ??
func target0*(element: Element): string =
  if element.attrb(satTarget):
    return element.attr(satTarget)
  for base in element.document.elements(TAG_BASE):
    if base.attrb(satTarget):
      return base.attr(satTarget)
  return ""

# HTMLHyperlinkElementUtils (for <a> and <area>)
func href0(element: HTMLElement): string =
  if not element.attrb(satHref):
    return ""
  let url = parseURL(element.attr(satHref), some(element.document.baseURL))
  if url.isSome:
    return $url.get
  return ""

# <base>
func href(base: HTMLBaseElement): string {.jsfget.} =
  #TODO with fallback base url
  let url = parseURL(base.attr(satHref))
  if url.isSome:
    return $url.get
  return ""

# <a>
func href*(anchor: HTMLAnchorElement): string {.jsfget.} =
  return anchor.href0

proc setHref(anchor: HTMLAnchorElement; href: string) {.jsfset: "href".} =
  anchor.attr(satHref, href)

func `$`(anchor: HTMLAnchorElement): string {.jsfunc.} =
  return anchor.href

proc setRelList(anchor: HTMLAnchorElement; s: string) {.jsfset: "relList".} =
  anchor.attr(satRel, s)

# <area>
func href(area: HTMLAreaElement): string {.jsfget.} =
  return area.href0

proc setHref(area: HTMLAreaElement; href: string) {.jsfset: "href".} =
  area.attr(satHref, href)

func `$`(area: HTMLAreaElement): string {.jsfunc.} =
  return area.href

proc setRelList(area: HTMLAreaElement; s: string) {.jsfset: "relList".} =
  area.attr(satRel, s)

# <label>
func control*(label: HTMLLabelElement): FormAssociatedElement {.jsfget.} =
  let f = label.attr(satFor)
  if f != "":
    let elem = label.document.getElementById(f)
    #TODO the supported check shouldn't be needed, just labelable
    if elem of FormAssociatedElement and elem.tagType in LabelableElements:
      return FormAssociatedElement(elem)
    return nil
  for elem in label.elements(LabelableElements):
    if elem of FormAssociatedElement: #TODO remove this
      return FormAssociatedElement(elem)
    return nil
  return nil

func form(label: HTMLLabelElement): HTMLFormElement {.jsfget.} =
  let control = label.control
  if control != nil:
    return control.form
  return nil

# <link>
proc setRelList(link: HTMLLinkElement; s: string) {.jsfset: "relList".} =
  link.attr(satRel, s)

# <form>
proc setRelList(form: HTMLFormElement; s: string) {.jsfset: "relList".} =
  form.attr(satRel, s)

func elements(form: HTMLFormElement): HTMLFormControlsCollection {.jsfget.} =
  if form.cachedElements == nil:
    form.cachedElements = newCollection[HTMLFormControlsCollection](
      root = form.rootNode,
      match = func(node: Node): bool =
        if node of FormAssociatedElement:
          let element = FormAssociatedElement(node)
          if element.tagType in ListedElements:
            return element.form == form
        return false,
      islive = true,
      childonly = false
    )
  return form.cachedElements

# <input>
func jsForm(this: HTMLInputElement): HTMLFormElement {.jsfget: "form".} =
  return this.form

proc setValue(this: HTMLInputElement; value: string) {.jsfset: "value".} =
  this.value = value
  this.setInvalid()

# <select>
func jsForm(this: HTMLSelectElement): HTMLFormElement {.jsfget: "form".} =
  return this.form

# <button>
func jsForm(this: HTMLButtonElement): HTMLFormElement {.jsfget: "form".} =
  return this.form

# <textarea>
func jsForm(this: HTMLTextAreaElement): HTMLFormElement {.jsfget: "form".} =
  return this.form

# <video>
func getSrc*(this: HTMLElement): string =
  let src = this.attr(satSrc)
  if src != "":
    return src
  for el in this.elements(TAG_SOURCE):
    let src = el.attr(satSrc)
    if src != "":
      return src
  return ""

func newText*(document: Document; data: string): Text =
  return Text(
    internalDocument: document,
    data: data,
    index: -1
  )

func newText(ctx: JSContext; data = ""): Text {.jsctor.} =
  let window = ctx.getGlobal()
  return window.document.newText(data)

func newCDATASection(document: Document; data: string): CDATASection =
  return CDATASection(
    internalDocument: document,
    data: data,
    index: -1
  )

func newProcessingInstruction(document: Document; target, data: string):
    ProcessingInstruction =
  return ProcessingInstruction(
    internalDocument: document,
    target: target,
    data: data,
    index: -1
  )

func newDocumentFragment(document: Document): DocumentFragment =
  return DocumentFragment(internalDocument: document, index: -1)

func newDocumentFragment(ctx: JSContext): DocumentFragment {.jsctor.} =
  let window = ctx.getGlobal()
  return window.document.newDocumentFragment()

func newComment(document: Document; data: string): Comment =
  return Comment(
    internalDocument: document,
    data: data,
    index: -1
  )

func newComment(ctx: JSContext; data: string = ""): Comment {.jsctor.} =
  let window = ctx.getGlobal()
  return window.document.newComment(data)

#TODO custom elements
proc newHTMLElement*(document: Document; localName: CAtom;
    namespace = Namespace.HTML; prefix = NO_PREFIX): HTMLElement =
  let tagType = document.toTagType(localName)
  case tagType
  of TAG_INPUT:
    result = HTMLInputElement()
  of TAG_A:
    let anchor = HTMLAnchorElement()
    let localName = document.toAtom(satRel)
    anchor.relList = DOMTokenList(element: anchor, localName: localName)
    result = anchor
  of TAG_SELECT:
    result = HTMLSelectElement()
  of TAG_OPTGROUP:
    result = HTMLOptGroupElement()
  of TAG_OPTION:
    result = HTMLOptionElement()
  of TAG_H1, TAG_H2, TAG_H3, TAG_H4, TAG_H5, TAG_H6:
    result = HTMLHeadingElement()
  of TAG_BR:
    result = HTMLBRElement()
  of TAG_SPAN:
    result = HTMLSpanElement()
  of TAG_OL:
    result = HTMLOListElement()
  of TAG_UL:
    result = HTMLUListElement()
  of TAG_MENU:
    result = HTMLMenuElement()
  of TAG_LI:
    result = HTMLLIElement()
  of TAG_STYLE:
    result = HTMLStyleElement()
  of TAG_LINK:
    let link = HTMLLinkElement()
    let localName = document.toAtom(satRel)
    link.relList = DOMTokenList(element: link, localName: localName)
    result = link
  of TAG_FORM:
    let form = HTMLFormElement()
    let localName = document.toAtom(satRel)
    form.relList = DOMTokenList(element: form, localName: localName)
    result = form
  of TAG_TEMPLATE:
    result = HTMLTemplateElement(
      content: DocumentFragment(internalDocument: document, host: result)
    )
  of TAG_UNKNOWN:
    result = HTMLUnknownElement()
  of TAG_SCRIPT:
    result = HTMLScriptElement(forceAsync: true)
  of TAG_BASE:
    result = HTMLBaseElement()
  of TAG_BUTTON:
    result = HTMLButtonElement()
  of TAG_TEXTAREA:
    result = HTMLTextAreaElement()
  of TAG_LABEL:
    result = HTMLLabelElement()
  of TAG_CANVAS:
    let bitmap = if document.scriptingEnabled:
      NetworkBitmap(
        contentType: "image/x-cha-canvas",
        imageId: document.window.getImageId(),
        width: 300,
        height: 150
      )
    else:
      nil
    result = HTMLCanvasElement(bitmap: bitmap)
  of TAG_IMG:
    result = HTMLImageElement()
  of TAG_VIDEO:
    result = HTMLVideoElement()
  of TAG_AUDIO:
    result = HTMLAudioElement()
  of TAG_AREA:
    let area = HTMLAreaElement()
    let localName = document.toAtom(satRel)
    area.relList = DOMTokenList(element: area, localName: localName)
    result = area
  else:
    result = HTMLElement()
  result.localName = localName
  result.namespace = namespace
  result.namespacePrefix = prefix
  result.internalDocument = document
  let localName = document.toAtom(satClassList)
  result.classList = DOMTokenList(element: result, localName: localName)
  result.index = -1
  result.dataset = DOMStringMap(target: result)

proc newHTMLElement*(document: Document; tagType: TagType): HTMLElement =
  let localName = document.toAtom(tagType)
  return document.newHTMLElement(localName, Namespace.HTML, NO_PREFIX)

func newDocument*(factory: CAtomFactory): Document =
  assert factory != nil
  let document = Document(
    url: newURL("about:blank").get,
    index: -1,
    factory: factory
  )
  document.implementation = DOMImplementation(document: document)
  document.contentType = "application/xml"
  return document

func newDocument(ctx: JSContext): Document {.jsctor.} =
  return newDocument(ctx.getGlobal().factory)

func newDocumentType*(document: Document; name, publicId, systemId: string):
    DocumentType =
  return DocumentType(
    internalDocument: document,
    name: name,
    publicId: publicId,
    systemId: systemId,
    index: -1
  )

func isHostIncludingInclusiveAncestor*(a, b: Node): bool =
  for parent in b.branch:
    if parent == a:
      return true
  let root = b.rootNode
  if root of DocumentFragment and DocumentFragment(root).host != nil:
    for parent in root.branch:
      if parent == a:
        return true
  return false

func baseURL*(document: Document): URL =
  #TODO frozen base url...
  var href = ""
  for base in document.elements(TAG_BASE):
    if base.attrb(satHref):
      href = base.attr(satHref)
  if href == "":
    return document.url
  if document.url == nil:
    return newURL("about:blank").get #TODO ???
  let url = parseURL(href, some(document.url))
  if url.isNone:
    return document.url
  return url.get

func baseURI(node: Node): string {.jsfget.} =
  return $node.document.baseURL

func parseURL*(document: Document; s: string): Option[URL] =
  #TODO encodings
  return parseURL(s, some(document.baseURL))

func media*(element: HTMLElement): string =
  return element.attr(satMedia)

func title*(document: Document): string {.jsfget.} =
  if (let title = document.findFirst(TAG_TITLE); title != nil):
    return title.childTextContent.stripAndCollapse()
  return ""

# https://html.spec.whatwg.org/multipage/form-elements.html#concept-option-disabled
func isDisabled*(option: HTMLOptionElement): bool =
  if option.parentElement of HTMLOptGroupElement and
      option.parentElement.attrb(satDisabled):
    return true
  return option.attrb(satDisabled)

func text(option: HTMLOptionElement): string {.jsfget.} =
  var s = ""
  for child in option.descendants:
    let parent = child.parentElement
    if child of Text and (parent.tagTypeNoNS != TAG_SCRIPT or
        parent.namespace notin {Namespace.HTML, Namespace.SVG}):
      s &= Text(child).data
  return s.stripAndCollapse()

func value*(option: HTMLOptionElement): string {.jsfget.} =
  if option.attrb(satValue):
    return option.attr(satValue)
  return option.text

proc invalidateCollections(node: Node) =
  for id in node.liveCollections:
    node.document.invalidCollections.incl(id)

proc setInvalid*(element: Element) =
  element.invalid = true
  if element.document != nil:
    element.document.invalid = true

proc delAttr(element: Element; i: int; keep = false) =
  let map = element.internalAttributes
  let name = element.attrs[i].qualifiedName
  element.attrs.delete(i) # ordering matters
  if map != nil:
    # delete from attrlist + adjust indices invalidated
    var j = -1
    for i, attr in map.attrlist.mpairs:
      if attr.dataIdx == i:
        j = i
      elif attr.dataIdx > i:
        dec attr.dataIdx
    if j != -1:
      if keep:
        let attr = map.attrlist[j]
        let data = attr.data
        attr.ownerElement = AttrDummyElement(
          internalDocument: attr.ownerElement.document,
          index: -1,
          attrs: @[data]
        )
        attr.dataIdx = 0
      map.attrlist.del(j) # ordering does not matter
  element.reflectAttr(name, none(string))
  element.invalidateCollections()
  element.setInvalid()

proc newCSSStyleDeclaration(element: Element; value: string):
    CSSStyleDeclaration =
  let inlineRules = value.parseDeclarations2()
  var decls: seq[CSSDeclaration]
  for rule in inlineRules:
    if rule.name.isSupportedProperty():
      decls.add(rule)
  return CSSStyleDeclaration(decls: inlineRules, element: element)

proc cssText(this: CSSStyleDeclaration): string {.jsfunc.} =
  #TODO this is incorrect
  return $this.decls

func length(this: CSSStyleDeclaration): uint32 =
  return uint32(this.decls.len)

func item(this: CSSStyleDeclaration; u: uint32): Option[string] =
  if u < this.length:
    return some(this.decls[int(u)].name)
  return none(string)

func find(this: CSSStyleDeclaration; s: string): int =
  for i, decl in this.decls:
    if decl.name == s:
      return i
  return -1

proc getPropertyValue(this: CSSStyleDeclaration; s: string): string =
  if (let i = this.find(s); i != -1):
    return $this.decls[i].value
  return ""

# https://drafts.csswg.org/cssom/#idl-attribute-to-css-property
func IDLAttributeToCSSProperty(s: string; dashPrefix = false): string =
  result = if dashPrefix: "-" else: ""
  for c in s:
    if c in AsciiUpperAlpha:
      result &= '-'
      result &= c.toLowerAscii()
    else:
      result &= c

proc getter(ctx: JSContext; this: CSSStyleDeclaration; atom: JSAtom):
    JSValue {.jsgetprop.} =
  var u: uint32
  if ctx.fromJS(atom, u).isSome:
    return ctx.toJS(this.item(u))
  var s: string
  if ctx.fromJS(atom, s).isNone:
    return JS_EXCEPTION
  if s.isSupportedProperty():
    return ctx.toJS(this.getPropertyValue(s))
  s = IDLAttributeToCSSProperty(s)
  if s.isSupportedProperty():
    return ctx.toJS(this.getPropertyValue(s))
  return JS_NULL #TODO eh?

proc setValue(this: CSSStyleDeclaration; i: int; cvals: seq[CSSComponentValue]):
    Err[void] =
  if i notin 0 .. this.decls.high:
    return err()
  var dummy: seq[CSSComputedEntry]
  ?parseComputedValues(dummy, this.decls[i].name, cvals)
  this.decls[i].value = cvals
  return ok()

proc setter(ctx: JSContext; this: CSSStyleDeclaration; atom: JSAtom;
    value: string): Opt[void] {.jssetprop.} =
  let cvals = parseComponentValues(value)
  var u: uint32
  if ctx.fromJS(atom, u).isSome:
    if this.setValue(int(u), cvals).isNone:
      return ok()
  else:
    var s: string
    ?ctx.fromJS(atom, s)
    if (let i = this.find(s); i != -1):
      if this.setValue(i, cvals).isNone:
        # not err! this does not throw.
        return ok()
    else:
      var dummy: seq[CSSComputedEntry]
      let val0 = parseComputedValues(dummy, s, cvals)
      if val0.isNone:
        return ok()
      this.decls.add(CSSDeclaration(name: s, value: cvals))
  this.element.attr(satStyle, $this.decls)
  ok()

proc style*(element: Element): CSSStyleDeclaration {.jsfget.} =
  if element.cachedStyle == nil:
    element.cachedStyle = CSSStyleDeclaration(element: element)
  return element.cachedStyle

# see https://html.spec.whatwg.org/multipage/links.html#link-type-stylesheet
#TODO make this somewhat compliant with ^this
proc loadResource(window: Window; link: HTMLLinkElement) =
  if not window.styling or satStylesheet notin link.relList:
    return
  if link.fetchStarted:
    return
  link.fetchStarted = true
  let href = link.attr(satHref)
  if href == "":
    return
  let url = parseURL(href, window.document.url.some)
  if url.isSome:
    let url = url.get
    let media = link.media
    if media != "":
      let cvals = parseComponentValues(media)
      let media = parseMediaQueryList(cvals)
      if not media.appliesFwdDecl(window):
        return
    let p = window.loader.fetch(
      newRequest(url)
    ).then(proc(res: JSResult[Response]): Promise[JSResult[string]] =
      if res.isSome:
        let res = res.get
        if res.getContentType() == "text/css":
          return res.text()
        res.close()
      return newResolvedPromise(JSResult[string].err(nil))
    ).then(proc(s: JSResult[string]) =
      if s.isSome:
        #TODO non-utf-8 css?
        link.sheet = parseStylesheet(s.get, window.factory)
        window.document.cachedSheetsInvalid = true
    )
    window.loadingResourcePromises.add(p)

proc getImageId(window: Window): int =
  result = window.imageId
  inc window.imageId

proc loadResource(window: Window; image: HTMLImageElement) =
  if not window.images or image.fetchStarted:
    return
  image.fetchStarted = true
  let src = image.attr(satSrc)
  if src == "":
    return
  let url = parseURL(src, window.document.url.some)
  if url.isSome:
    let url = url.get
    if window.document.url.scheme == "https" and url.scheme == "http":
      # mixed content :/
      #TODO maybe do this in loader?
      url.scheme = "https"
    let surl = $url
    window.imageURLCache.withValue(surl, p):
      if p[].expiry > getTime().utc().toTime().toUnix():
        image.bitmap = p[].bmp
        return
      elif p[].loading:
        p[].shared.add(image)
        return
    let cachedURL = CachedURLImage(expiry: -1, loading: true)
    window.imageURLCache[surl] = cachedURL
    let headers = newHeaders({"Accept": "*/*"})
    let p = window.loader.fetch(newRequest(url, headers = headers)).then(
      proc(res: JSResult[Response]): EmptyPromise =
        if res.isNone:
          return newResolvedPromise()
        let response = res.get
        let contentType = response.getContentType("image/x-unknown")
        if not contentType.startsWith("image/"):
          return newResolvedPromise()
        let cacheId = window.loader.addCacheFile(response.outputId,
          window.loader.clientPid)
        let url = newURL("img-codec+" & contentType.after('/') & ":decode")
        if url.isNone:
          return newResolvedPromise()
        let request = newRequest(
          url.get,
          httpMethod = hmPost,
          headers = newHeaders({"Cha-Image-Info-Only": "1"}),
          body = RequestBody(t: rbtOutput, outputId: response.outputId),
        )
        let r = window.loader.fetch(request)
        response.resume()
        response.close()
        var expiry = -1i64
        if "Cache-Control" in response.headers:
          for hdr in response.headers.table["Cache-Control"]:
            var i = hdr.find("max-age=")
            if i != -1:
              i = hdr.skipBlanks(i + "max-age=".len)
              let s = hdr.until(AllChars - AsciiDigit, i)
              let pi = parseInt64(s)
              if pi.isSome:
                expiry = getTime().utc().toTime().toUnix() + pi.get
              break
        cachedURL.loading = false
        cachedURL.expiry = expiry
        return r.then(proc(res: JSResult[Response]) =
          if res.isNone:
            return
          let response = res.get
          # close immediately; all data we're interested in is in the headers.
          response.resume()
          response.close()
          if "Cha-Image-Dimensions" notin response.headers.table:
            window.console.error("Cha-Image-Dimensions missing in",
              $response.url)
            return
          let dims = response.headers.table["Cha-Image-Dimensions"][0]
          let width = parseUInt64(dims.until('x'), allowSign = false)
          let height = parseUInt64(dims.after('x'), allowSign = false)
          if width.isNone or height.isNone or width.get > uint64(int.high) or
              height.get > uint64(int.high):
            window.console.error("wrong Cha-Image-Dimensions in", $response.url)
            return
          let bmp = NetworkBitmap(
            width: int(width.get),
            height: int(height.get),
            cacheId: cacheId,
            imageId: window.getImageId(),
            contentType: contentType
          )
          image.bitmap = bmp
          cachedURL.bmp = bmp
          for share in cachedURL.shared:
            share.bitmap = bmp
            share.setInvalid()
          image.setInvalid()
        )
      )
    window.loadingResourcePromises.add(p)

proc reflectEvent(element: Element; target: EventTarget; name, ctype: StaticAtom;
    value: string) =
  let document = element.document
  let ctx = document.window.jsctx
  let urls = document.baseURL.serialize(excludepassword = true)
  let fun = ctx.newFunction(["event"], value)
  assert ctx != nil
  if JS_IsException(fun):
    document.window.console.error("Exception in body content attribute of",
      urls, ctx.getExceptionMsg())
  else:
    let jsTarget = ctx.toJS(target)
    ctx.definePropertyC(jsTarget, $name, JS_DupValue(ctx, fun))
    JS_FreeValue(ctx, jsTarget)
    #TODO this is subtly wrong. In fact, we should not pass `fun'
    # directly here, but a wrapper function that calls fun. Currently
    # you can run removeEventListener with element.onclick, that should
    # not work.
    doAssert ctx.addEventListener(target, document.toAtom(ctype), fun).isSome
  JS_FreeValue(ctx, fun)

proc reflectAttr(element: Element; name: CAtom; value: Option[string]) =
  let name = element.document.toStaticAtom(name)
  template reflect_str(element: Element; n: StaticAtom; val: untyped) =
    if name == n:
      element.val = value.get("")
      return
  template reflect_atom(element: Element; n: StaticAtom; val: untyped) =
    if name == n:
      if value.isSome:
        element.val = element.document.toAtom(value.get)
      else:
        element.val = CAtomNull
      return
  template reflect_bool(element: Element; n: StaticAtom; val: untyped) =
    if name == n:
      element.val = true
      return
  template reflect_domtoklist0(element: Element; val: untyped) =
    element.val.toks.setLen(0)
    if value.isSome:
      for x in value.get.split(AsciiWhitespace):
        if x != "":
          let a = element.document.toAtom(x)
          if a notin element.val:
            element.val.toks.add(a)
  template reflect_domtoklist(element: Element; n: StaticAtom; val: untyped) =
    if name == n:
      element.reflect_domtoklist0 val
      return
  element.reflect_atom satId, id
  element.reflect_atom satName, name
  element.reflect_domtoklist satClass, classList
  #TODO internalNonce
  if name == satStyle:
    if value.isSome:
      element.cachedStyle = newCSSStyleDeclaration(element, value.get)
    else:
      element.cachedStyle = nil
    return
  if name == satOnclick and element.scriptingEnabled:
    element.reflectEvent(element, name, satClick, value.get(""))
    return
  case element.tagType
  of TAG_BODY:
    if name == satOnload and element.scriptingEnabled:
      element.reflectEvent(element.document.window, name, satLoad, value.get(""))
      return
  of TAG_INPUT:
    let input = HTMLInputElement(element)
    input.reflect_str satValue, value
    if name == satChecked:
      input.setChecked(value.isSome)
    elif name == satType:
      input.inputType = parseEnumNoCase[InputType](value.get("")).get(itText)
  of TAG_OPTION:
    let option = HTMLOptionElement(element)
    option.reflect_bool satSelected, selected
  of TAG_BUTTON:
    let button = HTMLButtonElement(element)
    button.reflect_str satValue, value
    if name == satType:
      button.ctype = parseEnumNoCase[ButtonType](value.get("")).get(btSubmit)
  of TAG_LINK:
    let link = HTMLLinkElement(element)
    if name == satRel:
      link.reflect_domtoklist0 relList # do not return
    if link.isConnected and satStylesheet in link.relList and
        name in {satHref, satRel}:
      link.fetchStarted = false
      let window = link.document.window
      if window != nil:
        window.loadResource(link)
  of TAG_A:
    let anchor = HTMLAnchorElement(element)
    anchor.reflect_domtoklist satRel, relList
  of TAG_AREA:
    let area = HTMLAreaElement(element)
    area.reflect_domtoklist satRel, relList
  of TAG_CANVAS:
    if element.scriptingEnabled and name in {satWidth, satHeight}:
      let w = element.attrul(satWidth).get(300)
      let h = element.attrul(satHeight).get(150)
      if w <= uint64(int.high) and h <= uint64(int.high):
        let w = int(w)
        let h = int(h)
        let canvas = HTMLCanvasElement(element)
        if canvas.bitmap == nil or canvas.bitmap.width != w or
            canvas.bitmap.height != h:
          let window = element.document.window
          if canvas.ctx2d != nil and canvas.ctx2d.ps != nil:
            let i = window.pendingCanvasCtls.find(canvas.ctx2d)
            window.pendingCanvasCtls.del(i)
            canvas.ctx2d.ps.sclose()
            canvas.ctx2d = nil
          canvas.bitmap = NetworkBitmap(
            contentType: "image/x-cha-canvas",
            imageId: window.getImageId(),
            width: w,
            height: h
          )
  of TAG_IMG:
    let image = HTMLImageElement(element)
    # https://html.spec.whatwg.org/multipage/images.html#relevant-mutations
    if name == satSrc:
      image.fetchStarted = false
      let window = image.document.window
      if window != nil:
        window.loadResource(image)
  else: discard

func cmpAttrName(a: AttrData; b: CAtom): int =
  return cmp(int(a.qualifiedName), int(b))

# Returns the attr index if found, or the negation - 1 of an upper bound
# (where a new attr with the passed name may be inserted).
func findAttrOrNext(element: Element; qualName: CAtom): int =
  for i, data in element.attrs:
    if data.qualifiedName == qualName:
      return i
    if int(data.qualifiedName) > int(qualName):
      return -(i + 1)
  return -(element.attrs.len + 1)

proc attr*(element: Element; name: CAtom; value: string) =
  let i = element.findAttrOrNext(name)
  if i >= 0:
    element.attrs[i].value = value
    element.invalidateCollections()
    element.setInvalid()
  else:
    element.attrs.insert(AttrData(
      qualifiedName: name,
      localName: name,
      value: value
    ), -(i + 1))
  element.reflectAttr(name, some(value))

proc attr*(element: Element; name: StaticAtom; value: string) =
  element.attr(element.document.toAtom(name), value)

proc attrns*(element: Element; localName: CAtom; prefix: NamespacePrefix;
    namespace: Namespace; value: sink string) =
  if prefix == NO_PREFIX and namespace == NO_NAMESPACE:
    element.attr(localName, value)
    return
  let namespace = element.document.toAtom(namespace)
  let i = element.findAttrNS(namespace, localName)
  var prefixAtom, qualifiedName: CAtom
  if prefix != NO_PREFIX:
    prefixAtom = element.document.toAtom(prefix)
    let tmp = $prefix & ':' & element.document.toStr(localName)
    qualifiedName = element.document.toAtom(tmp)
  else:
    qualifiedName = localName
  if i != -1:
    element.attrs[i].prefix = prefixAtom
    element.attrs[i].qualifiedName = qualifiedName
    element.attrs[i].value = value
    element.invalidateCollections()
    element.setInvalid()
  else:
    element.attrs.insert(AttrData(
      prefix: prefixAtom,
      localName: localName,
      qualifiedName: qualifiedName,
      namespace: namespace,
      value: value
    ), element.attrs.upperBound(qualifiedName, cmpAttrName))
  element.reflectAttr(qualifiedName, some(value))

proc attrl(element: Element; name: StaticAtom; value: int32) =
  element.attr(name, $value)

proc attrul(element: Element; name: StaticAtom; value: uint32) =
  element.attr(name, $value)

proc attrulgz(element: Element; name: StaticAtom; value: uint32) =
  if value > 0:
    element.attrul(name, value)

proc setAttribute(element: Element; qualifiedName, value: string):
    Err[DOMException] {.jsfunc.} =
  ?validateAttributeName(qualifiedName)
  let qualifiedName = if element.namespace == Namespace.HTML and
      not element.document.isxml:
    element.document.toAtom(qualifiedName.toLowerAscii())
  else:
    element.document.toAtom(qualifiedName)
  element.attr(qualifiedName, value)
  return ok()

proc setAttributeNS(element: Element; namespace, qualifiedName,
    value: string): Err[DOMException] {.jsfunc.} =
  ?validateAttributeQName(qualifiedName)
  let ps = qualifiedName.until(':')
  let prefix = if ps.len < qualifiedName.len: ps else: ""
  let localName = element.document.toAtom(qualifiedName.substr(prefix.len))
  #TODO atomize here
  if prefix != "" and namespace == "" or
      prefix == "xml" and namespace != $Namespace.XML or
      (qualifiedName == "xmlns" or prefix == "xmlns") and
        namespace != $Namespace.XMLNS or
      namespace == $Namespace.XMLNS and qualifiedName != "xmlns" and
        prefix != "xmlns":
    return errDOMException("Unexpected namespace", "NamespaceError")
  let qualifiedName = element.document.toAtom(qualifiedName)
  let namespace = element.document.toAtom(namespace)
  let i = element.findAttrNS(namespace, localName)
  if i != -1:
    element.attrs[i].value = value
  else:
    element.attrs.add(AttrData(
      localName: localName,
      namespace: namespace,
      qualifiedName: qualifiedName,
      value: value
    ))
  return ok()

proc removeAttribute(element: Element; qualifiedName: string) {.jsfunc.} =
  let i = element.findAttr(qualifiedName)
  if i != -1:
    element.delAttr(i)

proc removeAttributeNS(element: Element; namespace, localName: string)
    {.jsfunc.} =
  let i = element.findAttrNS(namespace, localName)
  if i != -1:
    element.delAttr(i)

proc toggleAttribute(element: Element; qualifiedName: string;
    force = none(bool)): DOMResult[bool] {.jsfunc.} =
  ?validateAttributeName(qualifiedName)
  let qualifiedName = element.normalizeAttrQName(qualifiedName)
  if not element.attrb(qualifiedName):
    if force.get(true):
      element.attr(qualifiedName, "")
      return ok(true)
    return ok(false)
  if not force.get(false):
    let i = element.findAttr(qualifiedName)
    if i != -1:
      element.delAttr(i)
    return ok(false)
  return ok(true)

proc value(attr: Attr; s: string) {.jsfset.} =
  attr.ownerElement.attr(attr.data.qualifiedName, s)

proc setNamedItem(map: NamedNodeMap; attr: Attr): DOMResult[Attr]
    {.jsfunc.} =
  if attr.ownerElement == map.element:
    # Setting attr on its owner element does nothing, since the "get an
    # attribute by namespace and local name" step is used for retrieval
    # (which will always return self).
    return
  if attr.jsOwnerElement != nil:
    return errDOMException("Attribute is currently in use",
      "InUseAttributeError")
  let i = map.element.findAttrNS(attr.data.namespace, attr.data.localName)
  attr.ownerElement = map.element
  if i != -1:
    map.element.attrs[i] = attr.data
    return ok(attr)
  map.element.attrs.add(attr.data)
  return ok(nil)

proc setNamedItemNS(map: NamedNodeMap; attr: Attr): DOMResult[Attr]
    {.jsfunc.} =
  return map.setNamedItem(attr)

proc removeNamedItem(map: NamedNodeMap; qualifiedName: string):
    DOMResult[Attr] {.jsfunc.} =
  let i = map.element.findAttr(qualifiedName)
  if i != -1:
    let attr = map.getAttr(i)
    map.element.delAttr(i, keep = true)
    return ok(attr)
  return errDOMException("Item not found", "NotFoundError")

proc removeNamedItemNS(map: NamedNodeMap; namespace, localName: string):
    DOMResult[Attr] {.jsfunc.} =
  let i = map.element.findAttrNS(namespace, localName)
  if i != -1:
    let attr = map.getAttr(i)
    map.element.delAttr(i, keep = true)
    return ok(attr)
  return errDOMException("Item not found", "NotFoundError")

proc jsId(element: Element; id: string) {.jsfset: "id".} =
  element.attr(satId, id)

# Pass an index to avoid searching for the node in parent's child list.
proc remove*(node: Node; suppressObservers: bool) =
  let parent = node.parentNode
  assert parent != nil
  assert node.index != -1
  #TODO live ranges
  #TODO NodeIterator
  for i in node.index ..< parent.childList.len - 1:
    parent.childList[i] = parent.childList[i + 1]
    parent.childList[i].index = i
  parent.childList.setLen(parent.childList.len - 1)
  parent.invalidateCollections()
  node.invalidateCollections()
  if parent of Element:
    Element(parent).setInvalid()
  node.parentNode = nil
  node.index = -1
  if node.document != nil and (node of HTMLStyleElement or
      node of HTMLLinkElement):
    node.document.cachedSheetsInvalid = true

  #TODO assigned, shadow root, shadow root again, custom nodes, registered
  # observers
  #TODO not suppress observers => queue tree mutation record

proc remove*(node: Node) {.jsfunc.} =
  if node.parentNode != nil:
    node.remove(suppressObservers = false)

proc adopt(document: Document; node: Node) =
  let oldDocument = node.document
  if node.parentNode != nil:
    remove(node)
  if oldDocument != document:
    #TODO shadow root
    for desc in node.descendants:
      desc.internalDocument = document
      if desc of Element:
        for attr in Element(desc).attributes.attrlist:
          attr.internalDocument = document
    #TODO custom elements
    #..adopting steps

proc resetElement*(element: Element) =
  case element.tagType
  of TAG_INPUT:
    let input = HTMLInputElement(element)
    case input.inputType
    of itCheckbox, itRadio:
      input.setChecked(input.attrb(satChecked))
    of itFile:
      input.file = nil
    else:
      input.value = input.attr(satValue)
    input.setInvalid()
  of TAG_SELECT:
    let select = HTMLSelectElement(element)
    if not select.attrb(satMultiple):
      if select.attrul(satSize).get(1) == 1:
        var i = 0
        var firstOption: HTMLOptionElement
        for option in select.options:
          if firstOption == nil:
            firstOption = option
          if option.selected:
            inc i
        if i == 0 and firstOption != nil:
          firstOption.selected = true
        elif i > 2:
          # Set the selectedness of all but the last selected option element to
          # false.
          var j = 0
          for option in select.options:
            if j == i: break
            if option.selected:
              option.selected = false
              inc j
  of TAG_TEXTAREA:
    let textarea = HTMLTextAreaElement(element)
    textarea.value = textarea.childTextContent()
    textarea.setInvalid()
  else: discard

proc setForm*(element: FormAssociatedElement; form: HTMLFormElement) =
  case element.tagType
  of TAG_INPUT:
    let input = HTMLInputElement(element)
    input.form = form
    form.controls.add(input)
  of TAG_SELECT:
    let select = HTMLSelectElement(element)
    select.form = form
    form.controls.add(select)
  of TAG_BUTTON:
    let button = HTMLButtonElement(element)
    button.form = form
    form.controls.add(button)
  of TAG_TEXTAREA:
    let textarea = HTMLTextAreaElement(element)
    textarea.form = form
    form.controls.add(textarea)
  of TAG_FIELDSET, TAG_OBJECT, TAG_OUTPUT, TAG_IMG:
    discard #TODO
  else: assert false

proc resetFormOwner(element: FormAssociatedElement) =
  element.parserInserted = false
  if element.form != nil:
    if element.tagType notin ListedElements:
      return
    let lastForm = element.findAncestor({TAG_FORM})
    if not element.attrb(satForm) and lastForm == element.form:
      return
  element.form = nil
  if element.tagType in ListedElements and element.isConnected:
    let form = element.document.getElementById(element.attr(satForm))
    if form of HTMLFormElement:
      element.setForm(HTMLFormElement(form))

proc elementInsertionSteps(element: Element) =
  if element of HTMLOptionElement:
    if element.parentElement != nil:
      let parent = element.parentElement
      var select: HTMLSelectElement
      if parent of HTMLSelectElement:
        select = HTMLSelectElement(parent)
      elif parent.tagType == TAG_OPTGROUP and parent.parentElement != nil and
          parent.parentElement of HTMLSelectElement:
        select = HTMLSelectElement(parent.parentElement)
      if select != nil:
        select.resetElement()
  elif element of FormAssociatedElement:
    let element = FormAssociatedElement(element)
    if element.parserInserted:
      return
    element.resetFormOwner()
  elif element of HTMLLinkElement:
    let window = element.document.window
    if window != nil:
      let link = HTMLLinkElement(element)
      window.loadResource(link)
  elif element of HTMLImageElement:
    let window = element.document.window
    if window != nil:
      let image = HTMLImageElement(element)
      window.loadResource(image)

proc insertionSteps(insertedNode: Node) =
  if insertedNode of Element:
    let element = Element(insertedNode)
    element.elementInsertionSteps()

func isValidParent(node: Node): bool =
  return node of Element or node of Document or node of DocumentFragment

func isValidChild(node: Node): bool =
  return node.isValidParent or node of DocumentType or node of CharacterData

func checkParentValidity(parent: Node): Err[DOMException] =
  if parent.isValidParent():
    return ok()
  const msg = "Parent must be a document, a document fragment, or an element."
  return errDOMException(msg, "HierarchyRequestError")

# WARNING the ordering of the arguments in the standard is whack so this
# doesn't match that
func preInsertionValidity*(parent, node, before: Node): Err[DOMException] =
  ?checkParentValidity(parent)
  if node.isHostIncludingInclusiveAncestor(parent):
    return errDOMException("Parent must be an ancestor",
      "HierarchyRequestError")
  if before != nil and before.parentNode != parent:
    return errDOMException("Reference node is not a child of parent",
      "NotFoundError")
  if not node.isValidChild():
    return errDOMException("Node is not a valid child", "HierarchyRequestError")
  if node of Text and parent of Document:
    return errDOMException("Cannot insert text into document",
      "HierarchyRequestError")
  if node of DocumentType and not (parent of Document):
    return errDOMException("Document type can only be inserted into document",
      "HierarchyRequestError")
  if parent of Document:
    if node of DocumentFragment:
      let elems = node.countChildren(Element)
      if elems > 1 or node.hasChild(Text):
        return errDOMException("Document fragment has invalid children",
          "HierarchyRequestError")
      elif elems == 1 and (parent.hasChild(Element) or
          before != nil and (before of DocumentType or
          before.hasNextSibling(DocumentType))):
        return errDOMException("Document fragment has invalid children",
          "HierarchyRequestError")
    elif node of Element:
      if parent.hasChild(Element):
        return errDOMException("Document already has an element child",
          "HierarchyRequestError")
      elif before != nil and (before of DocumentType or
            before.hasNextSibling(DocumentType)):
        return errDOMException("Cannot insert element before document type",
          "HierarchyRequestError")
    elif node of DocumentType:
      if parent.hasChild(DocumentType) or
          before != nil and before.hasPreviousSibling(Element) or
          before == nil and parent.hasChild(Element):
        const msg = "Cannot insert document type before an element node"
        return errDOMException(msg, "HierarchyRequestError")
    else: discard
  return ok() # no exception reached

proc insertNode(parent, node, before: Node) =
  parent.document.adopt(node)
  parent.childList.setLen(parent.childList.len + 1)
  if before == nil:
    node.index = parent.childList.high
  else:
    node.index = before.index
    for i in countdown(parent.childList.high - 1, node.index):
      parent.childList[i + 1] = parent.childList[i]
      parent.childList[i + 1].index = i + 1
  parent.childList[node.index] = node
  node.parentNode = parent
  node.invalidateCollections()
  parent.invalidateCollections()
  if node.document != nil and (node of HTMLStyleElement or
      node of HTMLLinkElement):
    node.document.cachedSheetsInvalid = true
  if node of Element:
    #TODO shadow root
    insertionSteps(node)

# WARNING ditto
proc insert*(parent, node, before: Node; suppressObservers = false) =
  var nodes = if node of DocumentFragment:
    node.childList
  else:
    @[node]
  let count = nodes.len
  if count == 0:
    return
  if node of DocumentFragment:
    for i in countdown(node.childList.high, 0):
      node.childList[i].remove(true)
    #TODO tree mutation record
  if before != nil:
    #TODO live ranges
    discard
  if parent of Element:
    Element(parent).setInvalid()
  for node in nodes:
    insertNode(parent, node, before)

proc insertBefore*(parent, node, before: Node): DOMResult[Node] {.jsfunc.} =
  ?parent.preInsertionValidity(node, before)
  let referenceChild = if before == node:
    node.nextSibling
  else:
    before
  parent.insert(node, referenceChild)
  return ok(node)

proc appendChild(parent, node: Node): DOMResult[Node] {.jsfunc.} =
  return parent.insertBefore(node, nil)

proc append*(parent, node: Node) =
  discard parent.appendChild(node)

#TODO replaceChild

proc removeChild(parent, node: Node): DOMResult[Node] {.jsfunc.} =
  if node.parentNode != parent:
    return errDOMException("Node is not a child of parent", "NotFoundError")
  node.remove()
  return ok(node)

# WARNING the ordering of the arguments in the standard is whack so this
# doesn't match that
# Note: the standard returns child if not err. We don't, it's just a
# pointless copy.
proc replace*(parent, child, node: Node): Err[DOMException] =
  ?checkParentValidity(parent)
  if node.isHostIncludingInclusiveAncestor(parent):
    return errDOMException("Parent must be an ancestor",
      "HierarchyRequestError")
  if child.parentNode != parent:
    return errDOMException("Node to replace is not a child of parent",
      "NotFoundError")
  if not node.isValidChild():
    return errDOMException("Node is not a valid child", "HierarchyRequesError")
  if node of Text and parent of Document or
      node of DocumentType and not (parent of Document):
    return errDOMException("Replacement cannot be placed in parent",
      "HierarchyRequesError")
  let childNextSibling = child.nextSibling
  let childPreviousSibling = child.previousSibling
  if parent of Document:
    if node of DocumentFragment:
      let elems = node.countChildren(Element)
      if elems > 1 or node.hasChild(Text):
        return errDOMException("Document fragment has invalid children",
          "HierarchyRequestError")
      elif elems == 1 and (parent.hasChildExcept(Element, child) or
          childNextSibling != nil and childNextSibling of DocumentType):
        return errDOMException("Document fragment has invalid children",
          "HierarchyRequestError")
    elif node of Element:
      if parent.hasChildExcept(Element, child):
        return errDOMException("Document already has an element child",
          "HierarchyRequestError")
      elif childNextSibling != nil and childNextSibling of DocumentType:
        return errDOMException("Cannot insert element before document type ",
          "HierarchyRequestError")
    elif node of DocumentType:
      if parent.hasChildExcept(DocumentType, child) or
          childPreviousSibling != nil and childPreviousSibling of DocumentType:
        const msg = "Cannot insert document type before an element node"
        return errDOMException(msg, "HierarchyRequestError")
  let referenceChild = if childNextSibling == node:
    node.nextSibling
  else:
    childNextSibling
  #NOTE the standard says "if parent is not null", but the adoption step
  # that made it necessary has been removed.
  child.remove(suppressObservers = true)
  parent.insert(node, referenceChild, suppressObservers = true)
  #TODO tree mutation record
  return ok()

proc replaceAll(parent, node: Node) =
  var removedNodes = parent.childList # copy
  for child in removedNodes:
    child.remove(true)
  assert parent != node
  if node != nil:
    if node of DocumentFragment:
      var addedNodes = node.childList # copy
      for child in addedNodes:
        parent.append(child)
    else:
      parent.append(node)
  #TODO tree mutation record

proc createTextNode*(document: Document; data: string): Text {.jsfunc.} =
  return newText(document, data)

proc textContent*(node: Node; data: Option[string]) {.jsfset.} =
  if node of Element or node of DocumentFragment:
    let x = if data.isSome:
      node.document.createTextNode(data.get)
    else:
      nil
    node.replaceAll(x)
  elif node of CharacterData:
    CharacterData(node).data = data.get("")
  elif node of Attr:
    value(Attr(node), data.get(""))

proc reset*(form: HTMLFormElement) =
  for control in form.controls:
    control.resetElement()
    control.setInvalid()

proc renderBlocking*(element: Element): bool =
  if "render" in element.attr(satBlocking).split(AsciiWhitespace):
    return true
  if element of HTMLScriptElement:
    let element = HTMLScriptElement(element)
    if element.ctype == stClassic and element.parserDocument != nil and
        not element.attrb(satAsync) and not element.attrb(satDefer):
      return true
  return false

proc blockRendering*(element: Element) =
  let document = element.document
  if document.contentType == "text/html" and document.body == nil:
    element.document.renderBlockingElements.add(element)

proc markAsReady(element: HTMLScriptElement; res: ScriptResult) =
  element.scriptResult = res
  if element.onReady != nil:
    element.onReady()
    element.onReady = nil
  element.delayingTheLoadEvent = false

type OnCompleteProc = proc(element: HTMLScriptElement, res: ScriptResult)

proc fetchClassicScript(element: HTMLScriptElement; url: URL;
    options: ScriptOptions; cors: CORSAttribute; cs: Charset;
    onComplete: OnCompleteProc) =
  let window = element.document.window
  if not element.scriptingEnabled:
    element.onComplete(ScriptResult(t: srtNull))
    return
  let request = createPotentialCORSRequest(url, rdScript, cors)
  request.client = some(window.settings)
  #TODO make this non-blocking somehow
  let response = window.loader.doRequest(request.request)
  if response.res != 0:
    element.onComplete(ScriptResult(t: srtNull))
    return
  response.resume()
  let s = response.body.recvAll()
  let cs = if cs == CHARSET_UNKNOWN: CHARSET_UTF_8 else: cs
  let source = s.decodeAll(cs)
  response.body.sclose()
  let script = window.jsctx.newClassicScript(source, url, options, false)
  element.onComplete(script)

#TODO settings object
proc fetchDescendantsAndLink(element: HTMLScriptElement; script: Script;
    destination: RequestDestination; onComplete: OnCompleteProc)
proc fetchSingleModule(element: HTMLScriptElement; url: URL;
    destination: RequestDestination; options: ScriptOptions;
    referrer: URL; isTopLevel: bool; onComplete: OnCompleteProc)

#TODO settings object
proc fetchExternalModuleGraph(element: HTMLScriptElement; url: URL;
    options: ScriptOptions; onComplete: OnCompleteProc) =
  let window = element.document.window
  if not element.scriptingEnabled:
    element.onComplete(ScriptResult(t: srtNull))
    return
  window.importMapsAllowed = false
  element.fetchSingleModule(
    url,
    rdScript,
    options,
    parseURL("about:client").get,
    isTopLevel = true,
    onComplete = proc(element: HTMLScriptElement; res: ScriptResult) =
      if res.t == srtNull:
        element.onComplete(res)
      else:
        element.fetchDescendantsAndLink(res.script, rdScript, onComplete)
  )

proc fetchDescendantsAndLink(element: HTMLScriptElement; script: Script;
    destination: RequestDestination; onComplete: OnCompleteProc) =
  discard

#TODO settings object
proc fetchSingleModule(element: HTMLScriptElement; url: URL;
    destination: RequestDestination; options: ScriptOptions,
    referrer: URL; isTopLevel: bool; onComplete: OnCompleteProc) =
  discard #TODO implement
  let moduleType = "javascript"
  #TODO moduleRequest
  let window = element.document.window
  let settings = window.settings
  let i = settings.moduleMap.find(url, moduleType)
  if i != -1:
    if settings.moduleMap[i].value.t == srtFetching:
      #TODO await value
      assert false
    element.onComplete(settings.moduleMap[i].value)
    return
  let destination = moduleType.moduleTypeToRequestDest(destination)
  let mode = if destination in {rdWorker, rdSharedworker, rdServiceworker}:
    rmSameOrigin
  else:
    rmCors
  #TODO client
  #TODO initiator type
  let request = JSRequest(
    request: newRequest(
      url,
      referrer = referrer,
    ),
    destination: destination,
    mode: mode
  )
  #TODO set up module script request
  #TODO performFetch
  let ctx = window.jsctx
  let v = ctx.toJS(request)
  let p = window.windowFetch(v)
  JS_FreeValue(ctx, v)
  if p.isSome:
    p.get.then(proc(res: JSResult[Response]) =
      if res.isNone:
        let res = ScriptResult(t: srtNull)
        settings.moduleMap.set(url, moduleType, res, ctx)
        element.onComplete(res)
        return
      let res = res.get
      let contentType = res.getContentType()
      let referrerPolicy = res.getReferrerPolicy()
      res.text().then(proc(s: JSResult[string]) =
        if s.isNone:
          let res = ScriptResult(t: srtNull)
          settings.moduleMap.set(url, moduleType, res, ctx)
          element.onComplete(res)
          return
        if contentType.isJavaScriptType():
          let res = ctx.newJSModuleScript(s.get, element.document.baseURL,
            options)
          if referrerPolicy.isSome:
            res.script.options.referrerPolicy = referrerPolicy
          settings.moduleMap.set(url, moduleType, res, ctx)
          element.onComplete(res)
        else:
          #TODO non-JS modules
          discard
      )
    )

proc execute*(element: HTMLScriptElement) =
  let document = element.document
  if document != element.preparationTimeDocument:
    return
  let i = document.renderBlockingElements.find(element)
  if i != -1:
    document.renderBlockingElements.delete(i)
  #TODO this should work eventually (when module & importmap are implemented)
  #assert element.scriptResult != nil
  if element.scriptResult == nil:
    return
  if element.scriptResult.t == srtNull:
    #TODO fire error event
    return
  let needsInc = element.external or element.ctype == stModule
  if needsInc:
    inc document.ignoreDestructiveWrites
  case element.ctype
  of stClassic:
    let oldCurrentScript = document.currentScript
    #TODO not if shadow root
    document.currentScript = element
    let window = document.window
    if window != nil and window.jsctx != nil:
      let script = element.scriptResult.script
      let urls = script.baseURL.serialize(excludepassword = true)
      let ctx = window.jsctx
      if JS_IsException(script.record):
        window.console.error("Exception in document", urls,
          ctx.getExceptionMsg())
      else:
        let ret = ctx.evalFunction(script.record)
        if JS_IsException(ret):
          window.console.error("Exception in document", urls,
            ctx.getExceptionMsg())
        JS_FreeValue(ctx, ret)
    document.currentScript = oldCurrentScript
  else: discard #TODO
  if needsInc:
    dec document.ignoreDestructiveWrites

# https://html.spec.whatwg.org/multipage/scripting.html#prepare-the-script-element
proc prepare*(element: HTMLScriptElement) =
  if element.alreadyStarted:
    return
  let parserDocument = element.parserDocument
  element.parserDocument = nil
  if parserDocument != nil and not element.attrb(satAsync):
    element.forceAsync = true
  let sourceText = element.childTextContent
  if not element.attrb(satSrc) and sourceText == "":
    return
  if not element.isConnected:
    return
  let t = element.attr(satType)
  let typeString = if t != "":
    t.strip(chars = AsciiWhitespace).toLowerAscii()
  elif (let l = element.attr(satLanguage); l != ""):
    "text/" & l.toLowerAscii()
  else:
    "text/javascript"
  if typeString.isJavaScriptType():
    element.ctype = stClassic
  elif typeString == "module":
    element.ctype = stModule
  elif typeString == "importmap":
    element.ctype = stImportMap
  else:
    return
  if parserDocument != nil:
    element.parserDocument = parserDocument
    element.forceAsync = false
  element.alreadyStarted = true
  element.preparationTimeDocument = element.document
  if parserDocument != nil and
      parserDocument != element.preparationTimeDocument:
    return
  if not element.scriptingEnabled:
    return
  if element.attrb(satNomodule) and element.ctype == stClassic:
    return
  #TODO content security policy
  if element.ctype == stClassic and element.attrb(satEvent) and
      element.attrb(satFor):
    let f = element.attr(satFor).strip(chars = AsciiWhitespace)
    let event = element.attr(satEvent).strip(chars = AsciiWhitespace)
    if not f.equalsIgnoreCase("window"):
      return
    if not event.equalsIgnoreCase("onload") and
        not event.equalsIgnoreCase("onload()"):
      return
  let cs = getCharset(element.attr(satCharset))
  let encoding = if cs != CHARSET_UNKNOWN: cs else: element.document.charset
  let classicCORS = element.crossOrigin
  let parserMetadata = if element.parserDocument != nil:
    pmParserInserted
  else:
    pmNotParserInserted
  var options = ScriptOptions(
    nonce: element.internalNonce,
    integrity: element.attr(satIntegrity),
    parserMetadata: parserMetadata,
    referrerpolicy: element.referrerpolicy
  )
  #TODO settings object
  if element.attrb(satSrc):
    if element.ctype == stImportMap:
      #TODO fire error event
      return
    let src = element.attr(satSrc)
    if src == "":
      #TODO fire error event
      return
    element.external = true
    let url = element.document.parseURL(src)
    if url.isNone:
      #TODO fire error event
      return
    if element.renderBlocking:
      element.blockRendering()
    element.delayingTheLoadEvent = true
    if element in element.document.renderBlockingElements:
      options.renderBlocking = true
    if element.ctype == stClassic:
      element.fetchClassicScript(url.get, options, classicCORS, encoding,
        markAsReady)
    else:
      element.fetchExternalModuleGraph(url.get, options, markAsReady)
  else:
    let baseURL = element.document.baseURL
    if element.ctype == stClassic:
      let ctx = element.document.window.jsctx
      let script = ctx.newClassicScript(sourceText, baseURL, options)
      element.markAsReady(script)
    else:
      #TODO stModule, stImportMap
      element.markAsReady(ScriptResult(t: srtNull))
  if element.ctype == stClassic and element.attrb(satSrc) or
      element.ctype == stModule:
    let prepdoc = element.preparationTimeDocument
    if element.attrb(satAsync):
      prepdoc.scriptsToExecSoon.add(element)
      element.onReady = (proc() =
        element.execute()
        let i = prepdoc.scriptsToExecSoon.find(element)
        element.preparationTimeDocument.scriptsToExecSoon.delete(i)
      )
    elif element.parserDocument == nil:
      prepdoc.scriptsToExecInOrder.addFirst(element)
      element.onReady = (proc() =
        if prepdoc.scriptsToExecInOrder.len > 0 and
            prepdoc.scriptsToExecInOrder[0] != element:
          while prepdoc.scriptsToExecInOrder.len > 0:
            let script = prepdoc.scriptsToExecInOrder[0]
            if script.scriptResult == nil:
              break
            script.execute()
            prepdoc.scriptsToExecInOrder.shrink(1)
      )
    elif element.ctype == stModule or element.attrb(satDefer):
      element.parserDocument.scriptsToExecOnLoad.addFirst(element)
      element.onReady = (proc() =
        element.readyForParserExec = true
      )
    else:
      element.parserDocument.parserBlockingScript = element
      element.blockRendering()
      element.onReady = (proc() =
        element.readyForParserExec = true
      )
  else:
    #TODO if stClassic, parserDocument != nil, parserDocument has a style sheet
    # that is blocking scripts, either the parser is an XML parser or a HTML
    # parser with a script level <= 1
    element.execute()

#TODO options/custom elements
proc createElement(document: Document; localName: string):
    DOMResult[Element] {.jsfunc.} =
  if not localName.matchNameProduction():
    return errDOMException("Invalid character in element name",
      "InvalidCharacterError")
  let localName = if not document.isxml:
    document.toAtom(localName.toLowerAscii())
  else:
    document.toAtom(localName)
  let namespace = if not document.isxml:
    #TODO or content type is application/xhtml+xml
    Namespace.HTML
  else:
    NO_NAMESPACE
  return ok(document.newHTMLElement(localName, namespace))

#TODO createElementNS

proc createDocumentFragment(document: Document): DocumentFragment {.jsfunc.} =
  return newDocumentFragment(document)

proc createDocumentType(implementation: var DOMImplementation; qualifiedName,
    publicId, systemId: string): DOMResult[DocumentType] {.jsfunc.} =
  if not qualifiedName.matchQNameProduction():
    return errDOMException("Invalid character in document type name",
      "InvalidCharacterError")
  let document = implementation.document
  return ok(document.newDocumentType(qualifiedName, publicId, systemId))

proc createHTMLDocument(ctx: JSContext; implementation: var DOMImplementation;
    title = none(string)): Document {.jsfunc.} =
  let doc = newDocument(ctx)
  doc.contentType = "text/html"
  doc.append(doc.newDocumentType("html", "", ""))
  let html = doc.newHTMLElement(TAG_HTML)
  doc.append(html)
  let head = doc.newHTMLElement(TAG_HEAD)
  html.append(head)
  if title.isSome:
    let titleElement = doc.newHTMLElement(TAG_TITLE)
    titleElement.append(doc.newText(title.get))
    head.append(titleElement)
  html.append(doc.newHTMLElement(TAG_BODY))
  #TODO set origin
  return doc

proc hasFeature(implementation: var DOMImplementation): bool {.jsfunc.} =
  return true

proc createCDATASection(document: Document; data: string):
    DOMResult[CDATASection] {.jsfunc.} =
  if not document.isxml:
    return errDOMException("CDATA sections are not supported in HTML",
      "NotSupportedError")
  if "]]>" in data:
    return errDOMException("CDATA sections may not contain the string ]]>",
      "InvalidCharacterError")
  return ok(newCDATASection(document, data))

proc createComment*(document: Document; data: string): Comment {.jsfunc.} =
  return newComment(document, data)

proc createProcessingInstruction(document: Document; target, data: string):
    DOMResult[ProcessingInstruction] {.jsfunc.} =
  if not target.matchNameProduction() or "?>" in data:
    return errDOMException("Invalid data for processing instruction",
      "InvalidCharacterError")
  return ok(newProcessingInstruction(document, target, data))

proc clone(node: Node; document = none(Document), deep = false): Node =
  let document = document.get(node.document)
  let copy = if node of Element:
    #TODO is value
    let element = Element(node)
    let x = document.newHTMLElement(element.localName, element.namespace,
      element.namespacePrefix)
    x.attrs = element.attrs
    #TODO namespaced attrs?
    # Cloning steps
    if x of HTMLScriptElement:
      let x = HTMLScriptElement(x)
      let element = HTMLScriptElement(element)
      x.alreadyStarted = element.alreadyStarted
    elif x of HTMLInputElement:
      let x = HTMLInputElement(x)
      let element = HTMLInputElement(element)
      x.value = element.value
      #TODO dirty value flag
      x.setChecked(element.checked)
      #TODO dirty checkedness flag
    Node(x)
  elif node of Attr:
    let attr = Attr(node)
    let data = attr.data
    let x = Attr(
      ownerElement: AttrDummyElement(
        internalDocument: attr.ownerElement.document,
        index: -1,
        attrs: @[data]
      ),
      dataIdx: 0
    )
    Node(x)
  elif node of Text:
    let text = Text(node)
    let x = document.newText(text.data)
    Node(x)
  elif node of CDATASection:
    let x = document.newCDATASection("")
    #TODO is this really correct??
    # really, I don't know. only relevant with xhtml anyway...
    Node(x)
  elif node of Comment:
    let comment = Comment(node)
    let x = document.newComment(comment.data)
    Node(x)
  elif node of ProcessingInstruction:
    let procinst = ProcessingInstruction(node)
    let x = document.newProcessingInstruction(procinst.target, procinst.data)
    Node(x)
  elif node of Document:
    let document = Document(node)
    let x = newDocument(document.factory)
    x.charset = document.charset
    x.contentType = document.contentType
    x.url = document.url
    x.isxml = document.isxml
    x.mode = document.mode
    Node(x)
  elif node of DocumentType:
    let doctype = DocumentType(node)
    let x = document.newDocumentType(doctype.name, doctype.publicId,
      doctype.systemId)
    Node(x)
  elif node of DocumentFragment:
    let x = document.newDocumentFragment()
    Node(x)
  else:
    assert false
    Node(nil)
  if deep:
    for child in node.childList:
      copy.append(child.clone(deep = true))
  return copy

proc cloneNode(node: Node; deep = false): Node {.jsfunc.} =
  #TODO shadow root
  return node.clone(deep = deep)

func equals(a, b: AttrData): bool =
  return a.qualifiedName == b.qualifiedName and
    a.namespace == b.namespace and
    a.value == b.value

func isEqualNode(node, other: Node): bool {.jsfunc.} =
  if node.childList.len != other.childList.len:
    return false
  if node of DocumentType:
    if not (other of DocumentType):
      return false
    let node = DocumentType(node)
    let other = DocumentType(other)
    if node.name != other.name or node.publicId != other.publicId or
        node.systemId != other.systemId:
      return false
  elif node of Element:
    if not (other of Element):
      return false
    let node = Element(node)
    let other = Element(other)
    if node.namespace != other.namespace or
        node.namespacePrefix != other.namespacePrefix or
        node.localName != other.localName or
        node.attrs.len != other.attrs.len:
      return false
    for i, attr in node.attrs.mpairs:
      if not attr.equals(other.attrs[i]):
        return false
  elif node of Attr:
    if not (other of Attr):
      return false
    if not Attr(node).data.equals(Attr(other).data):
      return false
  elif node of ProcessingInstruction:
    if not (other of ProcessingInstruction):
      return false
    let node = ProcessingInstruction(node)
    let other = ProcessingInstruction(other)
    if node.target != other.target or node.data != other.data:
      return false
  elif node of CharacterData:
    if node of Text and not (other of Text) or
        node of Comment and not (other of Comment):
      return false
    return CharacterData(node).data == CharacterData(other).data
  for i, child in node.childList:
    if not child.isEqualNode(other.childList[i]):
      return false
  true

func isSameNode(node, other: Node): bool {.jsfunc.} =
  return node == other

proc querySelectorAll(node: Node; q: string): seq[Element] {.jsfunc.} =
  return doqsa(node, q)

proc querySelector(node: Node; q: string): Element {.jsfunc.} =
  return doqs(node, q)

const (ReflectTable, TagReflectMap, ReflectAllStartIndex) = (func(): (
    seq[ReflectEntry],
    Table[TagType, seq[int16]],
    int16) =
  var i: int16 = 0
  while i < ReflectTable0.len:
    let x = ReflectTable0[i]
    result[0].add(x)
    if x.tags == AllTagTypes:
      break
    for tag in result[0][i].tags:
      if tag notin result[1]:
        result[1][tag] = newSeq[int16]()
      result[1][tag].add(i)
    assert result[0][i].tags.len != 0
    inc i
  result[2] = i
  while i < ReflectTable0.len:
    let x = ReflectTable0[i]
    assert x.tags == AllTagTypes
    result[0].add(x)
    inc i
)()

proc jsReflectGet(ctx: JSContext; this: JSValue; magic: cint): JSValue
    {.cdecl.} =
  let entry = ReflectTable[uint16(magic)]
  let op = this.getOpaque()
  if unlikely(not ctx.isInstanceOf(this, "Element") or op == nil):
    return JS_ThrowTypeError(ctx,
      "Reflected getter called on a value that is not an element")
  let element = cast[Element](op)
  if element.tagType notin entry.tags:
    return JS_ThrowTypeError(ctx, "Invalid tag type %s", element.tagType)
  case entry.t
  of rtStr: return ctx.toJS(element.attr(entry.attrname))
  of rtBool: return ctx.toJS(element.attrb(entry.attrname))
  of rtLong: return ctx.toJS(element.attrl(entry.attrname).get(entry.i))
  of rtUlong: return ctx.toJS(element.attrul(entry.attrname).get(entry.u))
  of rtUlongGz: return ctx.toJS(element.attrulgz(entry.attrname).get(entry.u))
  of rtFunction:
    let val = ctx.toJS(entry.attrname)
    let atom = JS_ValueToAtom(ctx, val)
    var res = JS_NULL
    var desc: JSPropertyDescriptor
    if JS_GetOwnProperty(ctx, addr desc, this, atom) > 0:
      JS_FreeValue(ctx, desc.setter)
      JS_FreeValue(ctx, desc.getter)
      res = desc.value
    JS_FreeValue(ctx, val)
    JS_FreeAtom(ctx, atom)
    return res

proc jsReflectSet(ctx: JSContext; this, val: JSValue; magic: cint): JSValue
    {.cdecl.} =
  if unlikely(not ctx.isInstanceOf(this, "Element")):
    return JS_ThrowTypeError(ctx,
      "Reflected getter called on a value that is not an element")
  let entry = ReflectTable[uint16(magic)]
  let op = this.getOpaque()
  assert op != nil
  let element = cast[Element](op)
  if element.tagType notin entry.tags:
    return JS_ThrowTypeError(ctx, "Invalid tag type %s", element.tagType)
  case entry.t
  of rtStr:
    var x: string
    if ctx.fromJS(val, x).isSome:
      element.attr(entry.attrname, x)
  of rtBool:
    var x: bool
    if ctx.fromJS(val, x).isSome:
      if x:
        element.attr(entry.attrname, "")
      else:
        let i = element.findAttr(entry.attrname)
        if i != -1:
          element.delAttr(i)
  of rtLong:
    var x: int32
    if ctx.fromJS(val, x).isSome:
      element.attrl(entry.attrname, x)
  of rtUlong:
    var x: uint32
    if ctx.fromJS(val, x).isSome:
      element.attrul(entry.attrname, x)
  of rtUlongGz:
    var x: uint32
    if ctx.fromJS(val, x).isSome:
      element.attrulgz(entry.attrname, x)
  of rtFunction:
    if JS_IsFunction(ctx, val):
      var target: EventTarget
      assert ctx.fromJS(this, target).isSome
      ctx.definePropertyC(this, $entry.attrname, JS_DupValue(ctx, val))
      #TODO I haven't checked but this might also be wrong
      let ctype = ctx.getGlobal().toAtom(entry.ctype)
      doAssert ctx.addEventListener(target, ctype, val).isSome
  return JS_DupValue(ctx, val)

func getReflectFunctions(tags: set[TagType]): seq[TabGetSet] =
  result = @[]
  for tag in tags:
    if tag in TagReflectMap:
      for i in TagReflectMap[tag]:
        result.add(TabGetSet(
          name: ReflectTable[i].funcname,
          get: jsReflectGet,
          set: jsReflectSet,
          magic: i
        ))

func getElementReflectFunctions(): seq[TabGetSet] =
  result = @[]
  for i in ReflectAllStartIndex ..< int16(ReflectTable.len):
    let entry = ReflectTable[i]
    assert entry.tags == AllTagTypes
    result.add(TabGetSet(
      name: ReflectTable[i].funcname,
      get: jsReflectGet,
      set: jsReflectSet,
      magic: i
    ))

proc getContext*(jctx: JSContext; this: HTMLCanvasElement; contextId: string;
    options = JS_UNDEFINED): RenderingContext {.jsfunc.} =
  if contextId == "2d":
    if this.ctx2d == nil:
      create2DContext(jctx, this, options)
    return this.ctx2d
  return nil

# Note: the standard says quality should be converted in a strange way for
# backwards compat, but I don't care.
proc toBlob(ctx: JSContext; this: HTMLCanvasElement; callback: JSValue;
    contentType = "image/png"; quality = none(float64)) {.jsfunc.} =
  let contentType = contentType.toLowerAscii()
  if not contentType.startsWith("image/") or this.bitmap.cacheId == 0:
    return
  let url0 = newURL("img-codec+" & contentType.after('/') & ":encode")
  if url0.isNone:
    return
  let url = url0.get
  let headers = newHeaders({
    "Cha-Image-Dimensions": $this.bitmap.width & 'x' & $this.bitmap.height
  })
  if (var quality = quality.get(-1); 0 <= quality and quality <= 1):
    quality *= 99
    quality += 1
    headers.add("Cha-Image-Quality", $quality)
  # callback will go out of scope when we return, so capture a new reference.
  let callback = JS_DupValue(ctx, callback)
  let window = this.document.window
  let loader = window.loader
  loader.fetch(newRequest(
    newURL("img-codec+x-cha-canvas:decode").get,
    httpMethod = hmPost,
    body = RequestBody(t: rbtCache, cacheId: this.bitmap.cacheId)
  )).then(proc(res: JSResult[Response]): FetchPromise =
    if res.isNone:
      return newResolvedPromise(res)
    let res = res.get
    let p = loader.fetch(newRequest(
      url,
      httpMethod = hmPost,
      headers = headers,
      body = RequestBody(t: rbtOutput, outputId: res.outputId)
    ))
    res.resume()
    res.close()
    return p
  ).then(proc(res: JSResult[Response]) =
    if res.isNone:
      if contentType != "image/png":
        # redo as PNG.
        # Note: this sounds dumb, and is dumb, but also standard mandated so
        # whatever.
        ctx.toBlob(this, callback, "image/png") # PNG doesn't understand quality
      else: # the png encoder doesn't work...
        window.console.error("missing/broken PNG encoder")
      JS_FreeValue(ctx, callback)
      return
    res.get.blob().then(proc(blob: JSResult[Blob]) =
      let jsBlob = ctx.toJS(blob)
      let res = JS_Call(ctx, callback, JS_UNDEFINED, 1, jsBlob.toJSValueArray())
      if JS_IsException(res):
        window.console.error("Exception in canvas toBlob:",
          ctx.getExceptionMsg())
      else:
        JS_FreeValue(ctx, res)
      JS_FreeValue(ctx, callback)
    )
  )

# https://w3c.github.io/DOM-Parsing/#dfn-fragment-parsing-algorithm
proc fragmentParsingAlgorithm*(element: Element; s: string): DocumentFragment =
  #TODO xml
  let newChildren = domParseHTMLFragment(element, s)
  let fragment = element.document.newDocumentFragment()
  for child in newChildren:
    fragment.append(child)
  return fragment

proc innerHTML(element: Element; s: string) {.jsfset.} =
  #TODO shadow root
  let fragment = fragmentParsingAlgorithm(element, s)
  let ctx = if element of HTMLTemplateElement:
    HTMLTemplateElement(element).content
  else:
    element
  ctx.replaceAll(fragment)

proc outerHTML(element: Element; s: string): Err[DOMException] {.jsfset.} =
  let parent0 = element.parentNode
  if parent0 == nil:
    return ok()
  if parent0 of Document:
    let ex = newDOMException("outerHTML is disallowed for Document children",
      "NoModificationAllowedError")
    return err(ex)
  let parent = if parent0 of DocumentFragment:
    element.document.newHTMLElement(TAG_BODY)
  else:
    # neither a document, nor a document fragment => parent must be an
    # element node
    Element(parent0)
  let fragment = fragmentParsingAlgorithm(parent, s)
  return parent.replace(element, fragment)

type InsertAdjacentPosition = enum
  iapBeforeBegin = "beforebegin"
  iapAfterEnd = "afterend"
  iapAfterBegin = "afterbegin"
  iapBeforeEnd = "beforeend"

func parseInsertAdjacentPosition(s: string): DOMResult[InsertAdjacentPosition] =
  for iap in InsertAdjacentPosition.low .. InsertAdjacentPosition.high:
    if ($iap).equalsIgnoreCase(s):
      return ok(iap)
  return errDOMException("Invalid position", "SyntaxError")

# https://w3c.github.io/DOM-Parsing/#dom-element-insertadjacenthtml
proc insertAdjacentHTML(element: Element; position, text: string):
    Err[DOMException] {.jsfunc.} =
  let position = ?parseInsertAdjacentPosition(position)
  let ctx0 = case position
  of iapBeforeBegin, iapAfterEnd:
    if element.parentNode of Document or element.parentNode == nil:
      return errDOMException("Parent is not a valid element",
        "NoModificationAllowedError")
    element.parentNode
  of iapAfterBegin, iapBeforeEnd:
    Node(element)
  let document = ctx0.document
  let ctx = if not (ctx0 of Element) or not document.isxml or
      Element(ctx0).namespace == Namespace.HTML:
    document.newHTMLElement(TAG_BODY)
  else:
    Element(ctx0)
  let fragment = ctx.fragmentParsingAlgorithm(text)
  case position
  of iapBeforeBegin:
    ctx.parentNode.insert(fragment, ctx)
  of iapAfterBegin:
    ctx.insert(fragment, ctx.firstChild)
  of iapBeforeEnd:
    ctx.append(fragment)
  of iapAfterEnd:
    ctx.parentNode.insert(fragment, ctx.nextSibling)

proc registerElements(ctx: JSContext; nodeCID: JSClassID) =
  let elementCID = ctx.registerType(Element, parent = nodeCID)
  const extraGetSet = getElementReflectFunctions()
  let htmlElementCID = ctx.registerType(HTMLElement, parent = elementCID,
    hasExtraGetSet = true, extraGetSet = extraGetSet)
  template register(t: typed; tags: set[TagType]) =
    const extraGetSet = getReflectFunctions(tags)
    ctx.registerType(t, parent = htmlElementCID,
      hasExtraGetSet = true, extraGetSet = extra_getset)
  template register(t: typed; tag: TagType) =
    register(t, {tag})
  register(HTMLInputElement, TAG_INPUT)
  register(HTMLAnchorElement, TAG_A)
  register(HTMLSelectElement, TAG_SELECT)
  register(HTMLSpanElement, TAG_SPAN)
  register(HTMLOptGroupElement, TAG_OPTGROUP)
  register(HTMLOptionElement, TAG_OPTION)
  register(HTMLHeadingElement, {TAG_H1, TAG_H2, TAG_H3, TAG_H4, TAG_H5, TAG_H6})
  register(HTMLBRElement, TAG_BR)
  register(HTMLMenuElement, TAG_MENU)
  register(HTMLUListElement, TAG_UL)
  register(HTMLOListElement, TAG_OL)
  register(HTMLLIElement, TAG_LI)
  register(HTMLStyleElement, TAG_STYLE)
  register(HTMLLinkElement, TAG_LINK)
  register(HTMLFormElement, TAG_FORM)
  register(HTMLTemplateElement, TAG_TEMPLATE)
  register(HTMLUnknownElement, TAG_UNKNOWN)
  register(HTMLScriptElement, TAG_SCRIPT)
  register(HTMLBaseElement, TAG_BASE)
  register(HTMLAreaElement, TAG_AREA)
  register(HTMLButtonElement, TAG_BUTTON)
  register(HTMLTextAreaElement, TAG_TEXTAREA)
  register(HTMLLabelElement, TAG_LABEL)
  register(HTMLCanvasElement, TAG_CANVAS)
  register(HTMLImageElement, TAG_IMG)
  register(HTMLVideoElement, TAG_VIDEO)
  register(HTMLAudioElement, TAG_AUDIO)

proc addDOMModule*(ctx: JSContext) =
  let eventTargetCID = ctx.getClass("EventTarget")
  let nodeCID = ctx.registerType(Node, parent = eventTargetCID)
  ctx.defineConsts(nodeCID, NodeType, uint16)
  let nodeListCID = ctx.registerType(NodeList)
  let htmlCollectionCID = ctx.registerType(HTMLCollection)
  ctx.registerType(HTMLAllCollection, ishtmldda = true)
  ctx.registerType(HTMLFormControlsCollection, parent = htmlCollectionCID)
  ctx.registerType(RadioNodeList, parent = nodeListCID)
  ctx.registerType(Location)
  ctx.registerType(Document, parent = nodeCID)
  ctx.registerType(DOMImplementation)
  ctx.registerType(DOMTokenList)
  ctx.registerType(DOMStringMap)
  let characterDataCID = ctx.registerType(CharacterData, parent = nodeCID)
  ctx.registerType(Comment, parent = characterDataCID)
  ctx.registerType(CDATASection, parent = characterDataCID)
  ctx.registerType(DocumentFragment, parent = nodeCID)
  ctx.registerType(ProcessingInstruction, parent = characterDataCID)
  ctx.registerType(Text, parent = characterDataCID)
  ctx.registerType(DocumentType, parent = nodeCID)
  ctx.registerType(Attr, parent = nodeCID)
  ctx.registerType(NamedNodeMap)
  ctx.registerType(CanvasRenderingContext2D)
  ctx.registerType(TextMetrics)
  ctx.registerType(CSSStyleDeclaration)
  ctx.registerElements(nodeCID)