@smilodon/core 1.3.9 → 1.3.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1439,7 +1439,7 @@ class SelectConfigManager {
1439
1439
  deepMerge(target, source) {
1440
1440
  const result = { ...target };
1441
1441
  for (const key in source) {
1442
- if (source.hasOwnProperty(key)) {
1442
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
1443
1443
  const sourceValue = source[key];
1444
1444
  const targetValue = result[key];
1445
1445
  if (sourceValue && typeof sourceValue === 'object' && !Array.isArray(sourceValue)) {
@@ -1471,182 +1471,20 @@ function resetSelectConfig() {
1471
1471
  }
1472
1472
 
1473
1473
  /**
1474
- * Enhanced Select Component
1475
- * Implements all advanced features: infinite scroll, load more, busy state,
1476
- * server-side selection, and full customization
1474
+ * Independent Option Component
1475
+ * High cohesion, low coupling - handles its own selection state and events
1477
1476
  */
1478
- class EnhancedSelect extends HTMLElement {
1479
- constructor() {
1477
+ class SelectOption extends HTMLElement {
1478
+ constructor(config) {
1480
1479
  super();
1481
- this._pageCache = {};
1482
- this._typeBuffer = '';
1483
- this._hasError = false;
1484
- this._errorMessage = '';
1485
- this._boundArrowClick = null;
1480
+ this._config = config;
1486
1481
  this._shadow = this.attachShadow({ mode: 'open' });
1487
- this._uniqueId = `enhanced-select-${Math.random().toString(36).substr(2, 9)}`;
1488
- // Merge global config with component-level config
1489
- this._config = selectConfig.getConfig();
1490
- // Initialize state
1491
- this._state = {
1492
- isOpen: false,
1493
- isBusy: false,
1494
- isSearching: false,
1495
- currentPage: this._config.infiniteScroll.initialPage || 1,
1496
- totalPages: 1,
1497
- selectedIndices: new Set(),
1498
- selectedItems: new Map(),
1499
- activeIndex: -1,
1500
- searchQuery: '',
1501
- loadedItems: [],
1502
- groupedItems: [],
1503
- preserveScrollPosition: false,
1504
- lastScrollPosition: 0,
1505
- lastNotifiedQuery: null,
1506
- lastNotifiedResultCount: 0,
1507
- isExpanded: false,
1508
- };
1509
- // Create DOM structure
1510
- this._container = this._createContainer();
1511
- this._inputContainer = this._createInputContainer();
1512
- this._input = this._createInput();
1513
- this._arrowContainer = this._createArrowContainer();
1514
- this._dropdown = this._createDropdown();
1515
- this._optionsContainer = this._createOptionsContainer();
1516
- this._liveRegion = this._createLiveRegion();
1517
- // Initialize styles BEFORE assembling DOM (order matters in shadow DOM)
1482
+ this._container = document.createElement('div');
1483
+ this._container.className = 'option-container';
1518
1484
  this._initializeStyles();
1519
- this._assembleDOM();
1485
+ this._render();
1520
1486
  this._attachEventListeners();
1521
- this._initializeObservers();
1522
- }
1523
- connectedCallback() {
1524
- // WORKAROUND: Force display style on host element for Angular compatibility
1525
- // Angular's rendering seems to not apply :host styles correctly in some cases
1526
- // Must be done in connectedCallback when element is attached to DOM
1527
- this.style.display = 'block';
1528
- this.style.width = '100%';
1529
- // Load initial data if server-side is enabled
1530
- if (this._config.serverSide.enabled && this._config.serverSide.initialSelectedValues) {
1531
- this._loadInitialSelectedItems();
1532
- }
1533
- // Emit open event if configured to start open
1534
- if (this._config.callbacks.onOpen) {
1535
- this._config.callbacks.onOpen();
1536
- }
1537
- }
1538
- disconnectedCallback() {
1539
- // Cleanup observers
1540
- this._resizeObserver?.disconnect();
1541
- this._intersectionObserver?.disconnect();
1542
- if (this._busyTimeout)
1543
- clearTimeout(this._busyTimeout);
1544
- if (this._typeTimeout)
1545
- clearTimeout(this._typeTimeout);
1546
- if (this._searchTimeout)
1547
- clearTimeout(this._searchTimeout);
1548
- // Cleanup arrow click listener
1549
- if (this._boundArrowClick && this._arrowContainer) {
1550
- this._arrowContainer.removeEventListener('click', this._boundArrowClick);
1551
- }
1552
- }
1553
- _createContainer() {
1554
- const container = document.createElement('div');
1555
- container.className = 'select-container';
1556
- if (this._config.styles.classNames?.container) {
1557
- container.className += ' ' + this._config.styles.classNames.container;
1558
- }
1559
- if (this._config.styles.container) {
1560
- Object.assign(container.style, this._config.styles.container);
1561
- }
1562
- return container;
1563
- }
1564
- _createInputContainer() {
1565
- const container = document.createElement('div');
1566
- container.className = 'input-container';
1567
- return container;
1568
- }
1569
- _createInput() {
1570
- const input = document.createElement('input');
1571
- input.type = 'text';
1572
- input.className = 'select-input';
1573
- input.placeholder = this._config.placeholder || 'Select an option...';
1574
- input.disabled = !this._config.enabled;
1575
- input.readOnly = !this._config.searchable;
1576
- // Update readonly when input is focused if searchable
1577
- input.addEventListener('focus', () => {
1578
- if (this._config.searchable) {
1579
- input.readOnly = false;
1580
- }
1581
- });
1582
- if (this._config.styles.classNames?.input) {
1583
- input.className += ' ' + this._config.styles.classNames.input;
1584
- }
1585
- if (this._config.styles.input) {
1586
- Object.assign(input.style, this._config.styles.input);
1587
- }
1588
- input.setAttribute('role', 'combobox');
1589
- input.setAttribute('aria-expanded', 'false');
1590
- input.setAttribute('aria-haspopup', 'listbox');
1591
- input.setAttribute('aria-autocomplete', this._config.searchable ? 'list' : 'none');
1592
- return input;
1593
- }
1594
- _createDropdown() {
1595
- const dropdown = document.createElement('div');
1596
- dropdown.className = 'select-dropdown';
1597
- dropdown.style.display = 'none';
1598
- if (this._config.styles.classNames?.dropdown) {
1599
- dropdown.className += ' ' + this._config.styles.classNames.dropdown;
1600
- }
1601
- if (this._config.styles.dropdown) {
1602
- Object.assign(dropdown.style, this._config.styles.dropdown);
1603
- }
1604
- dropdown.setAttribute('role', 'listbox');
1605
- if (this._config.selection.mode === 'multi') {
1606
- dropdown.setAttribute('aria-multiselectable', 'true');
1607
- }
1608
- return dropdown;
1609
- }
1610
- _createOptionsContainer() {
1611
- const container = document.createElement('div');
1612
- container.className = 'options-container';
1613
- return container;
1614
- }
1615
- _createLiveRegion() {
1616
- const liveRegion = document.createElement('div');
1617
- liveRegion.setAttribute('role', 'status');
1618
- liveRegion.setAttribute('aria-live', 'polite');
1619
- liveRegion.setAttribute('aria-atomic', 'true');
1620
- liveRegion.style.cssText = 'position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0;';
1621
- return liveRegion;
1622
- }
1623
- _createArrowContainer() {
1624
- const container = document.createElement('div');
1625
- container.className = 'dropdown-arrow-container';
1626
- container.innerHTML = `
1627
- <svg class="dropdown-arrow" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
1628
- <path d="M4 6L8 10L12 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
1629
- </svg>
1630
- `;
1631
- return container;
1632
- }
1633
- _assembleDOM() {
1634
- this._inputContainer.appendChild(this._input);
1635
- if (this._arrowContainer) {
1636
- this._inputContainer.appendChild(this._arrowContainer);
1637
- }
1638
- this._container.appendChild(this._inputContainer);
1639
- this._dropdown.appendChild(this._optionsContainer);
1640
- this._container.appendChild(this._dropdown);
1641
1487
  this._shadow.appendChild(this._container);
1642
- if (this._liveRegion) {
1643
- this._shadow.appendChild(this._liveRegion);
1644
- }
1645
- // Set ARIA relationships
1646
- const listboxId = `${this._uniqueId}-listbox`;
1647
- this._dropdown.id = listboxId;
1648
- this._input.setAttribute('aria-controls', listboxId);
1649
- this._input.setAttribute('aria-owns', listboxId);
1650
1488
  }
1651
1489
  _initializeStyles() {
1652
1490
  const style = document.createElement('style');
@@ -1654,1618 +1492,2075 @@ class EnhancedSelect extends HTMLElement {
1654
1492
  :host {
1655
1493
  display: block;
1656
1494
  position: relative;
1657
- width: 100%;
1658
- }
1659
-
1660
- .select-container {
1661
- position: relative;
1662
- width: 100%;
1663
- }
1664
-
1665
- .input-container {
1666
- position: relative;
1667
- width: 100%;
1668
- display: flex;
1669
- align-items: center;
1670
- flex-wrap: wrap;
1671
- gap: var(--select-input-gap, 6px);
1672
- padding: var(--select-input-padding, 6px 52px 6px 8px);
1673
- min-height: var(--select-input-min-height, 44px);
1674
- background: var(--select-input-bg, white);
1675
- border: var(--select-input-border, 1px solid #d1d5db);
1676
- border-radius: var(--select-input-border-radius, 6px);
1677
- box-sizing: border-box;
1678
- transition: all 0.2s ease;
1679
- }
1680
-
1681
- .input-container:focus-within {
1682
- border-color: var(--select-input-focus-border, #667eea);
1683
- box-shadow: var(--select-input-focus-shadow, 0 0 0 3px rgba(102, 126, 234, 0.1));
1684
- }
1685
-
1686
- /* Gradient separator before arrow */
1687
- .input-container::after {
1688
- content: '';
1689
- position: absolute;
1690
- top: 50%;
1691
- right: var(--select-separator-position, 40px);
1692
- transform: translateY(-50%);
1693
- width: var(--select-separator-width, 1px);
1694
- height: var(--select-separator-height, 60%);
1695
- background: var(--select-separator-bg, var(--select-separator-gradient, linear-gradient(
1696
- to bottom,
1697
- transparent 0%,
1698
- rgba(0, 0, 0, 0.1) 20%,
1699
- rgba(0, 0, 0, 0.1) 80%,
1700
- transparent 100%
1701
- )));
1702
- pointer-events: none;
1703
- z-index: 1;
1704
1495
  }
1705
1496
 
1706
- .dropdown-arrow-container {
1707
- position: absolute;
1708
- top: 0;
1709
- right: 0;
1710
- bottom: 0;
1711
- width: var(--select-arrow-width, 40px);
1497
+ .option-container {
1712
1498
  display: flex;
1713
1499
  align-items: center;
1714
- justify-content: center;
1500
+ justify-content: space-between;
1501
+ padding: 8px 12px;
1715
1502
  cursor: pointer;
1503
+ user-select: none;
1716
1504
  transition: background-color 0.2s ease;
1717
- border-radius: var(--select-arrow-border-radius, 0 4px 4px 0);
1718
- z-index: 2;
1719
1505
  }
1720
1506
 
1721
- .dropdown-arrow-container:hover {
1722
- background-color: var(--select-arrow-hover-bg, rgba(102, 126, 234, 0.08));
1507
+ .option-container:hover {
1508
+ background-color: var(--select-option-hover-bg, #f0f0f0);
1723
1509
  }
1724
1510
 
1725
- .dropdown-arrow {
1726
- width: var(--select-arrow-size, 16px);
1727
- height: var(--select-arrow-size, 16px);
1728
- color: var(--select-arrow-color, #667eea);
1729
- transition: transform 0.2s ease, color 0.2s ease;
1730
- transform: translateY(0);
1511
+ .option-container.selected {
1512
+ background-color: var(--select-option-selected-bg, #e3f2fd);
1513
+ color: var(--select-option-selected-color, #1976d2);
1731
1514
  }
1732
1515
 
1733
- .dropdown-arrow path {
1734
- stroke-width: var(--select-arrow-stroke-width, 2);
1516
+ .option-container.active {
1517
+ outline: 2px solid var(--select-option-active-outline, #1976d2);
1518
+ outline-offset: -2px;
1735
1519
  }
1736
1520
 
1737
- .dropdown-arrow-container:hover .dropdown-arrow {
1738
- color: var(--select-arrow-hover-color, #667eea);
1739
- }
1740
-
1741
- .dropdown-arrow.open {
1742
- transform: rotate(180deg);
1743
- }
1744
-
1745
- .select-input {
1746
- flex: 1;
1747
- min-width: var(--select-input-min-width, 120px);
1748
- padding: var(--select-input-field-padding, 4px);
1749
- border: none;
1750
- font-size: var(--select-input-font-size, 14px);
1751
- line-height: var(--select-input-line-height, 1.5);
1752
- color: var(--select-input-color, #1f2937);
1753
- background: transparent;
1754
- box-sizing: border-box;
1755
- outline: none;
1756
- font-family: var(--select-font-family, inherit);
1757
- }
1758
-
1759
- .select-input::placeholder {
1760
- color: var(--select-input-placeholder-color, #9ca3af);
1761
- }
1762
-
1763
- .selection-badge {
1764
- display: inline-flex;
1765
- align-items: center;
1766
- gap: var(--select-badge-gap, 4px);
1767
- padding: var(--select-badge-padding, 4px 8px);
1768
- margin: var(--select-badge-margin, 2px);
1769
- background: var(--select-badge-bg, #667eea);
1770
- color: var(--select-badge-color, white);
1771
- border-radius: var(--select-badge-border-radius, 4px);
1772
- font-size: var(--select-badge-font-size, 13px);
1773
- line-height: 1;
1774
- }
1775
-
1776
- .badge-remove {
1777
- display: inline-flex;
1778
- align-items: center;
1779
- justify-content: center;
1780
- width: var(--select-badge-remove-size, 16px);
1781
- height: var(--select-badge-remove-size, 16px);
1782
- padding: 0;
1783
- margin-left: 4px;
1784
- background: var(--select-badge-remove-bg, rgba(255, 255, 255, 0.3));
1785
- border: none;
1786
- border-radius: 50%;
1787
- color: var(--select-badge-remove-color, white);
1788
- font-size: var(--select-badge-remove-font-size, 16px);
1789
- line-height: 1;
1790
- cursor: pointer;
1791
- transition: background 0.2s;
1792
- }
1793
-
1794
- .badge-remove:hover {
1795
- background: var(--select-badge-remove-hover-bg, rgba(255, 255, 255, 0.5));
1796
- }
1797
-
1798
- .select-input:disabled {
1799
- background-color: var(--select-disabled-bg, #f5f5f5);
1521
+ .option-container.disabled {
1522
+ opacity: 0.5;
1800
1523
  cursor: not-allowed;
1524
+ pointer-events: none;
1801
1525
  }
1802
1526
 
1803
- .select-dropdown {
1804
- position: absolute;
1805
- scroll-behavior: smooth;
1806
- top: 100%;
1807
- left: 0;
1808
- right: 0;
1809
- margin-top: var(--select-dropdown-margin-top, 4px);
1810
- max-height: var(--select-dropdown-max-height, 300px);
1527
+ .option-content {
1528
+ flex: 1;
1811
1529
  overflow: hidden;
1812
- background: var(--select-dropdown-bg, white);
1813
- border: var(--select-dropdown-border, 1px solid #ccc);
1814
- border-radius: var(--select-dropdown-border-radius, 4px);
1815
- box-shadow: var(--select-dropdown-shadow, 0 4px 6px rgba(0,0,0,0.1));
1816
- z-index: var(--select-dropdown-z-index, 1000);
1817
- }
1818
-
1819
- .options-container {
1820
- position: relative;
1821
- max-height: var(--select-options-max-height, 300px);
1822
- overflow: auto;
1823
- transition: opacity 0.2s ease-in-out;
1824
- background: var(--select-options-bg, white);
1825
- }
1826
-
1827
- .option {
1828
- padding: var(--select-option-padding, 8px 12px);
1829
- cursor: pointer;
1830
- color: var(--select-option-color, #1f2937);
1831
- background: var(--select-option-bg, white);
1832
- transition: var(--select-option-transition, background-color 0.15s ease);
1833
- user-select: none;
1834
- font-size: var(--select-option-font-size, 14px);
1835
- line-height: var(--select-option-line-height, 1.5);
1836
- border: var(--select-option-border, none);
1837
- border-bottom: var(--select-option-border-bottom, none);
1838
- }
1839
-
1840
- .option:hover {
1841
- background-color: var(--select-option-hover-bg, #f3f4f6);
1842
- color: var(--select-option-hover-color, #1f2937);
1843
- }
1844
-
1845
- .option.selected {
1846
- background-color: var(--select-option-selected-bg, #e0e7ff);
1847
- color: var(--select-option-selected-color, #4338ca);
1848
- font-weight: var(--select-option-selected-weight, 500);
1849
- }
1850
-
1851
- .option.active {
1852
- background-color: var(--select-option-active-bg, #f3f4f6);
1853
- color: var(--select-option-active-color, #1f2937);
1854
- }
1855
-
1856
- .load-more-container {
1857
- padding: var(--select-load-more-padding, 12px);
1858
- text-align: center;
1859
- border-top: var(--select-divider-border, 1px solid #e0e0e0);
1860
- background: var(--select-load-more-bg, white);
1530
+ text-overflow: ellipsis;
1531
+ white-space: nowrap;
1861
1532
  }
1862
1533
 
1863
- .load-more-button {
1864
- padding: var(--select-button-padding, 8px 16px);
1865
- border: var(--select-button-border, 1px solid #1976d2);
1866
- background: var(--select-button-bg, white);
1867
- color: var(--select-button-color, #1976d2);
1868
- border-radius: var(--select-button-border-radius, 4px);
1534
+ .remove-button {
1535
+ margin-left: 8px;
1536
+ padding: 2px 6px;
1537
+ border: none;
1538
+ background-color: var(--select-remove-btn-bg, transparent);
1539
+ color: var(--select-remove-btn-color, #666);
1869
1540
  cursor: pointer;
1870
- font-size: var(--select-button-font-size, 14px);
1871
- font-family: var(--select-font-family, inherit);
1541
+ border-radius: 3px;
1542
+ font-size: 16px;
1543
+ line-height: 1;
1872
1544
  transition: all 0.2s ease;
1873
1545
  }
1874
1546
 
1875
- .load-more-button:hover {
1876
- background: var(--select-button-hover-bg, #1976d2);
1877
- color: var(--select-button-hover-color, white);
1878
- }
1879
-
1880
- .load-more-button:disabled {
1881
- opacity: var(--select-button-disabled-opacity, 0.5);
1882
- cursor: not-allowed;
1883
- }
1884
-
1885
- .busy-bucket {
1886
- padding: var(--select-busy-padding, 16px);
1887
- text-align: center;
1888
- color: var(--select-busy-color, #666);
1889
- background: var(--select-busy-bg, white);
1890
- font-size: var(--select-busy-font-size, 14px);
1891
- }
1892
-
1893
- .spinner {
1894
- display: inline-block;
1895
- width: var(--select-spinner-size, 20px);
1896
- height: var(--select-spinner-size, 20px);
1897
- border: var(--select-spinner-border, 2px solid #ccc);
1898
- border-top-color: var(--select-spinner-active-color, #1976d2);
1899
- border-radius: 50%;
1900
- animation: spin 0.6s linear infinite;
1901
- }
1902
-
1903
- @keyframes spin {
1904
- to { transform: rotate(360deg); }
1905
- }
1906
-
1907
- .empty-state {
1908
- padding: var(--select-empty-padding, 24px);
1909
- text-align: center;
1910
- color: var(--select-empty-color, #999);
1911
- font-size: var(--select-empty-font-size, 14px);
1912
- background: var(--select-empty-bg, white);
1913
- }
1914
-
1915
- .searching-state {
1916
- padding: var(--select-searching-padding, 24px);
1917
- text-align: center;
1918
- color: var(--select-searching-color, #667eea);
1919
- font-size: var(--select-searching-font-size, 14px);
1920
- font-style: italic;
1921
- background: var(--select-searching-bg, white);
1922
- animation: pulse 1.5s ease-in-out infinite;
1923
- }
1924
-
1925
- @keyframes pulse {
1926
- 0%, 100% { opacity: 1; }
1927
- 50% { opacity: 0.5; }
1928
- }
1929
-
1930
- /* Error states */
1931
- .select-input[aria-invalid="true"] {
1932
- border-color: var(--select-error-border, #dc2626);
1933
- }
1934
-
1935
- .select-input[aria-invalid="true"]:focus {
1936
- border-color: var(--select-error-border, #dc2626);
1937
- box-shadow: 0 0 0 2px var(--select-error-shadow, rgba(220, 38, 38, 0.1));
1938
- outline-color: var(--select-error-border, #dc2626);
1547
+ .remove-button:hover {
1548
+ background-color: var(--select-remove-btn-hover-bg, #ffebee);
1549
+ color: var(--select-remove-btn-hover-color, #c62828);
1939
1550
  }
1940
1551
 
1941
- /* Accessibility: Reduced motion */
1942
- @media (prefers-reduced-motion: reduce) {
1943
- * {
1944
- animation-duration: 0.01ms !important;
1945
- animation-iteration-count: 1 !important;
1946
- transition-duration: 0.01ms !important;
1947
- }
1552
+ .remove-button:focus {
1553
+ outline: 2px solid var(--select-remove-btn-focus-outline, #1976d2);
1554
+ outline-offset: 2px;
1948
1555
  }
1949
-
1950
- /* Dark mode - Opt-in via class or data attribute */
1951
- :host(.dark-mode),
1952
- :host([data-theme="dark"]) {
1953
- .input-container {
1954
- background: var(--select-dark-bg, #1f2937);
1955
- border-color: var(--select-dark-border, #4b5563);
1956
- }
1957
-
1958
- .select-input {
1959
- color: var(--select-dark-text, #f9fafb);
1960
- }
1961
-
1962
- .select-input::placeholder {
1963
- color: var(--select-dark-placeholder, #6b7280);
1556
+ `;
1557
+ this._shadow.appendChild(style);
1558
+ }
1559
+ _render() {
1560
+ const { item, index, selected, disabled, active, render, showRemoveButton } = this._config;
1561
+ // Clear container
1562
+ this._container.innerHTML = '';
1563
+ // Apply state classes
1564
+ this._container.classList.toggle('selected', selected);
1565
+ this._container.classList.toggle('disabled', disabled || false);
1566
+ this._container.classList.toggle('active', active || false);
1567
+ // Custom class name
1568
+ if (this._config.className) {
1569
+ this._container.className += ' ' + this._config.className;
1964
1570
  }
1965
-
1966
- .select-dropdown {
1967
- background: var(--select-dark-dropdown-bg, #1f2937);
1968
- border-color: var(--select-dark-dropdown-border, #4b5563);
1571
+ // Apply custom styles
1572
+ if (this._config.style) {
1573
+ Object.assign(this._container.style, this._config.style);
1969
1574
  }
1970
-
1971
- .options-container {
1972
- background: var(--select-dark-options-bg, #1f2937);
1973
- }
1974
-
1975
- .option {
1976
- color: var(--select-dark-option-color, #f9fafb);
1977
- background: var(--select-dark-option-bg, #1f2937);
1978
- }
1979
-
1980
- .option:hover {
1981
- background-color: var(--select-dark-option-hover-bg, #374151);
1982
- color: var(--select-dark-option-hover-color, #f9fafb);
1983
- }
1984
-
1985
- .option.selected {
1986
- background-color: var(--select-dark-option-selected-bg, #3730a3);
1987
- color: var(--select-dark-option-selected-text, #e0e7ff);
1988
- }
1989
-
1990
- .option.active {
1991
- background-color: var(--select-dark-option-active-bg, #374151);
1992
- color: var(--select-dark-option-active-color, #f9fafb);
1993
- }
1994
-
1995
- .busy-bucket,
1996
- .empty-state {
1997
- color: var(--select-dark-busy-color, #9ca3af);
1998
- }
1999
-
2000
- .input-container::after {
2001
- background: linear-gradient(
2002
- to bottom,
2003
- transparent 0%,
2004
- rgba(255, 255, 255, 0.1) 20%,
2005
- rgba(255, 255, 255, 0.1) 80%,
2006
- transparent 100%
2007
- );
2008
- }
2009
- }
2010
-
2011
- /* Accessibility: High contrast mode */
2012
- @media (prefers-contrast: high) {
2013
- .select-input:focus {
2014
- outline-width: 3px;
2015
- outline-color: Highlight;
2016
- }
2017
-
2018
- .select-input {
2019
- border-width: 2px;
2020
- }
2021
- }
2022
-
2023
- /* Touch targets (WCAG 2.5.5) */
2024
- .load-more-button,
2025
- select-option {
2026
- min-height: 44px;
2027
- }
2028
- `;
2029
- // Insert as first child to ensure styles are processed first
2030
- if (this._shadow.firstChild) {
2031
- this._shadow.insertBefore(style, this._shadow.firstChild);
1575
+ // Render content
1576
+ const contentDiv = document.createElement('div');
1577
+ contentDiv.className = 'option-content';
1578
+ if (render) {
1579
+ const rendered = render(item, index);
1580
+ if (typeof rendered === 'string') {
1581
+ contentDiv.innerHTML = rendered;
1582
+ }
1583
+ else {
1584
+ contentDiv.appendChild(rendered);
1585
+ }
2032
1586
  }
2033
1587
  else {
2034
- this._shadow.appendChild(style);
1588
+ const label = this._getLabel();
1589
+ contentDiv.textContent = label;
1590
+ }
1591
+ this._container.appendChild(contentDiv);
1592
+ // Add remove button if needed
1593
+ if (showRemoveButton && selected) {
1594
+ this._removeButton = document.createElement('button');
1595
+ this._removeButton.className = 'remove-button';
1596
+ this._removeButton.innerHTML = '×';
1597
+ this._removeButton.setAttribute('aria-label', 'Remove option');
1598
+ this._removeButton.setAttribute('type', 'button');
1599
+ this._container.appendChild(this._removeButton);
2035
1600
  }
1601
+ // Set ARIA attributes
1602
+ this.setAttribute('role', 'option');
1603
+ this.setAttribute('aria-selected', String(selected));
1604
+ if (disabled)
1605
+ this.setAttribute('aria-disabled', 'true');
1606
+ this.id = this._config.id || `select-option-${index}`;
2036
1607
  }
2037
1608
  _attachEventListeners() {
2038
- // Arrow click handler
2039
- if (this._arrowContainer) {
2040
- this._boundArrowClick = (e) => {
2041
- e.stopPropagation();
2042
- e.preventDefault();
2043
- const wasOpen = this._state.isOpen;
2044
- this._state.isOpen = !this._state.isOpen;
2045
- this._updateDropdownVisibility();
2046
- this._updateArrowRotation();
2047
- if (this._state.isOpen && this._config.callbacks.onOpen) {
2048
- this._config.callbacks.onOpen();
2049
- }
2050
- else if (!this._state.isOpen && this._config.callbacks.onClose) {
2051
- this._config.callbacks.onClose();
2052
- }
2053
- // Scroll to selected when opening
2054
- if (!wasOpen && this._state.isOpen && this._state.selectedIndices.size > 0) {
2055
- setTimeout(() => this._scrollToSelected(), 50);
2056
- }
2057
- };
2058
- this._arrowContainer.addEventListener('click', this._boundArrowClick);
2059
- }
2060
- // Input container click - prevent event from reaching document listener
1609
+ // Click handler for selection
2061
1610
  this._container.addEventListener('click', (e) => {
2062
- e.stopPropagation();
2063
- });
2064
- // Input focus/blur
2065
- this._input.addEventListener('focus', () => this._handleOpen());
2066
- this._input.addEventListener('blur', (e) => {
2067
- // Delay to allow option click
2068
- setTimeout(() => {
2069
- if (!this._dropdown.contains(document.activeElement)) {
2070
- this._handleClose();
2071
- }
2072
- }, 200);
2073
- });
2074
- // Input search
2075
- this._input.addEventListener('input', (e) => {
2076
- if (!this._config.searchable)
1611
+ // Don't trigger selection if clicking remove button
1612
+ if (e.target === this._removeButton) {
2077
1613
  return;
2078
- const query = e.target.value;
2079
- this._handleSearch(query);
1614
+ }
1615
+ if (!this._config.disabled) {
1616
+ this._handleSelect();
1617
+ }
2080
1618
  });
2081
- // Keyboard navigation
2082
- this._input.addEventListener('keydown', (e) => this._handleKeydown(e));
2083
- // Click outside to close
2084
- document.addEventListener('click', (e) => {
2085
- const target = e.target;
2086
- // Check if click is outside shadow root
2087
- if (!this._shadow.contains(target) && !this._container.contains(target)) {
2088
- this._handleClose();
1619
+ // Remove button handler
1620
+ if (this._removeButton) {
1621
+ this._removeButton.addEventListener('click', (e) => {
1622
+ e.stopPropagation();
1623
+ this._handleRemove();
1624
+ });
1625
+ }
1626
+ // Keyboard handler
1627
+ this.addEventListener('keydown', (e) => {
1628
+ if (this._config.disabled)
1629
+ return;
1630
+ if (e.key === 'Enter' || e.key === ' ') {
1631
+ e.preventDefault();
1632
+ this._handleSelect();
1633
+ }
1634
+ else if (e.key === 'Delete' || e.key === 'Backspace') {
1635
+ if (this._config.selected && this._config.showRemoveButton) {
1636
+ e.preventDefault();
1637
+ this._handleRemove();
1638
+ }
2089
1639
  }
2090
1640
  });
2091
1641
  }
2092
- _initializeObservers() {
2093
- // Disconnect existing observer if any
2094
- if (this._intersectionObserver) {
2095
- this._intersectionObserver.disconnect();
2096
- this._intersectionObserver = undefined;
2097
- }
2098
- // Intersection observer for infinite scroll
2099
- if (this._config.infiniteScroll.enabled) {
2100
- this._intersectionObserver = new IntersectionObserver((entries) => {
2101
- entries.forEach((entry) => {
2102
- if (entry.isIntersecting) {
2103
- if (!this._state.isBusy) {
2104
- this._loadMoreItems();
2105
- }
2106
- }
2107
- });
2108
- }, { threshold: 0.1 });
2109
- }
1642
+ _handleSelect() {
1643
+ const detail = {
1644
+ item: this._config.item,
1645
+ index: this._config.index,
1646
+ value: this._getValue(),
1647
+ label: this._getLabel(),
1648
+ selected: !this._config.selected,
1649
+ };
1650
+ this.dispatchEvent(new CustomEvent('optionSelect', {
1651
+ detail,
1652
+ bubbles: true,
1653
+ composed: true,
1654
+ }));
2110
1655
  }
2111
- async _loadInitialSelectedItems() {
2112
- if (!this._config.serverSide.fetchSelectedItems || !this._config.serverSide.initialSelectedValues) {
2113
- return;
2114
- }
2115
- this._setBusy(true);
2116
- try {
2117
- const items = await this._config.serverSide.fetchSelectedItems(this._config.serverSide.initialSelectedValues);
2118
- // Add to state
2119
- items.forEach((item, index) => {
2120
- this._state.selectedItems.set(index, item);
2121
- this._state.selectedIndices.add(index);
2122
- });
2123
- this._updateInputDisplay();
2124
- }
2125
- catch (error) {
2126
- this._handleError(error);
2127
- }
2128
- finally {
2129
- this._setBusy(false);
1656
+ _handleRemove() {
1657
+ const detail = {
1658
+ item: this._config.item,
1659
+ index: this._config.index,
1660
+ value: this._getValue(),
1661
+ label: this._getLabel(),
1662
+ selected: false,
1663
+ };
1664
+ this.dispatchEvent(new CustomEvent('optionRemove', {
1665
+ detail,
1666
+ bubbles: true,
1667
+ composed: true,
1668
+ }));
1669
+ }
1670
+ _getValue() {
1671
+ if (this._config.getValue) {
1672
+ return this._config.getValue(this._config.item);
2130
1673
  }
1674
+ return this._config.item?.value ?? this._config.item;
2131
1675
  }
2132
- _handleOpen() {
2133
- if (!this._config.enabled || this._state.isOpen)
2134
- return;
2135
- this._state.isOpen = true;
2136
- this._dropdown.style.display = 'block';
2137
- this._input.setAttribute('aria-expanded', 'true');
2138
- this._updateArrowRotation();
2139
- // Clear search query when opening to show all options
2140
- // This ensures we can scroll to selected item
2141
- if (this._config.searchable) {
2142
- this._state.searchQuery = '';
2143
- // Don't clear input value if it represents selection
2144
- // But if we want to search, we might want to clear it?
2145
- // Standard behavior: input keeps value (label), but dropdown shows all options
2146
- // until user types.
2147
- // However, our filtering logic uses _state.searchQuery.
2148
- // So clearing it here resets the filter.
1676
+ _getLabel() {
1677
+ if (this._config.getLabel) {
1678
+ return this._config.getLabel(this._config.item);
2149
1679
  }
2150
- // Render options when opening
2151
- this._renderOptions();
2152
- this._emit('open', {});
2153
- this._config.callbacks.onOpen?.();
2154
- // Scroll to selected if configured
2155
- if (this._config.scrollToSelected.enabled) {
2156
- // Use requestAnimationFrame for better timing after render
2157
- requestAnimationFrame(() => {
2158
- // Double RAF to ensure layout is complete
2159
- requestAnimationFrame(() => {
2160
- this._scrollToSelected();
2161
- });
2162
- });
1680
+ return this._config.item?.label ?? String(this._config.item);
1681
+ }
1682
+ /**
1683
+ * Update option configuration and re-render
1684
+ */
1685
+ updateConfig(updates) {
1686
+ this._config = { ...this._config, ...updates };
1687
+ this._render();
1688
+ this._attachEventListeners();
1689
+ }
1690
+ /**
1691
+ * Get current configuration
1692
+ */
1693
+ getConfig() {
1694
+ return this._config;
1695
+ }
1696
+ /**
1697
+ * Get option value
1698
+ */
1699
+ getValue() {
1700
+ return this._getValue();
1701
+ }
1702
+ /**
1703
+ * Get option label
1704
+ */
1705
+ getLabel() {
1706
+ return this._getLabel();
1707
+ }
1708
+ /**
1709
+ * Set selected state
1710
+ */
1711
+ setSelected(selected) {
1712
+ this._config.selected = selected;
1713
+ this._render();
1714
+ }
1715
+ /**
1716
+ * Set active state
1717
+ */
1718
+ setActive(active) {
1719
+ this._config.active = active;
1720
+ this._render();
1721
+ }
1722
+ /**
1723
+ * Set disabled state
1724
+ */
1725
+ setDisabled(disabled) {
1726
+ this._config.disabled = disabled;
1727
+ this._render();
1728
+ }
1729
+ }
1730
+ // Register custom element
1731
+ if (!customElements.get('select-option')) {
1732
+ customElements.define('select-option', SelectOption);
1733
+ }
1734
+
1735
+ /**
1736
+ * Enhanced Select Component
1737
+ * Implements all advanced features: infinite scroll, load more, busy state,
1738
+ * server-side selection, and full customization
1739
+ */
1740
+ class EnhancedSelect extends HTMLElement {
1741
+ constructor() {
1742
+ super();
1743
+ this._pageCache = {};
1744
+ this._typeBuffer = '';
1745
+ this._hasError = false;
1746
+ this._errorMessage = '';
1747
+ this._boundArrowClick = null;
1748
+ this._pendingFirstRenderMark = false;
1749
+ this._pendingSearchRenderMark = false;
1750
+ this._rangeAnchorIndex = null;
1751
+ this._shadow = this.attachShadow({ mode: 'open' });
1752
+ this._uniqueId = `enhanced-select-${Math.random().toString(36).substr(2, 9)}`;
1753
+ this._rendererHelpers = this._buildRendererHelpers();
1754
+ // Merge global config with component-level config
1755
+ this._config = selectConfig.getConfig();
1756
+ // Initialize state
1757
+ this._state = {
1758
+ isOpen: false,
1759
+ isBusy: false,
1760
+ isSearching: false,
1761
+ currentPage: this._config.infiniteScroll.initialPage || 1,
1762
+ totalPages: 1,
1763
+ selectedIndices: new Set(),
1764
+ selectedItems: new Map(),
1765
+ activeIndex: -1,
1766
+ searchQuery: '',
1767
+ loadedItems: [],
1768
+ groupedItems: [],
1769
+ preserveScrollPosition: false,
1770
+ lastScrollPosition: 0,
1771
+ lastNotifiedQuery: null,
1772
+ lastNotifiedResultCount: 0,
1773
+ isExpanded: false,
1774
+ };
1775
+ // Create DOM structure
1776
+ this._container = this._createContainer();
1777
+ this._inputContainer = this._createInputContainer();
1778
+ this._input = this._createInput();
1779
+ this._arrowContainer = this._createArrowContainer();
1780
+ this._dropdown = this._createDropdown();
1781
+ this._optionsContainer = this._createOptionsContainer();
1782
+ this._liveRegion = this._createLiveRegion();
1783
+ // Initialize styles BEFORE assembling DOM (order matters in shadow DOM)
1784
+ this._initializeStyles();
1785
+ this._assembleDOM();
1786
+ this._attachEventListeners();
1787
+ this._initializeObservers();
1788
+ }
1789
+ connectedCallback() {
1790
+ // WORKAROUND: Force display style on host element for Angular compatibility
1791
+ // Angular's rendering seems to not apply :host styles correctly in some cases
1792
+ // Must be done in connectedCallback when element is attached to DOM
1793
+ this.style.display = 'block';
1794
+ this.style.width = '100%';
1795
+ // Load initial data if server-side is enabled
1796
+ if (this._config.serverSide.enabled && this._config.serverSide.initialSelectedValues) {
1797
+ this._loadInitialSelectedItems();
1798
+ }
1799
+ // Emit open event if configured to start open
1800
+ if (this._config.callbacks.onOpen) {
1801
+ this._config.callbacks.onOpen();
2163
1802
  }
2164
1803
  }
2165
- _handleClose() {
2166
- if (!this._state.isOpen)
2167
- return;
2168
- this._state.isOpen = false;
2169
- this._dropdown.style.display = 'none';
2170
- this._input.setAttribute('aria-expanded', 'false');
2171
- this._updateArrowRotation();
2172
- this._emit('close', {});
2173
- this._config.callbacks.onClose?.();
1804
+ disconnectedCallback() {
1805
+ // Cleanup observers
1806
+ this._resizeObserver?.disconnect();
1807
+ this._intersectionObserver?.disconnect();
1808
+ if (this._busyTimeout)
1809
+ clearTimeout(this._busyTimeout);
1810
+ if (this._typeTimeout)
1811
+ clearTimeout(this._typeTimeout);
1812
+ if (this._searchTimeout)
1813
+ clearTimeout(this._searchTimeout);
1814
+ // Cleanup arrow click listener
1815
+ if (this._boundArrowClick && this._arrowContainer) {
1816
+ this._arrowContainer.removeEventListener('click', this._boundArrowClick);
1817
+ }
2174
1818
  }
2175
- _updateDropdownVisibility() {
2176
- if (this._state.isOpen) {
2177
- this._dropdown.style.display = 'block';
2178
- this._input.setAttribute('aria-expanded', 'true');
1819
+ _createContainer() {
1820
+ const container = document.createElement('div');
1821
+ container.className = 'select-container';
1822
+ if (this._config.styles.classNames?.container) {
1823
+ container.className += ' ' + this._config.styles.classNames.container;
2179
1824
  }
2180
- else {
2181
- this._dropdown.style.display = 'none';
2182
- this._input.setAttribute('aria-expanded', 'false');
1825
+ if (this._config.styles.container) {
1826
+ Object.assign(container.style, this._config.styles.container);
2183
1827
  }
1828
+ return container;
2184
1829
  }
2185
- _updateArrowRotation() {
2186
- if (this._arrowContainer) {
2187
- const arrow = this._arrowContainer.querySelector('.dropdown-arrow');
2188
- if (arrow) {
2189
- if (this._state.isOpen) {
2190
- arrow.classList.add('open');
2191
- }
2192
- else {
2193
- arrow.classList.remove('open');
2194
- }
1830
+ _createInputContainer() {
1831
+ const container = document.createElement('div');
1832
+ container.className = 'input-container';
1833
+ return container;
1834
+ }
1835
+ _createInput() {
1836
+ const input = document.createElement('input');
1837
+ input.type = 'text';
1838
+ input.className = 'select-input';
1839
+ input.id = `${this._uniqueId}-input`;
1840
+ input.placeholder = this._config.placeholder || 'Select an option...';
1841
+ input.disabled = !this._config.enabled;
1842
+ input.readOnly = !this._config.searchable;
1843
+ // Update readonly when input is focused if searchable
1844
+ input.addEventListener('focus', () => {
1845
+ if (this._config.searchable) {
1846
+ input.readOnly = false;
2195
1847
  }
1848
+ });
1849
+ if (this._config.styles.classNames?.input) {
1850
+ input.className += ' ' + this._config.styles.classNames.input;
1851
+ }
1852
+ if (this._config.styles.input) {
1853
+ Object.assign(input.style, this._config.styles.input);
2196
1854
  }
1855
+ input.setAttribute('role', 'combobox');
1856
+ input.setAttribute('aria-expanded', 'false');
1857
+ input.setAttribute('aria-haspopup', 'listbox');
1858
+ input.setAttribute('aria-autocomplete', this._config.searchable ? 'list' : 'none');
1859
+ return input;
2197
1860
  }
2198
- _handleSearch(query) {
2199
- this._state.searchQuery = query;
2200
- // Clear previous search timeout
2201
- if (this._searchTimeout) {
2202
- clearTimeout(this._searchTimeout);
1861
+ _createDropdown() {
1862
+ const dropdown = document.createElement('div');
1863
+ dropdown.className = 'select-dropdown';
1864
+ dropdown.style.display = 'none';
1865
+ if (this._config.styles.classNames?.dropdown) {
1866
+ dropdown.className += ' ' + this._config.styles.classNames.dropdown;
2203
1867
  }
2204
- // Search immediately - no debouncing for better responsiveness
2205
- // Users expect instant feedback as they type
2206
- this._state.isSearching = false;
2207
- // Ensure dropdown is open when searching
2208
- if (!this._state.isOpen) {
2209
- this._handleOpen();
1868
+ if (this._config.styles.dropdown) {
1869
+ Object.assign(dropdown.style, this._config.styles.dropdown);
2210
1870
  }
2211
- else {
2212
- // Filter and render options immediately
2213
- this._renderOptions();
1871
+ dropdown.setAttribute('role', 'listbox');
1872
+ dropdown.setAttribute('aria-labelledby', `${this._uniqueId}-input`);
1873
+ if (this._config.selection.mode === 'multi') {
1874
+ dropdown.setAttribute('aria-multiselectable', 'true');
2214
1875
  }
2215
- // Get filtered items based on search query - searches ENTIRE phrase
2216
- const getLabel = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
2217
- // FIX: Do not trim query to allow searching for phrases with spaces
2218
- const searchQuery = query.toLowerCase();
2219
- const filteredItems = searchQuery
2220
- ? this._state.loadedItems.filter((item) => {
2221
- try {
2222
- const label = String(getLabel(item)).toLowerCase();
2223
- // Match the entire search phrase
2224
- return label.includes(searchQuery);
2225
- }
2226
- catch (e) {
2227
- return false;
2228
- }
2229
- })
2230
- : this._state.loadedItems;
2231
- const count = filteredItems.length;
2232
- // Announce search results for accessibility
2233
- if (searchQuery) {
2234
- this._announce(`${count} result${count !== 1 ? 's' : ''} found for "${query}"`);
1876
+ return dropdown;
1877
+ }
1878
+ _createOptionsContainer() {
1879
+ const container = document.createElement('div');
1880
+ container.className = 'options-container';
1881
+ return container;
1882
+ }
1883
+ _createLiveRegion() {
1884
+ const liveRegion = document.createElement('div');
1885
+ liveRegion.setAttribute('role', 'status');
1886
+ liveRegion.setAttribute('aria-live', 'polite');
1887
+ liveRegion.setAttribute('aria-atomic', 'true');
1888
+ liveRegion.style.cssText = 'position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0;';
1889
+ return liveRegion;
1890
+ }
1891
+ _createArrowContainer() {
1892
+ const container = document.createElement('div');
1893
+ container.className = 'dropdown-arrow-container';
1894
+ container.innerHTML = `
1895
+ <svg class="dropdown-arrow" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
1896
+ <path d="M4 6L8 10L12 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
1897
+ </svg>
1898
+ `;
1899
+ return container;
1900
+ }
1901
+ _assembleDOM() {
1902
+ this._inputContainer.appendChild(this._input);
1903
+ if (this._arrowContainer) {
1904
+ this._inputContainer.appendChild(this._arrowContainer);
1905
+ }
1906
+ this._container.appendChild(this._inputContainer);
1907
+ this._dropdown.appendChild(this._optionsContainer);
1908
+ this._container.appendChild(this._dropdown);
1909
+ this._shadow.appendChild(this._container);
1910
+ if (this._liveRegion) {
1911
+ this._shadow.appendChild(this._liveRegion);
1912
+ }
1913
+ // Set ARIA relationships
1914
+ const listboxId = `${this._uniqueId}-listbox`;
1915
+ this._dropdown.id = listboxId;
1916
+ this._input.setAttribute('aria-controls', listboxId);
1917
+ this._input.setAttribute('aria-owns', listboxId);
1918
+ }
1919
+ _initializeStyles() {
1920
+ const style = document.createElement('style');
1921
+ style.textContent = `
1922
+ :host {
1923
+ display: block;
1924
+ position: relative;
1925
+ width: 100%;
1926
+ }
1927
+
1928
+ .select-container {
1929
+ position: relative;
1930
+ width: 100%;
1931
+ }
1932
+
1933
+ .input-container {
1934
+ position: relative;
1935
+ width: 100%;
1936
+ display: flex;
1937
+ align-items: center;
1938
+ flex-wrap: wrap;
1939
+ gap: var(--select-input-gap, 6px);
1940
+ padding: var(--select-input-padding, 6px 52px 6px 8px);
1941
+ min-height: var(--select-input-min-height, 44px);
1942
+ max-height: var(--select-input-max-height, 160px);
1943
+ overflow-y: var(--select-input-overflow-y, auto);
1944
+ align-content: flex-start;
1945
+ background: var(--select-input-bg, white);
1946
+ border: var(--select-input-border, 1px solid #d1d5db);
1947
+ border-radius: var(--select-input-border-radius, 6px);
1948
+ box-sizing: border-box;
1949
+ transition: all 0.2s ease;
1950
+ }
1951
+
1952
+ .input-container:focus-within {
1953
+ border-color: var(--select-input-focus-border, #667eea);
1954
+ box-shadow: var(--select-input-focus-shadow, 0 0 0 3px rgba(102, 126, 234, 0.1));
1955
+ }
1956
+
1957
+ /* Gradient separator before arrow */
1958
+ .input-container::after {
1959
+ content: '';
1960
+ position: absolute;
1961
+ top: 50%;
1962
+ right: var(--select-separator-position, 40px);
1963
+ transform: translateY(-50%);
1964
+ width: var(--select-separator-width, 1px);
1965
+ height: var(--select-separator-height, 60%);
1966
+ background: var(--select-separator-bg, var(--select-separator-gradient, linear-gradient(
1967
+ to bottom,
1968
+ transparent 0%,
1969
+ rgba(0, 0, 0, 0.1) 20%,
1970
+ rgba(0, 0, 0, 0.1) 80%,
1971
+ transparent 100%
1972
+ )));
1973
+ pointer-events: none;
1974
+ z-index: 1;
1975
+ }
1976
+
1977
+ .dropdown-arrow-container {
1978
+ position: absolute;
1979
+ top: 0;
1980
+ right: 0;
1981
+ bottom: 0;
1982
+ width: var(--select-arrow-width, 40px);
1983
+ display: flex;
1984
+ align-items: center;
1985
+ justify-content: center;
1986
+ cursor: pointer;
1987
+ transition: background-color 0.2s ease;
1988
+ border-radius: var(--select-arrow-border-radius, 0 4px 4px 0);
1989
+ z-index: 2;
1990
+ }
1991
+
1992
+ .dropdown-arrow-container:hover {
1993
+ background-color: var(--select-arrow-hover-bg, rgba(102, 126, 234, 0.08));
1994
+ }
1995
+
1996
+ .dropdown-arrow {
1997
+ width: var(--select-arrow-size, 16px);
1998
+ height: var(--select-arrow-size, 16px);
1999
+ color: var(--select-arrow-color, #667eea);
2000
+ transition: transform 0.2s ease, color 0.2s ease;
2001
+ transform: translateY(0);
2002
+ }
2003
+
2004
+ .dropdown-arrow path {
2005
+ stroke-width: var(--select-arrow-stroke-width, 2);
2006
+ }
2007
+
2008
+ .dropdown-arrow-container:hover .dropdown-arrow {
2009
+ color: var(--select-arrow-hover-color, #667eea);
2010
+ }
2011
+
2012
+ .dropdown-arrow.open {
2013
+ transform: rotate(180deg);
2014
+ }
2015
+
2016
+ .select-input {
2017
+ flex: 1;
2018
+ min-width: var(--select-input-min-width, 120px);
2019
+ padding: var(--select-input-field-padding, 4px);
2020
+ border: none;
2021
+ font-size: var(--select-input-font-size, 14px);
2022
+ line-height: var(--select-input-line-height, 1.5);
2023
+ color: var(--select-input-color, #1f2937);
2024
+ background: transparent;
2025
+ box-sizing: border-box;
2026
+ outline: none;
2027
+ font-family: var(--select-font-family, inherit);
2028
+ }
2029
+
2030
+ .select-input::placeholder {
2031
+ color: var(--select-input-placeholder-color, #9ca3af);
2032
+ }
2033
+
2034
+ .selection-badge {
2035
+ display: inline-flex;
2036
+ align-items: center;
2037
+ gap: var(--select-badge-gap, 4px);
2038
+ padding: var(--select-badge-padding, 4px 8px);
2039
+ margin: var(--select-badge-margin, 2px);
2040
+ background: var(--select-badge-bg, #667eea);
2041
+ color: var(--select-badge-color, white);
2042
+ border-radius: var(--select-badge-border-radius, 4px);
2043
+ font-size: var(--select-badge-font-size, 13px);
2044
+ line-height: 1;
2045
+ max-width: var(--select-badge-max-width, 100%);
2046
+ white-space: nowrap;
2047
+ overflow: hidden;
2048
+ text-overflow: ellipsis;
2049
+ }
2050
+
2051
+ .badge-remove {
2052
+ display: inline-flex;
2053
+ align-items: center;
2054
+ justify-content: center;
2055
+ width: var(--select-badge-remove-size, 16px);
2056
+ height: var(--select-badge-remove-size, 16px);
2057
+ padding: 0;
2058
+ margin-left: 4px;
2059
+ background: var(--select-badge-remove-bg, rgba(255, 255, 255, 0.3));
2060
+ border: none;
2061
+ border-radius: 50%;
2062
+ color: var(--select-badge-remove-color, white);
2063
+ font-size: var(--select-badge-remove-font-size, 16px);
2064
+ line-height: 1;
2065
+ cursor: pointer;
2066
+ transition: background 0.2s;
2067
+ }
2068
+
2069
+ .badge-remove:hover {
2070
+ background: var(--select-badge-remove-hover-bg, rgba(255, 255, 255, 0.5));
2071
+ }
2072
+
2073
+ .badge-remove:focus-visible {
2074
+ outline: 2px solid var(--select-badge-remove-focus-outline, rgba(255, 255, 255, 0.8));
2075
+ outline-offset: 2px;
2076
+ }
2077
+
2078
+ .select-input:disabled {
2079
+ background-color: var(--select-disabled-bg, #f5f5f5);
2080
+ cursor: not-allowed;
2081
+ }
2082
+
2083
+ .select-dropdown {
2084
+ position: absolute;
2085
+ scroll-behavior: smooth;
2086
+ top: 100%;
2087
+ left: 0;
2088
+ right: 0;
2089
+ margin-top: var(--select-dropdown-margin-top, 4px);
2090
+ max-height: var(--select-dropdown-max-height, 300px);
2091
+ overflow: hidden;
2092
+ background: var(--select-dropdown-bg, white);
2093
+ border: var(--select-dropdown-border, 1px solid #ccc);
2094
+ border-radius: var(--select-dropdown-border-radius, 4px);
2095
+ box-shadow: var(--select-dropdown-shadow, 0 4px 6px rgba(0,0,0,0.1));
2096
+ z-index: var(--select-dropdown-z-index, 1000);
2097
+ }
2098
+
2099
+ .options-container {
2100
+ position: relative;
2101
+ max-height: var(--select-options-max-height, 300px);
2102
+ overflow: auto;
2103
+ transition: opacity 0.2s ease-in-out;
2104
+ background: var(--select-options-bg, white);
2105
+ }
2106
+
2107
+ .option {
2108
+ padding: var(--select-option-padding, 8px 12px);
2109
+ cursor: pointer;
2110
+ color: var(--select-option-color, #1f2937);
2111
+ background: var(--select-option-bg, white);
2112
+ transition: var(--select-option-transition, background-color 0.15s ease);
2113
+ user-select: none;
2114
+ font-size: var(--select-option-font-size, 14px);
2115
+ line-height: var(--select-option-line-height, 1.5);
2116
+ border: var(--select-option-border, none);
2117
+ border-bottom: var(--select-option-border-bottom, none);
2118
+ }
2119
+
2120
+ .option:hover {
2121
+ background-color: var(--select-option-hover-bg, #f3f4f6);
2122
+ color: var(--select-option-hover-color, #1f2937);
2123
+ }
2124
+
2125
+ .option.selected {
2126
+ background-color: var(--select-option-selected-bg, #e0e7ff);
2127
+ color: var(--select-option-selected-color, #4338ca);
2128
+ font-weight: var(--select-option-selected-weight, 500);
2129
+ }
2130
+
2131
+ .option.active {
2132
+ background-color: var(--select-option-active-bg, #f3f4f6);
2133
+ color: var(--select-option-active-color, #1f2937);
2134
+ outline: var(--select-option-active-outline, 2px solid rgba(99, 102, 241, 0.45));
2135
+ outline-offset: -2px;
2136
+ }
2137
+
2138
+ .option:active {
2139
+ background-color: var(--select-option-pressed-bg, #e5e7eb);
2140
+ }
2141
+
2142
+ .load-more-container {
2143
+ padding: var(--select-load-more-padding, 12px);
2144
+ text-align: center;
2145
+ border-top: var(--select-divider-border, 1px solid #e0e0e0);
2146
+ background: var(--select-load-more-bg, white);
2147
+ }
2148
+
2149
+ .load-more-button {
2150
+ padding: var(--select-button-padding, 8px 16px);
2151
+ border: var(--select-button-border, 1px solid #1976d2);
2152
+ background: var(--select-button-bg, white);
2153
+ color: var(--select-button-color, #1976d2);
2154
+ border-radius: var(--select-button-border-radius, 4px);
2155
+ cursor: pointer;
2156
+ font-size: var(--select-button-font-size, 14px);
2157
+ font-family: var(--select-font-family, inherit);
2158
+ transition: all 0.2s ease;
2159
+ }
2160
+
2161
+ .load-more-button:hover {
2162
+ background: var(--select-button-hover-bg, #1976d2);
2163
+ color: var(--select-button-hover-color, white);
2164
+ }
2165
+
2166
+ .load-more-button:disabled {
2167
+ opacity: var(--select-button-disabled-opacity, 0.5);
2168
+ cursor: not-allowed;
2169
+ }
2170
+
2171
+ .busy-bucket {
2172
+ padding: var(--select-busy-padding, 16px);
2173
+ text-align: center;
2174
+ color: var(--select-busy-color, #666);
2175
+ background: var(--select-busy-bg, white);
2176
+ font-size: var(--select-busy-font-size, 14px);
2177
+ }
2178
+
2179
+ .spinner {
2180
+ display: inline-block;
2181
+ width: var(--select-spinner-size, 20px);
2182
+ height: var(--select-spinner-size, 20px);
2183
+ border: var(--select-spinner-border, 2px solid #ccc);
2184
+ border-top-color: var(--select-spinner-active-color, #1976d2);
2185
+ border-radius: 50%;
2186
+ animation: spin 0.6s linear infinite;
2187
+ }
2188
+
2189
+ @keyframes spin {
2190
+ to { transform: rotate(360deg); }
2191
+ }
2192
+
2193
+ .empty-state {
2194
+ padding: var(--select-empty-padding, 24px);
2195
+ text-align: center;
2196
+ color: var(--select-empty-color, #6b7280);
2197
+ font-size: var(--select-empty-font-size, 14px);
2198
+ background: var(--select-empty-bg, white);
2199
+ display: flex;
2200
+ flex-direction: column;
2201
+ align-items: center;
2202
+ justify-content: center;
2203
+ gap: 6px;
2204
+ min-height: var(--select-empty-min-height, 72px);
2205
+ }
2206
+
2207
+ .searching-state {
2208
+ padding: var(--select-searching-padding, 24px);
2209
+ text-align: center;
2210
+ color: var(--select-searching-color, #667eea);
2211
+ font-size: var(--select-searching-font-size, 14px);
2212
+ font-style: italic;
2213
+ background: var(--select-searching-bg, white);
2214
+ animation: pulse 1.5s ease-in-out infinite;
2215
+ display: flex;
2216
+ flex-direction: column;
2217
+ align-items: center;
2218
+ justify-content: center;
2219
+ gap: 6px;
2220
+ min-height: var(--select-searching-min-height, 72px);
2221
+ }
2222
+
2223
+ @keyframes pulse {
2224
+ 0%, 100% { opacity: 1; }
2225
+ 50% { opacity: 0.5; }
2226
+ }
2227
+
2228
+ /* Error states */
2229
+ .select-input[aria-invalid="true"] {
2230
+ border-color: var(--select-error-border, #dc2626);
2231
+ }
2232
+
2233
+ .select-input[aria-invalid="true"]:focus {
2234
+ border-color: var(--select-error-border, #dc2626);
2235
+ box-shadow: 0 0 0 2px var(--select-error-shadow, rgba(220, 38, 38, 0.1));
2236
+ outline-color: var(--select-error-border, #dc2626);
2237
+ }
2238
+
2239
+ /* Accessibility: Reduced motion */
2240
+ @media (prefers-reduced-motion: reduce) {
2241
+ * {
2242
+ animation-duration: 0.01ms !important;
2243
+ animation-iteration-count: 1 !important;
2244
+ transition-duration: 0.01ms !important;
2245
+ }
2246
+ }
2247
+
2248
+ /* Dark mode - Opt-in via class or data attribute */
2249
+ :host(.dark-mode),
2250
+ :host([data-theme="dark"]) {
2251
+ .input-container {
2252
+ background: var(--select-dark-bg, #1f2937);
2253
+ border-color: var(--select-dark-border, #4b5563);
2254
+ }
2255
+
2256
+ .select-input {
2257
+ color: var(--select-dark-text, #f9fafb);
2258
+ }
2259
+
2260
+ .select-input::placeholder {
2261
+ color: var(--select-dark-placeholder, #6b7280);
2262
+ }
2263
+
2264
+ .select-dropdown {
2265
+ background: var(--select-dark-dropdown-bg, #1f2937);
2266
+ border-color: var(--select-dark-dropdown-border, #4b5563);
2267
+ }
2268
+
2269
+ .options-container {
2270
+ background: var(--select-dark-options-bg, #1f2937);
2271
+ }
2272
+
2273
+ .option {
2274
+ color: var(--select-dark-option-color, #f9fafb);
2275
+ background: var(--select-dark-option-bg, #1f2937);
2276
+ }
2277
+
2278
+ .option:hover {
2279
+ background-color: var(--select-dark-option-hover-bg, #374151);
2280
+ color: var(--select-dark-option-hover-color, #f9fafb);
2281
+ }
2282
+
2283
+ .option.selected {
2284
+ background-color: var(--select-dark-option-selected-bg, #3730a3);
2285
+ color: var(--select-dark-option-selected-text, #e0e7ff);
2286
+ }
2287
+
2288
+ .option.active {
2289
+ background-color: var(--select-dark-option-active-bg, #374151);
2290
+ color: var(--select-dark-option-active-color, #f9fafb);
2291
+ outline: var(--select-dark-option-active-outline, 2px solid rgba(129, 140, 248, 0.55));
2292
+ }
2293
+
2294
+ .selection-badge {
2295
+ background: var(--select-dark-badge-bg, #4f46e5);
2296
+ color: var(--select-dark-badge-color, #eef2ff);
2297
+ }
2298
+
2299
+ .badge-remove {
2300
+ background: var(--select-dark-badge-remove-bg, rgba(255, 255, 255, 0.15));
2301
+ color: var(--select-dark-badge-remove-color, #e5e7eb);
2302
+ }
2303
+
2304
+ .badge-remove:hover {
2305
+ background: var(--select-dark-badge-remove-hover-bg, rgba(255, 255, 255, 0.3));
2306
+ }
2307
+
2308
+ .busy-bucket,
2309
+ .empty-state {
2310
+ color: var(--select-dark-busy-color, #9ca3af);
2311
+ background: var(--select-dark-empty-bg, #111827);
2312
+ }
2313
+
2314
+ .searching-state {
2315
+ background: var(--select-dark-searching-bg, #111827);
2316
+ }
2317
+
2318
+ .input-container::after {
2319
+ background: linear-gradient(
2320
+ to bottom,
2321
+ transparent 0%,
2322
+ rgba(255, 255, 255, 0.1) 20%,
2323
+ rgba(255, 255, 255, 0.1) 80%,
2324
+ transparent 100%
2325
+ );
2326
+ }
2327
+ }
2328
+
2329
+ /* Accessibility: High contrast mode */
2330
+ @media (prefers-contrast: high) {
2331
+ .select-input:focus {
2332
+ outline-width: 3px;
2333
+ outline-color: Highlight;
2334
+ }
2335
+
2336
+ .select-input {
2337
+ border-width: 2px;
2338
+ }
2339
+ }
2340
+
2341
+ /* Touch targets (WCAG 2.5.5) */
2342
+ .load-more-button,
2343
+ select-option {
2344
+ min-height: 44px;
2345
+ }
2346
+ `;
2347
+ // Insert as first child to ensure styles are processed first
2348
+ if (this._shadow.firstChild) {
2349
+ this._shadow.insertBefore(style, this._shadow.firstChild);
2235
2350
  }
2236
- // Only notify if query or result count changed to prevent infinite loops
2237
- if (query !== this._state.lastNotifiedQuery || count !== this._state.lastNotifiedResultCount) {
2238
- this._state.lastNotifiedQuery = query;
2239
- this._state.lastNotifiedResultCount = count;
2240
- // Use setTimeout to avoid synchronous state updates during render
2241
- setTimeout(() => {
2242
- this._emit('search', { query, results: filteredItems, count });
2243
- this._config.callbacks.onSearch?.(query);
2244
- }, 0);
2351
+ else {
2352
+ this._shadow.appendChild(style);
2245
2353
  }
2246
2354
  }
2247
- _handleKeydown(e) {
2248
- switch (e.key) {
2249
- case 'ArrowDown':
2250
- e.preventDefault();
2251
- if (!this._state.isOpen) {
2252
- this._handleOpen();
2253
- }
2254
- else {
2255
- this._moveActive(1);
2256
- }
2257
- break;
2258
- case 'ArrowUp':
2259
- e.preventDefault();
2260
- if (!this._state.isOpen) {
2261
- this._handleOpen();
2262
- }
2263
- else {
2264
- this._moveActive(-1);
2265
- }
2266
- break;
2267
- case 'Home':
2268
- e.preventDefault();
2269
- if (this._state.isOpen) {
2270
- this._setActive(0);
2271
- }
2272
- break;
2273
- case 'End':
2274
- e.preventDefault();
2275
- if (this._state.isOpen) {
2276
- const options = Array.from(this._optionsContainer.children);
2277
- this._setActive(options.length - 1);
2278
- }
2279
- break;
2280
- case 'PageDown':
2281
- e.preventDefault();
2282
- if (this._state.isOpen) {
2283
- this._moveActive(10);
2284
- }
2285
- break;
2286
- case 'PageUp':
2287
- e.preventDefault();
2288
- if (this._state.isOpen) {
2289
- this._moveActive(-10);
2290
- }
2291
- break;
2292
- case 'Enter':
2355
+ _attachEventListeners() {
2356
+ // Arrow click handler
2357
+ if (this._arrowContainer) {
2358
+ this._boundArrowClick = (e) => {
2359
+ e.stopPropagation();
2293
2360
  e.preventDefault();
2294
- if (this._state.activeIndex >= 0) {
2295
- this._selectOption(this._state.activeIndex);
2361
+ const wasOpen = this._state.isOpen;
2362
+ this._state.isOpen = !this._state.isOpen;
2363
+ this._updateDropdownVisibility();
2364
+ this._updateArrowRotation();
2365
+ if (this._state.isOpen && this._config.callbacks.onOpen) {
2366
+ this._config.callbacks.onOpen();
2296
2367
  }
2297
- break;
2298
- case 'Escape':
2299
- e.preventDefault();
2300
- this._handleClose();
2301
- break;
2302
- case 'a':
2303
- case 'A':
2304
- if ((e.ctrlKey || e.metaKey) && this._config.selection.mode === 'multi') {
2305
- e.preventDefault();
2306
- this._selectAll();
2368
+ else if (!this._state.isOpen && this._config.callbacks.onClose) {
2369
+ this._config.callbacks.onClose();
2307
2370
  }
2308
- break;
2309
- default:
2310
- // Type-ahead search
2311
- if (e.key.length === 1 && !e.ctrlKey && !e.altKey && !e.metaKey) {
2312
- this._handleTypeAhead(e.key);
2371
+ // Scroll to selected when opening
2372
+ if (!wasOpen && this._state.isOpen && this._state.selectedIndices.size > 0) {
2373
+ setTimeout(() => this._scrollToSelected(), 50);
2313
2374
  }
2314
- break;
2375
+ };
2376
+ this._arrowContainer.addEventListener('click', this._boundArrowClick);
2315
2377
  }
2316
- }
2317
- _moveActive(delta) {
2318
- const options = Array.from(this._optionsContainer.children);
2319
- const next = Math.max(0, Math.min(options.length - 1, this._state.activeIndex + delta));
2320
- this._setActive(next);
2321
- }
2322
- _setActive(index) {
2323
- const options = Array.from(this._optionsContainer.children);
2324
- // Clear previous active state
2325
- if (this._state.activeIndex >= 0 && options[this._state.activeIndex]) {
2326
- const prevOption = options[this._state.activeIndex];
2327
- // Check if it's a custom SelectOption or a lightweight DOM element
2328
- if ('setActive' in prevOption && typeof prevOption.setActive === 'function') {
2329
- prevOption.setActive(false);
2378
+ // Input container click - prevent event from reaching document listener
2379
+ this._container.addEventListener('click', (e) => {
2380
+ e.stopPropagation();
2381
+ });
2382
+ // Input focus/blur
2383
+ this._input.addEventListener('focus', () => this._handleOpen());
2384
+ this._input.addEventListener('blur', (e) => {
2385
+ const related = e.relatedTarget;
2386
+ if (related && (this._shadow.contains(related) || this._container.contains(related))) {
2387
+ return;
2330
2388
  }
2331
- else {
2332
- // Lightweight option - remove active class
2333
- prevOption.classList.remove('smilodon-option--active');
2334
- prevOption.setAttribute('aria-selected', 'false');
2389
+ // Delay to allow option click/focus transitions
2390
+ setTimeout(() => {
2391
+ const active = document.activeElement;
2392
+ if (active && (this._shadow.contains(active) || this._container.contains(active))) {
2393
+ return;
2394
+ }
2395
+ this._handleClose();
2396
+ }, 0);
2397
+ });
2398
+ // Input search
2399
+ this._input.addEventListener('input', (e) => {
2400
+ if (!this._config.searchable)
2401
+ return;
2402
+ const query = e.target.value;
2403
+ this._handleSearch(query);
2404
+ });
2405
+ // Keyboard navigation
2406
+ this._input.addEventListener('keydown', (e) => this._handleKeydown(e));
2407
+ // Click outside to close
2408
+ document.addEventListener('pointerdown', (e) => {
2409
+ const path = (e.composedPath && e.composedPath()) || [];
2410
+ const clickedInside = path.includes(this) || path.includes(this._container) || this._shadow.contains(e.target);
2411
+ if (!clickedInside) {
2412
+ this._handleClose();
2335
2413
  }
2414
+ });
2415
+ }
2416
+ _initializeObservers() {
2417
+ // Disconnect existing observer if any
2418
+ if (this._intersectionObserver) {
2419
+ this._intersectionObserver.disconnect();
2420
+ this._intersectionObserver = undefined;
2336
2421
  }
2337
- this._state.activeIndex = index;
2338
- // Set new active state
2339
- if (options[index]) {
2340
- const option = options[index];
2341
- // Check if it's a custom SelectOption or a lightweight DOM element
2342
- if ('setActive' in option && typeof option.setActive === 'function') {
2343
- option.setActive(true);
2344
- }
2345
- else {
2346
- // Lightweight option - add active class
2347
- option.classList.add('smilodon-option--active');
2348
- option.setAttribute('aria-selected', 'true');
2349
- }
2350
- option.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
2351
- // Announce position for screen readers
2352
- const total = options.length;
2353
- this._announce(`Item ${index + 1} of ${total}`);
2354
- // Update aria-activedescendant
2355
- const optionId = `${this._uniqueId}-option-${index}`;
2356
- this._input.setAttribute('aria-activedescendant', optionId);
2422
+ // Intersection observer for infinite scroll
2423
+ if (this._config.infiniteScroll.enabled) {
2424
+ this._intersectionObserver = new IntersectionObserver((entries) => {
2425
+ entries.forEach((entry) => {
2426
+ if (entry.isIntersecting) {
2427
+ if (!this._state.isBusy) {
2428
+ this._loadMoreItems();
2429
+ }
2430
+ }
2431
+ });
2432
+ }, { threshold: 0.1 });
2357
2433
  }
2358
2434
  }
2359
- _handleTypeAhead(char) {
2360
- if (this._typeTimeout)
2361
- clearTimeout(this._typeTimeout);
2362
- this._typeBuffer += char.toLowerCase();
2363
- this._typeTimeout = window.setTimeout(() => {
2364
- this._typeBuffer = '';
2365
- }, 500);
2366
- // Find first matching option
2367
- const getValue = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
2368
- const matchIndex = this._state.loadedItems.findIndex((item) => getValue(item).toLowerCase().startsWith(this._typeBuffer));
2369
- if (matchIndex >= 0) {
2370
- this._setActive(matchIndex);
2435
+ async _loadInitialSelectedItems() {
2436
+ if (!this._config.serverSide.fetchSelectedItems || !this._config.serverSide.initialSelectedValues) {
2437
+ return;
2438
+ }
2439
+ this._setBusy(true);
2440
+ try {
2441
+ const items = await this._config.serverSide.fetchSelectedItems(this._config.serverSide.initialSelectedValues);
2442
+ // Add to state
2443
+ items.forEach((item, index) => {
2444
+ this._state.selectedItems.set(index, item);
2445
+ this._state.selectedIndices.add(index);
2446
+ });
2447
+ this._updateInputDisplay();
2448
+ }
2449
+ catch (error) {
2450
+ this._handleError(error);
2451
+ }
2452
+ finally {
2453
+ this._setBusy(false);
2371
2454
  }
2372
2455
  }
2373
- _selectAll() {
2374
- if (this._config.selection.mode !== 'multi')
2456
+ _handleOpen() {
2457
+ if (!this._config.enabled || this._state.isOpen)
2375
2458
  return;
2376
- const options = Array.from(this._optionsContainer.children);
2377
- const maxSelections = this._config.selection.maxSelections || 0;
2378
- options.forEach((option, index) => {
2379
- if (maxSelections > 0 && this._state.selectedIndices.size >= maxSelections) {
2380
- return;
2381
- }
2382
- if (!this._state.selectedIndices.has(index)) {
2383
- // Check if it's a custom SelectOption or a lightweight DOM element
2384
- if ('getConfig' in option && typeof option.getConfig === 'function') {
2385
- const config = option.getConfig();
2386
- this._state.selectedIndices.add(index);
2387
- this._state.selectedItems.set(index, config.item);
2388
- option.setSelected(true);
2389
- }
2390
- else {
2391
- // Lightweight option - get item from data attribute or state
2392
- const item = this._state.loadedItems[index];
2393
- if (item) {
2394
- this._state.selectedIndices.add(index);
2395
- this._state.selectedItems.set(index, item);
2396
- option.classList.add('smilodon-option--selected');
2397
- option.setAttribute('aria-selected', 'true');
2398
- }
2399
- }
2400
- }
2401
- });
2402
- this._updateInputDisplay();
2403
- this._emitChange();
2404
- this._announce(`Selected all ${options.length} items`);
2405
- }
2406
- _announce(message) {
2407
- if (this._liveRegion) {
2408
- this._liveRegion.textContent = message;
2409
- setTimeout(() => {
2410
- if (this._liveRegion)
2411
- this._liveRegion.textContent = '';
2412
- }, 1000);
2459
+ this._markOpenStart();
2460
+ this._state.isOpen = true;
2461
+ this._dropdown.style.display = 'block';
2462
+ this._input.setAttribute('aria-expanded', 'true');
2463
+ this._updateArrowRotation();
2464
+ // Clear search query when opening to show all options
2465
+ // This ensures we can scroll to selected item
2466
+ if (this._config.searchable) {
2467
+ this._state.searchQuery = '';
2468
+ // Don't clear input value if it represents selection
2469
+ // But if we want to search, we might want to clear it?
2470
+ // Standard behavior: input keeps value (label), but dropdown shows all options
2471
+ // until user types.
2472
+ // However, our filtering logic uses _state.searchQuery.
2473
+ // So clearing it here resets the filter.
2474
+ }
2475
+ // Render options when opening
2476
+ this._renderOptions();
2477
+ this._setInitialActiveOption();
2478
+ this._emit('open', {});
2479
+ this._config.callbacks.onOpen?.();
2480
+ this._announce('Options expanded');
2481
+ // Scroll to selected if configured
2482
+ if (this._config.scrollToSelected.enabled) {
2483
+ // Use requestAnimationFrame for better timing after render
2484
+ requestAnimationFrame(() => {
2485
+ // Double RAF to ensure layout is complete
2486
+ requestAnimationFrame(() => {
2487
+ this._scrollToSelected();
2488
+ });
2489
+ });
2413
2490
  }
2414
2491
  }
2415
- _selectOption(index) {
2416
- // FIX: Do not rely on this._optionsContainer.children[index] because filtering changes the children
2417
- // Instead, use the index to update state directly
2418
- const item = this._state.loadedItems[index];
2419
- if (!item)
2492
+ _handleClose() {
2493
+ if (!this._state.isOpen)
2420
2494
  return;
2421
- const isCurrentlySelected = this._state.selectedIndices.has(index);
2422
- if (this._config.selection.mode === 'single') {
2423
- // Single select: clear previous and select new
2424
- const wasSelected = this._state.selectedIndices.has(index);
2425
- this._state.selectedIndices.clear();
2426
- this._state.selectedItems.clear();
2427
- if (!wasSelected) {
2428
- // Select this option
2429
- this._state.selectedIndices.add(index);
2430
- this._state.selectedItems.set(index, item);
2431
- }
2432
- // Re-render to update all option styles
2433
- this._renderOptions();
2434
- if (this._config.selection.closeOnSelect) {
2435
- this._handleClose();
2436
- }
2495
+ this._state.isOpen = false;
2496
+ this._dropdown.style.display = 'none';
2497
+ this._input.setAttribute('aria-expanded', 'false');
2498
+ this._input.removeAttribute('aria-activedescendant');
2499
+ this._updateArrowRotation();
2500
+ this._emit('close', {});
2501
+ this._config.callbacks.onClose?.();
2502
+ this._announce('Options collapsed');
2503
+ }
2504
+ _updateDropdownVisibility() {
2505
+ if (this._state.isOpen) {
2506
+ this._dropdown.style.display = 'block';
2507
+ this._input.setAttribute('aria-expanded', 'true');
2437
2508
  }
2438
2509
  else {
2439
- // Multi select with toggle
2440
- const maxSelections = this._config.selection.maxSelections || 0;
2441
- if (isCurrentlySelected) {
2442
- // Deselect (toggle off)
2443
- this._state.selectedIndices.delete(index);
2444
- this._state.selectedItems.delete(index);
2445
- }
2446
- else {
2447
- // Select (toggle on)
2448
- if (maxSelections > 0 && this._state.selectedIndices.size >= maxSelections) {
2449
- this._announce(`Maximum ${maxSelections} selections allowed`);
2450
- return; // Max selections reached
2510
+ this._dropdown.style.display = 'none';
2511
+ this._input.setAttribute('aria-expanded', 'false');
2512
+ }
2513
+ }
2514
+ _updateArrowRotation() {
2515
+ if (this._arrowContainer) {
2516
+ const arrow = this._arrowContainer.querySelector('.dropdown-arrow');
2517
+ if (arrow) {
2518
+ if (this._state.isOpen) {
2519
+ arrow.classList.add('open');
2520
+ }
2521
+ else {
2522
+ arrow.classList.remove('open');
2451
2523
  }
2452
- this._state.selectedIndices.add(index);
2453
- this._state.selectedItems.set(index, item);
2454
2524
  }
2455
- // Re-render to update styles (safer than trying to find the element in filtered list)
2456
- this._renderOptions();
2457
2525
  }
2458
- this._updateInputDisplay();
2459
- this._emitChange();
2460
- // Call user callback
2461
- const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
2462
- const getLabel = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
2463
- this._config.callbacks.onSelect?.({
2464
- item: item,
2465
- index,
2466
- value: getValue(item),
2467
- label: getLabel(item),
2468
- selected: this._state.selectedIndices.has(index),
2469
- });
2470
2526
  }
2471
- _handleOptionRemove(index) {
2472
- const option = this._optionsContainer.children[index];
2473
- if (!option)
2527
+ _isPerfEnabled() {
2528
+ return typeof globalThis !== 'undefined'
2529
+ && globalThis.__SMILODON_DEV__ === true
2530
+ && typeof performance !== 'undefined'
2531
+ && typeof performance.mark === 'function'
2532
+ && typeof performance.measure === 'function';
2533
+ }
2534
+ _perfMark(name) {
2535
+ if (!this._isPerfEnabled())
2474
2536
  return;
2475
- this._state.selectedIndices.delete(index);
2476
- this._state.selectedItems.delete(index);
2477
- option.setSelected(false);
2478
- this._updateInputDisplay();
2479
- this._emitChange();
2480
- const config = option.getConfig();
2481
- this._emit('remove', { item: config.item, index });
2537
+ performance.mark(name);
2482
2538
  }
2483
- _updateInputDisplay() {
2484
- const selectedItems = Array.from(this._state.selectedItems.values());
2485
- const getLabel = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
2486
- if (selectedItems.length === 0) {
2487
- this._input.value = '';
2488
- this._input.placeholder = this._config.placeholder || 'Select an option...';
2489
- // Clear any badges
2490
- const existingBadges = this._inputContainer.querySelectorAll('.selection-badge');
2491
- existingBadges.forEach(badge => badge.remove());
2539
+ _perfMeasure(name, start, end) {
2540
+ if (!this._isPerfEnabled())
2541
+ return;
2542
+ performance.measure(name, start, end);
2543
+ }
2544
+ _markOpenStart() {
2545
+ if (!this._isPerfEnabled())
2546
+ return;
2547
+ this._pendingFirstRenderMark = true;
2548
+ this._perfMark('smilodon-dropdown-open-start');
2549
+ }
2550
+ _finalizePerfMarks() {
2551
+ if (!this._isPerfEnabled()) {
2552
+ this._pendingFirstRenderMark = false;
2553
+ this._pendingSearchRenderMark = false;
2554
+ return;
2492
2555
  }
2493
- else if (this._config.selection.mode === 'single') {
2494
- this._input.value = getLabel(selectedItems[0]);
2556
+ if (this._pendingFirstRenderMark) {
2557
+ this._pendingFirstRenderMark = false;
2558
+ this._perfMark('smilodon-first-render-complete');
2559
+ this._perfMeasure('smilodon-dropdown-to-first-render', 'smilodon-dropdown-open-start', 'smilodon-first-render-complete');
2495
2560
  }
2496
- else {
2497
- // Multi-select: show badges instead of text in input
2498
- this._input.value = '';
2499
- this._input.placeholder = '';
2500
- // Clear existing badges
2501
- const existingBadges = this._inputContainer.querySelectorAll('.selection-badge');
2502
- existingBadges.forEach(badge => badge.remove());
2503
- // Create badges for each selected item
2504
- const selectedEntries = Array.from(this._state.selectedItems.entries());
2505
- selectedEntries.forEach(([index, item]) => {
2506
- const badge = document.createElement('span');
2507
- badge.className = 'selection-badge';
2508
- badge.textContent = getLabel(item);
2509
- // Add remove button to badge
2510
- const removeBtn = document.createElement('button');
2511
- removeBtn.className = 'badge-remove';
2512
- removeBtn.innerHTML = '×';
2513
- removeBtn.setAttribute('aria-label', `Remove ${getLabel(item)}`);
2514
- removeBtn.addEventListener('click', (e) => {
2515
- e.stopPropagation();
2516
- this._state.selectedIndices.delete(index);
2517
- this._state.selectedItems.delete(index);
2518
- this._updateInputDisplay();
2519
- this._renderOptions();
2520
- this._emitChange();
2521
- });
2522
- badge.appendChild(removeBtn);
2523
- this._inputContainer.insertBefore(badge, this._input);
2524
- });
2561
+ if (this._pendingSearchRenderMark) {
2562
+ this._pendingSearchRenderMark = false;
2563
+ this._perfMark('smilodon-search-render-complete');
2564
+ this._perfMeasure('smilodon-search-to-render', 'smilodon-search-input-last', 'smilodon-search-render-complete');
2525
2565
  }
2526
2566
  }
2527
- _renderOptionsWithAnimation() {
2528
- // Add fade-out animation
2529
- this._optionsContainer.style.opacity = '0';
2530
- this._optionsContainer.style.transition = 'opacity 0.15s ease-out';
2531
- setTimeout(() => {
2567
+ _handleSearch(query) {
2568
+ this._state.searchQuery = query;
2569
+ if (query.length > 0) {
2570
+ this._perfMark('smilodon-search-input-last');
2571
+ this._pendingSearchRenderMark = true;
2572
+ }
2573
+ else {
2574
+ this._pendingSearchRenderMark = false;
2575
+ }
2576
+ // Clear previous search timeout
2577
+ if (this._searchTimeout) {
2578
+ clearTimeout(this._searchTimeout);
2579
+ }
2580
+ // Search immediately - no debouncing for better responsiveness
2581
+ // Users expect instant feedback as they type
2582
+ this._state.isSearching = false;
2583
+ // Ensure dropdown is open when searching
2584
+ if (!this._state.isOpen) {
2585
+ this._handleOpen();
2586
+ }
2587
+ else {
2588
+ // Filter and render options immediately
2532
2589
  this._renderOptions();
2533
- // Fade back in
2534
- this._optionsContainer.style.opacity = '1';
2535
- this._optionsContainer.style.transition = 'opacity 0.2s ease-in';
2536
- }, 150);
2590
+ }
2591
+ // Get filtered items based on search query - searches ENTIRE phrase
2592
+ const getLabel = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
2593
+ // FIX: Do not trim query to allow searching for phrases with spaces
2594
+ const searchQuery = query.toLowerCase();
2595
+ const filteredItems = searchQuery
2596
+ ? this._state.loadedItems.filter((item) => {
2597
+ try {
2598
+ const label = String(getLabel(item)).toLowerCase();
2599
+ // Match the entire search phrase
2600
+ return label.includes(searchQuery);
2601
+ }
2602
+ catch (e) {
2603
+ return false;
2604
+ }
2605
+ })
2606
+ : this._state.loadedItems;
2607
+ const count = filteredItems.length;
2608
+ // Announce search results for accessibility
2609
+ if (searchQuery) {
2610
+ this._announce(`${count} result${count !== 1 ? 's' : ''} found for "${query}"`);
2611
+ }
2612
+ // Only notify if query or result count changed to prevent infinite loops
2613
+ if (query !== this._state.lastNotifiedQuery || count !== this._state.lastNotifiedResultCount) {
2614
+ this._state.lastNotifiedQuery = query;
2615
+ this._state.lastNotifiedResultCount = count;
2616
+ // Use setTimeout to avoid synchronous state updates during render
2617
+ setTimeout(() => {
2618
+ this._emit('search', { query, results: filteredItems, count });
2619
+ this._config.callbacks.onSearch?.(query);
2620
+ }, 0);
2621
+ }
2537
2622
  }
2538
- _scrollToSelected() {
2539
- if (this._state.selectedIndices.size === 0)
2540
- return;
2541
- const target = this._config.scrollToSelected.multiSelectTarget;
2542
- const indices = Array.from(this._state.selectedIndices).sort((a, b) => a - b);
2543
- // For multi-select, find the closest selected item to the current scroll position
2544
- let targetIndex;
2545
- if (this._config.selection.mode === 'multi' && indices.length > 1) {
2546
- // Calculate which selected item is closest to the center of the viewport
2547
- const dropdownRect = this._dropdown.getBoundingClientRect();
2548
- const viewportCenter = this._dropdown.scrollTop + (dropdownRect.height / 2);
2549
- // Find the selected item closest to viewport center
2550
- let closestIndex = indices[0];
2551
- let closestDistance = Infinity;
2552
- for (const index of indices) {
2553
- const optionId = `${this._uniqueId}-option-${index}`;
2554
- const option = this._optionsContainer.querySelector(`[id="${optionId}"]`);
2555
- if (option) {
2556
- const optionTop = option.offsetTop;
2557
- const distance = Math.abs(optionTop - viewportCenter);
2558
- if (distance < closestDistance) {
2559
- closestDistance = distance;
2560
- closestIndex = index;
2623
+ _handleKeydown(e) {
2624
+ switch (e.key) {
2625
+ case 'ArrowDown':
2626
+ e.preventDefault();
2627
+ if (!this._state.isOpen) {
2628
+ this._handleOpen();
2629
+ }
2630
+ else {
2631
+ this._moveActive(1, { shiftKey: e.shiftKey, toggleKey: e.ctrlKey || e.metaKey });
2632
+ }
2633
+ break;
2634
+ case 'ArrowUp':
2635
+ e.preventDefault();
2636
+ if (!this._state.isOpen) {
2637
+ this._handleOpen();
2638
+ }
2639
+ else {
2640
+ this._moveActive(-1, { shiftKey: e.shiftKey, toggleKey: e.ctrlKey || e.metaKey });
2641
+ }
2642
+ break;
2643
+ case 'Home':
2644
+ e.preventDefault();
2645
+ if (this._state.isOpen) {
2646
+ this._setActive(0);
2647
+ if (this._config.selection.mode === 'multi' && e.shiftKey) {
2648
+ this._selectRange(this._rangeAnchorIndex ?? 0, 0, { clear: !(e.ctrlKey || e.metaKey) });
2649
+ }
2650
+ }
2651
+ break;
2652
+ case 'End':
2653
+ e.preventDefault();
2654
+ if (this._state.isOpen) {
2655
+ const options = Array.from(this._optionsContainer.children);
2656
+ const lastIndex = Math.max(0, options.length - 1);
2657
+ this._setActive(lastIndex);
2658
+ if (this._config.selection.mode === 'multi' && e.shiftKey) {
2659
+ this._selectRange(this._rangeAnchorIndex ?? lastIndex, lastIndex, { clear: !(e.ctrlKey || e.metaKey) });
2561
2660
  }
2562
2661
  }
2563
- }
2564
- targetIndex = closestIndex;
2565
- }
2566
- else {
2567
- // For single select or only one selected item, use the configured target
2568
- targetIndex = target === 'first' ? indices[0] : indices[indices.length - 1];
2569
- }
2570
- // Find and scroll to the target option
2571
- const optionId = `${this._uniqueId}-option-${targetIndex}`;
2572
- const option = this._optionsContainer.querySelector(`[id="${optionId}"]`);
2573
- if (option) {
2574
- // Use smooth scrolling with center alignment for better UX
2575
- option.scrollIntoView({
2576
- block: this._config.scrollToSelected.block || 'center',
2577
- behavior: 'smooth',
2578
- });
2579
- // Also set it as active for keyboard navigation
2580
- this._setActive(targetIndex);
2662
+ break;
2663
+ case 'PageDown':
2664
+ e.preventDefault();
2665
+ if (this._state.isOpen) {
2666
+ this._moveActive(10, { shiftKey: e.shiftKey, toggleKey: e.ctrlKey || e.metaKey });
2667
+ }
2668
+ break;
2669
+ case 'PageUp':
2670
+ e.preventDefault();
2671
+ if (this._state.isOpen) {
2672
+ this._moveActive(-10, { shiftKey: e.shiftKey, toggleKey: e.ctrlKey || e.metaKey });
2673
+ }
2674
+ break;
2675
+ case 'Enter':
2676
+ e.preventDefault();
2677
+ if (this._state.activeIndex >= 0) {
2678
+ this._selectOption(this._state.activeIndex, { shiftKey: e.shiftKey, toggleKey: e.ctrlKey || e.metaKey });
2679
+ }
2680
+ break;
2681
+ case 'Escape':
2682
+ e.preventDefault();
2683
+ this._handleClose();
2684
+ break;
2685
+ case 'Tab':
2686
+ if (this._state.isOpen) {
2687
+ this._handleClose();
2688
+ }
2689
+ break;
2690
+ case 'a':
2691
+ case 'A':
2692
+ if ((e.ctrlKey || e.metaKey) && this._config.selection.mode === 'multi') {
2693
+ e.preventDefault();
2694
+ this._selectAll();
2695
+ }
2696
+ break;
2697
+ default:
2698
+ // Type-ahead search
2699
+ if (e.key.length === 1 && !e.ctrlKey && !e.altKey && !e.metaKey) {
2700
+ this._handleTypeAhead(e.key);
2701
+ }
2702
+ break;
2581
2703
  }
2582
2704
  }
2583
- async _loadMoreItems() {
2584
- if (this._state.isBusy)
2585
- return;
2586
- this._setBusy(true);
2587
- // Save scroll position before loading
2588
- if (this._dropdown) {
2589
- this._state.lastScrollPosition = this._dropdown.scrollTop;
2590
- this._state.preserveScrollPosition = true;
2591
- // Update dropdown to show loading indicator but keep the
2592
- // same scrollTop so the visible items don't move.
2593
- this._renderOptions();
2594
- this._dropdown.scrollTop = this._state.lastScrollPosition;
2595
- }
2596
- try {
2597
- // Emit event for parent to handle
2598
- this._state.currentPage++;
2599
- this._emit('loadMore', { page: this._state.currentPage, items: [] });
2600
- this._config.callbacks.onLoadMore?.(this._state.currentPage);
2601
- // NOTE: We do NOT set isBusy = false here.
2602
- // The parent component MUST call setItems() or similar to clear the busy state.
2603
- // This prevents the sentinel from reappearing before new items are loaded.
2604
- }
2605
- catch (error) {
2606
- this._handleError(error);
2607
- this._setBusy(false); // Only clear on error
2705
+ _moveActive(delta, opts) {
2706
+ const options = Array.from(this._optionsContainer.children);
2707
+ const next = Math.max(0, Math.min(options.length - 1, this._state.activeIndex + delta));
2708
+ this._setActive(next);
2709
+ if (this._config.selection.mode === 'multi' && opts?.shiftKey) {
2710
+ const anchor = this._rangeAnchorIndex ?? this._state.activeIndex;
2711
+ const anchorIndex = anchor >= 0 ? anchor : next;
2712
+ if (this._rangeAnchorIndex === null) {
2713
+ this._rangeAnchorIndex = anchorIndex;
2714
+ }
2715
+ this._selectRange(anchorIndex, next, { clear: !opts?.toggleKey });
2608
2716
  }
2609
2717
  }
2610
- _setBusy(busy) {
2611
- this._state.isBusy = busy;
2612
- // Trigger re-render to show/hide busy indicator
2613
- // We use _renderOptions to handle the UI update
2614
- this._renderOptions();
2615
- }
2616
- _showBusyBucket() {
2617
- // Deprecated: Logic moved to _renderOptions
2618
- }
2619
- _hideBusyBucket() {
2620
- // Deprecated: Logic moved to _renderOptions
2621
- }
2622
- _handleError(error) {
2623
- this._emit('error', { message: error.message, cause: error });
2624
- this._config.callbacks.onError?.(error);
2625
- }
2626
- _emit(name, detail) {
2627
- this.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true }));
2628
- }
2629
- _emitChange() {
2630
- const selectedItems = Array.from(this._state.selectedItems.values());
2631
- const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
2632
- const selectedValues = selectedItems.map(getValue);
2633
- const selectedIndices = Array.from(this._state.selectedIndices);
2634
- this._emit('change', { selectedItems, selectedValues, selectedIndices });
2635
- this._config.callbacks.onChange?.(selectedItems, selectedValues);
2636
- }
2637
- // Public API
2638
- /**
2639
- * Set items to display in the select
2640
- */
2641
- setItems(items) {
2642
- const previousLength = this._state.loadedItems.length;
2643
- this._state.loadedItems = items;
2644
- // If grouped items exist, flatten them to items
2645
- if (this._state.groupedItems.length > 0) {
2646
- this._state.loadedItems = this._state.groupedItems.flatMap(group => group.options);
2647
- }
2648
- const newLength = this._state.loadedItems.length;
2649
- // When infinite scroll is active (preserveScrollPosition = true),
2650
- // we need to maintain scroll position during the update
2651
- if (this._state.preserveScrollPosition && this._dropdown) {
2652
- const targetScrollTop = this._state.lastScrollPosition;
2653
- // Only clear loading if we actually got more items
2654
- if (newLength > previousLength) {
2655
- this._state.isBusy = false;
2718
+ _setActive(index) {
2719
+ const options = Array.from(this._optionsContainer.children);
2720
+ // Clear previous active state
2721
+ if (this._state.activeIndex >= 0 && options[this._state.activeIndex]) {
2722
+ const prevOption = options[this._state.activeIndex];
2723
+ // Check if it's a custom SelectOption or a lightweight DOM element
2724
+ if ('setActive' in prevOption && typeof prevOption.setActive === 'function') {
2725
+ prevOption.setActive(false);
2656
2726
  }
2657
- this._renderOptions();
2658
- // Restore the exact scrollTop we had before loading
2659
- // so the previously visible items stay in place and
2660
- // new ones simply appear below.
2661
- this._dropdown.scrollTop = targetScrollTop;
2662
- // Ensure it sticks after layout
2663
- requestAnimationFrame(() => {
2664
- if (this._dropdown) {
2665
- this._dropdown.scrollTop = targetScrollTop;
2666
- }
2667
- });
2668
- // Only clear preserveScrollPosition if we got new items
2669
- if (newLength > previousLength) {
2670
- this._state.preserveScrollPosition = false;
2727
+ else {
2728
+ // Lightweight option - remove active class
2729
+ prevOption.classList.remove('smilodon-option--active');
2730
+ prevOption.setAttribute('aria-selected', 'false');
2671
2731
  }
2672
2732
  }
2673
- else {
2674
- // Normal update - just render normally
2675
- this._state.isBusy = false;
2676
- this._renderOptions();
2733
+ this._state.activeIndex = index;
2734
+ // Set new active state
2735
+ if (options[index]) {
2736
+ const option = options[index];
2737
+ // Check if it's a custom SelectOption or a lightweight DOM element
2738
+ if ('setActive' in option && typeof option.setActive === 'function') {
2739
+ option.setActive(true);
2740
+ }
2741
+ else {
2742
+ // Lightweight option - add active class
2743
+ option.classList.add('smilodon-option--active');
2744
+ option.setAttribute('aria-selected', 'true');
2745
+ }
2746
+ option.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
2747
+ // Announce position for screen readers
2748
+ const total = options.length;
2749
+ this._announce(`Item ${index + 1} of ${total}`);
2750
+ // Update aria-activedescendant using the actual option id when available
2751
+ const optionId = option.id || `${this._uniqueId}-option-${index}`;
2752
+ this._input.setAttribute('aria-activedescendant', optionId);
2677
2753
  }
2678
2754
  }
2679
- /**
2680
- * Set grouped items
2681
- */
2682
- setGroupedItems(groupedItems) {
2683
- this._state.groupedItems = groupedItems;
2684
- this._state.loadedItems = groupedItems.flatMap(group => group.options);
2685
- this._renderOptions();
2686
- }
2687
- /**
2688
- * Get currently selected items
2689
- */
2690
- getSelectedItems() {
2691
- return Array.from(this._state.selectedItems.values());
2692
- }
2693
- /**
2694
- * Get all loaded items
2695
- */
2696
- get loadedItems() {
2697
- return this._state.loadedItems;
2755
+ _getOptionElementByIndex(index) {
2756
+ return this._optionsContainer.querySelector(`[data-index="${index}"]`);
2698
2757
  }
2699
- /**
2700
- * Get currently selected values
2701
- */
2702
- getSelectedValues() {
2703
- const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
2704
- return this.getSelectedItems().map(getValue);
2758
+ _buildRendererHelpers() {
2759
+ return {
2760
+ onSelect: (_item, index) => this._selectOption(index),
2761
+ getIndex: (node) => {
2762
+ const el = node?.closest?.('[data-selectable]');
2763
+ if (!el)
2764
+ return null;
2765
+ const idx = Number(el.dataset.index);
2766
+ return Number.isFinite(idx) ? idx : null;
2767
+ },
2768
+ keyboardFocus: (index) => {
2769
+ this._setActive(index);
2770
+ const el = this._getOptionElementByIndex(index);
2771
+ el?.focus?.();
2772
+ },
2773
+ };
2705
2774
  }
2706
- /**
2707
- * Set selected items by value
2708
- */
2709
- async setSelectedValues(values) {
2710
- if (this._config.serverSide.enabled && this._config.serverSide.fetchSelectedItems) {
2711
- await this._loadSelectedItemsByValues(values);
2775
+ _handleTypeAhead(char) {
2776
+ if (this._typeTimeout)
2777
+ clearTimeout(this._typeTimeout);
2778
+ this._typeBuffer += char.toLowerCase();
2779
+ this._typeTimeout = window.setTimeout(() => {
2780
+ this._typeBuffer = '';
2781
+ }, 500);
2782
+ // Find first matching option
2783
+ const getValue = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
2784
+ const matchIndex = this._state.loadedItems.findIndex((item) => getValue(item).toLowerCase().startsWith(this._typeBuffer));
2785
+ if (matchIndex >= 0) {
2786
+ this._setActive(matchIndex);
2712
2787
  }
2713
- else {
2714
- // Select from loaded items
2715
- const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
2716
- this._state.selectedIndices.clear();
2717
- this._state.selectedItems.clear();
2718
- this._state.loadedItems.forEach((item, index) => {
2719
- if (values.includes(getValue(item))) {
2788
+ }
2789
+ _selectAll() {
2790
+ if (this._config.selection.mode !== 'multi')
2791
+ return;
2792
+ const options = Array.from(this._optionsContainer.children);
2793
+ const maxSelections = this._config.selection.maxSelections || 0;
2794
+ options.forEach((option, index) => {
2795
+ if (maxSelections > 0 && this._state.selectedIndices.size >= maxSelections) {
2796
+ return;
2797
+ }
2798
+ if (!this._state.selectedIndices.has(index)) {
2799
+ // Check if it's a custom SelectOption or a lightweight DOM element
2800
+ if ('getConfig' in option && typeof option.getConfig === 'function') {
2801
+ const config = option.getConfig();
2720
2802
  this._state.selectedIndices.add(index);
2721
- this._state.selectedItems.set(index, item);
2803
+ this._state.selectedItems.set(index, config.item);
2804
+ option.setSelected(true);
2722
2805
  }
2723
- });
2724
- this._renderOptions();
2725
- this._updateInputDisplay();
2726
- this._emitChange();
2727
- }
2806
+ else {
2807
+ // Lightweight option - get item from data attribute or state
2808
+ const item = this._state.loadedItems[index];
2809
+ if (item) {
2810
+ this._state.selectedIndices.add(index);
2811
+ this._state.selectedItems.set(index, item);
2812
+ option.classList.add('smilodon-option--selected');
2813
+ option.setAttribute('aria-selected', 'true');
2814
+ }
2815
+ }
2816
+ }
2817
+ });
2818
+ this._updateInputDisplay();
2819
+ this._emitChange();
2820
+ this._announce(`Selected all ${options.length} items`);
2728
2821
  }
2729
- /**
2730
- * Load and select items by their values (for infinite scroll scenario)
2731
- */
2732
- async _loadSelectedItemsByValues(values) {
2733
- if (!this._config.serverSide.fetchSelectedItems)
2822
+ _selectRange(start, end, opts) {
2823
+ if (this._config.selection.mode !== 'multi')
2734
2824
  return;
2735
- this._setBusy(true);
2736
- try {
2737
- const items = await this._config.serverSide.fetchSelectedItems(values);
2825
+ const maxSelections = this._config.selection.maxSelections || 0;
2826
+ const [min, max] = start < end ? [start, end] : [end, start];
2827
+ if (opts?.clear) {
2738
2828
  this._state.selectedIndices.clear();
2739
2829
  this._state.selectedItems.clear();
2740
- items.forEach((item, index) => {
2741
- this._state.selectedIndices.add(index);
2742
- this._state.selectedItems.set(index, item);
2743
- });
2744
- this._renderOptions();
2745
- this._updateInputDisplay();
2746
- this._emitChange();
2747
- // Scroll to selected if configured
2748
- if (this._config.scrollToSelected.enabled) {
2749
- this._scrollToSelected();
2750
- }
2751
- }
2752
- catch (error) {
2753
- this._handleError(error);
2754
2830
  }
2755
- finally {
2756
- this._setBusy(false);
2831
+ for (let i = min; i <= max; i += 1) {
2832
+ if (maxSelections > 0 && this._state.selectedIndices.size >= maxSelections)
2833
+ break;
2834
+ const item = this._state.loadedItems[i];
2835
+ if (!item)
2836
+ continue;
2837
+ this._state.selectedIndices.add(i);
2838
+ this._state.selectedItems.set(i, item);
2757
2839
  }
2758
- }
2759
- /**
2760
- * Clear all selections
2761
- */
2762
- clear() {
2763
- this._state.selectedIndices.clear();
2764
- this._state.selectedItems.clear();
2765
2840
  this._renderOptions();
2766
2841
  this._updateInputDisplay();
2767
2842
  this._emitChange();
2843
+ this._announce(`${this._state.selectedIndices.size} items selected`);
2768
2844
  }
2769
- /**
2770
- * Open dropdown
2771
- */
2772
- open() {
2773
- this._handleOpen();
2774
- }
2775
- /**
2776
- * Close dropdown
2777
- */
2778
- close() {
2779
- this._handleClose();
2780
- }
2781
- /**
2782
- * Update component configuration
2783
- */
2784
- updateConfig(config) {
2785
- this._config = selectConfig.mergeWithComponentConfig(config);
2786
- // Update input state based on new config
2787
- if (this._input) {
2788
- this._input.readOnly = !this._config.searchable;
2789
- this._input.setAttribute('aria-autocomplete', this._config.searchable ? 'list' : 'none');
2790
- }
2791
- // Re-initialize observers in case infinite scroll was enabled/disabled
2792
- this._initializeObservers();
2793
- this._renderOptions();
2794
- }
2795
- /**
2796
- * Set error state
2797
- */
2798
- setError(message) {
2799
- this._hasError = true;
2800
- this._errorMessage = message;
2801
- this._input.setAttribute('aria-invalid', 'true');
2802
- this._announce(`Error: ${message}`);
2803
- }
2804
- /**
2805
- * Clear error state
2806
- */
2807
- clearError() {
2808
- this._hasError = false;
2809
- this._errorMessage = '';
2810
- this._input.removeAttribute('aria-invalid');
2811
- }
2812
- /**
2813
- * Set required state
2814
- */
2815
- setRequired(required) {
2816
- if (required) {
2817
- this._input.setAttribute('aria-required', 'true');
2818
- this._input.setAttribute('required', '');
2819
- }
2820
- else {
2821
- this._input.removeAttribute('aria-required');
2822
- this._input.removeAttribute('required');
2845
+ _setInitialActiveOption() {
2846
+ const options = Array.from(this._optionsContainer.children);
2847
+ if (options.length === 0)
2848
+ return;
2849
+ const selected = Array.from(this._state.selectedIndices).sort((a, b) => a - b);
2850
+ if (this._config.selection.mode === 'multi' && selected.length === 0) {
2851
+ this._state.activeIndex = -1;
2852
+ this._input.removeAttribute('aria-activedescendant');
2853
+ return;
2823
2854
  }
2855
+ const target = selected.length > 0 ? selected[0] : 0;
2856
+ this._setActive(Math.min(target, options.length - 1));
2824
2857
  }
2825
- /**
2826
- * Validate selection (for required fields)
2827
- */
2828
- validate() {
2829
- const isRequired = this._input.hasAttribute('required');
2830
- if (isRequired && this._state.selectedIndices.size === 0) {
2831
- this.setError('Selection is required');
2832
- return false;
2858
+ _announce(message) {
2859
+ if (this._liveRegion) {
2860
+ this._liveRegion.textContent = message;
2861
+ setTimeout(() => {
2862
+ if (this._liveRegion)
2863
+ this._liveRegion.textContent = '';
2864
+ }, 1000);
2833
2865
  }
2834
- this.clearError();
2835
- return true;
2836
2866
  }
2837
- /**
2838
- * Render options based on current state
2839
- */
2840
- _renderOptions() {
2841
- // Cleanup observer
2842
- if (this._loadMoreTrigger && this._intersectionObserver) {
2843
- this._intersectionObserver.unobserve(this._loadMoreTrigger);
2844
- }
2845
- // Clear options container
2846
- this._optionsContainer.innerHTML = '';
2847
- // Ensure dropdown only contains options container (cleanup legacy direct children)
2848
- // We need to preserve optionsContainer, so we can't just clear dropdown.innerHTML
2849
- // But we can check if there are other children and remove them
2850
- Array.from(this._dropdown.children).forEach(child => {
2851
- if (child !== this._optionsContainer) {
2852
- this._dropdown.removeChild(child);
2853
- }
2854
- });
2855
- // Ensure dropdown is visible if we are rendering options
2856
- if (this._state.isOpen && this._dropdown.style.display === 'none') {
2857
- this._dropdown.style.display = 'block';
2858
- }
2859
- // Show searching state (exclusive state)
2860
- if (this._state.isSearching) {
2861
- const searching = document.createElement('div');
2862
- searching.className = 'searching-state';
2863
- searching.textContent = 'Searching...';
2864
- this._optionsContainer.appendChild(searching);
2867
+ _selectOption(index, opts) {
2868
+ // FIX: Do not rely on this._optionsContainer.children[index] because filtering changes the children
2869
+ // Instead, use the index to update state directly
2870
+ const item = this._state.loadedItems[index];
2871
+ if (!item)
2865
2872
  return;
2866
- }
2867
- const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
2868
- const getLabel = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
2869
- // Filter items by search query
2870
- const query = this._state.searchQuery.toLowerCase();
2871
- // Handle Grouped Items Rendering (when no search query)
2872
- if (this._state.groupedItems.length > 0 && !query) {
2873
- this._state.groupedItems.forEach(group => {
2874
- const header = document.createElement('div');
2875
- header.className = 'group-header';
2876
- header.textContent = group.label;
2877
- Object.assign(header.style, {
2878
- padding: '8px 12px',
2879
- fontWeight: '600',
2880
- color: '#6b7280',
2881
- backgroundColor: '#f3f4f6',
2882
- fontSize: '12px',
2883
- textTransform: 'uppercase',
2884
- letterSpacing: '0.05em',
2885
- position: 'sticky',
2886
- top: '0',
2887
- zIndex: '1',
2888
- borderBottom: '1px solid #e5e7eb'
2889
- });
2890
- this._optionsContainer.appendChild(header);
2891
- group.options.forEach(item => {
2892
- // Find original index for correct ID generation and selection
2893
- const index = this._state.loadedItems.indexOf(item);
2894
- if (index !== -1) {
2895
- this._renderSingleOption(item, index, getValue, getLabel);
2896
- }
2897
- });
2898
- });
2873
+ const isCurrentlySelected = this._state.selectedIndices.has(index);
2874
+ if (this._config.selection.mode === 'single') {
2875
+ // Single select: clear previous and select new
2876
+ const wasSelected = this._state.selectedIndices.has(index);
2877
+ this._state.selectedIndices.clear();
2878
+ this._state.selectedItems.clear();
2879
+ if (!wasSelected) {
2880
+ // Select this option
2881
+ this._state.selectedIndices.add(index);
2882
+ this._state.selectedItems.set(index, item);
2883
+ }
2884
+ // Re-render to update all option styles
2885
+ this._renderOptions();
2886
+ if (this._config.selection.closeOnSelect) {
2887
+ this._handleClose();
2888
+ }
2899
2889
  }
2900
2890
  else {
2901
- // Normal rendering (flat list or filtered)
2902
- let hasRenderedItems = false;
2903
- this._state.loadedItems.forEach((item, index) => {
2904
- // Apply filter if query exists
2905
- if (query) {
2906
- try {
2907
- const label = String(getLabel(item)).toLowerCase();
2908
- if (!label.includes(query))
2909
- return;
2910
- }
2911
- catch (e) {
2912
- return;
2913
- }
2914
- }
2915
- hasRenderedItems = true;
2916
- this._renderSingleOption(item, index, getValue, getLabel);
2917
- });
2918
- if (!hasRenderedItems && !this._state.isBusy) {
2919
- const empty = document.createElement('div');
2920
- empty.className = 'empty-state';
2921
- if (query) {
2922
- empty.textContent = `No results found for "${this._state.searchQuery}"`;
2923
- }
2924
- else {
2925
- empty.textContent = 'No options available';
2926
- }
2927
- this._optionsContainer.appendChild(empty);
2891
+ const toggleKey = Boolean(opts?.toggleKey);
2892
+ const shiftKey = Boolean(opts?.shiftKey);
2893
+ if (shiftKey) {
2894
+ const anchor = this._rangeAnchorIndex ?? index;
2895
+ this._selectRange(anchor, index, { clear: !toggleKey });
2896
+ this._rangeAnchorIndex = anchor;
2897
+ return;
2928
2898
  }
2929
- }
2930
- // Append Busy Indicator if busy
2931
- if (this._state.isBusy && this._config.busyBucket.enabled) {
2932
- const busyBucket = document.createElement('div');
2933
- busyBucket.className = 'busy-bucket';
2934
- if (this._config.busyBucket.showSpinner) {
2935
- const spinner = document.createElement('div');
2936
- spinner.className = 'spinner';
2937
- busyBucket.appendChild(spinner);
2899
+ // Multi select with toggle
2900
+ const maxSelections = this._config.selection.maxSelections || 0;
2901
+ if (isCurrentlySelected) {
2902
+ // Deselect (toggle off)
2903
+ this._state.selectedIndices.delete(index);
2904
+ this._state.selectedItems.delete(index);
2938
2905
  }
2939
- if (this._config.busyBucket.message) {
2940
- const message = document.createElement('div');
2941
- message.textContent = this._config.busyBucket.message;
2942
- busyBucket.appendChild(message);
2906
+ else {
2907
+ // Select (toggle on)
2908
+ if (maxSelections > 0 && this._state.selectedIndices.size >= maxSelections) {
2909
+ this._announce(`Maximum ${maxSelections} selections allowed`);
2910
+ return; // Max selections reached
2911
+ }
2912
+ this._state.selectedIndices.add(index);
2913
+ this._state.selectedItems.set(index, item);
2943
2914
  }
2944
- this._optionsContainer.appendChild(busyBucket);
2945
- }
2946
- // Append Load More Trigger (Button or Sentinel) if enabled and not busy
2947
- else if ((this._config.loadMore.enabled || this._config.infiniteScroll.enabled) && this._state.loadedItems.length > 0) {
2948
- this._addLoadMoreTrigger();
2915
+ // Re-render to update styles (safer than trying to find the element in filtered list)
2916
+ this._renderOptions();
2949
2917
  }
2950
- }
2951
- _renderSingleOption(item, index, getValue, getLabel) {
2952
- const option = document.createElement('div');
2953
- option.className = 'option';
2954
- option.id = `${this._uniqueId}-option-${index}`;
2955
- const value = getValue(item);
2918
+ this._rangeAnchorIndex = index;
2919
+ this._updateInputDisplay();
2920
+ this._emitChange();
2921
+ const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
2922
+ const getLabel = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
2956
2923
  const label = getLabel(item);
2957
- option.textContent = label;
2958
- option.dataset.value = String(value);
2959
- option.dataset.index = String(index); // Also useful for debugging/selectors
2960
- // Check if selected using selectedItems map
2961
- const isSelected = this._state.selectedIndices.has(index);
2962
- if (isSelected) {
2963
- option.classList.add('selected');
2964
- option.setAttribute('aria-selected', 'true');
2924
+ if (this._config.selection.mode === 'single') {
2925
+ this._announce(`Selected ${label}`);
2965
2926
  }
2966
2927
  else {
2967
- option.setAttribute('aria-selected', 'false');
2928
+ const selectedCount = this._state.selectedIndices.size;
2929
+ const action = isCurrentlySelected ? 'Deselected' : 'Selected';
2930
+ this._announce(`${action} ${label}. ${selectedCount} selected`);
2968
2931
  }
2969
- option.addEventListener('click', () => {
2970
- this._selectOption(index);
2932
+ this._config.callbacks.onSelect?.({
2933
+ item: item,
2934
+ index,
2935
+ value: getValue(item),
2936
+ label: getLabel(item),
2937
+ selected: this._state.selectedIndices.has(index),
2971
2938
  });
2972
- this._optionsContainer.appendChild(option);
2973
2939
  }
2974
- _addLoadMoreTrigger() {
2975
- const container = document.createElement('div');
2976
- container.className = 'load-more-container';
2977
- if (this._config.infiniteScroll.enabled) {
2978
- // Infinite Scroll: Render an invisible sentinel
2979
- // It must have some height to be intersected
2980
- const sentinel = document.createElement('div');
2981
- sentinel.className = 'infinite-scroll-sentinel';
2982
- sentinel.style.height = '10px';
2983
- sentinel.style.width = '100%';
2984
- sentinel.style.opacity = '0'; // Invisible
2985
- this._loadMoreTrigger = sentinel;
2986
- container.appendChild(sentinel);
2940
+ _handleOptionRemove(index) {
2941
+ const option = this._getOptionElementByIndex(index);
2942
+ if (!option)
2943
+ return;
2944
+ this._state.selectedIndices.delete(index);
2945
+ this._state.selectedItems.delete(index);
2946
+ option.setSelected(false);
2947
+ this._updateInputDisplay();
2948
+ this._emitChange();
2949
+ const config = option.getConfig();
2950
+ this._emit('remove', { item: config.item, index });
2951
+ }
2952
+ _updateInputDisplay() {
2953
+ const selectedItems = Array.from(this._state.selectedItems.values());
2954
+ const getLabel = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
2955
+ if (selectedItems.length === 0) {
2956
+ this._input.value = '';
2957
+ this._input.placeholder = this._config.placeholder || 'Select an option...';
2958
+ // Clear any badges
2959
+ const existingBadges = this._inputContainer.querySelectorAll('.selection-badge');
2960
+ existingBadges.forEach(badge => badge.remove());
2987
2961
  }
2988
- else {
2989
- // Manual Load More: Render a button
2990
- const button = document.createElement('button');
2991
- button.className = 'load-more-button';
2992
- button.textContent = `Load ${this._config.loadMore.itemsPerLoad} more`;
2993
- button.addEventListener('click', () => this._loadMoreItems());
2994
- this._loadMoreTrigger = button;
2995
- container.appendChild(button);
2962
+ else if (this._config.selection.mode === 'single') {
2963
+ this._input.value = getLabel(selectedItems[0]);
2996
2964
  }
2997
- this._optionsContainer.appendChild(container);
2998
- // Setup intersection observer for auto-load
2999
- if (this._intersectionObserver && this._loadMoreTrigger) {
3000
- this._intersectionObserver.observe(this._loadMoreTrigger);
2965
+ else {
2966
+ // Multi-select: show badges instead of text in input
2967
+ this._input.value = '';
2968
+ this._input.placeholder = '';
2969
+ // Clear existing badges
2970
+ const existingBadges = this._inputContainer.querySelectorAll('.selection-badge');
2971
+ existingBadges.forEach(badge => badge.remove());
2972
+ // Create badges for each selected item
2973
+ const selectedEntries = Array.from(this._state.selectedItems.entries());
2974
+ selectedEntries.forEach(([index, item]) => {
2975
+ const badge = document.createElement('span');
2976
+ badge.className = 'selection-badge';
2977
+ badge.textContent = getLabel(item);
2978
+ // Add remove button to badge
2979
+ const removeBtn = document.createElement('button');
2980
+ removeBtn.className = 'badge-remove';
2981
+ removeBtn.innerHTML = '×';
2982
+ removeBtn.setAttribute('aria-label', `Remove ${getLabel(item)}`);
2983
+ removeBtn.addEventListener('click', (e) => {
2984
+ e.stopPropagation();
2985
+ this._state.selectedIndices.delete(index);
2986
+ this._state.selectedItems.delete(index);
2987
+ this._updateInputDisplay();
2988
+ this._renderOptions();
2989
+ this._emitChange();
2990
+ });
2991
+ badge.appendChild(removeBtn);
2992
+ this._inputContainer.insertBefore(badge, this._input);
2993
+ });
3001
2994
  }
3002
2995
  }
3003
- }
3004
- // Register custom element
3005
- if (!customElements.get('enhanced-select')) {
3006
- customElements.define('enhanced-select', EnhancedSelect);
3007
- }
3008
-
3009
- /**
3010
- * Independent Option Component
3011
- * High cohesion, low coupling - handles its own selection state and events
3012
- */
3013
- class SelectOption extends HTMLElement {
3014
- constructor(config) {
3015
- super();
3016
- this._config = config;
3017
- this._shadow = this.attachShadow({ mode: 'open' });
3018
- this._container = document.createElement('div');
3019
- this._container.className = 'option-container';
3020
- this._initializeStyles();
3021
- this._render();
3022
- this._attachEventListeners();
3023
- this._shadow.appendChild(this._container);
2996
+ _renderOptionsWithAnimation() {
2997
+ // Add fade-out animation
2998
+ this._optionsContainer.style.opacity = '0';
2999
+ this._optionsContainer.style.transition = 'opacity 0.15s ease-out';
3000
+ setTimeout(() => {
3001
+ this._renderOptions();
3002
+ // Fade back in
3003
+ this._optionsContainer.style.opacity = '1';
3004
+ this._optionsContainer.style.transition = 'opacity 0.2s ease-in';
3005
+ }, 150);
3024
3006
  }
3025
- _initializeStyles() {
3026
- const style = document.createElement('style');
3027
- style.textContent = `
3028
- :host {
3029
- display: block;
3030
- position: relative;
3031
- }
3032
-
3033
- .option-container {
3034
- display: flex;
3035
- align-items: center;
3036
- justify-content: space-between;
3037
- padding: 8px 12px;
3038
- cursor: pointer;
3039
- user-select: none;
3040
- transition: background-color 0.2s ease;
3041
- }
3042
-
3043
- .option-container:hover {
3044
- background-color: var(--select-option-hover-bg, #f0f0f0);
3045
- }
3046
-
3047
- .option-container.selected {
3048
- background-color: var(--select-option-selected-bg, #e3f2fd);
3049
- color: var(--select-option-selected-color, #1976d2);
3050
- }
3051
-
3052
- .option-container.active {
3053
- outline: 2px solid var(--select-option-active-outline, #1976d2);
3054
- outline-offset: -2px;
3055
- }
3056
-
3057
- .option-container.disabled {
3058
- opacity: 0.5;
3059
- cursor: not-allowed;
3060
- pointer-events: none;
3061
- }
3062
-
3063
- .option-content {
3064
- flex: 1;
3065
- overflow: hidden;
3066
- text-overflow: ellipsis;
3067
- white-space: nowrap;
3068
- }
3069
-
3070
- .remove-button {
3071
- margin-left: 8px;
3072
- padding: 2px 6px;
3073
- border: none;
3074
- background-color: var(--select-remove-btn-bg, transparent);
3075
- color: var(--select-remove-btn-color, #666);
3076
- cursor: pointer;
3077
- border-radius: 3px;
3078
- font-size: 16px;
3079
- line-height: 1;
3080
- transition: all 0.2s ease;
3081
- }
3082
-
3083
- .remove-button:hover {
3084
- background-color: var(--select-remove-btn-hover-bg, #ffebee);
3085
- color: var(--select-remove-btn-hover-color, #c62828);
3086
- }
3087
-
3088
- .remove-button:focus {
3089
- outline: 2px solid var(--select-remove-btn-focus-outline, #1976d2);
3090
- outline-offset: 2px;
3091
- }
3092
- `;
3093
- this._shadow.appendChild(style);
3007
+ _scrollToSelected() {
3008
+ if (this._state.selectedIndices.size === 0)
3009
+ return;
3010
+ const target = this._config.scrollToSelected.multiSelectTarget;
3011
+ const indices = Array.from(this._state.selectedIndices).sort((a, b) => a - b);
3012
+ // For multi-select, find the closest selected item to the current scroll position
3013
+ let targetIndex;
3014
+ if (this._config.selection.mode === 'multi' && indices.length > 1) {
3015
+ // Calculate which selected item is closest to the center of the viewport
3016
+ const dropdownRect = this._dropdown.getBoundingClientRect();
3017
+ const viewportCenter = this._dropdown.scrollTop + (dropdownRect.height / 2);
3018
+ // Find the selected item closest to viewport center
3019
+ let closestIndex = indices[0];
3020
+ let closestDistance = Infinity;
3021
+ for (const index of indices) {
3022
+ const option = this._getOptionElementByIndex(index);
3023
+ if (option) {
3024
+ const optionTop = option.offsetTop;
3025
+ const distance = Math.abs(optionTop - viewportCenter);
3026
+ if (distance < closestDistance) {
3027
+ closestDistance = distance;
3028
+ closestIndex = index;
3029
+ }
3030
+ }
3031
+ }
3032
+ targetIndex = closestIndex;
3033
+ }
3034
+ else {
3035
+ // For single select or only one selected item, use the configured target
3036
+ targetIndex = target === 'first' ? indices[0] : indices[indices.length - 1];
3037
+ }
3038
+ // Find and scroll to the target option
3039
+ const option = this._getOptionElementByIndex(targetIndex);
3040
+ if (option) {
3041
+ // Use smooth scrolling with center alignment for better UX
3042
+ option.scrollIntoView({
3043
+ block: this._config.scrollToSelected.block || 'center',
3044
+ behavior: 'smooth',
3045
+ });
3046
+ // Also set it as active for keyboard navigation
3047
+ this._setActive(targetIndex);
3048
+ }
3094
3049
  }
3095
- _render() {
3096
- const { item, index, selected, disabled, active, render, showRemoveButton } = this._config;
3097
- // Clear container
3098
- this._container.innerHTML = '';
3099
- // Apply state classes
3100
- this._container.classList.toggle('selected', selected);
3101
- this._container.classList.toggle('disabled', disabled || false);
3102
- this._container.classList.toggle('active', active || false);
3103
- // Custom class name
3104
- if (this._config.className) {
3105
- this._container.className += ' ' + this._config.className;
3050
+ async _loadMoreItems() {
3051
+ if (this._state.isBusy)
3052
+ return;
3053
+ this._setBusy(true);
3054
+ // Save scroll position before loading
3055
+ if (this._dropdown) {
3056
+ this._state.lastScrollPosition = this._dropdown.scrollTop;
3057
+ this._state.preserveScrollPosition = true;
3058
+ // Update dropdown to show loading indicator but keep the
3059
+ // same scrollTop so the visible items don't move.
3060
+ this._renderOptions();
3061
+ this._dropdown.scrollTop = this._state.lastScrollPosition;
3106
3062
  }
3107
- // Apply custom styles
3108
- if (this._config.style) {
3109
- Object.assign(this._container.style, this._config.style);
3063
+ try {
3064
+ // Emit event for parent to handle
3065
+ this._state.currentPage++;
3066
+ this._emit('loadMore', { page: this._state.currentPage, items: [] });
3067
+ this._config.callbacks.onLoadMore?.(this._state.currentPage);
3068
+ // NOTE: We do NOT set isBusy = false here.
3069
+ // The parent component MUST call setItems() or similar to clear the busy state.
3070
+ // This prevents the sentinel from reappearing before new items are loaded.
3110
3071
  }
3111
- // Render content
3112
- const contentDiv = document.createElement('div');
3113
- contentDiv.className = 'option-content';
3114
- if (render) {
3115
- const rendered = render(item, index);
3116
- if (typeof rendered === 'string') {
3117
- contentDiv.innerHTML = rendered;
3118
- }
3119
- else {
3120
- contentDiv.appendChild(rendered);
3121
- }
3072
+ catch (error) {
3073
+ this._handleError(error);
3074
+ this._setBusy(false); // Only clear on error
3122
3075
  }
3123
- else {
3124
- const label = this._getLabel();
3125
- contentDiv.textContent = label;
3076
+ }
3077
+ _setBusy(busy) {
3078
+ this._state.isBusy = busy;
3079
+ if (busy) {
3080
+ this._dropdown.setAttribute('aria-busy', 'true');
3126
3081
  }
3127
- this._container.appendChild(contentDiv);
3128
- // Add remove button if needed
3129
- if (showRemoveButton && selected) {
3130
- this._removeButton = document.createElement('button');
3131
- this._removeButton.className = 'remove-button';
3132
- this._removeButton.innerHTML = '×';
3133
- this._removeButton.setAttribute('aria-label', 'Remove option');
3134
- this._removeButton.setAttribute('type', 'button');
3135
- this._container.appendChild(this._removeButton);
3082
+ else {
3083
+ this._dropdown.removeAttribute('aria-busy');
3136
3084
  }
3137
- // Set ARIA attributes
3138
- this.setAttribute('role', 'option');
3139
- this.setAttribute('aria-selected', String(selected));
3140
- if (disabled)
3141
- this.setAttribute('aria-disabled', 'true');
3142
- this.id = `select-option-${index}`;
3085
+ // Trigger re-render to show/hide busy indicator
3086
+ // We use _renderOptions to handle the UI update
3087
+ this._renderOptions();
3143
3088
  }
3144
- _attachEventListeners() {
3145
- // Click handler for selection
3146
- this._container.addEventListener('click', (e) => {
3147
- // Don't trigger selection if clicking remove button
3148
- if (e.target === this._removeButton) {
3149
- return;
3150
- }
3151
- if (!this._config.disabled) {
3152
- this._handleSelect();
3153
- }
3154
- });
3155
- // Remove button handler
3156
- if (this._removeButton) {
3157
- this._removeButton.addEventListener('click', (e) => {
3158
- e.stopPropagation();
3159
- this._handleRemove();
3160
- });
3089
+ _handleError(error) {
3090
+ this._emit('error', { message: error.message, cause: error });
3091
+ this._config.callbacks.onError?.(error);
3092
+ }
3093
+ _emit(name, detail) {
3094
+ this.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true }));
3095
+ }
3096
+ _emitChange() {
3097
+ const selectedItems = Array.from(this._state.selectedItems.values());
3098
+ const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
3099
+ const selectedValues = selectedItems.map(getValue);
3100
+ const selectedIndices = Array.from(this._state.selectedIndices);
3101
+ this._emit('change', { selectedItems, selectedValues, selectedIndices });
3102
+ this._config.callbacks.onChange?.(selectedItems, selectedValues);
3103
+ }
3104
+ // Public API
3105
+ get optionRenderer() {
3106
+ return this._optionRenderer;
3107
+ }
3108
+ set optionRenderer(renderer) {
3109
+ this._optionRenderer = renderer;
3110
+ this._renderOptions();
3111
+ }
3112
+ /**
3113
+ * Set items to display in the select
3114
+ */
3115
+ setItems(items) {
3116
+ const previousLength = this._state.loadedItems.length;
3117
+ this._state.loadedItems = items;
3118
+ // If grouped items exist, flatten them to items
3119
+ if (this._state.groupedItems.length > 0) {
3120
+ this._state.loadedItems = this._state.groupedItems.flatMap(group => group.options);
3161
3121
  }
3162
- // Keyboard handler
3163
- this.addEventListener('keydown', (e) => {
3164
- if (this._config.disabled)
3165
- return;
3166
- if (e.key === 'Enter' || e.key === ' ') {
3167
- e.preventDefault();
3168
- this._handleSelect();
3122
+ const newLength = this._state.loadedItems.length;
3123
+ // When infinite scroll is active (preserveScrollPosition = true),
3124
+ // we need to maintain scroll position during the update
3125
+ if (this._state.preserveScrollPosition && this._dropdown) {
3126
+ const targetScrollTop = this._state.lastScrollPosition;
3127
+ // Only clear loading if we actually got more items
3128
+ if (newLength > previousLength) {
3129
+ this._state.isBusy = false;
3169
3130
  }
3170
- else if (e.key === 'Delete' || e.key === 'Backspace') {
3171
- if (this._config.selected && this._config.showRemoveButton) {
3172
- e.preventDefault();
3173
- this._handleRemove();
3131
+ this._renderOptions();
3132
+ // Restore the exact scrollTop we had before loading
3133
+ // so the previously visible items stay in place and
3134
+ // new ones simply appear below.
3135
+ this._dropdown.scrollTop = targetScrollTop;
3136
+ // Ensure it sticks after layout
3137
+ requestAnimationFrame(() => {
3138
+ if (this._dropdown) {
3139
+ this._dropdown.scrollTop = targetScrollTop;
3174
3140
  }
3141
+ });
3142
+ // Only clear preserveScrollPosition if we got new items
3143
+ if (newLength > previousLength) {
3144
+ this._state.preserveScrollPosition = false;
3175
3145
  }
3176
- });
3146
+ }
3147
+ else {
3148
+ // Normal update - just render normally
3149
+ this._state.isBusy = false;
3150
+ this._renderOptions();
3151
+ }
3177
3152
  }
3178
- _handleSelect() {
3179
- const detail = {
3180
- item: this._config.item,
3181
- index: this._config.index,
3182
- value: this._getValue(),
3183
- label: this._getLabel(),
3184
- selected: !this._config.selected,
3185
- };
3186
- this.dispatchEvent(new CustomEvent('optionSelect', {
3187
- detail,
3188
- bubbles: true,
3189
- composed: true,
3190
- }));
3153
+ /**
3154
+ * Set grouped items
3155
+ */
3156
+ setGroupedItems(groupedItems) {
3157
+ this._state.groupedItems = groupedItems;
3158
+ this._state.loadedItems = groupedItems.flatMap(group => group.options);
3159
+ this._renderOptions();
3191
3160
  }
3192
- _handleRemove() {
3193
- const detail = {
3194
- item: this._config.item,
3195
- index: this._config.index,
3196
- value: this._getValue(),
3197
- label: this._getLabel(),
3198
- selected: false,
3199
- };
3200
- this.dispatchEvent(new CustomEvent('optionRemove', {
3201
- detail,
3202
- bubbles: true,
3203
- composed: true,
3204
- }));
3161
+ /**
3162
+ * Get currently selected items
3163
+ */
3164
+ getSelectedItems() {
3165
+ return Array.from(this._state.selectedItems.values());
3205
3166
  }
3206
- _getValue() {
3207
- if (this._config.getValue) {
3208
- return this._config.getValue(this._config.item);
3167
+ /**
3168
+ * Get all loaded items
3169
+ */
3170
+ get loadedItems() {
3171
+ return this._state.loadedItems;
3172
+ }
3173
+ /**
3174
+ * Get currently selected values
3175
+ */
3176
+ getSelectedValues() {
3177
+ const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
3178
+ return this.getSelectedItems().map(getValue);
3179
+ }
3180
+ /**
3181
+ * Set selected items by value
3182
+ */
3183
+ async setSelectedValues(values) {
3184
+ if (this._config.serverSide.enabled && this._config.serverSide.fetchSelectedItems) {
3185
+ await this._loadSelectedItemsByValues(values);
3186
+ }
3187
+ else {
3188
+ // Select from loaded items
3189
+ const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
3190
+ this._state.selectedIndices.clear();
3191
+ this._state.selectedItems.clear();
3192
+ this._state.loadedItems.forEach((item, index) => {
3193
+ if (values.includes(getValue(item))) {
3194
+ this._state.selectedIndices.add(index);
3195
+ this._state.selectedItems.set(index, item);
3196
+ }
3197
+ });
3198
+ this._renderOptions();
3199
+ this._updateInputDisplay();
3200
+ this._emitChange();
3209
3201
  }
3210
- return this._config.item?.value ?? this._config.item;
3211
3202
  }
3212
- _getLabel() {
3213
- if (this._config.getLabel) {
3214
- return this._config.getLabel(this._config.item);
3203
+ /**
3204
+ * Load and select items by their values (for infinite scroll scenario)
3205
+ */
3206
+ async _loadSelectedItemsByValues(values) {
3207
+ if (!this._config.serverSide.fetchSelectedItems)
3208
+ return;
3209
+ this._setBusy(true);
3210
+ try {
3211
+ const items = await this._config.serverSide.fetchSelectedItems(values);
3212
+ this._state.selectedIndices.clear();
3213
+ this._state.selectedItems.clear();
3214
+ items.forEach((item, index) => {
3215
+ this._state.selectedIndices.add(index);
3216
+ this._state.selectedItems.set(index, item);
3217
+ });
3218
+ this._renderOptions();
3219
+ this._updateInputDisplay();
3220
+ this._emitChange();
3221
+ // Scroll to selected if configured
3222
+ if (this._config.scrollToSelected.enabled) {
3223
+ this._scrollToSelected();
3224
+ }
3215
3225
  }
3216
- return this._config.item?.label ?? String(this._config.item);
3226
+ catch (error) {
3227
+ this._handleError(error);
3228
+ }
3229
+ finally {
3230
+ this._setBusy(false);
3231
+ }
3232
+ }
3233
+ /**
3234
+ * Clear all selections
3235
+ */
3236
+ clear() {
3237
+ this._state.selectedIndices.clear();
3238
+ this._state.selectedItems.clear();
3239
+ this._renderOptions();
3240
+ this._updateInputDisplay();
3241
+ this._emitChange();
3242
+ }
3243
+ /**
3244
+ * Open dropdown
3245
+ */
3246
+ open() {
3247
+ this._handleOpen();
3217
3248
  }
3218
3249
  /**
3219
- * Update option configuration and re-render
3250
+ * Close dropdown
3220
3251
  */
3221
- updateConfig(updates) {
3222
- this._config = { ...this._config, ...updates };
3223
- this._render();
3224
- this._attachEventListeners();
3252
+ close() {
3253
+ this._handleClose();
3225
3254
  }
3226
3255
  /**
3227
- * Get current configuration
3256
+ * Update component configuration
3228
3257
  */
3229
- getConfig() {
3230
- return this._config;
3258
+ updateConfig(config) {
3259
+ this._config = selectConfig.mergeWithComponentConfig(config);
3260
+ // Update input state based on new config
3261
+ if (this._input) {
3262
+ this._input.readOnly = !this._config.searchable;
3263
+ this._input.setAttribute('aria-autocomplete', this._config.searchable ? 'list' : 'none');
3264
+ if (this._state.selectedIndices.size === 0) {
3265
+ this._input.placeholder = this._config.placeholder || 'Select an option...';
3266
+ }
3267
+ }
3268
+ if (this._dropdown) {
3269
+ if (this._config.selection.mode === 'multi') {
3270
+ this._dropdown.setAttribute('aria-multiselectable', 'true');
3271
+ }
3272
+ else {
3273
+ this._dropdown.removeAttribute('aria-multiselectable');
3274
+ }
3275
+ }
3276
+ // Re-initialize observers in case infinite scroll was enabled/disabled
3277
+ this._initializeObservers();
3278
+ this._renderOptions();
3231
3279
  }
3232
3280
  /**
3233
- * Get option value
3281
+ * Set error state
3234
3282
  */
3235
- getValue() {
3236
- return this._getValue();
3283
+ setError(message) {
3284
+ this._hasError = true;
3285
+ this._errorMessage = message;
3286
+ this._input.setAttribute('aria-invalid', 'true');
3287
+ this._announce(`Error: ${message}`);
3237
3288
  }
3238
3289
  /**
3239
- * Get option label
3290
+ * Clear error state
3240
3291
  */
3241
- getLabel() {
3242
- return this._getLabel();
3292
+ clearError() {
3293
+ this._hasError = false;
3294
+ this._errorMessage = '';
3295
+ this._input.removeAttribute('aria-invalid');
3243
3296
  }
3244
3297
  /**
3245
- * Set selected state
3298
+ * Set required state
3246
3299
  */
3247
- setSelected(selected) {
3248
- this._config.selected = selected;
3249
- this._render();
3300
+ setRequired(required) {
3301
+ if (required) {
3302
+ this._input.setAttribute('aria-required', 'true');
3303
+ this._input.setAttribute('required', '');
3304
+ }
3305
+ else {
3306
+ this._input.removeAttribute('aria-required');
3307
+ this._input.removeAttribute('required');
3308
+ }
3250
3309
  }
3251
3310
  /**
3252
- * Set active state
3311
+ * Validate selection (for required fields)
3253
3312
  */
3254
- setActive(active) {
3255
- this._config.active = active;
3256
- this._render();
3313
+ validate() {
3314
+ const isRequired = this._input.hasAttribute('required');
3315
+ if (isRequired && this._state.selectedIndices.size === 0) {
3316
+ this.setError('Selection is required');
3317
+ return false;
3318
+ }
3319
+ this.clearError();
3320
+ return true;
3257
3321
  }
3258
3322
  /**
3259
- * Set disabled state
3323
+ * Render options based on current state
3260
3324
  */
3261
- setDisabled(disabled) {
3262
- this._config.disabled = disabled;
3263
- this._render();
3325
+ _renderOptions() {
3326
+ // Cleanup observer
3327
+ if (this._loadMoreTrigger && this._intersectionObserver) {
3328
+ this._intersectionObserver.unobserve(this._loadMoreTrigger);
3329
+ }
3330
+ // Clear options container
3331
+ this._optionsContainer.innerHTML = '';
3332
+ // Ensure dropdown only contains options container (cleanup legacy direct children)
3333
+ // We need to preserve optionsContainer, so we can't just clear dropdown.innerHTML
3334
+ // But we can check if there are other children and remove them
3335
+ Array.from(this._dropdown.children).forEach(child => {
3336
+ if (child !== this._optionsContainer) {
3337
+ this._dropdown.removeChild(child);
3338
+ }
3339
+ });
3340
+ // Ensure dropdown is visible if we are rendering options
3341
+ if (this._state.isOpen && this._dropdown.style.display === 'none') {
3342
+ this._dropdown.style.display = 'block';
3343
+ }
3344
+ // Show searching state (exclusive state)
3345
+ if (this._state.isSearching) {
3346
+ const searching = document.createElement('div');
3347
+ searching.className = 'searching-state';
3348
+ searching.textContent = 'Searching...';
3349
+ this._optionsContainer.appendChild(searching);
3350
+ return;
3351
+ }
3352
+ const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
3353
+ const getLabel = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
3354
+ // Filter items by search query
3355
+ const query = this._state.searchQuery.toLowerCase();
3356
+ // Handle Grouped Items Rendering (when no search query)
3357
+ if (this._state.groupedItems.length > 0 && !query) {
3358
+ this._state.groupedItems.forEach(group => {
3359
+ const header = document.createElement('div');
3360
+ header.className = 'group-header';
3361
+ header.textContent = group.label;
3362
+ Object.assign(header.style, {
3363
+ padding: '8px 12px',
3364
+ fontWeight: '600',
3365
+ color: '#6b7280',
3366
+ backgroundColor: '#f3f4f6',
3367
+ fontSize: '12px',
3368
+ textTransform: 'uppercase',
3369
+ letterSpacing: '0.05em',
3370
+ position: 'sticky',
3371
+ top: '0',
3372
+ zIndex: '1',
3373
+ borderBottom: '1px solid #e5e7eb'
3374
+ });
3375
+ this._optionsContainer.appendChild(header);
3376
+ group.options.forEach(item => {
3377
+ // Find original index for correct ID generation and selection
3378
+ const index = this._state.loadedItems.indexOf(item);
3379
+ if (index !== -1) {
3380
+ this._renderSingleOption(item, index, getValue, getLabel);
3381
+ }
3382
+ });
3383
+ });
3384
+ }
3385
+ else {
3386
+ // Normal rendering (flat list or filtered)
3387
+ let hasRenderedItems = false;
3388
+ this._state.loadedItems.forEach((item, index) => {
3389
+ // Apply filter if query exists
3390
+ if (query) {
3391
+ try {
3392
+ const label = String(getLabel(item)).toLowerCase();
3393
+ if (!label.includes(query))
3394
+ return;
3395
+ }
3396
+ catch (e) {
3397
+ return;
3398
+ }
3399
+ }
3400
+ hasRenderedItems = true;
3401
+ this._renderSingleOption(item, index, getValue, getLabel);
3402
+ });
3403
+ if (!hasRenderedItems && !this._state.isBusy) {
3404
+ const empty = document.createElement('div');
3405
+ empty.className = 'empty-state';
3406
+ if (query) {
3407
+ empty.textContent = `No results found for "${this._state.searchQuery}"`;
3408
+ }
3409
+ else {
3410
+ empty.textContent = 'No options available';
3411
+ }
3412
+ this._optionsContainer.appendChild(empty);
3413
+ }
3414
+ }
3415
+ // Append Busy Indicator if busy
3416
+ if (this._state.isBusy && this._config.busyBucket.enabled) {
3417
+ const busyBucket = document.createElement('div');
3418
+ busyBucket.className = 'busy-bucket';
3419
+ if (this._config.busyBucket.showSpinner) {
3420
+ const spinner = document.createElement('div');
3421
+ spinner.className = 'spinner';
3422
+ busyBucket.appendChild(spinner);
3423
+ }
3424
+ if (this._config.busyBucket.message) {
3425
+ const message = document.createElement('div');
3426
+ message.textContent = this._config.busyBucket.message;
3427
+ busyBucket.appendChild(message);
3428
+ }
3429
+ this._optionsContainer.appendChild(busyBucket);
3430
+ }
3431
+ // Append Load More Trigger (Button or Sentinel) if enabled and not busy
3432
+ else if ((this._config.loadMore.enabled || this._config.infiniteScroll.enabled) && this._state.loadedItems.length > 0) {
3433
+ this._addLoadMoreTrigger();
3434
+ }
3435
+ this._finalizePerfMarks();
3436
+ }
3437
+ _renderSingleOption(item, index, getValue, getLabel) {
3438
+ const isSelected = this._state.selectedIndices.has(index);
3439
+ const isDisabled = Boolean(item?.disabled);
3440
+ const optionId = `${this._uniqueId}-option-${index}`;
3441
+ if (this._optionRenderer) {
3442
+ const rendered = this._optionRenderer(item, index, this._rendererHelpers);
3443
+ const optionElement = this._normalizeCustomOptionElement(rendered, {
3444
+ index,
3445
+ value: getValue(item),
3446
+ label: getLabel(item),
3447
+ selected: isSelected,
3448
+ active: this._state.activeIndex === index,
3449
+ disabled: isDisabled,
3450
+ id: optionId,
3451
+ });
3452
+ this._optionsContainer.appendChild(optionElement);
3453
+ return;
3454
+ }
3455
+ const option = new SelectOption({
3456
+ item,
3457
+ index,
3458
+ id: optionId,
3459
+ selected: isSelected,
3460
+ disabled: isDisabled,
3461
+ active: this._state.activeIndex === index,
3462
+ getValue,
3463
+ getLabel,
3464
+ showRemoveButton: this._config.selection.mode === 'multi' && this._config.selection.showRemoveButton,
3465
+ });
3466
+ option.dataset.index = String(index);
3467
+ option.dataset.value = String(getValue(item));
3468
+ option.id = option.id || optionId;
3469
+ option.addEventListener('click', (e) => {
3470
+ const mouseEvent = e;
3471
+ this._selectOption(index, {
3472
+ shiftKey: mouseEvent.shiftKey,
3473
+ toggleKey: mouseEvent.ctrlKey || mouseEvent.metaKey,
3474
+ });
3475
+ });
3476
+ option.addEventListener('optionRemove', (event) => {
3477
+ const detail = event.detail;
3478
+ const targetIndex = detail?.index ?? index;
3479
+ this._handleOptionRemove(targetIndex);
3480
+ });
3481
+ this._optionsContainer.appendChild(option);
3482
+ }
3483
+ _normalizeCustomOptionElement(element, meta) {
3484
+ const optionEl = element instanceof HTMLElement ? element : document.createElement('div');
3485
+ optionEl.classList.add('smilodon-option');
3486
+ optionEl.classList.toggle('smilodon-option--selected', meta.selected);
3487
+ optionEl.classList.toggle('smilodon-option--active', meta.active);
3488
+ optionEl.classList.toggle('smilodon-option--disabled', meta.disabled);
3489
+ if (!optionEl.hasAttribute('data-selectable')) {
3490
+ optionEl.setAttribute('data-selectable', '');
3491
+ }
3492
+ optionEl.dataset.index = String(meta.index);
3493
+ optionEl.dataset.value = String(meta.value);
3494
+ optionEl.id = optionEl.id || meta.id;
3495
+ if (!optionEl.getAttribute('role')) {
3496
+ optionEl.setAttribute('role', 'option');
3497
+ }
3498
+ if (!optionEl.getAttribute('aria-label')) {
3499
+ optionEl.setAttribute('aria-label', meta.label);
3500
+ }
3501
+ optionEl.setAttribute('aria-selected', String(meta.selected));
3502
+ if (meta.disabled) {
3503
+ optionEl.setAttribute('aria-disabled', 'true');
3504
+ }
3505
+ else {
3506
+ optionEl.removeAttribute('aria-disabled');
3507
+ }
3508
+ if (!optionEl.hasAttribute('tabindex')) {
3509
+ optionEl.tabIndex = -1;
3510
+ }
3511
+ if (!meta.disabled) {
3512
+ optionEl.addEventListener('click', (e) => {
3513
+ const mouseEvent = e;
3514
+ this._selectOption(meta.index, {
3515
+ shiftKey: mouseEvent.shiftKey,
3516
+ toggleKey: mouseEvent.ctrlKey || mouseEvent.metaKey,
3517
+ });
3518
+ });
3519
+ optionEl.addEventListener('keydown', (e) => {
3520
+ if (e.key === 'Enter' || e.key === ' ') {
3521
+ e.preventDefault();
3522
+ this._selectOption(meta.index, {
3523
+ shiftKey: e.shiftKey,
3524
+ toggleKey: e.ctrlKey || e.metaKey,
3525
+ });
3526
+ }
3527
+ });
3528
+ }
3529
+ return optionEl;
3530
+ }
3531
+ _addLoadMoreTrigger() {
3532
+ const container = document.createElement('div');
3533
+ container.className = 'load-more-container';
3534
+ if (this._config.infiniteScroll.enabled) {
3535
+ // Infinite Scroll: Render an invisible sentinel
3536
+ // It must have some height to be intersected
3537
+ const sentinel = document.createElement('div');
3538
+ sentinel.className = 'infinite-scroll-sentinel';
3539
+ sentinel.style.height = '10px';
3540
+ sentinel.style.width = '100%';
3541
+ sentinel.style.opacity = '0'; // Invisible
3542
+ this._loadMoreTrigger = sentinel;
3543
+ container.appendChild(sentinel);
3544
+ }
3545
+ else {
3546
+ // Manual Load More: Render a button
3547
+ const button = document.createElement('button');
3548
+ button.className = 'load-more-button';
3549
+ button.textContent = `Load ${this._config.loadMore.itemsPerLoad} more`;
3550
+ button.addEventListener('click', () => this._loadMoreItems());
3551
+ this._loadMoreTrigger = button;
3552
+ container.appendChild(button);
3553
+ }
3554
+ this._optionsContainer.appendChild(container);
3555
+ // Setup intersection observer for auto-load
3556
+ if (this._intersectionObserver && this._loadMoreTrigger) {
3557
+ this._intersectionObserver.observe(this._loadMoreTrigger);
3558
+ }
3264
3559
  }
3265
3560
  }
3266
3561
  // Register custom element
3267
- if (!customElements.get('select-option')) {
3268
- customElements.define('select-option', SelectOption);
3562
+ if (!customElements.get('enhanced-select')) {
3563
+ customElements.define('enhanced-select', EnhancedSelect);
3269
3564
  }
3270
3565
 
3271
3566
  /**