All files / widgets openable.ts

91.28% Statements 419/459
80.74% Branches 130/161
86.58% Functions 71/82
91.05% Lines 407/447

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490        94x 94x   94x       94x                                                 94x                 94x 94x       94x 94x 94x 94x 94x 94x 94x 94x             94x   94x 94x   94x                                                                       94x         376x     17x 17x 17x                                             94x                                                                                                                                                     42x       47x   47x   47x 47x   47x       47x 100x 1x     99x   99x 184x     99x 14x     99x         47x 106x 11x     95x   95x 195x     95x 12x     95x 12x     95x         47x     12x 12x 12x               47x 47x 47x 76x 107x 577x 47x 47x 47x 47x   47x 8x 8x     47x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         94x   94x   3x           10x 10x   10x     9x       13x 13x       10x                         10x 10x   10x 10x     10x 10x 10x   10x 10x 5x 5x   5x 1x     5x 5x 5x 3x 3x 3x             10x 10x     10x 10x                                 10x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               94x   94x   10x           16x                     16x 16x   16x 16x       16x   16x 78x         78x 78x 78x                                                                                                                                                                                                                                                                                                                                                                                                                                                                       94x   94x   2x           11x                                                                                                                                                                                                                                                                                                                                                                                                                                                                       94x   94x   2x           2x                     2x 2x                                                                                                                                                                                   94x   94x 94x 94x 94x   94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x   94x   94x   94x   94x   94x             94x 94x       94x     94x         94x             96x     96x 96x         94x               3x     3x 3x       94x         10x                 94x               94x       2x       94x 47x 47x                                   94x 75x           75x 75x     6x       75x 75x 71x     75x         75x     94x       28x       28x 26x     28x 28x   28x 3x         25x 23x         71x     28x     94x           47x   47x   47x       108x 15x 15x 15x     108x     47x 41x 96x               6x 6x 12x       47x     94x         47x 47x   47x 47x               47x 47x   47x                   47x 14x 14x 14x   14x 14x 14x     33x     47x 1x     47x 2x     47x 47x   47x 11x 11x     47x 47x     47x 13x 13x       13x       13x             47x       94x         47x                 47x 95x 186x 186x 186x       47x 8x   8x 8x 8x   8x 8x     8x 13x 13x   13x 13x   13x           13x       13x 9x           8x   8x 8x 5x             47x 47x 155x       47x       47x 1x     46x   46x 44x     46x 14x               46x             46x     46x 106x 106x   106x         106x   106x           106x         46x   46x 9x       47x     94x           46x 46x   46x 46x 46x       46x                 46x 120x   234x   46x 290x       46x 120x 120x 120x 120x       120x               120x   88x 88x 88x   88x   88x 78x 32x 32x           32x             46x 20x         46x   8x         46x 20x 20x 20x 20x           46x 8x 8x 8x 8x   8x 8x                         46x 3x 3x           46x 3x 3x           3x           46x       194x 164x   164x       164x   164x 64x             46x 53x   53x   106x   106x 16x             46x   46x 99x     46x 95x 95x   95x 95x   95x 95x     46x 7x           94x           13x   13x   13x   13x 2x 2x   2x 2x   2x 4x 4x 4x     2x   2x           2x               94x       78x 78x 78x 78x 78x 78x 78x 78x 78x 78x                                                                             78x             78x 78x       78x     78x                             78x               78x           78x 78x       78x    
/**
 * @module Widgets
 */
 
import * as MC from "@lisn/globals/minification-constants";
import * as MH from "@lisn/globals/minification-helpers";
 
import { settings } from "@lisn/globals/settings";
 
import { XYDirection, Position } from "@lisn/globals/types";
 
import {
  disableInitialTransition,
  hasClass,
  addClasses,
  addClassesNow,
  removeClasses,
  removeClassesNow,
  getData,
  getBooleanData,
  setData,
  setDataNow,
  setBooleanData,
  setBooleanDataNow,
  unsetBooleanData,
  unsetBooleanDataNow,
  delData,
  delDataNow,
  setHasModal,
  delHasModal,
  getStyleProp,
  setStyleProp,
  delStyleProp,
  getComputedStyleProp,
  getMaxTransitionDuration,
} from "@lisn/utils/css-alter";
import {
  wrapElement,
  wrapElementNow,
  moveElement,
  moveElementNow,
  replaceElementNow,
  getOrAssignID,
  createWrapperFor,
} from "@lisn/utils/dom-alter";
import { waitForInteractive } from "@lisn/utils/dom-events";
import {
  waitForMeasureTime,
  waitForMutateTime,
} from "@lisn/utils/dom-optimize";
import { addEventListenerTo, removeEventListenerFrom } from "@lisn/utils/event";
import { logError } from "@lisn/utils/log";
import { keyWithMaxVal } from "@lisn/utils/math";
import { toBoolean, toArrayIfSingle } from "@lisn/utils/misc";
import { waitForDelay } from "@lisn/utils/tasks";
import { isValidPosition, isValidTwoFoldPosition } from "@lisn/utils/position";
import { fetchViewportSize } from "@lisn/utils/size";
import {
  validateStrList,
  validateBoolean,
  validateBooleanOrString,
  validateString,
} from "@lisn/utils/validation";
 
import { wrapCallback } from "@lisn/modules/callback";
 
import { SizeWatcher, SizeData } from "@lisn/watchers/size-watcher";
import { ViewWatcher, ViewData } from "@lisn/watchers/view-watcher";
 
import {
  Widget,
  WidgetHandler,
  WidgetCallback,
  WidgetConfigValidator,
  WidgetConfigValidatorObject,
  registerWidget,
  getWidgetConfig,
  getDefaultWidgetSelector,
} from "@lisn/widgets/widget";
 
/* ********************
 * Base Openable
 * ********************/
 
export type OpenableCreateFn<Config extends Record<string, unknown>> = (
  element: HTMLElement,
  config?: Config,
) => Openable;
 
/**
 * Enables automatic setting up of an {@link Openable} widget from an
 * elements matching its content element selector (`[data-lisn-<name>]` or
 * `.lisn-<name>`).
 *
 * The name you specify here should generally be the same name you pass in
 * {@link OpenableConfig.name | options.name} to the {@link Openable.constructor}
 * but it does not need to be the same.
 *
 * @param name            The name of the openable. Should be in kebab-case.
 * @param newOpenable     Called for every element matching the selector.
 * @param configValidator A validator object, or a function that returns such
 *                        an object, for all options supported by the widget.
 *
 * @see {@link registerWidget}
 */
export const registerOpenable = <Config extends Record<string, unknown>>(
  name: string,
  newOpenable: OpenableCreateFn<Config>,
  configValidator?: null | WidgetConfigValidator<Config>,
) => {
  registerWidget(
    name,
    (element, config) => {
      if (MH.isHTMLElement(element)) {
        if (!Openable.get(element)) {
          return newOpenable(element, config);
        }
      } else E{
        logError(MH.usageError("Openable widget supports only HTMLElement"));
      }
 
      return null;
    },
    configValidator,
  );
};
 
/**
 * {@link Openable} is an abstract base class. You should not directly
 * instantiate it but can inherit it to create your own custom openable widget.
 *
 * **IMPORTANT:** You should not instantiate more than one {@link Openable}
 * widget, regardless of type, on a given element. Use {@link Openable.get} to
 * get an existing instance if any. If there is already an {@link Openable}
 * widget of any type on this element, it will be destroyed!
 *
 * @see {@link registerOpenable}
 */
export abstract class Openable extends Widget {
  /**
   * Opens the widget unless it is disabled.
   */
  readonly open: () => Promise<void>;
 
  /**
   * Closes the widget.
   */
  readonly close: () => Promise<void>;
 
  /**
   * Closes the widget if it is open, or opens it if it is closed (unless
   * it is disabled).
   */
  readonly toggle: () => Promise<void>;
 
  /**
   * The given handler will be called when the widget is open.
   *
   * If it returns a promise, it will be awaited upon.
   */
  readonly onOpen: (handler: WidgetHandler) => void;
 
  /**
   * The given handler will be called when the widget is closed.
   *
   * If it returns a promise, it will be awaited upon.
   */
  readonly onClose: (handler: WidgetHandler) => void;
 
  /**
   * Returns true if the widget is currently open.
   */
  readonly isOpen: () => boolean;
 
  /**
   * Returns the root element created by us that wraps the original content
   * element passed to the constructor. It is located in the content element's
   * original place.
   */
  readonly getRoot: () => HTMLElement;
 
  /**
   * Returns the element that was found to be the container. It is the closest
   * ancestor that has a `lisn-collapsible-container` class, or if no such
   * ancestor then the immediate parent of the content element.
   */
  readonly getContainer: () => HTMLElement | null;
 
  /**
   * Returns the trigger elements, if any. Note that these may be wrappers
   * around the original triggers passed.
   */
  readonly getTriggers: () => Element[];
 
  /**
   * Returns the trigger elements along with their configuration.
   */
  readonly getTriggerConfigs: () => Map<Element, OpenableTriggerConfig>;
 
  /**
   * Retrieve an existing widget by its content element or any of its triggers.
   *
   * If the element is already part of a configured {@link Openable} widget,
   * the widget instance is returned. Otherwise `null`.
   *
   * Note that trigger elements are not guaranteed to be unique among openable
   * widgets as the same element can be a trigger for multiple such widgets. If
   * the element you pass is a trigger, then the last openable widget that was
   * created for it will be returned.
   */
  static get(element: Element): Openable | null {
    // We manage the instances here since we also map associated elements and
    // not just the main content element that created the widget.
    return instances.get(element) ?? null;
  }
 
  constructor(element: HTMLElement, config: OpenableConfig) {
    super(element);
 
    const { isModal, isOffcanvas } = config;
 
    const openCallbacks = MH.newSet<WidgetCallback>();
    const closeCallbacks = MH.newSet<WidgetCallback>();
 
    let isOpen = false;
 
    // ----------
 
    const open = async () => {
      if (this.isDisabled() || isOpen) {
        return;
      }
 
      isOpen = true;
 
      for (const callback of openCallbacks) {
        await callback.invoke(this);
      }
 
      if (isModal) {
        setHasModal();
      }
 
      await setBooleanData(root, PREFIX_IS_OPEN);
    };
 
    // ----------
 
    const close = async () => {
      if (this.isDisabled() || !isOpen) {
        return;
      }
 
      isOpen = false;
 
      for (const callback of closeCallbacks) {
        await callback.invoke(this);
      }
 
      if (isModal) {
        delHasModal();
      }
 
      if (isOffcanvas) {
        scrollWrapperToTop(); // no need to await
      }
 
      await unsetBooleanData(root, PREFIX_IS_OPEN);
    };
 
    // ----------
 
    const scrollWrapperToTop = async () => {
      // Wait a bit before scrolling since the hiding of the element is animated.
      // Assume no more than 1s animation time.
      await waitForDelay(1000);
      await waitForMeasureTime();
      MH.elScrollTo(outerWrapper, {
        top: 0,
        left: 0,
      });
    };
 
    // --------------------
 
    this.open = open;
    this.close = close;
    this[MC.S_TOGGLE] = () => (isOpen ? close() : open());
    this.onOpen = (handler) => openCallbacks.add(wrapCallback(handler));
    this.onClose = (handler) => closeCallbacks.add(wrapCallback(handler));
    this.isOpen = () => isOpen;
    this.getRoot = () => root;
    this.getContainer = () => container;
    this.getTriggers = () => [...triggers.keys()];
    this.getTriggerConfigs = () => MH.newMap([...triggers.entries()]);
 
    this.onDestroy(() => {
      openCallbacks.clear();
      closeCallbacks.clear();
    });
 
    const { root, container, triggers, outerWrapper } = init(
      this,
      element,
      config,
    );
  }
}
 
/**
 * Per-trigger based configuration. Can either be given as an object as the
 * value of the {@link OpenableConfig.triggers} map, or it can be set as a
 * string configuration in the `data-lisn-<name>-trigger` data attribute. See
 * {@link getWidgetConfig} and the example below for the syntax.
 *
 * @example
 * ```html
 * <div data-lisn-collapsible-trigger="id=my-trigger
 *                                     | class-name=clsA,clsB
 *                                     | auto-close
 *                                     | hover
 *                                     | prevent-default=false
 *                                     | icon=right
 *                                     | icon-closed=arrow-down
 *                                     | icon-open=x"
 * ></div>
 * ```
 *
 * @interface
 */
export type OpenableTriggerConfig = {
  /**
   * The DOM ID to set on the trigger. Will result in the trigger element, which
   * could be a wrapper around the original element (as in the case of {@link
   * Collapsible} you passed, getting this ID.
   *
   * **IMPORTANT:** If the trigger element already has an ID and is not being
   * wrapped, then this will override the ID and it _won't_ be restored on destroy.
   *
   * @defaultValue undefined
   */
  id?: string;
 
  /**
   * Class name(s) for the trigger. Will result in the trigger element, which
   * could be a wrapper around the original element you passed, getting these
   * classes.
   *
   * @defaultValue undefined
   */
  className?: string[] | string;
 
  /**
   * Override the widget's {@link OpenableConfig.autoClose} for this trigger.
   *
   * @defaultValue undefined // Widget default
   */
  autoClose?: boolean;
 
  /**
   * Open the openable when this trigger is hovered.
   *
   * If the device is touch and {@link OpenableConfig.autoClose} is enabled,
   * the widget will be closed shortly after the pointer leaves both the
   * trigger and the root element.
   *
   * @defaultValue false
   */
  hover?: boolean;
 
  /**
   * Whether to prevent default click action.
   *
   * @defaultValue true
   */
  preventDefault?: boolean;
 
  /**
   * Override the widget's {@link CollapsibleConfig.icon} for this trigger.
   *
   * Currently only relevant for {@link Collapsible}s.
   *
   * @defaultValue undefined // Widget default
   */
  icon?: false | Position;
 
  /**
   * Override the widget's {@link CollapsibleConfig.iconClosed} for this
   * trigger.
   *
   * Currently only relevant for {@link Collapsible}s.
   *
   * @defaultValue undefined // Widget default
   */
  iconClosed?: "plus" | `arrow-${XYDirection}`;
 
  /**
   * Override the widget's {@link CollapsibleConfig.iconOpen} for this
   * trigger.
   *
   * Currently only relevant for {@link Collapsible}s.
   *
   * @defaultValue undefined // Widget default
   */
  iconOpen?: "minus" | "x" | `arrow-${XYDirection}`;
};
 
/**
 * @interface
 *
 * @since v1.2.1 Previously called `OpenableProperties`
 */
export type OpenableConfig = {
  /**
   * The name of the _type_ of the openable. Will set the class prefix to
   * `lisn-<name>`.
   */
  name: string;
 
  /**
   * The DOM ID to set on the openable. Will result in the top-level root
   * element that's created by us getting this ID.
   *
   * @defaultValue undefined
   */
  id?: string;
 
  /**
   * Class name(s) or a list of class names to set on the openable. Will result
   * in the top-level root element that's created by us getting these classes.
   *
   * @defaultValue undefined
   */
  className?: string[] | string;
 
  /**
   * Whether to auto-close the widget on clicking outside the content element
   * or on pressing Escape key. Furthermore, if any trigger opens the widget on
   * {@link OpenableTriggerConfig.hover}, the widget will be closed when the
   * pointer leaves both the trigger and the root.
   *
   * This is true by default for {@link Popup}, {@link Modal} and {@link Offcanvas}.
   */
  autoClose: boolean;
 
  /**
   * If true, then while the widget is open, the `document.body` will be set to
   * `overflow: hidden`.
   *
   * This is true for {@link Modal}.
   */
  isModal: boolean;
 
  /**
   * If true, then the content element is assumed to be possibly scrollable and
   * will be scrolled back to its top after the widget is closed.
   *
   * This is true for {@link Modal} and {@link Offcanvas}.
   */
  isOffcanvas: boolean;
 
  /**
   * Add a close button at the top right.
   *
   * This is true by default for {@link Modal} and {@link Offcanvas}.
   */
  closeButton: boolean;
 
  /**
   * The elements that open the widget when clicked on.
   *
   * If not given, then the elements that will be used as triggers are
   * discovered in the following way (`<name>` is what is given as
   * {@link name}):
   * 1. If the content element has a `data-lisn-<name>-content-id` attribute,
   *    then it must be a unique (for the current page) ID. In this case, the
   *    trigger elements will be any element in the document that has a
   *    `lisn-<name>-trigger` class or `data-lisn-<name>-trigger` attribute
   *    and the same `data-lisn-<name>-content-id` attribute.
   * 2. Otherwise, the closest ancestor that has a `lisn-<name>-container`
   *    class, or if no such ancestor then the immediate parent of the content
   *    element, is searched for any elements that have a `lisn-<name>-trigger`
   *    class or `data-lisn-<name>-trigger` attribute and that do _not_ have a
   *    `data-lisn-<name>-content-id` attribute, and that are _not_ children of
   *    the content element.
   *
   * If you pass an array of elements, they will be used as triggers, and their
   * {@link OpenableTriggerConfig | configuration} will be taken from the
   * `data-lisn-<name>-trigger` attribute. If you pass a map, its keys are the
   * elements and its values are used as the configuration, ignoring the data
   * attribute.
   *
   * @defaultValue undefined
   */
  triggers?: Element[] | Map<Element, OpenableTriggerConfig | null>;
 
  /**
   * Whether to wrap each trigger in a new element.
   *
   * @defaultValue false
   */
  wrapTriggers?: boolean;
 
  /**
   * Hook to run once the widget is fully setup (which happens asynchronously).
   *
   * It is called during "mutate time". See {@link waitForMutateTime}.
   *
   * @defaultValue undefined
   */
  onSetup?: () => void;
};
 
/**
 * @interface
 * @ignore
 * @deprecated
 *
 * Deprecated alias for {@link OpenableConfig}
 */
export type OpenableProperties = OpenableConfig;
 
/* ********************
 * Collapsible
 * ********************/
 
/**
 * Configures the given element as a {@link Collapsible} widget.
 *
 * The Collapsible widget sets up the given element to be collapsed and
 * expanded upon activation. Activation can be done manually by calling
 * {@link open} or when clicking on any of the given
 * {@link CollapsibleConfig.triggers | triggers}.
 *
 * **NOTE:** The Collapsible widget always wraps each trigger element in
 * another element in order to allow positioning the icon, if any.
 *
 * **IMPORTANT:** You should not instantiate more than one {@link Openable}
 * widget, regardless of type, on a given element. Use {@link Openable.get} to
 * get an existing instance if any. If there is already an {@link Openable}
 * widget of any type on this element, it will be destroyed!
 *
 * -----
 *
 * You can use the following dynamic attributes or CSS properties in your
 * stylesheet:
 *
 * The following dynamic attributes are set on the root element that is created
 * by LISN and has a class `lisn-collapsible__root`:
 * - `data-lisn-is-open`: `"true"` or `"false"`
 * - `data-lisn-reverse`: `"true"` or `"false"`
 * - `data-lisn-orientation`: `"horizontal"` or `"vertical"`
 *
 * The following dynamic attributes are set on each trigger:
 * - `data-lisn-opens-on-hover: `"true"` or `"false"`
 *
 * -----
 *
 * To use with auto-widgets (HTML API) (see
 * {@link Settings.settings.autoWidgets | settings.autoWidgets}), the following
 * CSS classes or data attributes are recognized:
 * - `lisn-collapsible` class or `data-lisn-collapsible` attribute set on the
 *   element that holds the content of the collapsible
 * - `lisn-collapsible-trigger` class or `data-lisn-collapsible-trigger`
 *   attribute set on elements that should act as the triggers.
 *   If using a data attribute, you can configure the trigger via the value
 *   with a similar syntax to the configuration of the openable widget. For
 *   example:
 *   - Set the attribute to `"hover"` in order to have this trigger open the
 *     collapsible on hover _in addition to click_.
 *   - Set the attribute to `"hover|auto-close"` in order to have this trigger
 *     open the collapsible on hover but and override
 *     {@link CollapsibleConfig.autoClose} with true.
 *
 * When using auto-widgets, the elements that will be used as triggers are
 * discovered in the following way:
 * 1. If the content element has a `data-lisn-collapsible-content-id` attribute,
 *    then it must be a unique (for the current page) ID. In this case, the
 *    trigger elements will be any element in the document that has a
 *    `lisn-collapsible-trigger` class or `data-lisn-collapsible-trigger`
 *    attribute and the same `data-lisn-collapsible-content-id` attribute.
 * 2. Otherwise, the closest ancestor that has a `lisn-collapsible-container`
 *    class, or if no such ancestor then the immediate parent of the content
 *    element, is searched for any elements that have a
 *    `lisn-collapsible-trigger` class or `data-lisn-collapsible-trigger`
 *    attribute and that do _not_ have a `data-lisn-collapsible-content-id`
 *    attribute, and that are _not_ children of the content element.
 *
 * See below examples for what values you can use set for the data attributes
 * in order to modify the configuration of the automatically created widget.
 *
 * @example
 * This defines a simple collapsible with one trigger.
 *
 * ```html
 * <div>
 *   <div class="lisn-collapsible-trigger">Expand</div>
 *   <div class="lisn-collapsible">
 *     Some long content here...
 *   </div>
 * </div>
 * ```
 *
 * @example
 * This defines a collapsible that is partially visible when collapsed, and
 * where the trigger is in a different parent to the content.
 *
 * ```html
 * <div>
 *   <div data-lisn-collapsible-content-id="readmore"
 *        data-lisn-collapsible="peek">
 *     <p>
 *       Lorem ipsum odor amet, consectetuer adipiscing elit. Etiam duis
 *       viverra faucibus facilisis luctus. Nunc tellus turpis facilisi dapibus
 *       aliquet turpis. Diam potenti egestas dolor auctor nostra vestibulum.
 *       Tempus auctor quis turpis; pulvinar ante ultrices. Netus morbi
 *       imperdiet volutpat litora tellus turpis a. Sociosqu interdum sodales
 *       sapien nulla aptent pellentesque praesent. Senectus magnis
 *       pellentesque; dis porta justo habitant.
 *     </p>
 *
 *     <p>
 *       Imperdiet placerat habitant tristique turpis habitasse ligula pretium
 *       vehicula. Mauris molestie lectus leo aliquam condimentum elit fermentum
 *       tempus nisi. Eget mi vestibulum quisque enim himenaeos. Odio nascetur
 *       vel congue vivamus eleifend ut nascetur. Ultrices quisque non dictumst
 *       risus libero varius tincidunt vel. Suscipit netus maecenas imperdiet
 *       elementum donec maximus suspendisse luctus. Eu velit semper urna sem
 *       ullamcorper nisl turpis hendrerit. Gravida commodo nisl malesuada nibh
 *       ultricies scelerisque hendrerit tempus vehicula. Risus eleifend eros
 *       aliquam turpis elit ridiculus est class.
 *     </p>
 *   </div>
 * </div>
 *
 * <div>
 *   <div data-lisn-collapsible-content-id="readmore"
 *        class="lisn-collapsible-trigger">
 *     Read more
 *   </div>
 * </div>
 * ```
 *
 * @example
 * As above, but with all possible configuration settings set explicitly.
 *
 * ```html
 * <div>
 *   <div data-lisn-collapsible-content-id="readmore"
 *        data-lisn-collapsible="id=my-collapsible
 *                               | class-name=clsA,clsB
 *                               | horizontal=false
 *                               | reverse=false
 *                               | peek=50px
 *                               | auto-close
 *                               | icon=right
 *                               | icon-closed=arrow-up"
 *                               | icon-open=arrow-down">
 *     <p>
 *       Lorem ipsum odor amet, consectetuer adipiscing elit. Etiam duis
 *       viverra faucibus facilisis luctus. Nunc tellus turpis facilisi dapibus
 *       aliquet turpis. Diam potenti egestas dolor auctor nostra vestibulum.
 *       Tempus auctor quis turpis; pulvinar ante ultrices. Netus morbi
 *       imperdiet volutpat litora tellus turpis a. Sociosqu interdum sodales
 *       sapien nulla aptent pellentesque praesent. Senectus magnis
 *       pellentesque; dis porta justo habitant.
 *     </p>
 *
 *     <p>
 *       Imperdiet placerat habitant tristique turpis habitasse ligula pretium
 *       vehicula. Mauris molestie lectus leo aliquam condimentum elit fermentum
 *       tempus nisi. Eget mi vestibulum quisque enim himenaeos. Odio nascetur
 *       vel congue vivamus eleifend ut nascetur. Ultrices quisque non dictumst
 *       risus libero varius tincidunt vel. Suscipit netus maecenas imperdiet
 *       elementum donec maximus suspendisse luctus. Eu velit semper urna sem
 *       ullamcorper nisl turpis hendrerit. Gravida commodo nisl malesuada nibh
 *       ultricies scelerisque hendrerit tempus vehicula. Risus eleifend eros
 *       aliquam turpis elit ridiculus est class.
 *     </p>
 *   </div>
 * </div>
 *
 * <div>
 *   <div data-lisn-collapsible-content-id="readmore"
 *        class="lisn-collapsible-trigger">
 *     Read more
 *   </div>
 * </div>
 * ```
 */
export class Collapsible extends Openable {
  static register() {
    registerOpenable(
      WIDGET_NAME_COLLAPSIBLE,
      (element, config) => new Collapsible(element, config),
      collapsibleConfigValidator,
    );
  }
 
  constructor(element: HTMLElement, config?: CollapsibleConfig) {
    const isHorizontal = config?.horizontal;
    const orientation = isHorizontal ? MC.S_HORIZONTAL : MC.S_VERTICAL;
 
    const onSetup = () => {
      // The triggers here are wrappers around the original which will be
      // replaced by the original on destroy, so no need to clean up this.
      for (const [
        trigger,
        triggerConfig,
      ] of this.getTriggerConfigs().entries()) {
        insertCollapsibleIcon(trigger, triggerConfig, this, config);
        setDataNow(trigger, MC.PREFIX_ORIENTATION, orientation);
      }
    };
 
    super(element, {
      name: WIDGET_NAME_COLLAPSIBLE,
      id: config?.id,
      className: config?.className,
      autoClose: config?.autoClose ?? false,
      isModal: false,
      isOffcanvas: false,
      closeButton: false,
      triggers: config?.triggers,
      wrapTriggers: true,
      onSetup,
    });
 
    const root = this.getRoot();
    const wrapper = MH.childrenOf(root)[0];
 
    setData(root, MC.PREFIX_ORIENTATION, orientation);
    setBooleanData(root, PREFIX_REVERSE, config?.reverse ?? false);
 
    // -------------------- Transitions
    disableInitialTransition(element, 100);
    disableInitialTransition(root, 100);
    disableInitialTransition(wrapper, 100);
 
    let disableTransitionTimer: ReturnType<typeof setTimeout> | null = null;
    const tempEnableTransition = async () => {
      await removeClasses(root, MC.PREFIX_TRANSITION_DISABLE);
      await removeClasses(wrapper, MC.PREFIX_TRANSITION_DISABLE);
 
      if (disableTransitionTimer) {
        MH.clearTimer(disableTransitionTimer);
      }
 
      const transitionDuration = await getMaxTransitionDuration(root);
      disableTransitionTimer = MH.setTimer(() => {
        if (this.isOpen()) {
          addClasses(root, MC.PREFIX_TRANSITION_DISABLE);
          addClasses(wrapper, MC.PREFIX_TRANSITION_DISABLE);
          disableTransitionTimer = null;
        }
      }, transitionDuration);
    };
 
    // Disable transitions except during open/close, so that resizing the
    // window for example doesn't result in lagging width/height transition.
    this.onOpen(tempEnableTransition);
    this.onClose(tempEnableTransition);
 
    // -------------------- Peek
    const peek = config?.peek;
    Iif (peek) {
      (async () => {
        let peekSize: string | null = null;
        if (MH.isString(peek)) {
          peekSize = peek;
        } else {
          peekSize = await getStyleProp(element, VAR_PEEK_SIZE);
        }
 
        addClasses(root, PREFIX_PEEK);
        Iif (peekSize) {
          setStyleProp(root, VAR_PEEK_SIZE, peekSize);
        }
      })();
    }
 
    // -------------------- Width in horizontal mode
    Iif (isHorizontal) {
      const updateWidth = async () => {
        const width = await getComputedStyleProp(root, MC.S_WIDTH);
        await setStyleProp(element, VAR_JS_COLLAPSIBLE_WIDTH, width);
      };
 
      MH.setTimer(updateWidth);
 
      // Save its current width so that if it contains text, it does not
      // "collapse" and end up super tall.
      this.onClose(updateWidth);
 
      this.onOpen(async () => {
        // Update the content width before opening.
        await updateWidth();
 
        // Delete the fixed width property soon after opening to allow it to
        // resize again while it's open.
        waitForDelay(2000).then(() => {
          Iif (this.isOpen()) {
            delStyleProp(element, VAR_JS_COLLAPSIBLE_WIDTH);
          }
        });
      });
    }
  }
}
 
/**
 * @interface
 */
export type CollapsibleConfig = {
  /**
   * The DOM ID to set on the collapsible. Will result in the top-level root
   * element that's created by us getting this ID.
   *
   * Note, this does not replace or affect the
   * `data-lisn-collapsible-content-id` attribute used to link triggers to the
   * collapsible.
   *
   * @defaultValue undefined
   */
  id?: string;
 
  /**
   * Class name(s) or a list of class names to set on the collapsible. Will
   * result in the top-level root element that's created by us getting these
   * classes.
   *
   * @defaultValue undefined
   */
  className?: string[] | string;
 
  /**
   * The elements that open the widget when clicked on.
   *
   * If not given, then the elements that will be used as triggers are
   * discovered in the following way:
   * 1. If the content element has a `data-lisn-collapsible-content-id` attribute,
   *    then it must be a unique (for the current page) ID. In this case, the
   *    trigger elements will be any element in the document that has a
   *    `data-lisn-collapsible-trigger` class or `data-lisn-collapsible-trigger`
   *    attribute and the same `data-lisn-collapsible-content-id` attribute.
   * 2. Otherwise, the closest ancestor that has a `lisn-collapsible-container`
   *    class, or if no such ancestor then the immediate parent of the content
   *    element, is searched for any elements that have a
   *    `lisn-collapsible-trigger` class or `data-lisn-collapsible-trigger`
   *    attribute and that do _not_ have a `data-lisn-collapsible-content-id`
   *    attribute, and that are _not_ children of the content element.
   *
   * If you pass an array of elements, they will be used as triggers, and their
   * {@link OpenableTriggerConfig | configuration} will be taken from the
   * `data-lisn-collapsible-trigger` attribute. If you pass a map, its keys are
   * the elements and its values are used as the configuration, ignoring the
   * data attribute.
   *
   * @defaultValue undefined
   */
  triggers?: Element[] | Map<Element, OpenableTriggerConfig | null>;
 
  /**
   * Open sideways (to the right) instead of downwards (default).
   *
   * **IMPORTANT:** In horizontal mode the width of the content element should
   * not be set (or be `auto`), but you can use `min-width` or `max-width` in
   * your CSS if needed.
   *
   * @defaultValue false
   */
  horizontal?: boolean;
 
  /**
   * Open to the left if horizontal or upwards if vertical.
   *
   * @defaultValue false
   */
  reverse?: boolean;
 
  /**
   * If not false, part of the content will be visible when the collapsible is
   * closed. The value can be any valid CSS width specification.
   *
   * If you set this to `true`, then the size of the peek window will be
   * dictated by CSS. By default the size is 100px, but you can change this by
   * setting `--lisn-peek-size` CSS property on the content element or any of
   * its ancestors.
   *
   * Otherwise, if the value is a string, it must be a CSS length including units.
   *
   * @defaultValue false
   */
  peek?: boolean | string;
 
  /**
   * Automatically close the collapsible when clicking outside it or pressing
   * Escape. Furthermore, if any trigger opens the widget on
   * {@link OpenableTriggerConfig.hover}, the widget will be closed when the
   * pointer leaves both the trigger and the root.
   *
   * @defaultValue false
   */
  autoClose?: boolean;
 
  /**
   * Add an icon to each trigger.
   *
   * If set to something other than `false`, then by default the icon in the
   * closed state is a plus (+) and in the open state it's a minus (-), but
   * this can be configured with {@link iconClosed} and {@link iconOpen}.
   *
   * @defaultValue false
   */
  icon?: false | Position;
 
  /**
   * Set the type of icon used on the trigger(s) in the closed state.
   *
   * Note that {@link icon} must be set to something other than `false`.
   *
   * @defaultValue "plus"
   */
  iconClosed?: "plus" | `arrow-${XYDirection}`;
 
  /**
   * Set the type of icon used on the trigger(s) in the open state.
   *
   * Note that {@link icon} must be set to something other than `false`.
   *
   * @defaultValue "minus";
   */
  iconOpen?: "minus" | "x" | `arrow-${XYDirection}`;
};
 
/* ********************
 * Popup
 * ********************/
 
/**
 * Configures the given element as a {@link Popup} widget.
 *
 * The Popup widget sets up the given element to be hidden and open in a
 * floating popup upon activation. Activation can be done manually by calling
 * {@link open} or when clicking on any of the given
 * {@link PopupConfig.triggers | triggers}.
 *
 * **IMPORTANT:** The popup is positioned absolutely in its container and the
 * position is relative to the container. The container gets `width:
 * fit-content` by default but you can override this in your CSS. The popup
 * also gets a configurable `min-width` set.
 *
 * **IMPORTANT:** You should not instantiate more than one {@link Openable}
 * widget, regardless of type, on a given element. Use {@link Openable.get} to
 * get an existing instance if any. If there is already an {@link Openable}
 * widget of any type on this element, it will be destroyed!
 *
 * -----
 *
 * You can use the following dynamic attributes or CSS properties in your
 * stylesheet:
 *
 * The following dynamic attributes are set on the root element that is created
 * by LISN and has a class `lisn-popup__root`:
 * - `data-lisn-is-open`: `"true"` or `"false"`
 * - `data-lisn-place`: the actual position (top, bottom, left, top-left, etc)
 *
 * The following dynamic attributes are set on each trigger:
 * - `data-lisn-opens-on-hover: `"true"` or `"false"`
 *
 * -----
 *
 * To use with auto-widgets (HTML API) (see
 * {@link Settings.settings.autoWidgets | settings.autoWidgets}), the following
 * CSS classes or data attributes are recognized:
 * - `lisn-popup` class or `data-lisn-popup` attribute set on the element that
 *   holds the content of the popup
 * - `lisn-popup-trigger` class or `data-lisn-popup-trigger`
 *   attribute set on elements that should act as the triggers.
 *   If using a data attribute, you can configure the trigger via the value
 *   with a similar syntax to the configuration of the openable widget. For
 *   example:
 *   - Set the attribute to `"hover"` in order to have this trigger open the
 *     popup on hover _in addition to click_.
 *   - Set the attribute to `"hover|auto-close=false"` in order to have this
 *     trigger open the popup on hover but and override
 *     {@link PopupConfig.autoClose} with true.
 *
 * When using auto-widgets, the elements that will be used as triggers are
 * discovered in the following way:
 * 1. If the content element has a `data-lisn-popup-content-id` attribute, then
 *    it must be a unique (for the current page) ID. In this case, the trigger
 *    elements will be any element in the document that has a
 *    `lisn-popup-trigger` class or `data-lisn-popup-trigger` attribute and the
 *    same `data-lisn-popup-content-id` attribute.
 * 2. Otherwise, the closest ancestor that has a `lisn-popup-container` class,
 *    or if no such ancestor then the immediate parent of the content element,
 *    is searched for any elements that have a `lisn-popup-trigger` class or
 *    `data-lisn-popup-trigger` attribute and that do _not_ have a
 *    `data-lisn-popup-content-id` attribute, and that are _not_ children of
 *    the content element.
 *
 * See below examples for what values you can use set for the data attributes
 * in order to modify the configuration of the automatically created widget.
 *
 * @example
 * This defines a simple popup with one trigger.
 *
 * ```html
 * <div>
 *   <div class="lisn-popup-trigger">Open</div>
 *   <div class="lisn-popup">
 *     Some content here...
 *   </div>
 * </div>
 * ```
 *
 * @example
 * This defines a popup that has a close button, and where the trigger is in a
 * different parent to the content.
 *
 * ```html
 * <div>
 *   <div data-lisn-popup-content-id="popup"
 *        data-lisn-popup="close-button">
 *     Lorem ipsum odor amet, consectetuer adipiscing elit. Etiam duis viverra
 *     faucibus facilisis luctus. Nunc tellus turpis facilisi dapibus aliquet
 *     turpis. Diam potenti egestas dolor auctor nostra vestibulum. Tempus
 *     auctor quis turpis; pulvinar ante ultrices. Netus morbi imperdiet
 *     volutpat litora tellus turpis a. Sociosqu interdum sodales sapien nulla
 *     aptent pellentesque praesent. Senectus magnis pellentesque; dis porta
 *     justo habitant.
 *   </div>
 * </div>
 *
 * <div>
 *   <div data-lisn-popup-content-id="popup" class="lisn-popup-trigger">
 *     Open
 *   </div>
 * </div>
 * ```
 *
 * @example
 * As above, but with all possible configuration settings set explicitly.
 *
 * ```html
 * <div>
 *   <div data-lisn-popup-content-id="popup" class="lisn-popup-trigger">
 *     Open
 *   </div>
 * </div>
 *
 * <div>
 *   <div data-lisn-popup-content-id="popup"
 *        data-lisn-popup="id=my-popup
 *                         | class-name=clsA,clsB
 *                         | close-button
 *                         | position=bottom
 *                         | auto-close=false">
 *     Lorem ipsum odor amet, consectetuer adipiscing elit. Etiam duis viverra
 *     faucibus facilisis luctus. Nunc tellus turpis facilisi dapibus aliquet
 *     turpis. Diam potenti egestas dolor auctor nostra vestibulum. Tempus
 *     auctor quis turpis; pulvinar ante ultrices. Netus morbi imperdiet
 *     volutpat litora tellus turpis a. Sociosqu interdum sodales sapien nulla
 *     aptent pellentesque praesent. Senectus magnis pellentesque; dis porta
 *     justo habitant.
 *   </div>
 * </div>
 * ```
 */
export class Popup extends Openable {
  static register() {
    registerOpenable(
      WIDGET_NAME_POPUP,
      (element, config) => new Popup(element, config),
      popupConfigValidator,
    );
  }
 
  constructor(element: HTMLElement, config?: PopupConfig) {
    super(element, {
      name: WIDGET_NAME_POPUP,
      id: config?.id,
      className: config?.className,
      autoClose: config?.autoClose ?? true,
      isModal: false,
      isOffcanvas: false,
      closeButton: config?.closeButton ?? false,
      triggers: config?.triggers,
    });
 
    const root = this.getRoot();
    const container = this.getContainer();
 
    const position = config?.position || S_AUTO;
    Iif (position !== S_AUTO) {
      setData(root, MC.PREFIX_PLACE, position);
    }
 
    if (container && position === S_AUTO) {
      // Automatic position
      this.onOpen(async () => {
        const [contentSize, containerView] = await MH.promiseAll([
          SizeWatcher.reuse().fetchCurrentSize(element),
          ViewWatcher.reuse().fetchCurrentView(container),
        ]);
 
        const placement = await fetchPopupPlacement(contentSize, containerView);
        if (placement) {
          await setData(root, MC.PREFIX_PLACE, placement);
        }
      });
    }
  }
}
 
/**
 * @interface
 */
export type PopupConfig = {
  /**
   * The DOM ID to set on the popup. Will result in the top-level root element
   * that's created by us getting this ID.
   *
   * Note, this does not replace or affect the `data-lisn-popup-content-id`
   * attribute used to link triggers to the popup.
   *
   * @defaultValue undefined
   */
  id?: string;
 
  /**
   * Class name(s) or a list of class names to set on the popup. Will result in
   * the top-level root element that's created by us getting these classes.
   *
   * @defaultValue undefined
   */
  className?: string[] | string;
 
  /**
   * The elements that open the widget when clicked on.
   *
   * If not given, then the elements that will be used as triggers are
   * discovered in the following way:
   * 1. If the content element has a `data-lisn-popup-content-id` attribute,
   *    then it must be a unique (for the current page) ID. In this case, the
   *    trigger elements will be any element in the document that has a
   *    `lisn-popup-trigger` class or `data-lisn-popup-trigger` attribute
   *    and the same `data-lisn-popup-content-id` attribute.
   * 2. Otherwise, the closest ancestor that has a `lisn-popup-container`
   *    class, or if no such ancestor then the immediate parent of the content
   *    element, is searched for any elements that have a `lisn-popup-trigger`
   *    class or `data-lisn-popup-trigger` attribute and that do _not_ have a
   *    `data-lisn-popup-content-id` attribute, and that are _not_ children of
   *    the content element.
   *
   * If you pass an array of elements, they will be used as triggers, and their
   * {@link OpenableTriggerConfig | configuration} will be taken from the
   * `data-lisn-popup-trigger` attribute. If you pass a map, its keys are the
   * elements and its values are used as the configuration, ignoring the data
   * attribute.
   *
   * @defaultValue undefined
   */
  triggers?: Element[] | Map<Element, OpenableTriggerConfig | null>;
 
  /**
   * Add a close button at the top right.
   *
   * @defaultValue false
   */
  closeButton?: boolean;
 
  /**
   * Specify the popup position _relative to its container_. Supported
   * positions include `"top"`, `"bottom"`, `"left"`, `"right" `(which result
   * on the popup being placed on top, bottom, etc, but center-aligned), or
   * `"top-left"`, `"left-top"`, etc, as well as `"auto"`. If set to `"auto"`,
   * then popup position will be based on the container position within the
   * viewport at the time it's open.
   *
   * @defaultValue "auto"
   */
  position?: Position | `${Position}-${Position}` | "auto";
 
  /**
   * Automatically close the popup when clicking outside it or pressing Escape.
   * Furthermore, if any trigger opens the widget on
   * {@link OpenableTriggerConfig.hover}, the widget will be closed when the
   * pointer leaves both the trigger and the root.
   *
   * @defaultValue true
   */
  autoClose?: boolean;
};
 
/* ********************
 * Modal
 * ********************/
 
/**
 * Configures the given element as a {@link Modal} widget.
 *
 * The Modal widget sets up the given element to be hidden and open in a fixed
 * full-screen modal popup upon activation. Activation can be done manually by
 * calling {@link open} or when clicking on any of the given
 * {@link ModalConfig.triggers | triggers}.
 *
 * **IMPORTANT:** You should not instantiate more than one {@link Openable}
 * widget, regardless of type, on a given element. Use {@link Openable.get} to
 * get an existing instance if any. If there is already an {@link Openable}
 * widget of any type on this element, it will be destroyed!
 *
 * -----
 *
 * You can use the following dynamic attributes or CSS properties in your
 * stylesheet:
 *
 * The following dynamic attributes are set on the root element that is created
 * by LISN and has a class `lisn-modal__root`:
 * - `data-lisn-is-open`: `"true"` or `"false"`
 *
 * The following dynamic attributes are set on each trigger:
 * - `data-lisn-opens-on-hover: `"true"` or `"false"`
 *
 * -----
 *
 * To use with auto-widgets (HTML API) (see
 * {@link Settings.settings.autoWidgets | settings.autoWidgets}), the following
 * CSS classes or data attributes are recognized:
 * - `lisn-modal` class or `data-lisn-modal` attribute set on the element that
 *   holds the content of the modal
 * - `lisn-modal-trigger` class or `data-lisn-modal-trigger`
 *   attribute set on elements that should act as the triggers.
 *   If using a data attribute, you can configure the trigger via the value
 *   with a similar syntax to the configuration of the openable widget. For
 *   example:
 *   - Set the attribute to `"hover"` in order to have this trigger open the
 *     modal on hover _in addition to click_.
 *   - Set the attribute to `"hover|auto-close=false"` in order to have this
 *     trigger open the modal on hover but and override
 *     {@link ModalConfig.autoClose} with true.
 *
 * When using auto-widgets, the elements that will be used as triggers are
 * discovered in the following way:
 * 1. If the content element has a `data-lisn-modal-content-id` attribute, then
 *    it must be a unique (for the current page) ID. In this case, the trigger
 *    elements will be any element in the document that has a
 *    `lisn-modal-trigger` class or `data-lisn-modal-trigger` attribute and the
 *    same `data-lisn-modal-content-id` attribute.
 * 2. Otherwise, the closest ancestor that has a `lisn-modal-container` class,
 *    or if no such ancestor then the immediate parent of the content element,
 *    is searched for any elements that have a `lisn-modal-trigger` class or
 *    `data-lisn-modal-trigger` attribute and that do _not_ have a
 *    `data-lisn-modal-content-id` attribute, and that are _not_ children of
 *    the content element.
 *
 * See below examples for what values you can use set for the data attributes
 * in order to modify the configuration of the automatically created widget.
 *
 * @example
 * This defines a simple modal with one trigger.
 *
 * ```html
 * <div>
 *   <div class="lisn-modal-trigger">Open</div>
 *   <div class="lisn-modal">
 *     Some content here...
 *   </div>
 * </div>
 * ```
 *
 * @example
 * This defines a modal that doesn't automatically close on click outside or
 * Escape and, and that has several triggers in a different parent to the
 * content.
 *
 * ```html
 * <div>
 *   <div data-lisn-modal-content-id="modal"
 *        data-lisn-modal="auto-close=false">
 *     Lorem ipsum odor amet, consectetuer adipiscing elit. Etiam duis viverra
 *     faucibus facilisis luctus. Nunc tellus turpis facilisi dapibus aliquet
 *     turpis. Diam potenti egestas dolor auctor nostra vestibulum. Tempus
 *     auctor quis turpis; pulvinar ante ultrices. Netus morbi imperdiet
 *     volutpat litora tellus turpis a. Sociosqu interdum sodales sapien nulla
 *     aptent pellentesque praesent. Senectus magnis pellentesque; dis porta
 *     justo habitant.
 *   </div>
 * </div>
 *
 * <div>
 *   <div data-lisn-modal-content-id="modal" class="lisn-modal-trigger">
 *     Open
 *   </div>
 * </div>
 *
 * <div>
 *   <div data-lisn-modal-content-id="modal" class="lisn-modal-trigger">
 *     Another trigger
 *   </div>
 * </div>
 * ```
 *
 * @example
 * As above, but with all possible configuration settings set explicitly.
 *
 * ```html
 * <div>
 *   <div data-lisn-modal-content-id="modal"
 *        data-lisn-modal="id=my-modal
 *                         | class-name=clsA,clsB
 *                         | close-button=true
 *                         | auto-close=false">
 *     Lorem ipsum odor amet, consectetuer adipiscing elit. Etiam duis viverra
 *     faucibus facilisis luctus. Nunc tellus turpis facilisi dapibus aliquet
 *     turpis. Diam potenti egestas dolor auctor nostra vestibulum. Tempus
 *     auctor quis turpis; pulvinar ante ultrices. Netus morbi imperdiet
 *     volutpat litora tellus turpis a. Sociosqu interdum sodales sapien nulla
 *     aptent pellentesque praesent. Senectus magnis pellentesque; dis porta
 *     justo habitant.
 *   </div>
 * </div>
 *
 * <div>
 *   <div data-lisn-modal-content-id="modal" class="lisn-modal-trigger">
 *     Open
 *   </div>
 * </div>
 *
 * <div>
 *   <div data-lisn-modal-content-id="modal" class="lisn-modal-trigger">
 *     Another trigger
 *   </div>
 * </div>
 * ```
 */
export class Modal extends Openable {
  static register() {
    registerOpenable(
      WIDGET_NAME_MODAL,
      (element, config) => new Modal(element, config),
      modalConfigValidator,
    );
  }
 
  constructor(element: HTMLElement, config?: ModalConfig) {
    super(element, {
      name: WIDGET_NAME_MODAL,
      id: config?.id,
      className: config?.className,
      autoClose: config?.autoClose ?? true,
      isModal: true,
      isOffcanvas: true,
      closeButton: config?.closeButton ?? true,
      triggers: config?.triggers,
    });
  }
}
 
/**
 * @interface
 */
export type ModalConfig = {
  /**
   * The DOM ID to set on the modal. Will result in the top-level root element
   * that's created by us getting this ID.
   *
   * Note, this does not replace or affect the `data-lisn-modal-content-id`
   * attribute used to link triggers to the modal.
   *
   * @defaultValue undefined
   */
  id?: string;
 
  /**
   * Class name(s) or a list of class names to set on the modal. Will result in
   * the top-level root element that's created by us getting these classes.
   *
   * @defaultValue undefined
   */
  className?: string[] | string;
 
  /**
   * The elements that open the widget when clicked on.
   *
   * If not given, then the elements that will be used as triggers are
   * discovered in the following way:
   * 1. If the content element has a `data-lisn-modal-content-id` attribute,
   *    then it must be a unique (for the current page) ID. In this case, the
   *    trigger elements will be any element in the document that has a
   *    `lisn-modal-trigger` class or `data-lisn-modal-trigger` attribute
   *    and the same `data-lisn-modal-content-id` attribute.
   * 2. Otherwise, the closest ancestor that has a `lisn-modal-container`
   *    class, or if no such ancestor then the immediate parent of the content
   *    element, is searched for any elements that have a `lisn-modal-trigger`
   *    class or `data-lisn-modal-trigger` attribute and that do _not_ have a
   *    `data-lisn-modal-content-id` attribute, and that are _not_ children of
   *    the content element.
   *
   * If you pass an array of elements, they will be used as triggers, and their
   * {@link OpenableTriggerConfig | configuration} will be taken from the
   * `data-lisn-modal-trigger` attribute. If you pass a map, its keys are the
   * elements and its values are used as the configuration, ignoring the data
   * attribute.
   *
   * @defaultValue undefined
   */
  triggers?: Element[] | Map<Element, OpenableTriggerConfig | null>;
 
  /**
   * Add a close button at the top right.
   *
   * @defaultValue true
   */
  closeButton?: boolean;
 
  /**
   * Automatically close the modal when clicking outside it or pressing Escape.
   * Furthermore, if any trigger opens the widget on
   * {@link OpenableTriggerConfig.hover}, the widget will be closed when the
   * pointer leaves both the trigger and the root.
   *
   * If you set this to false, then you should ensure {@link closeButton} is
   * enabled.
   *
   * @defaultValue true
   */
  autoClose?: boolean;
};
 
/* ********************
 * Offcanvas
 * ********************/
 
/**
 * Configures the given element as a {@link Offcanvas} widget.
 *
 * The Offcanvas widget sets up the given element to be hidden and open in a
 * fixed overlay (non full-screen) upon activation. Activation can be done
 * manually by calling {@link open} or when clicking on any of the given
 * {@link OffcanvasConfig.triggers | triggers}.
 *
 * **IMPORTANT:** You should not instantiate more than one {@link Openable}
 * widget, regardless of type, on a given element. Use {@link Openable.get} to
 * get an existing instance if any. If there is already an {@link Openable}
 * widget of any type on this element, it will be destroyed!
 *
 * -----
 *
 * You can use the following dynamic attributes or CSS properties in your
 * stylesheet:
 *
 * The following dynamic attributes are set on the root element that is created
 * by LISN and has a class `lisn-offcanvas__root`:
 * - `data-lisn-is-open`: `"true"` or `"false"`
 * - `data-lisn-place`: the actual position `"top"`, `"bottom"`, `"left"` or
 *   `"right"`
 *
 * The following dynamic attributes are set on each trigger:
 * - `data-lisn-opens-on-hover: `"true"` or `"false"`
 *
 * -----
 *
 * To use with auto-widgets (HTML API) (see
 * {@link Settings.settings.autoWidgets | settings.autoWidgets}), the following
 * CSS classes or data attributes are recognized:
 * - `lisn-offcanvas` class or `data-lisn-offcanvas` attribute set on the
 *   element that holds the content of the offcanvas
 * - `lisn-offcanvas-trigger` class or `data-lisn-offcanvas-trigger`
 *   attribute set on elements that should act as the triggers.
 *   If using a data attribute, you can configure the trigger via the value
 *   with a similar syntax to the configuration of the openable widget. For
 *   example:
 *   - Set the attribute to `"hover"` in order to have this trigger open the
 *     offcanvas on hover _in addition to click_.
 *   - Set the attribute to `"hover|auto-close=false"` in order to have this
 *     trigger open the offcanvas on hover but and override
 *     {@link OffcanvasConfig.autoClose} with true.
 *
 * When using auto-widgets, the elements that will be used as triggers are
 * discovered in the following way:
 * 1. If the content element has a `data-lisn-offcanvas-content-id` attribute,
 *    then it must be a unique (for the current page) ID. In this case, the
 *    trigger elements will be any element in the document that has a
 *    `lisn-offcanvas-trigger` class or `data-lisn-offcanvas-trigger` attribute
 *    and the same `data-lisn-offcanvas-content-id` attribute.
 * 2. Otherwise, the closest ancestor that has a `lisn-offcanvas-container`
 *    class, or if no such ancestor then the immediate parent of the content
 *    element, is searched for any elements that have a
 *    `lisn-offcanvas-trigger` class or `data-lisn-offcanvas-trigger` attribute
 *    and that do _not_ have a `data-lisn-offcanvas-content-id`
 *    attribute, and that are _not_ children of the content element.
 *
 * See below examples for what values you can use set for the data attributes
 * in order to modify the configuration of the automatically created widget.
 *
 * @example
 * This defines a simple offcanvas with one trigger.
 *
 * ```html
 * <div>
 *   <div class="lisn-offcanvas-trigger">Open</div>
 *   <div class="lisn-offcanvas">
 *     Some content here...
 *   </div>
 * </div>
 * ```
 *
 * @example
 * This defines a offcanvas that doesn't automatically close on click outside
 * or Escape and, and that has several triggers in a different parent to the
 * content.
 *
 * ```html
 * <div>
 *   <div data-lisn-offcanvas-content-id="offcanvas"
 *        data-lisn-offcanvas="auto-close=false">
 *     Lorem ipsum odor amet, consectetuer adipiscing elit. Etiam duis viverra
 *     faucibus facilisis luctus. Nunc tellus turpis facilisi dapibus aliquet
 *     turpis. Diam potenti egestas dolor auctor nostra vestibulum. Tempus
 *     auctor quis turpis; pulvinar ante ultrices. Netus morbi imperdiet
 *     volutpat litora tellus turpis a. Sociosqu interdum sodales sapien nulla
 *     aptent pellentesque praesent. Senectus magnis pellentesque; dis porta
 *     justo habitant.
 *   </div>
 * </div>
 *
 * <div>
 *   <div data-lisn-offcanvas-content-id="offcanvas" class="lisn-offcanvas-trigger">
 *     Open
 *   </div>
 * </div>
 *
 * <div>
 *   <div data-lisn-offcanvas-content-id="offcanvas" class="lisn-offcanvas-trigger">
 *     Another trigger
 *   </div>
 * </div>
 * ```
 *
 * @example
 * As above, but with all possible configuration settings set explicitly.
 *
 * ```html
 * <div>
 *   <div data-lisn-offcanvas-content-id="offcanvas"
 *        data-lisn-offcanvas="id=my-offcanvas
 *                             | class-name=clsA,clsB
 *                             | close-button=true
 *                             | position=top
 *                             | auto-close=false">
 *     Lorem ipsum odor amet, consectetuer adipiscing elit. Etiam duis viverra
 *     faucibus facilisis luctus. Nunc tellus turpis facilisi dapibus aliquet
 *     turpis. Diam potenti egestas dolor auctor nostra vestibulum. Tempus
 *     auctor quis turpis; pulvinar ante ultrices. Netus morbi imperdiet
 *     volutpat litora tellus turpis a. Sociosqu interdum sodales sapien nulla
 *     aptent pellentesque praesent. Senectus magnis pellentesque; dis porta
 *     justo habitant.
 *   </div>
 * </div>
 *
 * <div>
 *   <div data-lisn-offcanvas-content-id="offcanvas" class="lisn-offcanvas-trigger">
 *     Open
 *   </div>
 * </div>
 *
 * <div>
 *   <div data-lisn-offcanvas-content-id="offcanvas" class="lisn-offcanvas-trigger">
 *     Another trigger
 *   </div>
 * </div>
 * ```
 */
export class Offcanvas extends Openable {
  static register() {
    registerOpenable(
      WIDGET_NAME_OFFCANVAS,
      (element, config) => new Offcanvas(element, config),
      offcanvasConfigValidator,
    );
  }
 
  constructor(element: HTMLElement, config?: OffcanvasConfig) {
    super(element, {
      name: WIDGET_NAME_OFFCANVAS,
      id: config?.id,
      className: config?.className,
      autoClose: config?.autoClose ?? true,
      isModal: false,
      isOffcanvas: true,
      closeButton: config?.closeButton ?? true,
      triggers: config?.triggers,
    });
 
    const position = config?.position || MC.S_RIGHT;
    setData(this.getRoot(), MC.PREFIX_PLACE, position);
  }
}
 
/**
 * @interface
 */
export type OffcanvasConfig = {
  /**
   * The DOM ID to set on the offcanvas. Will result in the top-level root
   * element that's created by us getting this ID.
   *
   * Note, this does not replace or affect the `data-lisn-offcanvas-content-id`
   * attribute used to link triggers to the offcanvas.
   *
   * @defaultValue undefined
   */
  id?: string;
 
  /**
   * Class name(s) or a list of class names to set on the offcanvas. Will result
   * in the top-level root element that's created by us getting these classes.
   *
   * @defaultValue undefined
   */
  className?: string[] | string;
 
  /**
   * The elements that open the widget when clicked on.
   *
   * If not given, then the elements that will be used as triggers are
   * discovered in the following way:
   * 1. If the content element has a `data-lisn-offcanvas-content-id` attribute,
   *    then it must be a unique (for the current page) ID. In this case, the
   *    trigger elements will be any element in the document that has a
   *    `lisn-offcanvas-trigger` class or `data-lisn-offcanvas-trigger`
   *    attribute and the same `data-lisn-offcanvas-content-id` attribute.
   * 2. Otherwise, the closest ancestor that has a `lisn-offcanvas-container`
   *    class, or if no such ancestor then the immediate parent of the content
   *    element, is searched for any elements that have a
   *    `lisn-offcanvas-trigger` class or `data-lisn-offcanvas-trigger`
   *    attribute and that do _not_ have a `data-lisn-offcanvas-content-id`
   *    attribute, and that are _not_ children of the content element.
   *
   * If you pass an array of elements, they will be used as triggers, and their
   * {@link OpenableTriggerConfig | configuration} will be taken from the
   * `data-lisn-offcanvas-trigger` attribute. If you pass a map, its keys are
   * the elements and its values are used as the configuration, ignoring the
   * data attribute.
   *
   * @defaultValue undefined
   */
  triggers?: Element[] | Map<Element, OpenableTriggerConfig | null>;
 
  /**
   * Specify the offcanvas position. Supported positions are top, bottom, left,
   * right.
   *
   * @defaultValue "right"
   */
  position?: Position;
 
  /**
   * Add a close button at the top right.
   *
   * @defaultValue true
   */
  closeButton?: boolean;
 
  /**
   * Automatically close the offcanvas when clicking outside it or pressing
   * Escape. Furthermore, if any trigger opens the widget on
   * {@link OpenableTriggerConfig.hover}, the widget will be closed when the
   * pointer leaves both the trigger and the root.
   *
   * @defaultValue true
   */
  autoClose?: boolean;
};
 
// ------------------------------
 
type ElementsCollection = {
  content: HTMLElement;
  root: HTMLElement;
  container: HTMLElement | null;
  outerWrapper: HTMLElement;
  triggers: Map<Element, OpenableTriggerConfig>;
};
 
const instances = MH.newWeakMap<Element, Openable>();
 
const WIDGET_NAME_COLLAPSIBLE = "collapsible";
const WIDGET_NAME_POPUP = "popup";
const WIDGET_NAME_MODAL = "modal";
const WIDGET_NAME_OFFCANVAS = "offcanvas";
 
const PREFIX_CLOSE_BTN = MH.prefixName("close-button");
const PREFIX_IS_OPEN = MH.prefixName("is-open");
const PREFIX_REVERSE = MH.prefixName(MC.S_REVERSE);
const PREFIX_PEEK = MH.prefixName("peek");
const PREFIX_OPENS_ON_HOVER = MH.prefixName("opens-on-hover");
const PREFIX_LINE = MH.prefixName("line");
const PREFIX_ICON_POSITION = MH.prefixName("icon-position");
const PREFIX_TRIGGER_ICON = MH.prefixName("trigger-icon");
const PREFIX_ICON_WRAPPER = MH.prefixName("icon-wrapper");
const S_AUTO = "auto";
const S_ARIA_EXPANDED = MC.ARIA_PREFIX + "expanded";
const S_ARIA_MODAL = MC.ARIA_PREFIX + "modal";
const VAR_PEEK_SIZE = MH.prefixCssVar("peek-size");
const VAR_JS_COLLAPSIBLE_WIDTH = MH.prefixCssJsVar("collapsible-width");
const MIN_CLICK_TIME_AFTER_HOVER_OPEN = 1000;
const S_ARROW_UP =
  `${MC.S_ARROW}-${MC.S_UP}` as `${typeof MC.S_ARROW}-${typeof MC.S_UP}`;
const S_ARROW_DOWN =
  `${MC.S_ARROW}-${MC.S_DOWN}` as `${typeof MC.S_ARROW}-${typeof MC.S_DOWN}`;
const S_ARROW_LEFT =
  `${MC.S_ARROW}-${MC.S_LEFT}` as `${typeof MC.S_ARROW}-${typeof MC.S_LEFT}`;
const S_ARROW_RIGHT =
  `${MC.S_ARROW}-${MC.S_RIGHT}` as `${typeof MC.S_ARROW}-${typeof MC.S_RIGHT}`;
 
const ARROW_TYPES = [
  S_ARROW_UP,
  S_ARROW_DOWN,
  S_ARROW_LEFT,
  S_ARROW_RIGHT,
] as const;
 
const ICON_CLOSED_TYPES = ["plus", ...ARROW_TYPES] as const;
const ICON_OPEN_TYPES = ["minus", "x", ...ARROW_TYPES] as const;
type IconCloseType = (typeof ICON_CLOSED_TYPES)[number];
type IconOpenType = (typeof ICON_OPEN_TYPES)[number];
 
const isValidIconClosed = (value: string): value is IconCloseType =>
  MH.includes(ICON_CLOSED_TYPES, value);
 
const isValidIconOpen = (value: string): value is IconOpenType =>
  MH.includes(ICON_OPEN_TYPES, value);
 
// For HTML API only
const triggerConfigValidator: WidgetConfigValidatorObject<OpenableTriggerConfig> =
  {
    id: validateString,
    className: validateStrList,
    autoClose: validateBoolean,
    hover: validateBoolean,
    preventDefault: validateBoolean,
    icon: (key, value) =>
      value && toBoolean(value) === false
        ? false
        : validateString(key, value, isValidPosition),
    iconClosed: (key, value) => validateString(key, value, isValidIconClosed),
    iconOpen: (key, value) => validateString(key, value, isValidIconOpen),
  };
 
// For HTML API only
const collapsibleConfigValidator: WidgetConfigValidatorObject<CollapsibleConfig> =
  {
    id: validateString,
    className: validateStrList,
    horizontal: validateBoolean,
    reverse: validateBoolean,
    peek: validateBooleanOrString,
    autoClose: validateBoolean,
    icon: (key, value) =>
      toBoolean(value) === false
        ? false
        : validateString(key, value, isValidPosition),
    iconClosed: (key, value) => validateString(key, value, isValidIconClosed),
    iconOpen: (key, value) => validateString(key, value, isValidIconOpen),
  };
 
// For HTML API only
const popupConfigValidator: WidgetConfigValidatorObject<PopupConfig> = {
  id: validateString,
  className: validateStrList,
  closeButton: validateBoolean,
  position: (key, value) =>
    validateString(
      key,
      value,
      (v) => v === S_AUTO || isValidPosition(v) || isValidTwoFoldPosition(v),
    ),
  autoClose: validateBoolean,
};
 
// For HTML API only
const modalConfigValidator: WidgetConfigValidatorObject<ModalConfig> = {
  id: validateString,
  className: validateStrList,
  closeButton: validateBoolean,
  autoClose: validateBoolean,
};
 
// For HTML API only
const offcanvasConfigValidator: WidgetConfigValidatorObject<OffcanvasConfig> = {
  id: validateString,
  className: validateStrList,
  closeButton: validateBoolean,
  position: (key, value) => validateString(key, value, isValidPosition),
  autoClose: validateBoolean,
};
 
const getPrefixedNames = (name: string) => {
  const pref = MH.prefixName(name);
  return {
    _root: `${pref}__root`,
    _overlay: `${pref}__overlay`, // only used for modal/offcanvas
    _innerWrapper: `${pref}__inner-wrapper`,
    _outerWrapper: `${pref}__outer-wrapper`,
    _content: `${pref}__content`,
    _container: `${pref}__container`,
    _trigger: `${pref}__trigger`,
    // Use different classes for styling to the ones used for auto-discovering
    // elements, so that re-creating existing widgets can correctly find the
    // elements to be used by the new widget synchronously before the current
    // one is destroyed.
    _containerForSelect: `${pref}-container`,
    _triggerForSelect: `${pref}-trigger`,
    _contentId: `${pref}-content-id`,
  };
};
 
const findContainer = (content: Element, cls: string) => {
  const currWidget = instances.get(content);
  // If there's an existing widget that we're about to destroy, the content
  // element will be wrapped in several elements and won't be restored until
  // the next mutate time. In that case, to correctly determine the container
  // element, use the current widget's root element, which is located in the
  // content element's original place.
  let childRef = currWidget?.getRoot() ?? content;
  if (!MH.parentOf(childRef)) {
    // The current widget is not yet initialized (i.e. we are re-creating it
    // immediately after it was constructed)
    childRef = content;
  }
 
  // Find the content container
  let container = MH.closestParent(childRef, `.${cls}`);
  if (!container) {
    container = MH.parentOf(childRef);
  }
 
  Iif (container && !MH.isHTMLElement(container)) {
    logError(MH.usageError("Openable widget supports only HTMLElement"));
    return null;
  }
 
  return container;
};
 
const findTriggers = (
  content: Element,
  prefixedNames: ReturnType<typeof getPrefixedNames>,
) => {
  const container = findContainer(content, prefixedNames._containerForSelect);
  // jsdom does not like the below selector when suffixed by [data-*] or :not()...
  // const triggerSelector = `:is(.${prefixedNames._triggerForSelect},[data-${prefixedNames._triggerForSelect}])`;
  // So use this:
  const getTriggerSelector = (suffix: string) =>
    `.${prefixedNames._triggerForSelect}${suffix},` +
    `[data-${prefixedNames._triggerForSelect}]${suffix}`;
 
  const contentId = getData(content, prefixedNames._contentId);
  let triggers: Element[] = [];
 
  if (contentId) {
    triggers = [
      ...MH.docQuerySelectorAll(
        getTriggerSelector(`[data-${prefixedNames._contentId}="${contentId}"]`),
      ),
    ];
  } else if (container) {
    triggers = [
      ...MH.querySelectorAll(
        container,
        getTriggerSelector(`:not([data-${prefixedNames._contentId}])`),
      ),
    ].filter((t) => !content.contains(t));
  }
 
  return triggers;
};
 
const getTriggersFrom = (
  content: Element,
  inputTriggers: OpenableConfig["triggers"],
  wrapTriggers: boolean,
  prefixedNames: ReturnType<typeof getPrefixedNames>,
) => {
  const triggerMap = MH.newMap<Element, OpenableTriggerConfig>();
 
  inputTriggers = inputTriggers ?? findTriggers(content, prefixedNames);
 
  const addTrigger = (
    trigger: Element,
    triggerConfig: OpenableTriggerConfig,
  ) => {
    if (wrapTriggers) {
      const wrapper = createWrapperFor(trigger);
      wrapElement(trigger, { wrapper, ignoreMove: true }); // no need to await
      trigger = wrapper;
    }
 
    triggerMap.set(trigger, triggerConfig);
  };
 
  if (MH.isArray(inputTriggers)) {
    for (const trigger of inputTriggers) {
      addTrigger(
        trigger,
        getWidgetConfig(
          getData(trigger, prefixedNames._triggerForSelect),
          triggerConfigValidator,
        ),
      );
    }
  } else if (MH.isInstanceOf(inputTriggers, Map)) {
    for (const [trigger, triggerConfig] of inputTriggers.entries()) {
      addTrigger(trigger, triggerConfig ?? {});
    }
  }
 
  return triggerMap;
};
 
const init = (
  widget: Openable,
  content: HTMLElement,
  config: OpenableConfig,
): ElementsCollection => {
  const prefixedNames = getPrefixedNames(config.name);
  const container = findContainer(content, prefixedNames._containerForSelect);
 
  const wrapTriggers = config.wrapTriggers ?? false;
  const triggers = getTriggersFrom(
    content,
    config.triggers,
    wrapTriggers,
    prefixedNames,
  );
 
  // Create two wrappers
  const innerWrapper = MH.createElement("div");
  addClasses(innerWrapper, prefixedNames._innerWrapper);
 
  const outerWrapper = wrapElementNow(innerWrapper);
 
  // Setup the root element.
  // For off-canvas types we need another wrapper to serve as the root and we
  // need a placeholder element to save the content's original position so it
  // can be restored on destroy.
  // Otherwise use outerWrapper for root and insert the root where the content
  // was.
  let root: HTMLElement;
  let placeholder: HTMLElement;
  if (config.isOffcanvas) {
    addClasses(outerWrapper, prefixedNames._outerWrapper);
    root = wrapElementNow(outerWrapper);
    placeholder = MH.createElement("div");
 
    const overlay = MH.createElement("div");
    addClasses(overlay, prefixedNames._overlay);
    moveElement(overlay, { to: root });
  } else {
    // Otherwise use the outer wrapper as the root
    root = placeholder = outerWrapper;
  }
 
  if (config.id) {
    root.id = config.id;
  }
 
  if (config.className) {
    addClassesNow(root, ...toArrayIfSingle(config.className));
  }
 
  unsetBooleanData(root, PREFIX_IS_OPEN);
  const domID = getOrAssignID(root, config.name);
 
  if (config.isModal) {
    MH.setAttr(root, MC.S_ROLE, "dialog");
    MH.setAttr(root, S_ARIA_MODAL);
  }
 
  addClasses(root, prefixedNames._root);
  disableInitialTransition(root);
 
  // Add a close button?
  if (config.closeButton) {
    const closeBtn = MH.createButton("Close");
    addClasses(closeBtn, PREFIX_CLOSE_BTN);
 
    // If autoClose is true, it will be closed on click anyway, because the
    // close button is outside the content.
    addEventListenerTo(closeBtn, MC.S_CLICK, () => {
      widget.close();
    });
 
    moveElement(closeBtn, { to: config.isOffcanvas ? root : innerWrapper });
  }
 
  // Transfer the relevant classes/data attrs from content to root element, so
  // that our CSS can work without :has.
  // This won't cause forced layout since the root is not yet attached to the
  // DOM.
  for (const cls of [
    settings.lightThemeClassName,
    settings.darkThemeClassName,
  ]) {
    Iif (hasClass(content, cls)) {
      addClasses(root, cls);
    }
  }
 
  const elements = {
    content,
    root,
    container,
    outerWrapper,
    triggers,
  };
 
  // -------------------- Close / destroy hooks
  widget.onClose(async () => {
    for (const trigger of triggers.keys()) {
      delData(trigger, PREFIX_OPENS_ON_HOVER);
      MH.unsetAttr(trigger, S_ARIA_EXPANDED);
      await unsetBooleanData(trigger, PREFIX_IS_OPEN);
    }
  });
 
  widget.onDestroy(async () => {
    await waitForMutateTime();
 
    replaceElementNow(placeholder, content, { ignoreMove: true });
    moveElementNow(root); // remove
    removeClassesNow(content, prefixedNames._content);
 
    if (container) {
      removeClassesNow(container, prefixedNames._container);
    }
 
    for (const [trigger, triggerConfig] of triggers.entries()) {
      MH.delAttr(trigger, MC.S_ARIA_CONTROLS);
      MH.delAttr(trigger, S_ARIA_EXPANDED);
 
      delDataNow(trigger, PREFIX_OPENS_ON_HOVER);
      delDataNow(trigger, PREFIX_IS_OPEN);
 
      removeClassesNow(
        trigger,
        prefixedNames._trigger,
        ...(triggerConfig?.className || []),
      );
 
      Iif (trigger.id === triggerConfig?.id) {
        trigger.id = "";
      }
 
      if (wrapTriggers) {
        replaceElementNow(trigger, MH.childrenOf(trigger)[0], {
          ignoreMove: true,
        });
      }
    }
 
    triggers.clear();
 
    for (const el of [content, ...triggers.keys()]) {
      if (instances.get(el) === widget) {
        MH.deleteKey(instances, el);
      }
    }
  });
 
  // -------------------- SETUP
  // Save the elements so we can lookup the instance
  const currWidget = instances.get(content);
  for (const el of [content, ...triggers.keys()]) {
    instances.set(el, widget);
  }
 
  // Wait for the DOMWatcher to be active, which may not be before interactive.
  waitForInteractive()
    .then(currWidget?.destroy)
    .then(waitForMutateTime)
    .then(() => {
      if (widget.isDestroyed()) {
        return;
      }
 
      addClassesNow(content, prefixedNames._content);
 
      if (container) {
        addClassesNow(container, prefixedNames._container);
      }
 
      if (config.isOffcanvas) {
        moveElementNow(root, {
          to: MH.getBody(),
          ignoreMove: true,
        });
      }
 
      // Move the placeholder element to before the content and then move
      // content into inner wrapper.
      moveElementNow(placeholder, {
        // for not-offcanvas it's also the root
        to: content,
        position: "before",
        ignoreMove: true,
      });
 
      moveElementNow(content, { to: innerWrapper, ignoreMove: true });
 
      // Setup the triggers
      for (const [trigger, triggerConfig] of triggers.entries()) {
        MH.setAttr(trigger, MC.S_ARIA_CONTROLS, domID);
        MH.unsetAttr(trigger, S_ARIA_EXPANDED);
 
        setBooleanDataNow(
          trigger,
          PREFIX_OPENS_ON_HOVER,
          triggerConfig[MC.S_HOVER],
        );
        unsetBooleanDataNow(trigger, PREFIX_IS_OPEN);
 
        addClassesNow(
          trigger,
          prefixedNames._trigger,
          ...(triggerConfig?.className || []),
        );
 
        Iif (triggerConfig?.id) {
          trigger.id = triggerConfig.id;
        }
      }
 
      setupListeners(widget, elements, config, prefixedNames);
 
      if (config.onSetup) {
        config.onSetup();
      }
    });
 
  return elements;
};
 
const setupListeners = (
  widget: Openable,
  elements: ElementsCollection,
  config: OpenableConfig,
  prefixedNames: ReturnType<typeof getPrefixedNames>,
) => {
  const { content, root, triggers } = elements;
  const doc = MH.getDoc();
 
  let hoverTimeOpened = 0;
  let isPointerOver = false;
  let activeTrigger: Element | null = null;
 
  // ----------
 
  const isTrigger = (element: Element) =>
    MH.includes(
      [...triggers.keys()],
      MH.closestParent(
        element,
        getDefaultWidgetSelector(prefixedNames._trigger),
      ),
    );
 
  const shouldPreventDefault = (trigger: Element) =>
    triggers.get(trigger)?.preventDefault ?? true;
 
  const usesHover = (trigger: Element) => triggers.get(trigger)?.hover;
 
  const usesAutoClose = (trigger: Element | null) =>
    (trigger ? triggers.get(trigger)?.autoClose : null) ?? config.autoClose;
 
  // ----------
 
  const toggleTrigger = (event: Event, openIt?: boolean) => {
    const trigger = MH.currentTargetOf(event);
    if (MH.isElement(trigger)) {
      if (shouldPreventDefault(trigger)) {
        MH.preventDefault(event);
      }
 
      // If a click was fired shortly after opening on hover, ignore
      Iif (
        openIt !== false && // not explicitly asked to close
        widget.isOpen() &&
        MH.timeSince(hoverTimeOpened) < MIN_CLICK_TIME_AFTER_HOVER_OPEN
      ) {
        return;
      }
 
      if (openIt ?? !widget.isOpen()) {
        // open it
        activeTrigger = trigger;
        MH.setAttr(trigger, S_ARIA_EXPANDED); // will be unset on close
        setBooleanData(trigger, PREFIX_IS_OPEN); // will be unset on close
 
        widget.open(); // no need to await
 
        if (usesAutoClose(trigger)) {
          if (usesHover(trigger)) {
            addEventListenerTo(root, MC.S_POINTERENTER, setIsPointerOver);
            addEventListenerTo(root, MC.S_POINTERLEAVE, pointerLeft);
          }
 
          // auto-close listeners setup by the onOpen handler below
        }
      } else {
        widget.close(); // out onClose handler below will remove listeners
      }
    }
  };
 
  // ----------
 
  const setIsPointerOver = () => {
    isPointerOver = true;
  };
 
  // ----------
 
  const unsetIsPointerOver = (event: Event) => {
    // Keep it set to true if this is a touch pointer type; otherwise unset
    isPointerOver = isPointerOver && MH.isTouchPointerEvent(event);
  };
 
  // ----------
 
  const pointerEntered = (event: Event) => {
    setIsPointerOver();
    if (!widget.isOpen()) {
      hoverTimeOpened = MH.timeNow();
      toggleTrigger(event, true);
    }
  };
 
  // ----------
 
  const pointerLeft = (event: Event) => {
    unsetIsPointerOver(event);
    const trigger = MH.currentTargetOf(event);
    if (MH.isElement(trigger) && usesAutoClose(trigger)) {
      MH.setTimer(
        () => {
          if (!isPointerOver) {
            widget.close();
          }
        },
        // use a delay that allows the mouse to move from trigger to content
        // without closing it
        // TODO make this user-configurable
        config.isOffcanvas ? 300 : 50,
      );
    }
  };
 
  // ----------
 
  const closeIfEscape = (event: Event) => {
    if ((event as KeyboardEvent).key === "Escape") {
      widget.close(); // no need to await
    }
  };
 
  // ----------
 
  const closeIfClickOutside = (event: Event) => {
    const target = MH.targetOf(event);
    if (
      target === doc ||
      (MH.isElement(target) &&
        !content.contains(target) && // outside content
        !isTrigger(target)) // handled by pointer watcher
    ) {
      widget.close();
    }
  };
 
  // ----------
 
  const maybeSetupAutoCloseListeners = (
    trigger: Element | null,
    remove: boolean,
  ) => {
    if (usesAutoClose(trigger)) {
      const addOrRemove = remove ? removeEventListenerFrom : addEventListenerTo;
 
      addOrRemove(doc, "keyup", closeIfEscape);
 
      // Add a short delay so that we don't catch the bubbling of the click event
      // that opened the widget.
      MH.setTimer(() => addOrRemove(doc, MC.S_CLICK, closeIfClickOutside), 100);
 
      if (trigger && usesHover(trigger)) {
        addOrRemove(trigger, MC.S_POINTERLEAVE, pointerLeft);
      }
    }
  };
 
  // ----------
 
  const setupOrCleanup = (remove: boolean) => {
    const addOrRemove = remove ? removeEventListenerFrom : addEventListenerTo;
 
    for (const [trigger, triggerConfig] of triggers.entries()) {
      // Always setup click listeners
      addOrRemove(trigger, MC.S_CLICK, toggleTrigger);
 
      if (triggerConfig[MC.S_HOVER]) {
        addOrRemove(trigger, MC.S_POINTERENTER, pointerEntered);
      }
    }
  };
 
  // ----------
 
  setupOrCleanup(false);
 
  widget.onOpen(() => {
    maybeSetupAutoCloseListeners(activeTrigger, false); // setup listeners if relevant
  });
 
  widget.onClose(() => {
    hoverTimeOpened = 0;
    isPointerOver = false;
 
    removeEventListenerFrom(root, MC.S_POINTERENTER, setIsPointerOver);
    removeEventListenerFrom(root, MC.S_POINTERLEAVE, pointerLeft);
 
    maybeSetupAutoCloseListeners(activeTrigger, true); // remove listeners if any
    activeTrigger = null;
  });
 
  widget.onDestroy(() => {
    setupOrCleanup(true); // remove
  });
};
 
// COLLAPSIBLE ------------------------------
 
const insertCollapsibleIcon = (
  trigger: Element,
  triggerConfig: OpenableTriggerConfig,
  widget: Collapsible,
  widgetConfig: CollapsibleConfig | undefined,
) => {
  const iconPosition = triggerConfig.icon ?? widgetConfig?.icon;
  const iconClosed =
    (triggerConfig.iconClosed ?? widgetConfig?.iconClosed) || "plus";
  const iconOpen =
    (triggerConfig.iconOpen ?? widgetConfig?.iconOpen) || "minus";
 
  if (iconPosition) {
    addClasses(trigger, PREFIX_ICON_WRAPPER);
    setData(trigger, PREFIX_ICON_POSITION, iconPosition);
 
    const icon = MH.createElement("span");
    setDataNow(icon, PREFIX_TRIGGER_ICON, iconClosed);
 
    for (let l = 0; l < 2; l++) {
      const line = MH.createElement("span");
      addClassesNow(line, PREFIX_LINE);
      moveElementNow(line, { to: icon });
    }
 
    moveElement(icon, { to: trigger, ignoreMove: true });
 
    widget.onOpen(() => {
      Iif (getBooleanData(trigger, PREFIX_IS_OPEN)) {
        setData(icon, PREFIX_TRIGGER_ICON, iconOpen);
      }
    });
 
    widget.onClose(() => {
      setData(icon, PREFIX_TRIGGER_ICON, iconClosed);
    });
  }
};
 
// POPUP ------------------------------
 
const fetchPopupPlacement = async (
  contentSize: SizeData,
  containerView: ViewData,
) => {
  const containerPosition = containerView.relative;
  const containerTop = containerPosition[MC.S_TOP];
  const containerBottom = containerPosition[MC.S_BOTTOM];
  const containerLeft = containerPosition[MC.S_LEFT];
  const containerRight = containerPosition[MC.S_RIGHT];
  const containerHMiddle = containerPosition.hMiddle;
  const containerVMiddle = containerPosition.vMiddle;
  const vpSize = await fetchViewportSize();
  const popupWidth = contentSize.border[MC.S_WIDTH] / vpSize[MC.S_WIDTH];
  const popupHeight = contentSize.border[MC.S_HEIGHT] / vpSize[MC.S_HEIGHT];
 
  // - Find the maximum of these quantities:
  //   - containerTop - popupHeight:
  //     the space on top if placed on top-(left|right|)
  //   - 1 - (containerBottom + popupHeight):
  //     the space on bottom be if placed on bottom-(left|right|)
  //   - containerLeft - popupWidth:
  //     the space on left if placed on left-(top|bottom|)
  //   - 1 - (containerRight + popupWidth):
  //     the space on right if placed on right-(top|bottom|)
  //
  // This determines the main placement: top|bottom|left|right
 
  // Then to determine secondary alignment:
  // - For top/bottom placement, determine horizontal alignment:
  //   - Find the maximum of these quantities:
  //     - 1 - (containerLeft + popupWidth):
  //       the space on right if left-aligned
  //     - containerRight - popupWidth:
  //       the space on left if right-aligned
  //     - min(
  //           containerHMiddle - popupWidth / 2,
  //           1 - (containerHMiddle + popupWidth / 2),
  //       ):
  //       the minimum of the space on either left or right if center-aligned
  //
  // - For left/right placement, determine vertical alignment:
  //   - Find the maximum of these quantities:
  //     - 1 - (containerTop + popupHeight):
  //       the space on bottom if top-aligned
  //     - containerBottom - popupHeight:
  //       the space on top if bottom-aligned
  //     - min(
  //           containerVMiddle - popupHeight / 2,
  //           1 - (containerVMiddle + popupHeight / 2),
  //       ):
  //       the minimum of the space on either top or bottom if center-aligned
 
  const placementVars = {
    top: containerTop - popupHeight,
    bottom: 1 - (containerBottom + popupHeight),
    left: containerLeft - popupWidth,
    right: 1 - (containerRight + popupWidth),
  };
 
  const placement = keyWithMaxVal(placementVars);
  Iif (placement === undefined) {
    // container must be out-view and so left/right are NaN
    return;
  }
  let finalPlacement = placement;
 
  let alignmentVars;
  switch (placement) {
    case MC.S_TOP:
    case MC.S_BOTTOM:
      alignmentVars = {
        left: 1 - (containerLeft + popupWidth),
        right: containerRight - popupWidth,
        middle: MH.min(
          containerHMiddle - popupWidth / 2,
          1 - (containerHMiddle + popupWidth / 2),
        ),
      };
      break;
 
    case MC.S_LEFT:
    case MC.S_RIGHT:
      alignmentVars = {
        top: 1 - (containerTop + popupHeight),
        bottom: containerBottom - popupHeight,
        middle: MH.min(
          containerVMiddle - popupHeight / 2,
          1 - (containerVMiddle + popupHeight / 2),
        ),
      };
      break;
 
    default:
      return;
  }
 
  const alignment = keyWithMaxVal(alignmentVars);
  Iif (alignment !== "middle") {
    finalPlacement += "-" + alignment;
  }
 
  return finalPlacement;
};