All files / src/form/select Select.ts

86.65% Statements 2104/2428
83.17% Branches 361/434
84.33% Functions 70/83
86.65% Lines 2104/2428

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 242992x 92x 365x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 262x 262x 262x 262x 262x 262x 262x 262x 262x 262x 262x 262x 262x 262x 262x 815x 815x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 876x 876x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 234x 234x 234x 234x 234x 242x 235x 235x 235x 242x 242x 344x 235x 235x 235x 235x 235x 1268x 1268x 1268x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 347x 368x 431x 431x 431x 431x 416x 416x 431x 92x 92x 2x 2x 2x 92x 18x 18x 92x 244x 227x 227x 227x 227x 880x 880x 880x 1769x 1769x 880x 880x 880x 880x 880x 880x 880x 880x 9x 9x 9x 9x 9x 9x 9x 880x 880x 880x 880x 880x 880x 751x 751x 751x 6x 880x 880x 880x 880x 7x 7x 15x 15x 227x 227x 127x 127x 127x 244x 92x 10x 10x 10x 10x 5x 5x 5x 5x 5x 5x 14x 14x 14x 14x 14x 14x 5x 2x 5x 5x 3x 5x 5x 5x 5x 5x 5x                           92x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 92x 1268x 134x 134x 134x 1268x 1268x 1268x 1268x 1268x 26x 26x 26x 26x 26x 26x 26x 26x 26x 1268x 1268x 1268x 259x 10x                           10x 10x 1268x 569x 569x 395x 395x 395x 395x 245x 245x 245x 245x 245x 245x 245x 92x 321x 5x 316x 316x 316x 316x 316x 316x 316x 316x 316x 316x 316x 316x 316x 316x 316x 92x 43x 43x 43x 43x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 92x 899x 899x 12x 12x 12x 92x 256x 256x 256x 256x 92x 686x 686x 686x 686x 643x 643x 43x 43x 43x 477x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 92x 686x 439x 439x 439x 439x 439x 439x 626x 374x 374x   612x 612x 278x 278x 278x 278x 278x 612x 92x 1268x 1268x 1268x 620x 620x 1268x 686x 1268x 1268x 133x 1268x 22x 22x 22x 22x 22x 22x 22x 22x 1x 1268x 1268x 1268x 1268x 133x 133x 133x 133x 111x 111x 111x 61x 61x 61x 61x 1x 111x 1268x 569x 569x 569x 44x 44x 1268x 1268x 1268x 1268x 1268x 1268x 345x 345x 345x 345x 345x 374x 374x 53x 53x 53x 6x 53x 6x 53x 47x 47x 47x 47x             47x 47x 47x 47x 27x 47x 374x 1268x 289x 289x 289x 289x 1268x 5x 7x 5x 5x 5x 1268x 1268x 1268x 1268x 1268x 1268x               92x 569x 569x 569x 569x 569x 44x 44x 44x 44x 44x 11x 44x 44x 293x 569x 56x 92x 2x 2x 2x 2x 2x 2x 4x 2x 2x 92x 619x 619x 619x 619x 444x 363x 363x 363x 251x 251x 251x 363x 251x 251x 251x 251x 251x 251x 251x 251x 251x 112x 112x 112x 112x 112x 284x 284x 284x 284x 284x 284x 284x 284x 284x 284x 284x 284x 284x 284x 284x 284x 284x 112x 363x 92x 14x 14x 14x 7x 7x 7x 7x 7x 14x 12x 14x 14x 14x 92x 195x 189x 195x   92x 14x 14x 2x 2x 14x     14x 14x 14x 14x 14x 14x 14x 14x 14x 14x                                                               14x 14x 14x 14x 14x 14x 63x 63x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x         1x 1x 1x 63x 63x 1x 1x 63x                                                 5x 5x 5x 5x   5x 63x 519x 519x 519x 519x 63x 561x 561x 561x 561x 561x 561x 561x 383x 383x 63x 63x 63x 63x 63x 555x 555x 555x 555x 555x     519x 519x 519x 36x 36x 63x 92x 92x 92x 92x 92x 92x 92x                               92x 92x 92x 2751x 2751x 2751x 2751x 92x 92x 92x 92x 92x 92x 92x 92x 92x 111x 111x 111x 111x 9x 9x 9x 9x 9x 19x 1x 1x 1x 1x 1x 1x 1x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 1x 19x 92x 92x 92x 92x 92x 92x 92x 39x 39x 39x 39x 6x 6x 6x 6x 6x 6x 6x 6x 12x 12x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 39x 32x 32x 32x 32x               32x 32x 32x 32x 32x 39x 1x 1x 1x 1x 92x 92x 92x 92x 92x 9157x 9157x 92x         92x 14x 14x 14x 14x 92x 2x 92x 27x 27x 27x 27x 76x 76x   76x 27x 27x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x                                                 5x 27x 15x 15x 15x 7x 7x 19x 25x 25x 25x 25x 15x 8x 6x 8x 8x 8x 8x 2x 2x 8x 8x 27x 27x 27x 27x 27x     27x 27x 27x 27x 27x 92x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 92x 92x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x                   27x 27x               27x 27x 3x 3x 3x                   3x       3x 3x 3x 3x 1x 1x 1x 1x 1x 1x         1x 1x 1x 3x 2x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                               1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x             1x 27x 24x 24x 24x 24x 24x 24x 92x 19x 19x 19x 19x 92x 19x 19x 19x 19x 19x 19x 19x 19x 2x 2x 2x 2x 2x 19x 19x 19x 12x 19x 11x 11x 19x 19x 19x 19x 19x   19x                   92x 42x 42x 92x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 10x 10x     10x 10x   10x 317x 317x 317x 317x 317x 317x 317x 4x   4x 4x 4x 4x 2x 2x 2x 4x 4x 4x 3x 3x 3x 92x 326x 326x 326x 326x   326x 326x 2x 2x 326x 2x 2x 1x 1x 1x 326x 324x 326x 11x 326x 11x 11x 326x 5x 5x 5x 5x 319x 319x 319x 326x 313x 313x 313x 326x 6x 6x 6x 6x       326x 326x 326x                                 319x 319x 92x 92x 314x 314x 314x 314x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x   314x 277x 277x 92x 92x 777x 92x 92x 92x 92x 92x 92x 92x 92x 55x 55x 92x 92x 92x 61x 61x 61x 61x 61x 61x 61x 61x 92x 98x 98x 1x 1x 97x 98x 61x 61x 61x 61x 98x 55x 55x 55x 55x 42x 55x 13x 13x 13x 55x   55x 13x 13x 92x 512x 512x 512x 512x 512x 512x 512x 512x 92x                     10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 3x 20x 20x 20x 20x 20x 20x 20x 20x 3x 20x 20x 20x 1169x 1159x 1159x 1159x 1169x   1169x 1169x 1169x 1169x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 1169x           1169x 1169x 92x 1081x 1081x 1081x 1081x 1081x 92x 780x 780x 780x 780x 780x 780x 218x 92x                         92x 1x 1x   1x 1x 1x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 92x 25x 25x 25x 25x 25x 25x 25x 25x 92x                                                             92x           92x                       2502x 2502x 2502x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 92x 92x 92x 92x 92x 92x 92x 311x 92x 92x 75x 75x 75x 75x 75x 324x 92x 92x 137x 92x 73x 68x 68x 68x 68x 68x 68x 68x 68x 68x 73x 73x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 391x 391x 92x 92x 92x 92x 332x 332x 92x 84x 84x 84x 84x 84x 84x 84x 84x 84x 742x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 173x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 513x 702x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 702x 63x 702x 702x 702x 702x 63x 91x 91x 91x 91x 91x 91x 91x 703x 512x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 512x 512x 512x 109x 109x 109x 109x 109x 109x 109x 63x 63x 63x 63x 63x 512x 512x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 63x 63x 63x 70x 70x 70x 512x 703x 194x 194x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 67x 67x 67x 67x 67x 67x 67x 92x 65x 65x 65x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 92x 92x 92x  
/* eslint-disable @typescript-eslint/no-empty-function */
import { PropertyValues, TemplateResult, html, css } from 'lit';
import { property, state } from 'lit/decorators.js';
import {
  getUrl,
  getClasses,
  fetchResults,
  WebResponse,
  postJSON
} from '../../utils';
import '../../display/Options';
import '../../list/SortableList';
import { EventHandler } from '../../RapidElement';
import { FieldElement } from '../../form/FieldElement';
 
import { lru } from 'tiny-lru';
import { CompletionOption, CustomEventType, Position } from '../../interfaces';
import {
  renderCompletionOption,
  updateInputElementWithCompletion,
  executeCompletionQuery,
  sessionParser,
  messageParser
} from '../../excellent/helpers';
import { tokenize } from '../../excellent/tokenizer';
import {
  getCaretOffset,
  getCaretEndOffset,
  setCaretRange,
  getTextFromEditableDiv
} from '../../excellent/caret-utils';
import {
  EXPRESSION_TOKENS,
  getTokenClass,
  tokenCss
} from '../../excellent/token-styles';
import { Store } from '../../store/Store';
import { StyleInfo, styleMap } from 'lit-html/directives/style-map.js';
import { Icon } from '../../Icons';
import { msg } from '@lit/localize';
 
const LOOK_AHEAD = 20;
 
export interface SelectOption {
  name: string;
  value?: string;
  expression?: boolean;
  selected?: boolean;
  arbitrary?: boolean;
}
 
export class Select<T extends SelectOption> extends FieldElement {
  private hiddenInputs: HTMLInputElement[] = [];
 
  static get styles() {
    return css`
      ${super.styles}
 
      :host {
        --transition-speed: 0;
        font-family: var(--font-family);
        transition: all ease-in-out var(--transition-speed);
        display: inline;
        line-height: normal;
        outline: none;
        position: relative;
        --icon-color: var(--color-text-dark-secondary);
      }
 
      temba-options {
        --temba-options-font-size: var(--temba-select-selected-font-size);
        --icon-color: var(--color-text-dark);
        --color-options-bg: #fff;
        /* Always use normal border colors for options popup, even when select is in error state */
        --color-widget-border: #ddd;
        --color-focus: #007bff;
        --widget-box-shadow-focused: 0 0 0 3px rgba(0, 123, 255, 0.25);
      }
 
      :host:focus {
        outline: none;
      }
 
      #anchor {
        position: absolute;
        visibility: hidden;
        width: 250px;
        height: 25px;
      }
 
      .remove-item {
        cursor: pointer;
        display: inline-block;
        padding: 3px 6px;
        border-right: 1px solid rgba(100, 100, 100, 0.2);
        margin: 0;
      }
 
      .selected-item.multi .remove-item {
        display: none;
      }
 
      .remove-item:hover {
        background: rgba(100, 100, 100, 0.1);
      }
 
      input:focus {
        outline: none;
        box-shadow: none;
        cursor: text;
      }
 
      .wrapper-bg {
        background: var(--select-wrapper-bg, #fff);
        box-shadow: var(
          --select-wrapper-shadow,
          inset 0px 0px 4px rgb(0 0 0 / 10%)
        );
        border-radius: var(--curvature-widget);
      }
 
      .select-container {
        display: flex;
        flex-direction: row;
        flex-wrap: nowrap;
        align-items: center;
        border: 1px solid var(--color-widget-border);
        transition: all ease-in-out var(--transition-speed);
        cursor: pointer;
        border-radius: var(--curvature-widget);
        background: var(--color-widget-bg);
        padding-top: 1px;
        box-shadow: var(--widget-box-shadow);
        position: relative;
        min-height: var(--temba-select-min-height, 2.4em);
        max-height: var(--temba-select-max-height, none);
        overflow: hidden;
      }
 
      temba-icon.select-open:hover,
      .clear-button:hover {
        --icon-color: var(--color-text-dark);
      }
 
      .select-container:focus {
        outline: none;
      }
 
      .select-container.multi {
        /* background: var(--color-widget-bg); */
      }
 
      .select-container.focused {
        background: var(--color-widget-bg-focused);
        border-color: var(--color-focus);
        box-shadow: var(--widget-box-shadow-focused);
      }
 
      .left-side {
        flex: 1;
        overflow: hidden;
        display: flex;
        align-items: center;
      }
 
      .empty .placeholder {
        display: block;
      }
 
      .selected {
        flex: 1;
        display: flex;
        flex-direction: row;
        align-items: stretch;
        user-select: none;
        padding: var(--temba-select-selected-padding, 0px 4px);
      }
 
      .searchable .selected {
        padding: 4px !important;
      }
 
      .multi .selected {
        flex-wrap: wrap;
        padding: 4px;
      }
 
      .multi.empty .selected {
        padding: var(--temba-select-selected-padding);
      }
 
      .selected .selected-item {
        display: flex;
        overflow: hidden;
        color: var(--color-widget-text);
        line-height: var(--temba-select-selected-line-height);
        --icon-color: var(--color-text-dark);
      }
 
      .multi .selected .selected-item {
        vertical-align: middle;
        background: #fff;
        border: 1px solid rgba(100, 100, 100, 0.3);
        user-select: none;
        border-radius: 2px;
        align-items: stretch;
        flex-direction: row;
        flex-wrap: nowrap;
        margin: 2px 2px;
      }
 
      .option-name > span {
        text-align: left;
      }
 
      .selected-item .option-name {
        padding: 0px;
        font-size: var(--temba-select-selected-font-size);
        align-self: center;
      }
 
      .multi .selected-item .option-name {
        flex: 1 1 auto;
        align-self: center;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        font-size: 12px;
        padding: 2px 8px;
      }
 
      .multi .selected .selected-item.focused {
        background: rgba(100, 100, 100, 0.3);
      }
 
      .multi .selected-item.sortable {
        cursor: move;
      }
 
      .multi .selected-item.dragging {
        opacity: 0.5;
      }
 
      .multi temba-sortable-list {
        margin: 0 !important;
        flex-grow: 1;
      }
 
      input {
        font-size: 13px;
        width: 0px;
        cursor: pointer;
        background: none;
        resize: none;
        border: none !important;
        visibility: visible;
        line-height: inherit !important;
        height: var(--search-input-height) !important;
        margin: 0px !important;
        padding: 0px !important;
        box-shadow: none !important;
        font-family: var(--font-family);
        caret-color: var(--input-caret);
        border: 0px solid purple !important;
      }
 
      .input-wrapper:focus-within {
        min-width: 1px;
        display: flex;
      }
 
      .input-wrapper {
        min-width: 1px;
        margin-left: 6px;
        margin-right: -6px;
        display: none;
        pointer-events: none;
      }
 
      .multi .input-wrapper {
        margin-left: 6px !important;
        margin-right: 2px !important;
        margin-top: 2px;
        margin-bottom: 2px;
        min-width: 50px;
        flex: 1 0 auto;
        align-self: center;
      }
 
      .input-wrapper:focus-within .placeholder {
        display: none;
      }
 
      input:focus {
        box-shadow: none !important;
        flex-grow: 1;
      }
 
      .searchable.single.search-input .input-wrapper {
        flex-grow: 1;
        min-width: 1px !important;
      }
 
      .searchable.single.search-input .selected .selected-item {
        display: none;
      }
 
      .searchable input {
        visibility: visible;
        cursor: pointer;
        background: none;
        color: var(--color-text);
        resize: none;
        box-shadow: none !important;
        border: none;
        caret-color: var(--input-caret);
      }
 
      .searchable input:focus {
        box-shadow: none !important;
      }
 
      .input-wrapper .searchbox {
      }
 
      .searchbox {
        border: 0px;
      }
 
      /* Expression-highlighting contenteditable input */
      .searchbox.expression-input {
        outline: none;
        white-space: pre;
        overflow: hidden;
        min-width: 1px;
        background: none;
        color: var(--color-text);
        caret-color: var(--input-caret);
        font-family: var(--font-family);
        font-size: inherit;
        line-height: inherit;
        padding: 0;
      }
 
      .searchbox.expression-input:empty::before {
        content: '';
      }
 
      ${tokenCss}
 
      .placeholder {
        font-size: var(--temba-select-selected-font-size);
        color: var(--color-placeholder);
        display: none;
        line-height: var(--temba-select-selected-line-height);
        margin-left: 6px;
        pointer-events: none;
      }
 
      .empty .placeholder {
        display: block;
      }
 
      .multi .placeholder {
        display: block;
        margin: 2px 2px;
        padding: 2px 8px;
        align-self: center;
      }
 
      .footer {
        padding: 5px 10px;
        background: var(--color-primary-light);
        color: rgba(0, 0, 0, 0.5);
        font-size: 80%;
        border-bottom-left-radius: var(--curvature-widget);
        border-bottom-right-radius: var(--curvature-widget);
      }
 
      .small {
        --temba-select-selected-padding: 6px;
        --temba-select-selected-line-height: 12px;
        --temba-select-selected-font-size: 14px;
        --temba-select-min-height: 2.28em;
      }
 
      .xsmall {
        --temba-select-selected-padding: 4px 6px;
        --temba-select-selected-line-height: 13px;
        --temba-select-selected-font-size: 13px;
        --temba-select-min-height: 0em;
      }
 
      .info-text {
        opacity: 1;
        transition:
          padding-top var(--transition-speed) ease-in-out,
          padding-bottom var(--transition-speed) ease-in-out;
        margin-bottom: 16px;
        padding: 0.5em 1em;
        border-radius: var(--curvature);
        font-size: 0.9em;
        color: rgba(0, 0, 0, 0.5);
        position: relative;
      }
 
      .info-text.focused {
        opacity: 1;
      }
 
      .info-text.hide {
        opacity: 0;
        max-height: 0;
        margin-bottom: 0px;
        pointer-events: none;
        padding: 0px;
      }
 
      .enter-hint {
        position: fixed;
        z-index: 10000;
        font-size: 0.75em;
        color: rgba(0, 0, 0, 0.4);
        white-space: nowrap;
        pointer-events: none;
        background: rgba(255, 255, 255, 0.7);
        backdrop-filter: blur(4px);
        padding: 4px 10px;
        border-radius: 2px;
      }
    `;
  }
 
  @property({ type: Object })
  inputStyle: StyleInfo = {};
 
  @property({ type: Boolean })
  multi = false;
 
  @property({ type: Boolean })
  searchOnFocus = false;
 
  @property({ type: String })
  placeholder = '';
 
  @property()
  name = '';
 
  @property()
  endpoint: string;
 
  @property({ type: Boolean })
  allowCreate: boolean = false;
 
  @property({ type: String })
  nameKey = 'name';
 
  @property({ type: String })
  valueKey = 'value';
 
  @property({ type: Number })
  maxItems = 0;
 
  @property({ type: String })
  maxItemsText: string = 'Maximum items reached';
 
  @property({ attribute: false })
  currentFunction: CompletionOption;
 
  @property({ type: String })
  queryParam: string = null;
 
  @property({ type: String })
  input = '';
 
  @property({ type: Array })
  visibleOptions: any[] = [];
 
  @property({ type: Array })
  completionOptions: CompletionOption[] = [];
 
  @property({ type: Number })
  quietMillis = 0;
 
  @property({ type: Boolean })
  fetching: boolean;
 
  @property({ type: Boolean })
  resolving: boolean;
 
  @property({ type: Boolean })
  searchable = false;
 
  @property({ type: String })
  expressions: string;
 
  @property({ type: Boolean })
  cache = true;
 
  @property({ type: String })
  cacheKey = '';
 
  @property({ type: Boolean })
  focused = false;
 
  @property({ type: Boolean })
  disabled = false;
 
  @state()
  attemptedOpen = false;
 
  @property({ attribute: false })
  selectedIndex = -1;
 
  @property({ type: Number })
  cursorIndex: number;
 
  anchorElement: HTMLElement;
 
  anchorExpressions: HTMLElement;
 
  @property({ type: Object })
  anchorPosition: Position = { left: 0, top: 0 };
 
  @property({ type: Boolean })
  tags = false;
 
  @property({ type: Boolean })
  emails = false;
 
  @property({ type: Boolean, attribute: 'space_select' })
  spaceSelect: boolean;
 
  @property({ type: Boolean })
  jsonValue: boolean;
 
  @property({ type: Boolean })
  hideErrors: boolean;
 
  @property({ type: Boolean })
  clearable: boolean;
 
  @property({ type: Boolean })
  sorted: boolean;
 
  @property({ type: String })
  flavor = 'default';
 
  @property({ type: String, attribute: 'info_text' })
  infoText = '';
 
  // Override the setter to ensure values is always an array
  @property({ type: Array })
  set values(newValues: any) {
    this._values = Array.isArray(newValues) ? newValues : [];
    this.requestUpdate('values');
  }
 
  get values(): T[] {
    return this._values || [];
  }
 
  private _values: T[] = [];
 
  @property({ type: Object })
  selection: any;
 
  @property({ attribute: false })
  getName: (option: any) => string = (option: any) => {
    return option[this.nameKey || 'name'];
  };
 
  @property({ attribute: false })
  isMatch: (option: any, q: string) => boolean = this.isMatchDefault;
 
  @property({ attribute: false })
  getValue: (option: any) => string = (option: any) =>
    option[this.valueKey || 'value'] || option.id;
 
  @property({ type: Number, attribute: 'option-width' })
  optionWidth: number;
 
  @property({ type: Number, attribute: 'option-min-width' })
  optionMinWidth: number;
 
  @property({ type: Boolean, attribute: 'anchor-right' })
  anchorRight: boolean;
 
  @property({ attribute: false })
  shouldExclude: (option: any) => boolean;
 
  @property({ attribute: false })
  sortFunction: (a: any, b: any) => number = null;
 
  @property({ attribute: false })
  renderOption: (option: any, selected: boolean) => TemplateResult;
 
  @property({ attribute: false })
  renderOptionName: (option: any, selected: boolean) => TemplateResult;
 
  @property({ attribute: false })
  renderOptionDetail: (option: any, selected: boolean) => TemplateResult = () =>
    html``;
 
  @property({ attribute: false })
  renderSelectedItem: (option: any) => TemplateResult =
    this.renderSelectedItemDefault;
 
  @property({ attribute: false })
  createArbitraryOption: (input: string, options: any[]) => any =
    this.createArbitraryOptionDefault;
 
  @property({ attribute: false })
  getOptions: (response: WebResponse) => any[] = this.getOptionsDefault;
 
  @property({ attribute: false })
  prepareOptions: (options: any[]) => any[] = this.prepareOptionsDefault;
 
  @property({ attribute: false })
  isComplete: (newestOptions: any[], response: WebResponse) => boolean =
    this.isCompleteDefault;
 
  @property({ type: Array, attribute: 'options' })
  private staticOptions: any[] = [];
 
  @property({ type: Boolean })
  allowAnchor: boolean = true;
 
  @property({ type: String })
  draggingId: string;
 
  private alphaSort = (a: any, b: any) => {
    // by default, all endpoint values are sorted by name
    if (this.endpoint) {
      return this.getNameInternal(a).localeCompare(this.getNameInternal(b));
    }
    return 0;
  };
 
  private lastQuery: number;
 
  private complete: boolean;
  private page: number;
  private next: string = null;
  private query: string;
 
  private lruCache = lru(20, 60000);
 
  constructor() {
    super();
    this.renderOptionDefault = this.renderOptionDefault.bind(this);
    this.renderSelectedItemDefault = this.renderSelectedItemDefault.bind(this);
    this.prepareOptionsDefault = this.prepareOptionsDefault.bind(this);
    this.isMatchDefault = this.isMatchDefault.bind(this);
    this.handleOrderChanged = this.handleOrderChanged.bind(this);
    this.createArbitraryOption = this.createArbitraryOptionDefault.bind(this);
  }
 
  public prepareOptionsDefault(options: T[]): T[] {
    return options;
  }
 
  public isMatchDefault(option: T, q: string) {
    const name = this.getNameInternal(option) || '';
    return name.toLowerCase().indexOf(q) > -1;
  }
 
  public handleSlotChange() {
    if (this.staticOptions && this.staticOptions.length === 0) {
      for (const child of this.children) {
        if (child.tagName === 'TEMBA-OPTION') {
          const option: any = {};
          for (const attribute of child.attributes) {
            option[attribute.name] = attribute.value;
          }
 
          if (option) {
            let selected = false;
 
            // if the option is marked as selected then accept it
            if (option['selected'] !== undefined) {
              delete option['selected'];
              selected = true;
            }
 
            // the option value might also match the widget value
            const selectValue = this.value || this.getAttribute('value');
            if (selectValue) {
              const optionValue = this.getValue(option);
              if (optionValue == selectValue) {
                selected = true;
              }
            }
 
            this.staticOptions.push(option);
            if (selected) {
              if (this.isMultiMode) {
                this.addValue(option);
              } else {
                this.setValues([option]);
              }
            }
          }
        }
      }
    }
 
    if (this.searchable && this.staticOptions.length === 0) {
      this.quietMillis = 200;
    }
  }
 
  private checkSelectedOption() {
    // see if we need fetch to select an option
    if (
      this.value &&
      this.values.length == 0 &&
      this.staticOptions.length == 0 &&
      this.endpoint
    ) {
      const value = this.value;
      this.resolving = true;
 
      fetchResults(this.endpoint).then((results: any) => {
        if (results && results.length > 0) {
          if (value) {
            // if we started with a value, see if we can find it in the results
            const existing = results.find((option) => {
              return this.getValue(option) === value;
            });
            if (existing) {
              this.resolving = false;
              this.fetching = false;
              this.setValues([existing]);
              return;
            }
          }
 
          this.setValues([results[0]]);
          this.resolving = false;
        }
      });
    } else if (this.staticOptions.length > 0) {
      if (this.getAttribute('multi') !== null) {
        this.addValue(this.staticOptions[0]);
      } else {
        if (this.getAttribute('value')) {
          this.setSelectedValue(this.getAttribute('value'));
        } else {
          this.setValues([this.staticOptions[0]]);
        }
      }
    }
  }
 
  public firstUpdated(changedProperties: any) {
    super.firstUpdated(changedProperties);
    this.anchorElement = this.shadowRoot.querySelector('.select-container');
    this.anchorExpressions = this.shadowRoot.querySelector('#anchor');
    this.shadowRoot.addEventListener(
      'slotchange',
      this.handleSlotChange.bind(this)
    );
  }
 
  public willUpdate(changes: PropertyValues) {
    if (changes.has('createArbitraryOption')) {
      if (!this.createArbitraryOption) {
        this.createArbitraryOption =
          this.createArbitraryOptionDefault.bind(this);
      }
    }

    // default to the first option if we don't have a placeholder
    if (
      this.values.length === 0 &&
      !this.placeholder &&
      this.staticOptions.length > 0
    ) {
      const oldValues = this._values;
      this._values = [this.staticOptions[0]];
      this.requestUpdate('values', oldValues);
    }
 
    if (changes.has('sorted')) {
      this.sortFunction = this.sorted ? this.alphaSort : null;
    }
 
    // sync value → values for static options
    if (changes.has('value')) {
      if (this.value && !this.values.length) {
        if (this.staticOptions.length > 0) {
          const existing = this.staticOptions.find((option) => {
            return this.getValue(option) === this.value;
          });
          if (existing) {
            this._values = [existing];
            this.requestUpdate('values');
          }
        } else {
          this.checkSelectedOption();
        }
      }
    }
 
    // pre-sync value/selection from values to prevent warnings
    // when updateInputs() sets them again in updated()
    if (changes.has('values')) {
      if (this.values.length === 0) {
        this.value = null;
      } else {
        const name = this.getAttribute('name');
        if (name && !this.isMultiMode && this.values.length === 1) {
          this.selection = this.values[0];
          this.value = this.serializeValue(this.values[0]);
        }
      }
    }

    super.willUpdate(changes);
  }

  private measureInputTextWidth(searchbox: HTMLElement): number {
    if (this.useExpressionInput) {
      return searchbox.scrollWidth;
    }
    // Create a measuring span that inherits the searchbox's font styles
    const span = document.createElement('span');
    const style = getComputedStyle(searchbox);
    span.style.font = style.font;
    span.style.letterSpacing = style.letterSpacing;
    span.style.visibility = 'hidden';
    span.style.position = 'absolute';
    span.style.whiteSpace = 'pre';
    span.textContent = this.input;
    this.shadowRoot.appendChild(span);
    const width = span.offsetWidth;
    span.remove();
    return width;
  }
 
  private hintRepositionHandler: (() => void) | null = null;
 
  private addHintRepositionListeners() {
    if (this.hintRepositionHandler) return;
    this.hintRepositionHandler = () => this.updateEnterHintPosition();
    window.addEventListener('scroll', this.hintRepositionHandler, {
      capture: true,
      passive: true
    });
    window.addEventListener('resize', this.hintRepositionHandler);
  }
 
  private removeHintRepositionListeners() {
    if (!this.hintRepositionHandler) return;
    window.removeEventListener('scroll', this.hintRepositionHandler, {
      capture: true
    });
    window.removeEventListener('resize', this.hintRepositionHandler);
    this.hintRepositionHandler = null;
  }
 
  disconnectedCallback() {
    super.disconnectedCallback();
    this.removeHintRepositionListeners();
  }
 
  private updateEnterHintPosition() {
    const hint = this.shadowRoot.querySelector('.enter-hint') as HTMLElement;
    if (!hint) {
      this.removeHintRepositionListeners();
      return;
    }
    const searchbox = this.shadowRoot.querySelector(
      '.searchbox'
    ) as HTMLElement;
    if (!searchbox) return;
 
    this.addHintRepositionListeners();
 
    const searchboxRect = searchbox.getBoundingClientRect();
    const textWidth = this.measureInputTextWidth(searchbox);
 
    hint.style.left = `${searchboxRect.left + textWidth + 4}px`;
    hint.style.top = `${searchboxRect.top + (searchboxRect.height - hint.offsetHeight) / 2}px`;
  }
 
  private updateInputWrapperWidth() {
    if (!this.isMultiMode) return;
    const wrapper = this.shadowRoot.querySelector(
      '.input-wrapper'
    ) as HTMLElement;
    if (!wrapper) return;
    const searchbox = this.shadowRoot.querySelector(
      '.searchbox'
    ) as HTMLElement;
    if (!searchbox) return;
 
    if (this.input) {
      const textWidth = this.measureInputTextWidth(searchbox);
      // Add some breathing room for the caret and padding
      wrapper.style.minWidth = `${textWidth + 20}px`;
    } else {
      wrapper.style.minWidth = '';
    }
  }
 
  public updated(changes: Map<string, any>) {
    super.updated(changes);
 
    if (changes.has('input') || changes.has('focused')) {
      this.updateEnterHintPosition();
      this.updateInputWrapperWidth();
    }
 
    // Re-acquire anchor for expression completions (may not exist on first
    // render in multi mode since the input is only shown when focused)
    if (this.expressions && !this.anchorExpressions) {
      const anchor = this.shadowRoot.querySelector('#anchor') as HTMLElement;
      if (anchor) {
        this.anchorExpressions = anchor;
      }
    }
 
    // Patch the contenteditable expression input if it exists
    if (this.useExpressionInput) {
      const div = this.shadowRoot.querySelector(
        '.expression-input'
      ) as HTMLElement;
      if (div) {
        this.patchEditableAsInput(div);
        // Sync contenteditable content when input is changed programmatically
        // (e.g., cleared after adding a value). User-driven input is handled
        // synchronously in handleInput.
        if (changes.has('input')) {
          const currentText = getTextFromEditableDiv(div);
          if (currentText !== this.input) {
            this.renderExpressionHighlight(div, this.input);
          }
        }
      }
    }
 
    if (changes.has('values')) {
      this.updateInputs();
      if (this.hasChanges(changes.get('values'))) {
        this.fireEvent('change');
      }
    }
 
    // if our cache key changes, clear it out
    if (changes.has('cacheKey')) {
      this.lruCache.clear();
    }
 
    if (
      changes.has('input') &&
      !changes.has('values') &&
      !changes.has('options') &&
      this.focused
    ) {
      if (this.lastQuery) {
        window.clearTimeout(this.lastQuery);
      }
 
      this.lastQuery = window.setTimeout(() => {
        if (
          this.expressions &&
          this.input.indexOf('@') > -1 &&
          (!(this.emails || this.tags) ||
            this.input.trimStart().startsWith('@'))
        ) {
          this.fetchExpressions();
        } else {
          if (this.completionOptions.length > 0) {
            this.completionOptions = [];
          }
          if (!(this.emails || this.tags)) {
            this.fetchOptions(this.input);
          }
        }
      }, this.quietMillis);
    }
 
    if (this.endpoint && changes.has('fetching')) {
      if (!this.fetching && !this.isPastFetchThreshold()) {
        this.fireCustomEvent(CustomEventType.FetchComplete);
      }
    }
 
    // if our cursor changed, lets make sure our scrollbox is showing it
    if (
      (changes.has('cursorIndex') || changes.has('visibleOptions')) &&
      this.endpoint &&
      !this.fetching
    ) {
      if (this.isPastFetchThreshold()) {
        if (this.next) {
          this.fetchOptions(null, null, this.next);
        } else {
          this.fetchOptions(this.query, this.page + 1);
        }
      }
    }
  }

  private hasChanges(prev: T[]): boolean {
    // This will compare values to see if there is a change
    // Note: make sure value is populated or valueKey is set

    if (prev === undefined) {
      return false;
    }
 
    let prevValues = undefined;
    if (prev !== undefined) {
      prevValues = (prev || [])
        .map((option: T) => {
          return this.getValue(option);
        })
        .join(',');
    }
 
    const newValues = (this.values || [])
      .map((option: T) => {
        return option.arbitrary || this.getValue(option);
      })
      .join(',');
 
    return prevValues !== newValues;
  }
 
  public setSelectedValue(value: string) {
    if (this.staticOptions.length > 0) {
      const existing = this.staticOptions.find((option) => {
        return this.getValue(option) === value;
      });

      if (existing) {
        this.setValues([existing]);
      }
    } else {
      this.checkSelectedOption();
    }
  }
 
  private updateInputs(): void {
    for (let ele = null; (ele = this.hiddenInputs.pop()); ) {
      ele.remove();
    }
 
    if (this.values.length === 0) {
      this.value = null;
    } else {
      const name = this.getAttribute('name');
 
      if (name) {
        if (!this.isMultiMode && this.values.length === 1) {
          this.selection = this.values[0];
          this.value = this.serializeValue(this.values[0]);
 
          // Ensure FormElement internals are updated
          if (this.internals) {
            this.internals.setFormValue(this.value);
          }
        } else {
          if (this.inputRoot.parentElement) {
            this.values.forEach((value) => {
              const ele = document.createElement('input');
              ele.setAttribute('type', 'hidden');
              ele.setAttribute('name', name);
              ele.setAttribute('value', this.serializeValue(value));
              this.hiddenInputs.push(ele);
              this.inputRoot.parentElement.appendChild(ele);
            });
          }
        }
      }
    }
  }
 
  private setSelectedOption(option: any) {
    if (this.isMultiMode) {
      this.addValue(option);
    } else {
      this.setValues([option]);
    }
 
    if (!this.isMultiMode || !this.searchable) {
      this.blur();
      this.focused = false;
    }
 
    this.visibleOptions = [];
    this.attemptedOpen = false;
    this.input = '';
    this.next = null;
    this.complete = true;
    this.selectedIndex = -1;
  }
 
  private isPastFetchThreshold() {
    return (
      (this.visibleOptions.length > 0 || this.next) &&
      !this.complete &&
      (this.cursorIndex || 0) > this.visibleOptions.length - LOOK_AHEAD
    );
  }
 
  public handleOptionSelection(event: CustomEvent) {
    if (
      this.isMultiMode &&
      this.maxItems > 0 &&
      this.values.length >= this.maxItems
    ) {
      this.infoText = this.maxItemsText;
      return;
    } else {
      this.infoText = '';
    }
 
    const selected = event.detail.selected;
 
    // check if we should post it
    if (selected.arbitrary && this.allowCreate && this.endpoint) {
      this.resolving = true;
      postJSON(this.endpoint, selected).then((response) => {
        if (response.status >= 200 && response.status < 300) {
          this.setSelectedOption(response.json);
          this.lruCache = lru(20, 60000);
          this.errors = [];
        } else {
          this.setSelectedOption(selected);
          setTimeout(() => {
            this.errors = [
              'There was an error creating "' +
                this.getNameInternal(selected) +
                '"'
            ];
          }, 0);
          this.blur();
        }
        this.resolving = false;
      });
    } else {
      this.setSelectedOption(selected);
      this.errors = [];
    }
  }
 
  private handleExpressionSelection(evt: CustomEvent) {
    const option = evt.detail.selected as CompletionOption;
    const tabbed = evt.detail.tabbed;

    const ele = this.shadowRoot.querySelector('.searchbox') as HTMLInputElement;
    const textBefore = this.input;
    updateInputElementWithCompletion(this.query, ele, option);

    this.query = '';
    this.completionOptions = [];

    // If the completion didn't change the text, just hide the popup
    if (this.input === textBefore) {
      return;
    }

    if (tabbed) {
      this.fetchExpressions();
    } else if (this.emails || this.tags) {
      // In emails/tags mode, just complete the text — user presses Enter again to add
      this.fetchExpressions();
    } else if (this.input.indexOf('(') === -1) {
      this.addInputAsValue();
    }
  }

  protected getNameInternal: (option: T) => string = (option: T) => {
    return this.getName
      ? this.getName(option)
      : option[this.nameKey || 'name'] || '';
  };

  private getOptionsDefault(response: WebResponse): any[] {
    return response.json['results'];
  }
 
  private isCompleteDefault(
    newestOptions: any[],
    response: WebResponse
  ): boolean {
    const json = response.json;
    return !json['more'] && !json['next'];
  }
 
  public handleRemoveSelection(selectionToRemove: any): void {
    this.removeValue(selectionToRemove);
    this.visibleOptions = [];
    this.errors = [];
 
    // if we allow create, double check our values
    if (this.allowCreate) {
      const arbitrary = this.values.find((v) => v.arbitrary);
      if (arbitrary) {
        setTimeout(() => {
          this.errors = [
            'There was an error creating "' +
              this.getNameInternal(arbitrary) +
              '"'
          ];
        }, 0);
      }
    }
  }
 
  private createArbitraryOptionDefault(input: string, _options: any[]): any {
    if (this.expressions && input && this.isValidExpression(input)) {
      return { name: input, value: input, expression: true };
    }
    if (this.emails && input && this.isValidEmail(input)) {
      return { name: input, value: input };
    }
    if (this.tags && input) {
      return { name: input, value: input };
    }
    return null;
  }

  private isValidEmail(email: string): boolean {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  }

  private isDuplicateValue(input: string): boolean {
    const val = input.trim().toLowerCase();
    return this.values.some(
      (v: any) => (v.value || v.name || '').toLowerCase() === val
    );
  }

  /**
   * Whether the current input text would be accepted as a value on Enter.
   * Used for both grey text styling and Enter key gating.
   */
  private isAcceptableInput(input: string): boolean {
    if (!input || this.isDuplicateValue(input)) return false;
    const isExpression = this.expressions && input.trimStart().startsWith('@');
    if (isExpression) {
      return this.isValidExpression(input);
    }
    if (this.emails) {
      return this.isValidEmail(input.trim());
    }
    if (this.tags) {
      return input.trim().length > 0;
    }
    if (this.expressions) {
      return false;
    }
    return true;
  }
 
  private looksLikeExpression(input: string): boolean {
    return /^@[a-zA-Z_(]/.test(input.trim());
  }
 
  private isValidExpression(input: string): boolean {
    if (!this.looksLikeExpression(input)) return false;
    const parser =
      this.expressions === 'session' ? sessionParser : messageParser;
    const expressions = parser.findExpressions(input.trim());
    if (expressions.length === 0) return false;
    // Identifier expressions (e.g. @contact.email) are always valid.
    // Parenthesized expressions (e.g. @(upper(...))) must have balanced parens.
    return expressions.every(
      (expr) => !expr.text.startsWith('@(') || expr.closed
    );
  }
 
  /** Whether this select uses a contenteditable div for expression highlighting. */
  private get useExpressionInput(): boolean {
    return !!(this.expressions && this.searchable);
  }
 
  private expressionInputPatchedElement: HTMLElement = null;
 
  /**
   * Patches a contenteditable div to behave like an HTMLInputElement,
   * providing .value, .selectionStart, .selectionEnd, and .setSelectionRange().
   */
  private patchEditableAsInput(div: HTMLElement): void {
    if (this.expressionInputPatchedElement === div) return;
    // eslint-disable-next-line @typescript-eslint/no-this-alias
    const host = this;
    const anyDiv = div as any;

    Object.defineProperty(anyDiv, 'value', {
      get() {
        return getTextFromEditableDiv(div);
      },
      set(val: string) {
        host.renderExpressionHighlight(div, val);
      },
      configurable: true
    });

    Object.defineProperty(anyDiv, 'selectionStart', {
      get() {
        return getCaretOffset(div);
      },
      configurable: true
    });
 
    Object.defineProperty(anyDiv, 'selectionEnd', {
      get() {
        return getCaretEndOffset(div);
      },
      configurable: true
    });
 
    anyDiv.setSelectionRange = (start: number, end: number) => {
      setCaretRange(div, start, end);
    };
 
    this.expressionInputPatchedElement = div;
  }
 
  /**
   * Renders highlighted expression tokens into a contenteditable div.
   * Does NOT restore the caret — caller is responsible for that.
   */
  private renderExpressionHighlight(div: HTMLElement, text: string): void {
    div.textContent = '';
 
    // Only tokenize/highlight when input starts with @ (expression)
    // and is not a duplicate of an existing value.
    // Mid-string @ (e.g. email addresses) should render as plain text.
    if (
      text &&
      text.trimStart().startsWith('@') &&
      !this.isDuplicateValue(text)
    ) {
      const parser =
        this.expressions === 'session' ? sessionParser : messageParser;
      const tokens = tokenize(text, parser);
 
      for (const token of tokens) {
        const cls = getTokenClass(token);
        const isMono = EXPRESSION_TOKENS.has(token.type);
 
        if (token.text.length > 0) {
          const span = document.createElement('span');
          span.textContent = token.text;
          span.className = isMono ? `${cls} tok-mono` : cls;
          div.appendChild(span);
        }
      }
    } else if (text) {
      // Duplicate expressions still get monospace font, just no syntax colors
      if (text.trimStart().startsWith('@')) {
        const span = document.createElement('span');
        span.textContent = text;
        span.className = 'tok-mono';
        div.appendChild(span);
      } else {
        div.appendChild(document.createTextNode(text));
      }
    }
 
    // Ensure there's at least an empty text node for cursor placement
    if (!text) {
      div.appendChild(document.createTextNode(''));
    }
  }
 
  // Helper method to determine if this select should behave as multi-select
  // Returns true if multi is explicitly set OR if emails mode is enabled
  private get isMultiMode(): boolean {
    return this.multi || this.emails;
  }
 
  public open(): void {
    (
      this.shadowRoot.querySelector('.select-container') as HTMLDivElement
    ).click();
  }
 
  public isOpen(): boolean {
    return (
      this.visibleOptions.length > 0 || (this.attemptedOpen && this.focused)
    );
  }
 
  public setOptions(options: any[]): void {
    this.staticOptions = options;
  }

  private setVisibleOptions(options: any[]) {
    // if we have an exclusion filter apply it
    options = options.filter((option) => {
      // exclude unnamed
      if (!this.getNameInternal(option)) {
        return false;
      }
 
      if (this.shouldExclude) {
        return !this.shouldExclude(option);
      }
      return true;
    });
 
    if (this.input) {
      // if we are searching locally, filter for the query
      if (this.searchable && !this.queryParam) {
        const q = this.input.trim().toLowerCase();
        options = options.filter((option: any) => this.isMatch(option, q));
      }
 
      const arbitraryOption: any = this.createArbitraryOption(
        this.input,
        options
      );

      if (arbitraryOption) {
        // set our arbitrary flag so we never have more than one
        arbitraryOption.arbitrary = true;
 
        // make sure our id is not already present
        const exists = options.find(
          (option: any) =>
            this.getValue(option) === this.getValue(arbitraryOption)
        );
 
        if (!exists) {
          if (options.length > 0) {
            if (options[0].arbitrary) {
              options[0] = arbitraryOption;
            } else {
              options.unshift(arbitraryOption);
            }
          } else {
            options.unshift(arbitraryOption);
          }
        }
      }
    }
 
    // filter out any options already selected by id
    // TODO: should maybe be doing a deep equals here with option to optimize
    if (this.values.length > 0) {
      if (this.isMultiMode) {
        options = options.filter(
          (option) =>
            !this.values.find(
              (selected) => this.getValue(selected) === this.getValue(option)
            )
        );
      } else {
        // if no search, single select should set our cursor to the selected item
        if (!this.input) {
          this.cursorIndex = options.findIndex(
            (option) => this.getValue(option) === this.getValue(this.values[0])
          );
        } else {
          this.cursorIndex = 0;
        }
        this.requestUpdate('cursorIndex');
      }
    }

    if (
      this.isMultiMode &&
      this.maxItems > 0 &&
      this.values.length >= this.maxItems
    ) {
      options = [];
      this.infoText = this.maxItemsText;
    }

    // finally sort
    if (this.sortFunction) {
      options.sort(this.sortFunction);
    }
 
    this.visibleOptions = options;
 
    this.fireCustomEvent(CustomEventType.ContentChanged, {
      options: this.visibleOptions
    });
  }
 
  public fetchExpressions() {
    const store: Store = document.querySelector('temba-store');
    if (this.expressions && store) {
      const ele = this.shadowRoot.querySelector(
        '.searchbox'
      ) as HTMLInputElement;
 
      const result = executeCompletionQuery(
        ele,
        this.expressions === 'session'
      );
      this.query = result.query;
      this.completionOptions = result.options;
      this.visibleOptions = [];
      this.anchorPosition = result.anchorPosition;
      this.fireCustomEvent(CustomEventType.FetchComplete);
      return;
    }
  }
 
  // TODO: do we still need to support page numbers?
  public fetchOptions(query: string, page = 0, next = null) {
    this.completionOptions = [];
    if (!this.fetching) {
      this.fetching = true;
 
      const options: any = [...this.staticOptions];
      const q = (query || '').trim().toLowerCase();
 
      if (this.tags && q) {
        if (
          !options.find(
            (option: any) =>
              this.getValue(option) && this.getValue(option).toLowerCase() === q
          )
        ) {
          options.splice(0, 0, { name: query, value: query });
        }
      }
 
      if (this.emails && q) {
        if (
          this.isValidEmail(q) &&
          !options.find(
            (option: any) =>
              this.getValue(option) && this.getValue(option).toLowerCase() === q
          )
        ) {
          options.splice(0, 0, { name: query, value: query });
        }
      }
 
      if (this.endpoint) {
        let url = this.endpoint;
        if (next) {
          url = next;
        } else {
          if (query && this.queryParam) {
            if (url.indexOf('?') > -1) {
              url += '&';
            } else {
              url += '?';
            }

            url += this.queryParam + '=' + encodeURIComponent(query);
          }

          if (page) {
            if (url.indexOf('?') > -1) {
              url += '&';
            } else {
              url += '?';
            }
            url += 'page=' + page;
          }
        }

        const cache = this.lruCache.get(url);
        if (this.cache && !this.tags && !this.emails && cache) {
          if (page === 0 && !this.next) {
            this.cursorIndex = 0;
            this.setVisibleOptions([...options, ...cache.options]);
          } else {
            this.setVisibleOptions([...this.visibleOptions, ...cache.options]);
          }

          this.complete = cache.complete;
          this.next = cache.next;
          this.fetching = false;
          return;
        }

        // if we are searchable, but doing it locally, fetch all the options
        if (this.searchable && !this.queryParam) {
          fetchResults(url).then((results: any) => {
            results = this.prepareOptions(results);

            if (this.cache && !this.tags && !this.emails) {
              this.lruCache.set(url, {
                options: results,
                complete: true,
                next: null
              });
 
              this.complete = true;
              this.next = null;
              this.setVisibleOptions([...options, ...results]);
              this.fetching = false;
            }
          });
        } else {
          getUrl(url)
            .then((response: WebResponse) => {
              let results = this.getOptions(response).filter((option: any) => {
                return this.isMatch(option, q);
              });
              results = this.prepareOptions(results);
 
              this.next = null;
              const json = response.json;
              if (json['next']) {
                this.next = json['next'];
              }
 
              if (page === 0 && !this.next) {
                this.cursorIndex = 0;
                this.setVisibleOptions([...options, ...results]);
                this.query = query;
                this.complete = this.isComplete(this.visibleOptions, response);
              } else {
                if (results.length > 0) {
                  this.setVisibleOptions([...this.visibleOptions, ...results]);
                }
                this.complete = this.isComplete(results, response);
              }
 
              if (this.cache && !this.tags && !this.emails) {
                this.lruCache.set(url, {
                  options: results,
                  complete: this.complete,
                  next: this.next
                });
              }
 
              this.fetching = false;
              this.page = page;
            })
            .catch((reason: any) => {
              // cancelled
              this.fetching = false;
              console.error(reason);
            });
        }
      } else {
        this.fetching = false;
        this.setVisibleOptions(options);
      }
    }
  }

  private handleFocus(): void {
    if (!this.focused && this.visibleOptions.length === 0) {
      this.focused = true;
    }
  }

  private handleBlur() {
    // defer to avoid scheduling an update during the current cycle;
    // blur can fire synchronously during the lit-html render when DOM changes
    setTimeout(() => {
      this.focused = false;
      this.attemptedOpen = false;
      if (this.visibleOptions.length > 0) {
        this.input = '';
        this.next = null;
        this.complete = true;
        this.visibleOptions = [];
        this.cursorIndex = 0;
      }
      if (this.emails || this.tags) {
        this.input = '';
        this.completionOptions = [];
      }

      if (
        this.isMultiMode &&
        this.maxItems > 0 &&
        this.values.length >= this.maxItems
      ) {
        this.infoText = '';
      }
    }, 0);
  }
 
  private handleClick(): void {
    this.selectedIndex = -1;
    this.requestUpdate('input');
  }
 
  private addInputAsValue() {
    const ele = this.shadowRoot.querySelector('.searchbox') as HTMLInputElement;
    const expression = {
      name: ele.value,
      value: ele.value,
      expression: true
    };
 
    if (this.isMultiMode) {
      if (
        !this.values.find((option: T) => {
          return (
            option.expression &&
            option.value &&
            expression.value &&
            option.value.toLowerCase().trim() ==
              expression.value.toLowerCase().trim()
          );
        })
      ) {
        this.addValue(expression);
      }
    } else {
      this.setValues([expression]);
    }
 
    this.input = '';
    if (!this.isMultiMode) {
      this.blur();
    }
  }

  private handleBeforeInput(evt: InputEvent) {
    // Android virtual keyboards often don't fire keydown with key='Enter'.
    // Instead they fire beforeinput with inputType 'insertLineBreak' or
    // 'insertParagraph'. Prevent those from inserting newlines in the
    // contenteditable expression input, and then handle acceptable input
    // the same as Enter for tags/emails/expressions.
    if (
      evt.inputType === 'insertLineBreak' ||
      evt.inputType === 'insertParagraph'
    ) {
      if (this.useExpressionInput) {
        evt.preventDefault();
      }
 
      if (
        this.completionOptions.length === 0 &&
        (this.emails || this.tags || this.expressions) &&
        this.isAcceptableInput(this.input)
      ) {
        evt.preventDefault();
        this.addInputAsValue();
      }
    }
  }
 
  private handleKeyDown(evt: KeyboardEvent) {
    // Prevent Enter from inserting newlines in contenteditable
    if (evt.key === 'Enter' && this.useExpressionInput) {
      evt.preventDefault();
    }
 
    // In email mode, treat comma like Enter (but not inside expressions)
    if (
      evt.key === ',' &&
      this.emails &&
      !this.looksLikeExpression(this.input)
    ) {
      evt.preventDefault();
      if (this.isAcceptableInput(this.input)) {
        this.addInputAsValue();
      }
      return;
    }
 
    // if Enter is pressed with acceptable input (email, tag, or expression), add it
    if (
      evt.key === 'Enter' &&
      this.completionOptions.length === 0 &&
      (this.emails || this.tags || this.expressions) &&
      this.isAcceptableInput(this.input)
    ) {
      evt.preventDefault();
      this.addInputAsValue();
      return;
    }
 
    // see if we should open our options on a key event
    if (
      evt.key === 'Enter' ||
      evt.key === 'ArrowDown' ||
      (evt.key === 'n' && evt.ctrlKey)
    ) {
      if (
        this.visibleOptions.length === 0 &&
        this.completionOptions.length === 0 &&
        !this.input
      ) {
        this.attemptedOpen = true;
        this.requestUpdate('input');
        return;
      }
    }
 
    // focus our last item on delete
    if (this.isMultiMode && evt.key === 'Backspace' && !this.input) {
      if (this.visibleOptions.length > 0) {
        this.visibleOptions = [];
        return;
      }
 
      if (this.selectedIndex === -1) {
        // First backspace: highlight the last item
        this.selectedIndex = this.values.length - 1;
        this.visibleOptions = [];
      } else {
        // Second backspace: delete the highlighted item
        this.popValue();
        this.selectedIndex = -1;
      }
    } else {
      this.selectedIndex = -1;
    }
  }
 
  public getStaticOptions() {
    return this.staticOptions;
  }
 
  private handleInput(evt: Event) {
    const ele = evt.currentTarget as HTMLElement;
 
    if (this.useExpressionInput) {
      // Extract plain text and caret before modifying DOM
      const text = getTextFromEditableDiv(ele);
      const caretPos = getCaretOffset(ele);
      this.input = text;
      // Re-render with highlighting and restore caret synchronously
      this.renderExpressionHighlight(ele, text);
      try {
        setCaretRange(ele, caretPos, caretPos);
      } catch {
        // Caret restore may fail if text is empty
      }
    } else {
      this.input = (ele as HTMLInputElement).value;
    }
  }

  private handleCancel() {
    this.visibleOptions = [];
    this.attemptedOpen = false;
  }

  private handleCursorChanged(event: CustomEvent) {
    this.cursorIndex = event.detail.index;
  }
 
  /** Returns the searchbox element, whether it's an input or contenteditable div. */
  private getSearchboxElement(): HTMLElement | null {
    return this.shadowRoot.querySelector('.searchbox');
  }
 
  /** Checks if the event target is the expression contenteditable input. */
  private isExpressionInputTarget(target: EventTarget): boolean {
    return (
      target instanceof HTMLElement &&
      target.classList.contains('expression-input')
    );
  }
 
  private handleContainerClick(event: MouseEvent) {
    if (this.disabled) {
      // prevent opening dropdown right after drag-and-drop
      event.stopPropagation();
      event.preventDefault();
      return;
    }
 
    this.focused = true;
    const targetTag = (event.target as any).tagName;
    if (targetTag !== 'INPUT' && !this.isExpressionInputTarget(event.target)) {
      const input = this.getSearchboxElement();
      if (input) {
        input.click();
        input.focus();
        return;
      }
 
      // Check if dropdown is currently open (either with options or showing "No options")
      if (this.isOpen()) {
        this.visibleOptions = [];
        this.attemptedOpen = false;
      } else {
        this.attemptedOpen = true;
        this.requestUpdate('input');
        // Also trigger an immediate update to show empty dropdown
        this.requestUpdate();
      }
    }
  }
 
  public getEventHandlers(): EventHandler[] {
    return [
      { event: CustomEventType.Canceled, method: this.handleCancel },
      {
        event: CustomEventType.CursorChanged,
        method: this.handleCursorChanged
      },
      { event: 'blur', method: this.handleBlur },
      { event: 'focus', method: this.handleFocus }
    ];
  }
 
  private handleArrowClick(event: MouseEvent): void {
    if (this.disabled) {
      return;
    }
    if (this.isOpen()) {
      event.preventDefault();
      event.stopPropagation();
      this.blur();
    }
  }
 
  private renderHighlightedName(option: T): TemplateResult | string {
    const name = this.getNameInternal(option);
    if (this.expressions && name.startsWith('@')) {
      const parser =
        this.expressions === 'session' ? sessionParser : messageParser;
      const tokens = tokenize(name, parser);
      return html`${tokens.map((token) => {
        const cls = getTokenClass(token);
        const isMono = EXPRESSION_TOKENS.has(token.type);
        return html`<span class="${isMono ? `${cls} tok-mono` : cls}"
          >${token.text}</span
        >`;
      })}`;
    }
    return name;
  }

  public renderOptionDefault(option: T): TemplateResult {
    if (!option) {
      return null;
    }

    // special case for icons on any option type
    const icon = (option as any).icon;
    return html`
      <div
        class="option-name"
        style="flex: 1 1 auto;
        align-self: center;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        padding: var(--temba-select-option-padding, 2px 8px);
        display: flex;"
      >
        ${icon
          ? html`<temba-icon
              name="${icon}"
              style="margin-right:0.5em;"
            ></temba-icon>`
          : null}<span>${this.renderHighlightedName(option)}</span>
      </div>
    `;
  }
 
  public renderSelectedItemDefault(option: T): TemplateResult {
    const renderFn = this.renderOption || this.renderOptionDefault;
    return renderFn(option, true);
  }
 
  public serializeValue(value: any): string {
    // static options just use their value
    if (
      !this.jsonValue &&
      (this.staticOptions.length > 0 || this.isMultiMode)
    ) {
      return value.value;
    }
 
    return super.serializeValue(value);
  }
 
  public setSelection(value: string): void {
    for (const option of this.staticOptions) {
      if (this.getValue(option) === value) {
        if (this.values.length === 0 || this.values[0].value != '' + value) {
          this.setValues([option]);
        }
        return;
      }
    }
  }
 
  private handleClear(evt: MouseEvent): void {
    evt.preventDefault();
    evt.stopPropagation();
    this.setValues([]);
    if (this.visibleOptions.length > 0) {
      this.visibleOptions = [];
      this.requestUpdate();
    }

    this.fireCustomEvent(CustomEventType.Selection, {
      selected: null
    });
  }
 
  public setValues(values: any[]) {
    const oldValues = this.values;
    this.values.splice(0, this.values.length, ...values);
    this.requestUpdate('values', oldValues);
    this.updateInputs();
    this.fireEvent('change');
  }
 
  public addValue(value: any) {
    const oldValues = [...this.values];
    this.values.push(value);
    this.requestUpdate('values', oldValues);
    this.updateInputs();
    this.fireEvent('change');
  }

  public removeValue(valueToRemove: any) {
    const oldValues = [...this.values];
    const idx = this.values.indexOf(valueToRemove);

    if (idx > -1) {
      this.values.splice(idx, 1);

      // Also remove the 'selected' attribute from the corresponding temba-option element
      const valueToMatch = this.getValue(valueToRemove);
      for (const child of this.children) {
        if (child.tagName === 'TEMBA-OPTION') {
          const childValue = child.getAttribute('value');
          if (childValue === valueToMatch) {
            child.removeAttribute('selected');
            break;
          }
        }
      }
    }
    this.requestUpdate('values', oldValues);
    this.infoText = '';
    this.updateInputs();
    this.fireEvent('change');
  }
 
  public popValue() {
    const oldValues = [...this.values];
    this.values.pop();
    this.requestUpdate('values', oldValues);
    this.infoText = '';
    this.updateInputs();
    this.fireEvent('change');
  }
 
  public clear() {
    const oldValues = this.values;
    this.values.splice(0, this.values.length);
    this.requestUpdate('values', oldValues);
    this.updateInputs();
    this.fireEvent('change');
  }

  private shouldShowEmptyMessage(): boolean {
    return (
      this.attemptedOpen &&
      this.focused &&
      this.visibleOptions.length === 0 &&
      !this.input &&
      this.staticOptions.length === 0 &&
      !this.endpoint
    );
  }

  private handleOrderChanged(event: CustomEvent): void {
    const detail = event.detail;

    // Handle new swap-based format
    if (detail.swap && Array.isArray(detail.swap) && detail.swap.length === 2) {
      const [fromIdx, toIdx] = detail.swap;

      // Only reorder if the indexes are different and valid
      if (
        fromIdx !== toIdx &&
        fromIdx >= 0 &&
        toIdx >= 0 &&
        fromIdx < this.values.length &&
        toIdx < this.values.length
      ) {
        const oldValues = [...this.values];
        // Move the item using splice operations directly on this.values
        const movedItem = this.values.splice(fromIdx, 1)[0];
        this.values.splice(toIdx, 0, movedItem);
        this.requestUpdate('values', oldValues);
        this.updateInputs();
        this.fireEvent('change');
      }
    }
  }

  protected renderWidget(): TemplateResult {
    const placeholder = this.values.length === 0 ? this.placeholder : '';

    // Single unified placeholder - shows when empty and (not focused OR not searchable)
    const shouldShowPlaceholder =
      this.values.length === 0 && (!this.focused || !this.searchable);
    const placeholderElement = shouldShowPlaceholder
      ? html`<div class="placeholder">${placeholder}</div>`
      : null;
 
    const clear =
      this.clearable && this.values.length > 0 && !this.isMultiMode
        ? html`<temba-icon
            name="${Icon.select_clear}"
            size="1.1"
            class="clear-button"
            style="margin-right:6px"
            @click=${this.handleClear}
          />`
        : null;
 
    const classes = getClasses({
      multi: this.isMultiMode,
      single: !this.isMultiMode,
      searchable: this.searchable,
      empty: this.values.length === 0,
      options: this.visibleOptions.length > 0,
      focused: this.focused,
      'search-input': this.input.length > 0,
      'no-search-input': this.input.length === 0,
      [this.flavor]: this.flavor !== null,
      disabled: this.disabled
    });
 
    const anchorStyles = this.anchorPosition
      ? {
          top: `${this.anchorPosition.top || 0}px`,
          left: `${this.anchorPosition.left - 10}px`
        }
      : {};
 
    // Show grey text when input would not be accepted
    const inputGrey =
      this.input &&
      (this.emails || this.tags) &&
      !this.isAcceptableInput(this.input);
 
    const inputStyles: StyleInfo = {
      ...this.inputStyle,
      ...(inputGrey ? { color: '#ccc' } : {})
    };
 
    const showEnterHint =
      (this.emails || this.tags) &&
      this.focused &&
      this.input &&
      this.isAcceptableInput(this.input);
 
    const input = this.searchable
      ? html`
          <div
            class="input-wrapper"
            style="${this.focused ? 'display:flex;' : ''}"
          >
            ${this.useExpressionInput
              ? html`<div
                  class="searchbox expression-input"
                  contenteditable="true"
                  spellcheck="false"
                  style=${styleMap(inputStyles)}
                  @input=${this.handleInput}
                  @beforeinput=${this.handleBeforeInput}
                  @keydown=${this.handleKeyDown}
                  @click=${this.handleClick}
                ></div>`
              : html`<input
                  class="searchbox"
                  style=${styleMap(inputStyles)}
                  @input=${this.handleInput}
                  @beforeinput=${this.handleBeforeInput}
                  @keydown=${this.handleKeyDown}
                  @click=${this.handleClick}
                  type="text"
                  .value=${this.input}
                />`}
            <div id="anchor" style=${styleMap(anchorStyles)}></div>
          </div>
        `
      : null;
 
    const multiItems =
      this.isMultiMode &&
      (this.emails || this.tags || this.values.length > 1) &&
      (this.values.length > 0 || this.focused)
        ? html`
            <temba-sortable-list
              horizontal
              @temba-order-changed=${this.handleOrderChanged}
            >
              ${this.values.map(
                (selected: any, index: number) => html`
                  <div
                    class="sortable selected-item ${index === this.selectedIndex
                      ? 'focused'
                      : ''} ${this.draggingId === `selected-${index}`
                      ? 'dragging'
                      : ''}"
                    id="selected-${index}"
                    style="
                                vertical-align: middle;
                                background: #fff;
                                border: 1px solid rgba(100,100,100,0.3);
                                user-select: none;
                                border-radius: 2px;
                                align-items: center;
                                flex-direction: row;
                                flex-wrap: nowrap;
                                margin: 2px 2px;
                                display: flex;
                                overflow: hidden;
                                color: var(--color-widget-text);
                                line-height: var(--temba-select-selected-line-height);
                                --icon-color: var(--color-text-dark);
                                ${index === this.selectedIndex
                      ? 'background: rgba(100,100,100,0.3);'
                      : ''}
                                ${this.draggingId === `selected-${index}`
                      ? 'opacity: 0.5;'
                      : ''}
                              "
                  >
                    <div
                      class="remove-item"
                      style="
                                      cursor: pointer;
                                      display: inline-block;
                                      padding: 3px 6px;
                                      border-right: 1px solid rgba(100,100,100,0.2);
                                      margin: 0;
                                      background: rgba(100,100,100,0.05);
                                      margin-top:1px;
                                    "
                      @click=${(evt: MouseEvent) => {
                        evt.preventDefault();
                        evt.stopPropagation();
                        this.handleRemoveSelection(selected);
                      }}
                    >
                      <temba-icon
                        name="${Icon.delete_small}"
                        size="1"
                      ></temba-icon>
                    </div>
                    ${this.renderSelectedItem(selected)}
                  </div>
                `
              )}
              ${input}
            </temba-sortable-list>
          `
        : null;
 
    const singleItems = !multiItems
      ? html`${this.values.map(
          (selected: any, index: number) => html`
            <div
              class="selected-item ${index === this.selectedIndex
                ? 'focused'
                : ''}"
              style="
                            display: flex;
                            overflow: hidden;
                            color: var(--color-widget-text);
                            line-height: var(--temba-select-selected-line-height);
                            --icon-color: var(--color-text-dark);
                            ${this.isMultiMode
                ? 'vertical-align: middle; background: #fff; border: 1px solid rgba(100,100,100,0.3); user-select: none; border-radius: 2px; align-items: center; flex-direction: row; flex-wrap: nowrap; margin: 2px 2px;'
                : 'flex: 1; min-width: 0;'}
                            ${index === this.selectedIndex
                ? 'background: rgba(100,100,100,0.3);'
                : ''}
                          "
            >
              ${this.isMultiMode
                ? html`
                    <div
                      class="remove-item"
                      style="cursor: pointer; display: inline-block; padding: 3px 6px;
                             border-right: 1px solid rgba(100,100,100,0.2);
                             margin: 0; background: rgba(100,100,100,0.05); margin-top:1px;"
                      @click=${(evt: MouseEvent) => {
                        evt.preventDefault();
                        evt.stopPropagation();
                        this.handleRemoveSelection(selected);
                      }}
                    >
                      <temba-icon
                        name="${Icon.delete_small}"
                        size="1"
                      ></temba-icon>
                    </div>
                  `
                : null}
              ${!this.input || this.isMultiMode
                ? this.renderSelectedItem(selected)
                : null}
            </div>
          `
        )}
        ${this.isMultiMode && this.searchable && this.focused ? input : null}`
      : null;
 
    const items = html`${!this.isMultiMode && !this.resolving ? input : null}
    ${multiItems}${singleItems} ${placeholderElement}`;
 
    return html`
        <slot></slot>
        <div class="wrapper-bg">
        
        <div
          tabindex="0"
          class="select-container ${classes}"
          @click=${this.handleContainerClick}
        > 
          <div class="left-side">
          <slot name="prefix"></slot>
            <div class="selected">
              ${
                this.resolving
                  ? html`<temba-loading
                      style="margin-left:1em"
                    ></temba-loading>`
                  : items
              }
              
            </div>
 
          </div>
 
          ${clear}
 
          <slot name="right">${
            this.fetching
              ? html`<temba-loading
                  style="position:absolute;background:rgba(255,255,255,0.7);padding:2px;border-radius:var(--curvature);right:25px"
                ></temba-loading>`
              : null
          }</slot>
          ${
            !this.tags &&
            !this.emails &&
            !(this.clearable && this.values.length > 0 && !this.isMultiMode)
              ? html`<div
                  class="right-side arrow"
                  style="display:block;margin-right:5px"
                  @click=${this.handleArrowClick}
                >
                  <temba-icon
                    size="1.5"
                    name="${Icon.select_open}"
                    class="select-open ${this.visibleOptions.length > 0
                      ? 'open'
                      : ''}"
                  ></temba-icon>
                </div>`
              : null
          }
          </div>
 
        <div class="info-text ${!this.infoText ? 'hide' : ''} ${
          this.focused ? 'focused' : ''
        }">${this.infoText}</div></div></div>
 
    
    <temba-options
    @temba-selection=${this.handleOptionSelection}
    .cursorIndex=${this.cursorIndex}
    .renderOptionDetail=${this.renderOptionDetail}
    .renderOptionName=${this.renderOptionName}
    .renderOption=${this.renderOption || this.renderOptionDefault}
    .anchorTo=${this.allowAnchor ? this.anchorElement : null}
    .options=${this.visibleOptions}
    .spaceSelect=${this.spaceSelect}
    .nameKey=${this.nameKey}
    .getName=${this.getNameInternal}
    ?static-width=${this.optionWidth}
    .minWidth=${this.optionMinWidth || 0}
    ?anchor-right=${this.anchorRight}
    ?visible=${this.visibleOptions.length > 0 || this.shouldShowEmptyMessage()}
    ?showEmptyMessage=${this.shouldShowEmptyMessage()}
    ></temba-options>
 
    <temba-options
    @temba-selection=${this.handleExpressionSelection}
    @temba-canceled=${() => {}}
    .anchorTo=${this.allowAnchor ? this.anchorExpressions : null}
    .options=${this.completionOptions}
    .renderOption=${renderCompletionOption}
    ?visible=${this.completionOptions.length > 0}
    >
      ${
        this.currentFunction
          ? html`
              <div class="current-fn">
                ${renderCompletionOption(this.currentFunction, true)}
              </div>
            `
          : null
      }
      ${
        this.completionOptions.length > 0
          ? html`<div class="footer">
              ${msg('Tab to complete, enter to select')}
            </div>`
          : null
      }
    </temba-options>
    ${
      showEnterHint
        ? html`<div class="enter-hint">
            <span style="position:relative;top:3px">↵</span> ${msg('to add')}
          </div>`
        : null
    }
    `;
  }
 
  public render(): TemplateResult {
    return this.renderField();
  }
}