All files / coral-component-autocomplete/src/scripts Autocomplete.js

85.71% Statements 528/616
74.3% Branches 266/358
86.09% Functions 99/115
85.71% Lines 528/616

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                                                                      2x               2x             2x                       2x                             2x                         2x 2x   2x           278x   278x   278x 278x           278x       278x 278x 278x                                                           278x 278x   278x 278x 278x   278x 278x 278x 278x 278x   278x     278x   278x   278x   278x   278x   278x   278x   278x   278x                 2x         142x 108x     34x                   132x 104x 104x   28x 28x               437x                           159x             12x   12x 10x   10x       6x   6x 12x 12x                           250x 250x 250x   250x 250x   250x                       524x   524x                   1372x     1372x 1372x 1372x   5054x               5054x   5054x               946x     946x 532x                 572x   572x 572x   572x   158x   158x             82x     76x       572x                   524x   524x   88x   84x     84x 168x 168x   168x       4x   4x       4x   436x 432x 40x   392x                               34x   34x   34x 36x 2x       34x                   354x   46x   46x 30x     16x         354x   354x 268x     354x   354x 350x   4x       354x         354x   354x     354x                     206x   206x   202x     4x     4x   4x 4x 4x   4x   4x         4x   4x   4x   4x     4x   4x                     38x     38x   38x   38x 46x     38x                     162x   162x   162x             4x     4x 4x 4x   4x         4x           4x 2x     4x 4x 2x       2x   2x 2x     4x 2x                                                                                                       60x     60x   60x             60x   60x   6x   6x     54x 54x             24x   24x 22x           12x 6x     6x   6x   6x                                                       24x                                                           37x   37x 37x 37x   37x 10x         37x 35x 35x   35x 15x   20x     7x                 8x   8x 8x   8x                 10x   10x             8x 2x       6x   6x               2x                                                         2x   2x   2x   2x                 103x 103x   103x 219x 103x       103x     42x   42x 58x         58x 8x         103x               34x 22x                 44x   44x   14x 14x     30x                 49x             49x     49x 2x   2x   2x       49x 49x   49x   49x   15x 19x   15x   15x   15x             15x       15x 2x       15x   15x 8x   34x   3x     3x             31x   31x 4x   4x       27x       31x   31x 24x       49x                     83x     83x   83x   69x   14x 14x   14x 2x   12x       14x               83x                                                       8x   8x 4x       4x                                         26x   26x   26x           26x   26x 20x       20x     6x         26x 26x     26x   26x                               366x                     270x     270x   270x   270x 241x 114x 114x       270x 156x       270x 4x     270x                     584x     584x                     264x   264x                     228x 228x 228x   228x 184x 44x   30x   30x   30x   30x       14x 2x     2x                               128x 128x                                                             149x 149x                       447x   447x 30x 417x 32x     447x   447x                 6x   6x   6x 2x                   64x   64x                                             64x   64x           64x 114x 114x 114x 114x   114x 114x                       114x       64x   2x               2x   2x   2x   2x   62x                   66x   66x 6x   60x       66x   66x 66x   66x     66x   66x                 91x   91x   91x   91x     91x   91x                   27x 19x   19x   8x   8x   8x                     12x                       300x   300x   300x   300x 2x           274x   274x   274x   274x   274x   274x   274x   274x     274x   274x   274x     274x 254x       274x   274x 274x 274x 274x 274x   274x 1370x   1370x   1290x     80x         274x   274x     274x             300x   300x   300x 4x 4x                                                                 2474x 276x           2474x                           2367x     110x   110x   110x   110x 94x   16x   16x     110x                       60x     130x   130x 130x                                 669x     14x   14x                         40x     36x   36x                       8x     8x   6x                         12x     280x 280x   280x   280x 4x   4x   4x   276x   276x   276x                               34x       34x 34x   34x 34x                                     70x   70x 6x   6x   6x 6x       6x     6x 6x   64x                         824x                                                   190x 190x     588x                     534x     608x       608x   608x 414x         608x   608x   14x 8x   8x 8x         594x 192x 192x       608x     36x     36x 42x     42x     42x       572x   572x                             142x     22x   22x                 257x     83x     83x   83x   83x                         84x     32x   32x   32x   32x   32x 32x 32x 32x   32x      
/**
 * Copyright 2019 Adobe. All rights reserved.
 * This file is licensed to you under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. You may obtain a copy
 * of the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
 * OF ANY KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
 
import {BaseComponent} from '../../../coral-base-component';
import {BaseFormField} from '../../../coral-base-formfield';
import {Tag} from '../../../coral-component-taglist';
import {SelectableCollection} from '../../../coral-collection';
import AutocompleteItem from './AutocompleteItem';
import {Textfield} from '../../../coral-component-textfield';
import {Icon} from '../../../coral-component-icon';
import '../../../coral-component-button';
import '../../../coral-component-list';
import '../../../coral-component-popover';
import '../../../coral-component-wait';
import base from '../templates/base';
import loadIndicator from '../templates/loadIndicator';
import {transform, validate, commons, i18n} from '../../../coral-utils';
import {Decorator} from '../../../coral-decorator';
 
const CLASSNAME = '_coral-Autocomplete';
 
/**
 The distance, in pixels, from the bottom of the List at which we assume the user has scrolled
 to the bottom of the list.
 @type {Number}
 @ignore
 */
const SCROLL_BOTTOM_THRESHOLD = 50;
 
/**
 The number of milliseconds for which scroll events should be debounced.
 @type {Number}
 @ignore
 */
const SCROLL_DEBOUNCE = 100;
 
/**
 Enumeration for {@link Autocomplete} variants.
 
 @typedef {Object} AutocompleteVariantEnum
 
 @property {String} DEFAULT
 A default, gray Autocomplete.
 @property {String} QUIET
 An Autocomplete with no border or background.
 */
const variant = {
  DEFAULT: 'default',
  QUIET: 'quiet'
};
 
/**
 Enumeration for {@link Autocomplete} match options.
 
 @typedef {Object} AutocompleteMatchEnum
 
 @property {String} STARTSWITH
 Include only matches that start with the user provided value.
 @property {String} CONTAINS
 Include only matches that contain the user provided value.
 */
const match = {
  STARTSWITH: 'startswith',
  CONTAINS: 'contains'
};
 
/**
 @class Coral.Autocomplete
 @classdesc An Autocomplete component that allows users to search and select from a list of options.
 @htmltag coral-autocomplete
 @extends {HTMLElement}
 @extends {BaseComponent}
 @extends {BaseFormField}
 */
const Autocomplete = Decorator(class extends BaseFormField(BaseComponent(HTMLElement)) {
  /** @ignore */
  constructor() {
    super();
 
    // Template
    this._elements = {};
    base.call(this._elements, {Icon, commons, i18n});
 
    this._elements.tagList.reset = () => {
      // Kill inner tagList reset so it doesn't interfer with the autocomplete reset
    };
 
    // Pre-define labellable element
    this._labellableElement = this._elements.input;
 
    const overlayId = this._elements.overlay.id;
    const events = {
      // ARIA Autocomplete role keyboard interaction
      // http://www.w3.org/TR/wai-aria-practices/#autocomplete
      'key:up [handle="input"]': '_handleInputUpKeypress',
      'key:alt+up [handle="input"]': '_handleInputUpKeypress',
      'key:down [handle="input"]': '_handleInputDownKeypress',
      'key:alt+down [handle="input"]': '_handleInputDownKeypress',
      'key:tab [handle="input"]': '_handleInputTabKeypress',
      'key:shift+tab [handle="input"]': '_handleListFocusShift',
      'capture:change [handle="input"]': '_handleInput',
      'input [handle="input"]': '_handleInputEvent',
 
      // Manually listen to keydown event due to CUI-3973
      'keydown': '_handleInputKeypressEnter',
 
      // Interaction
      'click [handle="trigger"]': '_handleTriggerClick',
      'mousedown [handle="trigger"]': '_handleTriggerMousedown',
 
      // Focus
      'capture:blur': '_handleFocusOut',
      'global:click': '_onGlobalClick',
      'global:touchstart': '_onGlobalClick',
 
      // Taglist
      'coral-collection:add [handle="tagList"]': '_handleTagAdded',
      'coral-collection:remove [handle="tagList"]': '_handleTagRemoved',
      'change [handle="tagList"]': '_preventTagListChangeEvent',
 
      // Items
      'coral-autocomplete-item:_valuechanged': '_handleItemValueChange',
      'coral-autocomplete-item:_selectedchanged': '_handleItemSelectedChange',
      'coral-autocomplete-item:_contentchanged': '_handleItemContentChange'
    };
 
    // Interaction
    events[`global:key:shift+tab #${overlayId} [is="coral-buttonlist-item"]`] = '_handleListFocusShift';
    events[`global:key:esc`] = '_handleListFocusShift';
 
    // Overlay
    events[`global:capture:coral-overlay:positioned #${overlayId}`] = '_onOverlayPositioned';
    events[`global:capture:coral-overlay:open #${overlayId}`] = '_onOverlayOpenOrClose';
    events[`global:capture:coral-overlay:close #${overlayId}`] = '_onOverlayOpenOrClose';
 
    // SelectList
    events[`global:key:enter #${overlayId} button[is="coral-buttonlist-item"]`] = '_handleSelect';
    events[`global:capture:mousedown #${overlayId} button[is="coral-buttonlist-item"]`] = '_handleSelect';
    events[`global:capture:scroll #${overlayId} [handle="selectList"]`] = '_onScroll';
    events[`global:capture:mousewheel #${overlayId} [handle="selectList"]`] = '_onMouseWheel';
    events[`global:capture:mousedown #${overlayId} [handle="selectList"]`] = '_onMouseDown';
 
    // Events
    this._delegateEvents(events);
 
    // A map of values to tags
    this._tagMap = {};
 
    // A list of selected values
    this._values = [];
 
    // A list of options objects
    this._options = [];
 
    // A map of option values to their content
    this._optionsMap = {};
 
    // Used for reset
    this._initialSelectedValues = [];
 
    // Bind the debounced scroll method
    this._handleScrollBottom = this._handleScrollBottom.bind(this);
 
    // Listen for mutations
    this._observer = new MutationObserver(this._handleMutation.bind(this));
    this._startObserving();
  }
 
  /**
   Returns the inner overlay to allow customization.
 
   @type {Popover}
   @readonly
   */
  get overlay() {
    return this._elements.overlay;
  }
 
  /**
   The item collection.
 
   @type {SelectableCollection}
   @readonly
   */
  get items() {
    // Construct the collection on first request:
    if (!this._items) {
      this._items = new SelectableCollection({
        itemTagName: 'coral-autocomplete-item',
        host: this
      });
    }
 
    return this._items;
  }
 
  /**
   Indicates if the autocomplete is a single or multiple mode. In multiple mode, the user can select multiple
   values.
 
   @type {Boolean}
   @default false
   @htmlattribute multiple
   @htmlattributereflected
   */
  get multiple() {
    return this._multiple || false;
  }
 
  set multiple(value) {
    this._multiple = transform.booleanAttr(value);
    this._reflectAttribute('multiple', this._multiple);
 
    this._setName(this.name);
 
    if (this._multiple) {
      this._elements.tagList.hidden = false;
    } else {
      this._elements.tagList.hidden = true;
      this._elements.tagList.items.clear();
    }
 
    this.labelledBy = this.labelledBy;
  }
 
  /**
   Amount of time, in milliseconds, to wait after typing a character before the suggestion is shown.
 
   @type {Number}
   @default 200
   @htmlattribute delay
   */
  get delay() {
    return typeof this._delay === 'number' ? this._delay : 200;
  }
 
  set delay(value) {
    value = transform.number(value);
 
    if (typeof value === 'number' && value >= 0) {
      this._delay = transform.number(value);
    }
  }
E
  /**
   Set to <code>true</code> to restrict the selected value to one of the given options from the suggestions.
   When set to <code>false</code>, users can enter anything.
 
   <strong>NOTE:</strong> This API is under review and may be removed or changed in a subsequent release.
   @ignore
 
   @type {Boolean}
   @default false
   @htmlattribute forceselection
   @htmlattributereflected
   */
  get forceSelection() {
    return this._forceSelection || false;
  }
 
  set forceSelection(value) {
    this._forceSelection = transform.booleanAttr(value);
    thisE._reflectAttribute('forceselection', this._forceSelection);
  }
 
  /**
   A hint to the user of what can be entered.
 
   @type {String}
   @default ""
   @htmlattribute placeholder
   @htmlattributereflected
   */
  get placeholder() {
    return this._elements.input.placeholder;
  }
 
  set placeholder(value) {
    this._elements.input.placeholder = value;
    this._reflectAttribute('placeholder', this.placeholder);
  }
 
  /**
   Max length for the Input field
 
   @type {Number}
   @htmlattribute maxlength
   @htmlattributereflected
   */
  get maxLength() {
    return this._elements.input.maxLength;
  }
 
  set maxLength(value) {
    this._elements.input.maxLength = value;
    this._reflectAttribute('maxlength', this._elements.input.maxLength);
  }
 
  /**
   The Autocomplete's variant. See {@link AutocompleteVariantEnum}.
 
   @type {AutocompleteVariantEnum}
   @default AutocompleteVariantEnum.DEFAULT
   @htmlattribute variant
   @htmlattributereflected
   */
  get variant() {
    return this._variant || variant.DEFAULT;
  }
 
  set variant(value) {
    value = transform.string(value).toLowerCase();
    this._variant = validate.enumeration(variant)(value) && value || variant.DEFAULT;
    this._reflectAttribute('variant', this._variant);
 
    if (this._variant === variant.QUIET) {
      this._elements.inputGroup.classList.add('_coral-InputGroup--quiet');
      this._elements.input.variant = Textfield.variant.QUIET;
      this._elements.trigger.classList.add('_coral-FieldButton--quiet');
    } else {
      this._elements.inputGroup.classList.remove('_coral-InputGroup--quiet');
      this._elements.input.variant = Textfield.variant.DEFAULT;
      this._elements.trigger.classList.remove('_coral-FieldButton--quiet');
    }
  }
 
  /**
   The match mode. See {@link AutocompleteMatchEnum}.
 
   @type {String}
   @default AutocompleteMatchEnum.CONTAINS
   @htmlattribute match
   */
  get match() {
    return this._match || match.CONTAINS;
  }
 
  set match(value) {
    if (typeof value === 'function') {
      this._match = value;
      this._matchFunction = value;
    } else {
      value = transform.string(value).toLowerCase();
      this._match = validate.enumeration(match)(value) && value || match.CONTAINS;
 
      if (this._match === match.STARTSWITH) {
        this._matchFunction = this._optionStartsWithValue;
      } else if (this._match === match.CONTAINS) {
        this._matchFunction = this._optionContainsValue;
      }
    }
  }
 
  /**
   Indicates that the component is currently loading remote data. This will set the wait indicator inside the list.
 
   @type {Boolean}
   @default false
   @htmlattribute loading
   */
  get loading() {
    return this._loading || false;
  }
 
  set loading(value) {
    this._loading = transform.booleanAttr(value);
 
    if (this._loading) {
      const overlay = this._elements.overlay;
 
      // we decide first if we need to scroll to the bottom since adding the load will change the dimensions
      const scrollToBottom = overlay.scrollTop >= overlay.scrollHeight - overlay.clientHeight;
 
      // if it does not exist we create it
      if (!this._elements.loadIndicator) {
        loadIndicator.call(this._elements);
      }
 
      // inserts the item at the end
      this._elements.selectList.appendChild(this._elements.loadIndicator);
 
      // we make the load indicator visible
      if (scrollToBottom) {
        overlay.scrollTop = overlay.scrollHeight;
      }
    } else if (this._elements.loadIndicator) {
      this._elements.loadIndicator.remove();
    }
  }
 
  /**
   Returns an Array containing the set selected items.
   @type {Array.<HTMLElement>}
   @readonly
   */
  get selectedItems() {
    return this.items._getAllSelected();
  }
 
  /**
   Returns the first selected item in the Autocomplete. The value <code>null</code> is returned if no element is
   selected.
   @type {?HTMLElement}
   @readonly
   */
  get selectedItem() {
    return this.items._getAllSelected()[0] || null;
  }
 
  /**
   The current value, as submitted during form submission.
   When {@link Coral.Autocomplete#multiple} is <code>true</code>, the first selected value will be returned.
 
   @type {String}
   @default ""
   @htmlattribute value
   */
  get value() {
    // Get the first value (or empty string)
    const values = this.values;
    return values && values.length > 0 ? values[0] : '';
  }
 
  set value(value) {
    this.values = [transform.string(value)];
  }
 
  /**
   The current values, as submitted during form submission.
   When {@link Coral.Autocomplete#multiple} is <code>false</code>, this will be an array of length 1.
 
   @type {Array.<String>}
   */
  get values() {
    return this._values;
  }
 
  set values(values) {
    if (values === undefined || values === null) {
      values = [];
    }
 
    if (Array.isArray(values)) {
      // if value was set to empty string
      if (values.length === 1 && values[0] === '') {
        values = [];
      }
 
      let i;
      let value;
      const selectedValues = [];
 
      // Valid values only
      if (this.forceSelection) {
        // Add each valid value
        for (i = 0 ; i < values.length ; i++) {
          value = values[i];
          if (this._optionsMap[value] !== undefined) {
            selectedValues.push(value);
          }
        }
      }
      // Any value goes
      else {
        for (i = 0 ; i < values.length ; i++) {
          value = values[i];
          selectedValues.push(value);
        }
      }
 
      if (this.multiple) {
        // Remove existing tags, DOM selection, etc
        // This is a full override
        this._clearValues();
 
        // Add each tag
        for (i = 0 ; i < selectedValues.length ; i++) {
          value = selectedValues[i];
 
          // Ensure the item is selected if it's present in the DOM
          // This keeps the DOM in sync with the JS API and prevents bugs like CUI-5681
          this._selectItem(value);
 
          // Add the value to the tag list
          this._addValue(value, null, true);
        }
      E} else {
        E// Set value
        this._values = selectedValues.length > 0 ? [selectedValues[0]] : [];
        this._reflectCurrentValue();
      }
    }
  }
 
  /**
   Name used to submit the data in a form.
   @type {String}
   @default ""
   @htmlattribute name
   @htEmlattributereflected
   */
  get name() {
    return this._getName();
  }
 
  set name(value) {
    thEis._reflectAttribute('name', value);
 
    this._setName(value);
  }
 
  /**
   Inherited from {@link BaseFormField#invalid}.
   */
  get invalid() {
    return super.invalid;
  }
 
  set invalid(value) {
    super.invalid = value;
 
    // Add to outer component
    this._elements.inputGroup.classList.toggle('is-invalid', this.invalid);
    this._elements.trigger.classList.toggle('is-invalid', this.invalid);
    this._elements.input.invalid = this.invalid;
  }
 
  /**
   Whether this field is disabled or not.
   @type {Boolean}
   @default false
   @htmlattribute disabled
   @htmlattributereflected
   */
  get disabled() {
    return this._disabled || false;
  }
 
  set disabled(value) {
    this._disabled = transform.booleanAttr(value);
    this._reflectAttribute('disabled', this._disabled);
 
    this[this._disabled ? 'setAttribute' : 'removeAttribute']('aria-disabled', this._disabled);
    this._elements.inputGroup.classList.toggle('is-disabled', this._disabled);
 
    this._elements.input.disabled = this._disabled;
 
    const disabledOrReadOnly = this._disabled || this.readOnly;
    this._elements.trigger.disabled = disabledOrReadOnly;
    this._elements.tagList.disabled = disabledOrReadOnly;
    // Prevents the overlay to be shown
    this._elements.inputGroup.disabled = disabledOrReadOnly;
  }
 
  /**
   Whether this field is readOnly or not. Indicating that the user cannot modify the value of the control.
   @type {Boolean}
   @default false
   @htmlattribute readonly
   @htmlattributereflected
   */
  get readOnly() {
    return this._readOnly || false;
  }
I
  set readOnly(value) {
    this._readOnly = transform.booleanAttr(value);
    this._reflectAttribute('readonly', this._readOnly);

    this._elements.input.readOnly = this._readOnly;
 
    const readOnlyOrDisabled = this._readOnly || this.disabled;
    this._elements.trigger.readOnly = readOnlyOrDisabled;
    this._elements.tagList.readOnly = readOnlyOrDisabled;
    // Prevents the overlay to be shown
    this._elements.inputGroup.disabled = readOnlyOrDisabled;
  }I

  /**
   Whether this field is required or not.
   @type {Boolean}
   @default false
   @htmlattribute required
   @htmlattributereflected
   */
  get required() {
    return this._required || false;
  }
 
  set required(value) {
    this._required = transform.booleanAttr(value);
    this._reflectAttribute('required', this._required);
 
    this._elements.input.required = this._required;
  }

  /**
   Inherited from {@link BaseFormField#labelled}.
   */
  get labelled() {
    return super.labelled;
  }
 
  set labelled(value) {
    super.labelled = value;
 
    this[this.labelled ? 'setAttribute' : 'removeAttribute']('aria-label', this.labelled);
    this._elements.selectList[this.labelled ? 'setAttribute' : 'removeAttribute']('aria-label', this.labelled);

    if (this.labelled && this.multiple) {
      this._elements.tagList.setAttribute('aria-label', this.labelled);
    } else {
      this._elements.tagList.removeAttribute('aria-label');
    }
  }

  /**
   Inherited from {@link BaseFormField#labelledBy}.
   */
  get labelledBy() {
    return super.labelledBy;
  }

  set labelledBy(value) {
    super.labelledBy = value;

    this[this.labelledBy ? 'setAttribute' : 'removeAttribute']('aria-labelledby', this.labelledBy);
    this._elements.selectList[this.labelledBy ? 'setAttribute' : 'removeAttribute']('aria-labelledby', this.labelledBy);

    if (this.labelledBy && this.multiple) {
      this._elements.tagList.setAttribute('aria-labelledby', this.labelledBy);
    } else {
      this._elements.tagList.removeAttribute('aria-labelledby');
    }
  }
 
  /**
   @ignore
 
   Not supported anymore.
   */
  get icon() {
    return this._icon || '';
  }
 
  set icon(value) {
    this._icon = transform.string(value);
    this._reflectAttribute('icon', this._icon);
  }
 
  /** @private */
  _getName() {
    if (this.multiple) {
      return this._elements.tagList.name;
    }
 
    return this._elements.field.name;
  }
 
  /**
   Set the name accordingly for multiple/single mode so the form submits contain only the right fields.
 
   @private
   */
  _setName(value) {
    if (this.multiple) {
      this._elements.tagList.name = value;
      this._elements.field.name = '';
    } else {
      this._elements.field.name = value;
      this._elements.tagList.name = '';
    }
  }
 
  /** @private */
  _startObserving() {
    this._observer.observe(this, {
      // Only watch the childList
      // Items will tell us if selected/value/content changes
      childList: true
    });
  }
 
  /**
   Stop watching for mutations. This should be done before manually updating observed properties.
I
   @protected
   */
  _stopObserving() {
    this._observer.disconnect();
  }
 
  // Override to do nothing
  _onInputChange(event) {
    // stops the current event
    event.stopPropagation();

    if (!this.multiple) {
      const inputText = this._elements.input.value.toLowerCase();
 
      if (this.forceSelection || inputText === '') {
        // We need a way to deselect item in single selection mode
        // 1) by using an empty string if this.forceSelection === false
        // 2) by using an invalid string if this.forceSelection === true
        const items = this.items.getAll();
        for (let i = 0 ; i < items.length ; i++) {
          if (items[i].value.toLowerCase() !== inputText) {
            items[i].selected = false;
          }
        }
      }
    }
  }
 
  /**
   Handle mutations to children and childList. This is used to keep the options in sync with DOM changes.
 
   @private
   */
  _handleMutation(mutations) {
    for (let i = 0 ; i < mutations.length ; i++) {
      const mutation = mutations[i];
      const target = mutation.target;

      if (mutation.type === 'childList' && target === this) {
        this._setStateFromDOM();
        return;
      }
    }
  }
 
  /**
   Update the option set and selected options from the DOM.
 
   @private
   */
  _setStateFromDOM() {
    this._createOptionsFromDOM();
    this._setSelectedFromDOM();
  }
 
  /**
   Create the set of options from nodes in the DOM.
 
   @private
   */
  _createOptionsFromDOM() {
    // Reset options array and value to content map
    this._options.length = 0;
    this._optionsMap = {};
 
    this.items.getAll().forEach((item) => {
      // Don't use properties as children may not be initialized yet
      const itemObj = {
        value: item.getAttribute('value'),
        icon: item.getAttribute('icon'),
        disabled: item.hasAttribute('disabled'),
        content: item.innerHTML.replace(/\s{2,}/g, ' ').trim(),
        text: item.innerText
      };
      this._options.push(itemObj);
      this._optionsMap[itemObj.value] = itemObj;
    });
 
    // @todo update value in hidden field if changed value = old value?
  }
 
  /** @private */
  _setInputValues(value, content) {
    this._elements.field.value = value;
 
    // Set text into input if in "multiple selection mode" or in "single selection mode and content is not empty"
    // otherwise keep the current text for us (should be marked red)
    if (this.multiple || content !== '') {
      Ethis._elements.input.value = content.trim();
    }
  }
 
  /** @private */
  _reflectCurrentValue() {
    // Use empty string if no values
    const value = this._values.length > 0 ? this._values[0] : '';
 
    // Reflect the value in the field for form submit
    this._elements.field.value = value;
 
    let content = '';
    if (value !== '') {
      // Find the object with the corresponding content
      const itemObj = this._optionsMap[value];
 
      if (itemObj) {
        // Reflect the content in the input
        /*
          prefence would be first given to innerText instead of innerHtml
          as special characters like '&' transformed as ;amp in case of innerHtml.
        */
        content = itemObj.text && itemObj.text !== '' ? itemObj.text : itemObj.content;
      } else {
        // Just use the provided value
        content = value;
      }
    }
 
    this._setInputValues(value, content);
  }
 
  /**
   Update the option set and selected options from the DOM
   @ignore
   */
  _setSelectedFromDOM() {
    const selectedItems = this.selectedItems;
 
    if (selectedItems.length) {
      // Use this.hasAttribute('multiple') instead of this.multiple here, as this method is called from _render and element might not be ready
      if (this.hasAttribute('multiple')) {
        // Remove current tags
        this._resetValues();

        // Add new ones
        for (let i = 0 ; i < selectedItems.length ; i++) {
          const value = selectedItems[i].getAttribute('value');
          const content = selectedItems[i].innerHTML;
          this._addValue(value, content, true);
        }
      } else {
        // Select last
        const last = selectedItems[selectedItems.length - 1];

        // Deselect others
        this._deselectExcept(last, selectedItems);

        // Set value from the attribute
        // We don't want to use the property as the sub-component may not have been upgraded yet
        this.value = last.getAttribute('value');
      }
    } else if (!this.hasAttribute('value')) {
      if (this.hasAttribute('multiple')) {
        this._resetValues();
      } else {
        this.value = '';
      }
    }
  }
I
  /**
   De-select Ievery item except the provided item.

   @param {HTMLElement} exceptItem
   The item not to select
   @param {Array.<HTMLElement>} [items]
   The set of items to consider when deselecting. If not provided, the current set of selected items is used.
 
   @private
   */
  _deselectExcept(exceptItem, items) {
    const selectedItems = items || this.selectedItems;
 
    // Deselect others
    this._stopObserving();
    for (let i = 0 ; i < selectedItems.length ; i++) {
      if (selectedItems[i] !== exceptItem) {
        selectedItems[i].removeAttribute('selected');
      }
    }
    this._startObserving();
  }
 
  /**
   Add a tag to the taglist.
 
   @private
   */
  _addValue(value, content, asHTML) {
    if (!content) {
      // Find the content
      const itemObj = this._optionsMap[value];
      if (itemObj) {
        content = itemObj.content;
      } else {
        // Just use the value
        content = value;
      }
    }
 
    // Add to selected values
    const index = this._values.indexOf(value);
    if (index === -1) {
      this._values.push(value);
    }
 
    const labelContent = {};
    if (asHTML) {
      labelContent.innerHTML = content;
    } else {
      labelContent.textContent = content;
    }
 
    // Create a new tag
    const tag = new Tag().set({
      label: labelContent,
      value: value
    });
 
    // Add to map
    this._tagMap[value] = tag;
 
    // Add to taglist
    this._elements.tagList.items.add(tag);
 
    // make sure to remove text from input box (to easily choose next item)
    this._setInputValues('', '');
  }
 
  /**
   Remove a tag from the taglist.
I
   @private
   */
  _removeValue(value) {
    // Remove from selected values
    const index = this._values.indexOf(value);
 
    if (index === -1) {
      // Get out if we don't have the value
      return;
    }
 
    this._values.splice(index, 1);
E
    // Select autocomplete item
    const item = this.querySelector(`coral-autocomplete-item[value=${JSON.stringify(value)}]`);
 
    if (item) {
      if (item.hasAttribute('selected')) {
        this._stopObserving();
        item.removeAttribute('selected');
        this._startObserving();
      }
    }
 
    // Look up the tag by value
    const tag = this._tagMap[value];
 
    if (tag) {
      // Remove from map
      this._tagMap[value] = null;
 
      // Remove from taglist
      thIis._elements.tagList.items.remove(tag);
    }
 
    if (index !== -1) {
      // Emit the change event when a value is removed but only after a user interaction
      this.trigger('change');
    }
  }
 
  /**
   Remove all tags from the taglist.
 
   @private
   */
  _clearValues() {
    this._resetValues();
 
    // Deselect items
    this._stopObserving();
    const items = this.querySelectorAll('coral-autocomplete-item[selected]');
    for (let i = 0 ; i < items.length ; i++) {
      items[i].removeAttribute('selected');
    }
I
    this._startObserving();
  }
 
  /**
   Reset values without affecting the DOM.
 
   @private
   */
  _resetValues() {
    // Reset values
    this._values = [];
 
    // DroEp references to tags
    this._tagMap = {};
 
    // Clear taglist
    this._elements.tagList.items.clear();
  }
 
  /** @private */
  _focusNextItem() {
    // Display focus on next item in the selectList
    const selectList = this._elements.selectList;
    const currentItem = selectList.querySelector('.is-focused');
    const input = this._elements.input;
    const items = selectList._getSelectableItems();
    let index;
    let item;
 
    if (currentItem) {
      index = items.indexOf(currentItem);
      if (index < items.length - 1) {
        item = items[index + 1];
      }
    } else if (items && items.length > 0) {
      item = items[0];
    }
 
    window.requestAnimationFrame(() => {
      if (item) {
        if (currentItem) {
          currentItem.classList.remove('is-focused');
        }
        this._scrollItemIntoView(item);
        item.classList.add('is-focused');
        input.setAttribute('aria-activedescendant', item.id);
      }
      if (!selectList.querySelector('.is-focused')) {
        input.removeAttribute('aria-activedescendant');
      }
    });
  }
 
  /** @private */
  _focusPreviousItem() {
    // Display focus on previous item in the selectList
    const selectList = this._elements.selectList;
    const currentItem = selectList.querySelector('.is-focused');
    const input = this._elements.input;
    const items = selectList._getSelectableItems();
    let index;
    let item;
 
    if (currentItem) {
      index = items.indexOf(currentItem);
      if (index > 0) {
        item = items[index - 1];
      }
      currentItem.classList.remove('is-focused');
    } else if (items && items.length > 0) {
      item = items[items.length - 1];
    }
 
    window.requestAnimationFrame(() => {
      if (item) {
        this._scrollItemIntoView(item);
        item.classList.add('is-focused');
        input.setAttribute('aria-activedescendant', item.id);
      }
      if (!selectList.querySelector('.is-focused')) {
        input.removeAttribute('aria-activedescendant');
      }
    });
  }
 
  /** @private */
  _showSuggestions() {
    // Get value from the input
    const inputValue = this._elements.input.value.toLowerCase().trim();
 
    // Since we're showing fresh suggestions, clear the existing suggestions
    this.clearSuggestions();
 
    // Trigger an event
    const event = this.trigger('coral-autocomplete:showsuggestions', {
      // Pass user input
      value: inputValue,
      // Started at zero here, always
      start: 0
    });
 
    // Flag to indicate that the private method is called before public showSuggestions method
    this._showSuggestionsCalled = true;
 
    if (event.defaultPrevented) {
      // Set loading mode
      this.loading = true;
 
      // Show the menu
      this.showSuggestions();
    } else {
      // Show suggestions that match in the DOM
      this.addSuggestions(this._getMatches(inputValue, this._optionContainsValue));
      this.showSuggestions();
    }
  }
 
  _onOverlayPositioned(event) {
    // stops propagation cause the event is internal to the component
    event.stopImmediatePropagation();
 
    if (this._elements.overlay.open) {
      this._elements.overlay.style.width = `${this.offsetWidth}px`;
    }
  }
 
  _onGlobalClick(event) {
    ifI (!this._elements.overlay.open) {
      return;
    }
 
    const eventTargetWithinOverlayTarget = this._elements.inputGroup.contains(event.target);
    const eventTargetWithinItself = this._elements.overlay.contains(event.target);
    if (!eventTargetWithinOverlayTarget && !eventTargetWithinItself) {
      this.hideSuggestions();
    }
  }
 
  /** @private */
  _onScroll() {
    this._isOverlayScrolling = true;
    window.clearTimeout(this._scrollTimeout);
    this._scrollTimeout = window.setTimeout(this._handleScrollBottom, SCROLL_DEBOUNCE);
  }
 
  /** @private */
  _onMouseWheel(event) {
    const selectList = this._elements.selectList;
    // If scrolling with mouse wheel and if it has hit the top or bottom boundary
    // `SCROLL_BOTTOM_THRESHOLD` is ignored when hitting scroll bottom to allow debounced loading
    if (event.deltaY < 0 && selectList.scrollTop === 0 || event.deltaY > 0 && selectList.scrollTop >= selectList.scrollHeight - selectList.clientHeight) {
      event.preventDefault();
    }
  }
 
  _onMouseDown(event) {
    this._isOverlayScrollBarClicked = event.matchedTarget.clientWidth <= event.offsetX;
  }
 
  /** @private */
  _handleScrollBottom() {
    const selectList = this._elements.selectList;
 
    if (selectList.scrollTop >= selectList.scrollHeight - selectList.clientHeight - SCROLL_BOTTOM_THRESHOLD) {
      const inputValue = this._elements.input.value;
 
      // Do not clear the suggestions here, instead we'll expect them to append
 
      // Trigger an event
      const event = this.trigger('coral-autocomplete:showsuggestions', {
        // Pass user input
        value: inputValue,
        start: selectList.items.length
      });
 
      if (event.defaultPrevented) {
        // Set loading mode
        this.loading = true;
      }
    }
  }
 
  /** @private */
  _handleFocusOut(event) {
    const selectList = this._elements.selectList;
    const target = event.target;
    const inputBlur = target === this._elements.input;
 
    if (this._blurTimeout) {
      clearTimeout(this._blurTimeout);
    }
 
    // This is to hack around the fact that you cannot determine which element gets focus in a blur event
    // Firefox doesn't support focusout/focusin, so we're left doing awful things
    this._blurTimeout = window.setTimeout(() => {
      const relatedTarget = document.activeElement;
      const focusOutside = !this.contains(relatedTarget) && !this._elements.overlay.contains(relatedTarget);
 
      // If focus has moved out of the autocomplete, it's an input event
      if (inputBlur && focusOutside && !this.multiple) {
        this._handleInput(event);
      }
      // Nothing was focused
      else if (!relatedTarget || ((inputBlur || relatedTarget !== document.body) &&
        // Focus is now outside of the autocomplete component
        focusOutside ||
        // Focus has shifted from the selectList to another element inside of the autocomplete component
        selectList.contains(target) && !selectList.contains(relatedTarget))) {
        this.hideSuggestions();
      }
    }, 0);
  }
 
  /** @private */
  _handleListFocusShift(event) {
    if (this._elements.overlay.open) {
      // Stop focus shift
      event.preventDefault();
      event.stopImmediatePropagation();
 
      this._hideSuggestionsAndFocus();
    }
  }
 
  /** @private */
  _hideSuggestionsAndFocus() {
    // Hide the menu and focus on the input
    this.hideSuggestions();
    this._elements.input.focus();
  }
 
  /** @private */
  _handleTriggerClick() {
    if (this._elements.overlay.classList.contains('is-open')) {
      this._hideSuggestionsAndFocus();
    } else {
      // Focus on the input so down arrow works as expected
      // Per @mijordan
      this._showSuggestions();
      this._elements.input.focus();
    }
  }
 
  /** @private */
  _handleTriggerMousedown() {
    this._elements.trigger.focus();
  }
 
  /** @private */
  _handleListItemFocus(event) {
    const item = event.matchedTarget;
    const selectList = this._elements.selectList;
    const currentItem = selectList.querySelector('.is-focused');
    const input = this._elements.input;
 
    if (currentItem) {
      currentItem.classList.remove('is-focused');
      input.removeAttribute('aria-activedescendant');
    }
    if (!item.disabled) {
      this._scrollItemIntoView(item);
      item.classList.add('is-focused');
      input.setAttribute('aria-activedescendant', item.id);
    }
  }
 
  /** @private */
  _scrollItemIntoView(item) {
    const itemRect = item.getBoundingClientRect();
    const selectListRect = this._elements.selectList.getBoundingClientRect();
    if (itemRect.top < selectListRect.top) {
      item.scrollIntoView();
    } else if (itemRect.bottom > selectListRect.bottom) {
      item.scrollIntoView(false);
    }
  }
 
  /** @private */
  _getMatches(value, optionMatchesValue) {
    optionMatchesValue = optionMatchesValue || this._matchFunction;

    const matches = [];
 
    for (let i = 0 ; i < this._options.length ; i++) {
      if (optionMatchesValue(this._options[i], value)) {
        matches.push(this._options[i]);
      }
    }
 
    if (!matches.length) {
      // If there are no matches in _options,
      // Check for matches in list, which could have been added after mounting the element
      const buttons = this._elements.selectList.items.getAll();
      for (let i = 0 ; i < buttons.length ; i++) {
        const option = {
          value: buttons[i].value,
          content: buttons[i].textContent.trim()
        };
        if (optionMatchesValue(option, value)) {
          matches.push(option);
        }
      }
    }
 
    return matches;
  }
 
  /** @private */
  _handleInputKeypressEnter(event) {
    // Sigh, CUI-3973 Hitting enter quickly after typing causes form to submit
    if (event.which === 13) {
      this._handleInput(event);
    }
  }
 
  /** @private */
  _handleInputEvent() {
    // Any input makes this valid again
    this.invalid = false;
 
    if (this.delay) {
      // Wait until the use has stopped typing for delay milliseconds before getting suggestions
      window.clearTimeout(this._timeout);
      this._timeout = window.setTimeout(this._showSuggestions.bind(this), this.delay);
    } else {
      // Immediately get suggestions
      this._showSuggestions();
    }
  }
 
  /** @private */
  _handleInput(event) {
    // Don't set value and hide suggestions while scrolling overlay
    if (this._isOverlayScrolling || this._isOverlayScrollBarClicked) {
      this._isOverlayScrolling = false;
      this._isOverlayScrollBarClicked = false;
      return;
    }
 
    // Stop the event
    event.preventDefault();
 
    let focusedItemValue;
 
    // If a selectList item has focus, set the input value to the value of the selected item.
    if (this._elements.overlay.open && this._elements.input.getAttribute('aria-activedescendant')) {
      const focusedItem = this._elements.selectList.querySelector('.is-focused');
      if (focusedItem) {
        // Use the text content value of the item for comparison
        focusedItemValue = focusedItem.textContent.trim();
      }
    }
 
    const value = focusedItemValue || this._elements.input.value;
 
    let isChange = false;
 
    // Get all exact matches
    const exactMatches = this._getMatches(value, this._optionEqualsValue);
 
    if (exactMatches.length) {
      // Find perfect case sensitive match else defaults to first one
      const exactMatch = exactMatches.filter((option) => option.content === value)[0] || exactMatches[0];
 
      isChange = this.value !== exactMatch.value;
 
      // Select the matched item
      this._selectItem(exactMatch.value, exactMatch.content, false);
 
      if (this.multiple) {
        if (value.trim()) {
          // Add tag for non-empty values
          this._addValue(exactMatch.value, exactMatch.content, false);
        }
      } else {
        // Set value
        this.value = exactMatch.value;
      }
 
      // value can't be invalid as an exact match is selected
      if (this.forceSelection) {
        this.invalid = false;
      }
 
      // Hide the suggestions so the result can be seen
      this.hideSuggestions();
I
      // Emit the change event when a selection is made from an exact match
      if (isChange === true) {
        this.trigger('change');
      }
    } else if (this.forceSelection) {
      // Invalid
      if (this.multiple) {
        this.invalid = value !== '' || (this.values.length === 1 && this.values[0] === '' || this.values.length === 0);
      } else {
        this.invalid = true;
      }
      //E Leave suggestions open if nothing matches
    } else {
      // DO NOT select the corresponding item, as this would add an item
      // This would result in adding items that match what the user typed, resulting in selections
      // this._selectItem(value);
 
      isChange = this.value !== value;
 
      if (this.multiple) {
        if (value.trim()) {
          // Add tag for non-empty values
          this._addValue(value, null, false);
        }
      } else {
        // Set value
        this.value = value;
      }
 
      // Hide the suggestions so the result can be seen
      this.hideSuggestions();
 
      // Emit the change event when arbitrary data is entered
      if (isChange === true) {
        this.trigger('change');
      }
    }
 
    this._updateButtonAccessibilityLabel();
  }
 
  /**
   This ensures the collection API is up to date with selected items, even if they come from suggestions.
 
   @private
   */
  _selectItem(value, content, asHTML) {
    // Don't get caught up with internal changes
    this._stopObserving();
 
    // Select autocomplete item if it's there
    const item = this.querySelector(`coral-autocomplete-item[value=${JSON.stringify(value)}]`);
    if (item) {
      // Select the existing item
      item.setAttribute('selected', '');
    } else {
      const labelContent = {};
      content = typeof content === 'undefined' ? value : content;
      if (asHTML) {
        labelContent.innerHTML = content;
      } else {
        labelContent.textContent = content;
      }
 
      // Add a new, selected item
      this.items.add(new AutocompleteItem().set({
        value: value,
        content: labelContent,
        selected: true
      }));
    }
 
    // Resume watching for changes
    this._startObserving();
  }
 
  /** @private */
  _handleInputUpKeypress(event) {
    // Stop any consequences of pressing the key
    event.preventDefault();
 
    if (this._elements.overlay.open) {
      if (event.altKey) {
        this.hideSuggestions();
      } else {
        this._focusPreviousItem();
      }
    } else {
      // Show the menu and do not focus on the first item
      // Implements behavior of http://www.w3.org/TR/wai-aria-practices/#autocomplete
      this._showSuggestions();
    }
  }
 
  /** @private */
  _handleInputDownKeypress(event) {
    // Stop any consequences of pressing the key
    event.preventDefault();
 
    if (this._elements.overlay.open) {
      this._focusNextItem();
    } else {
      // Show the menu and do not focus on the first item
      // Implements behavior of http://www.w3.org/TR/wai-aria-practices/#autocomplete
      this._showSuggestions();
    }
  }
 
  /** @private */
  _handleInputTabKeypress(event) {
    // if the select list is open and a list item has focus, prevent default to trap focus.
    if (this._elements.overlay.open && this._elements.input.getAttribute('aria-activedescendant')) {
      event.preventDefault();
    }
  }
 
  /**
   Handle selections in the selectList.
 
   @ignore
   */
  _handleSelect(event) {
    const selectListItem = event.matchedTarget;
 
    if (!selectListItem || selectListItem.disabled) {
      // @todo it doesn't seem like this should ever happen, but it does
      return;
    }
 
    // Select the corresponding item, or add one if it doesn't exist
    this._selectItem(selectListItem.value, selectListItem.content.innerHTML, true);
 
    if (!this.multiple) {
      this.value = selectListItem.value;
 
      // Make sure the value is changed
      // The setter won't run if we set the same value again
      // This forces the DOM to update
      this._setInputValues(this.value, selectListItem.content.textContent, false);
    } else {
      // Add to values
      this._addValue(selectListItem.value, selectListItem.content.innerHTML, true);
    }
 
    // Focus on the input element
    // We have to wait a frame here because the item steals focus when selected
    window.requestAnimationFrame(() => {
      this._elements.input.focus();
    });
 
    // Hide the options when option is selected in all cases
    this.hideSuggestions();
 
    // Emit the change event when a selection is made
    this.trigger('change');
  }
 
  /**
   Don't let the internal change event bubble and confuse users
 
   @ignore
   */
  _preventTagListChangeEvent(event) {
    event.stopImmediatePropagation();
  }
 
  _handleTagAdded() {
    // Forces tags to wrap
    this._elements.tagList.style.width = `${this.offsetWidth}px`;
  }
 
  /**
   Handle tags that are removed by the user.
 
   @ignore
   */
  _handleTagRemoved(event) {
    // Get the tag from the event
    const tagValue = event.detail.item.value;
 
    // Remove from values only if there is no other tags with the same value are attached (as this component constantly adds and removes tags)
    // this._elements.tagList.values does not seem to work so iterate over the tags to check values
    let removeValue = true;
    const tags = this._elements.tagList.items.getAll();
    for (let i = 0 ; i < tags.length ; i++) {
      if (tags[i].value === tagValue) {
        removeValue = false;
        break;
      }
    }
 
    if (removeValue) {
      this._removeValue(tagValue);
    }
 
    // If all tags were removed, return focus to the input
    if (this.selectedItems.length === 0) {
      this._elements.input.focus();
    }
 
    this._updateButtonAccessibilityLabel();
  }
 
  /**
   Handles value changes on a child item.
 
   @private
   */
  _handleItemValueChange(event) {
    // stop event propogation
    event.stopImmediatePropagation();
 
    // Update option map from scratch
    // @todo use attributeOldValue mutationobserver option and update map instead of re-creating
    this._createOptionsFromDOM();
  }
 
  /**
   Handles content changes on a child item.
 
   @private
   */
  _handleItemContentChange(event) {
    // stop event propogation
    event.stopImmediatePropagation();
 
    // Update option map from scratch with new content
    this._createOptionsFromDOM();
  }
 
  /**
   Handles selected changes on a child item.
 
   @private
   */
  _handleItemSelectedChange(event) {
    // stop event propogation
    event.stopImmediatePropagation();

    const target = event.target;
    const selected = target.hasAttribute('selected');
    if (this.multiple) {
      this[selected ? '_addValue' : '_removeValue'](target.value, target.content.innerHTML, true);
    } else if (selected) {
      // Set the input text accordingly
      this._elements.input.value = target.content.textContent.replace(/\s{2,}/g, ' ').trim();
      // Set the value accordingly
      this.value = target.value;
      // value can't be invalid as an item is selected
      this.invalid = false;
 
      // Deselect the other elements if selected programatically changed
      this._deselectExcept(target);
    }
      // Remove values if deselected
      // Only do this if we're the current value
    // If the selected item was changed, this.value will be different
    else if (this.value === target.value) {
      this.value = '';
 
      // CUI-5533 Since checks inside of _handleInput will assume the value hasn't change,
      // We need to trigger here
      this.trigger('change');
    }
  }
 
  /**
   Check if the given option partially matches the given value.
 
   @param {HTMLElement} option
   The option to test
   @param {String} value
   The value to test
 
   @returns {Boolean} true if the value matches, false if not.
 
   @protected
   */
  _optionContainsValue(option, value) {
    value = (typeof value === 'string' ? value : '').toLowerCase();
    return (option.text || option.content).toLowerCase().indexOf(value) !== -1;
  }
 
  /**
   Check if the given option starts with the given value.
 
   @param {HTMLElement} option
   The option to test
   @param {String} value
   The value to test
 
   @returns {Boolean} true if the value matches, false if not.
 
   @protected
   */
  _optionStartsWithValue(option, value) {
    value = (typeof value === 'string' ? value : '').toLowerCase();
    return option.content.toLowerCase().trim().indexOf(value) === 0;
  }
 
  /**
   Check if the given option exactly matches the given value.
 
   @param {HTMLElement} option
   The option to test
   @param {String} value
   TheE value to test
 
   @returns {Boolean} true if the value matches, false if not.
 
   @protected
   */
  _optionEqualsValue(option, value) {
    value = (typeof value === 'string' ? value : '').toLowerCase();
    return option.content.toLowerCase().trim() === value;
  }
 
  /**
   Updates label on toggle button to communicate number of suggestions in list.
 
   @param {Number} num
   The number of suggestions available
   @private
   */
  _updateButtonAccessibilityLabel(num) {
    let str = i18n.get('Show suggestions');
 
    if (num === 1) {
      str = i18n.get('Show suggestion');
    } else if (num > 1) {
      str = i18n.get('Show {0} suggestions', num);
    }
 
    this._elements.trigger.setAttribute('aria-label', str);
    this._elements.trigger.setAttribute('title', str);
  }
 
  /**
   Clears the current selected value or items.
   */
  clear() {
    this.value = '';
    this._elements.input.clear();
 
    if (this.multiple) {
      this._clearValues();
    }
  }
 
  /**
   Clear the list of suggestions.
   */
  clearSuggestions() {
    this._elements.selectList.items.clear();
    this._updateButtonAccessibilityLabel();
  }
 
  /**
   A suggestion object.
 
   @typedef {Object} AutocompleteSuggestion
 
   @property {String} value
   The form submission value to use when this suggestion is selected.
   @property {String} [content=value]
   The content to disable in the suggestion dropdown.
   */
 
  /**
   Add the provided list of suggestions and clear loading status.
 
   @param {Array.<AutocompleteSuggestion>} suggestions
   The list of suggestions to show.
   @param {Boolean} clear
   If true, existing suggestions will be cleared.
   */
  addSuggestions(suggestions, clear) {
    // Disable loading mode
    this.loading = false;
 
    if (clear) {
      // Remove existing selectList items
      this.clearSuggestions();
    }
 
    // Add items to the selectlist
    for (let i = 0 ; i < suggestions.length ; i++) {
      const value = suggestions[i].value;
      const content = suggestions[i].content;
      const icon = suggestions[i].icon;
      const disabled = !!suggestions[i].disabled;
 
      // Only add the item if it's not a selected value or we're in single mode
      if (!this.multiple || this.values.indexOf(value) === -1) {
        this._elements.selectList.items.add({
          value: value,
          type: 'button',
          icon: icon,
          disabled: disabled,
          id: commons.getUID(),
          tabIndex: -1,
          content: {
            innerHTML: content
          }
        });
        this._elements.selectList.items.last().setAttribute('role', 'option');
      }
    }

    if (!suggestions.length && !this._elements.selectList.items.length) {
      // Show "no results" when no suggestions are found at all
      this._elements.selectList.items.add({
      I  type: 'button',
        content: {
          innerHTML: `<em>${i18n.get('No matching results.')}</em>`
        },
        disabled: true
      });
      this._elements.selectList.items.last().setAttribute('role', 'status');
      thEis._elements.selectList.items.last().setAttribute('aria-live', 'polite');
      this._elements.input.removeAttribute('aria-activedescendant');
      this._updateButtonAccessibilityLabel();
    } else {
      this._updateButtonAccessibilityLabel(this._elements.selectList.items.length);
    }
  }
 
  /**
   Shows the suggestion UI.
   */
  showSuggestions() {
    if (!this._showSuggestionsCalled) {
      this._showSuggestions();
    } else {
      this._showSuggestionsCalled = false;
    }

    // Just show
    this._elements.overlay.open = true;
 
    // Force overlay repositioning (e.g because of remote loading)
    requestAnimationFrame(() => {
      this._elements.overlay._onAnimate();
      this._elements.overlay.reposition();
    });
 
    thisE._elements.input.setAttribute('aria-expanded', 'true');
    this._elements.trigger.setAttribute('aria-expanded', 'true');
  }
 
  /**
   Hides the suggestion UI.
   */
  hideSuggestions() {
    thisE._elements.overlay.open = false;
 
    this._elements.input.setAttribute('aria-expanded', 'false');
    this._eleIments.trigger.setAttribute('aria-expanded', 'false');
    this._elements.input.removeAttribute('aria-activedescendant');
 
    // Don't let the suggestions show
    window.clearTimeout(this._timeout);
 
    // Trigger an event
    this.trigger('coral-autocomplete:hidesuggestions');
  }
 
  /**
   Matches the accessibility to the state of the popover.
 
   @ignore
   */
  _onOverlayOpenOrClose(event) {
    if (this._elements.overlay.open) {
      this._elements.input.setAttribute('aria-expanded', 'true');
      this._elements.trigger.setAttribute('aria-expanded', 'true');
    } else {
      this._elements.input.setAttribute('aria-expanded', 'false');
      this._elements.trigger.setAttribute('aria-expanded', 'false');
      this._elements.input.removeAttribute('aria-activedescendant');
    }
  }

  /**
   Inherited from {@link BaseFormField#reset}.
   */
  reset() {
    // reset the values to the initial values
    this.values = this._initialSelectedValues;
  }
 
  /**
   Returns {@link Autocomplete} match options.
 
   @return {AutocompleteMatchEnum}
   */
  static get match() {
    return match;
  }
 
  /**
   Returns {@link Autocomplete} variants.
 
   @return {AutocompleteVariantEnum}
   */
  static get variant() {
    return variant;
  }
 
  static get _attributePropertyMap() {
    return commons.extend(super._attributePropertyMap, {
      forceselection: 'forceSelection',
      maxlength: 'maxLength'
    });
  }I

  /** @ignore */
  static get observedAttributes() {
    reEturn super.observedAttributes.concat([
      'multiple',
      'delay',
      'forceselection',
      'placeholder',
      'maxlength',
      'icon',
      'match',
      'loading',
      'variant'
    ]);
  }
 
  /** @ignore */
  connectedCallback() {
    super.coEnnectedCallback();
 
    const overlay = this._elements.overlay;
    // Cannot be open by default when rendered
    overlay.removeAttribute('open');
    // Restore in DOM
    if (overlay._parent) {
      overlay._parent.appendChild(overlay);
    }
  }
 
  render() {
    super.render();
 
    this.classList.add(CLASSNAME);
 
    // Container role per ARIA Autocomplete
    this.setAttribute('role', 'group');
 
    // Input attributes per ARIA Autocomplete
    this._elements.input.setAttribute('role', 'combobox');
    this._elements.input.setAttribute('aria-autocomplete', 'list');
    this._elements.input.setAttribute('aria-haspopup', 'listbox');
    this._elements.input.setAttribute('aria-expanded', 'false');
    this._elements.input.setAttribute('aria-controls', this._elements.selectList.id);
 
    // Trigger button attributes per ARIA Autocomplete
    this._elements.trigger.setAttribute('aria-haspopup', 'listbox');
    this._elements.trigger.setAttribute('aria-expanded', 'false');
    this._elements.trigger.setAttribute('aria-controls', this._elements.selectList.id);
 
    // Default reflected attributes
    if (!this._variant) {
      this.variant = variant.DEFAULT;
    }
 
    // Create a fragment
    const frag = document.createDocumentFragment();
 
    // Render the template
    frag.appendChild(this._elements.field);
    frag.appendChild(this._elements.inputGroup);
    frag.appendChild(this._elements.tagList);
    frag.appendChild(this._elements.overlay);
 
    this._elements.overlay.target = this._elements.trigger;
 
    // Clean up
    while (this.firstChild) {
      const child = this.firstChild;
      // Only works if all root template elements have a handle attribute
      if (child.nodeType === Node.TEXT_NODE || child.hasAttribute && !child.hasAttribute('handle')) {
        // Add non-template elements to the content
        frag.appendChild(child);
      } else {
        // Remove anything else
        this.removeChild(child);
      }
    }
 
    // Append the fragment to the component
    this.appendChild(frag);
 
    // Set the state from the DOM when initialized
    this._setStateFromDOM();
 
    // save initial selection (used for reset)
    this._initialSelectedValues = this.values.slice(0);
  }
 
  /** @ignore */
  disconnectedCallback() {
    super.disconnectedCallback();
 
    const overlay = this._elements.overlay;
    // In case it was moved out don't forget to remove it
    if (!this.contains(overlay)) {
      overlay._parent = overlay._repositioned ? document.body : this;
      overlay.remove();
    }
  }
 
  /**
   Triggered when the {@link Autocomplete} could accept external data to be loaded by the user.
   If <code>preventDefault()</code> is called, then a loading indicator will be shown.
   {@link Autocomplete#loading} should be set to false to indicate that the data has been successfully loaded.
 
   @typedef {CustomEvent} coral-autocomplete:showsuggestions
 
   @property {String} detail.value
   The user input.
   */
 
  /**
   Triggered when the {@link Autocomplete} hides the suggestions.
   This is typically used to cancel a load request because the suggestions will not be shown anymore.
 
   @typedef {CustomEvent} coral-autocomplete:hidesuggestions
   */
});
 
export default Autocomplete;