@smilodon/core 1.1.8 → 1.2.0

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
@@ -948,6 +948,404 @@ function resetSelectConfig() {
948
948
  selectConfig.resetConfig();
949
949
  }
950
950
 
951
+ /**
952
+ * Custom Option Component Pool
953
+ *
954
+ * Manages lifecycle and recycling of custom option components for optimal performance.
955
+ * Uses object pooling pattern to minimize allocation/deallocation overhead.
956
+ */
957
+ /**
958
+ * Manages a pool of reusable custom option component instances
959
+ */
960
+ class CustomOptionPool {
961
+ constructor(maxPoolSize = 50) {
962
+ this._pool = new Map();
963
+ this._activeComponents = new Map();
964
+ this._maxPoolSize = maxPoolSize;
965
+ }
966
+ /**
967
+ * Get or create a component instance for the given index
968
+ *
969
+ * @param factory - Factory function to create new instances
970
+ * @param item - The data item
971
+ * @param index - The option index
972
+ * @param context - Context for mounting
973
+ * @param container - DOM container for mounting
974
+ * @returns Component instance
975
+ */
976
+ acquire(factory, item, index, context, container) {
977
+ const factoryKey = this._getFactoryKey(factory);
978
+ // Try to find an available component in the pool
979
+ const pooled = this._findAvailableComponent(factoryKey);
980
+ let component;
981
+ if (pooled) {
982
+ // Reuse pooled component
983
+ component = pooled.instance;
984
+ pooled.inUse = true;
985
+ pooled.lastUsedIndex = index;
986
+ console.log(`[CustomOptionPool] Reusing component for index ${index}`);
987
+ }
988
+ else {
989
+ // Create new component
990
+ try {
991
+ component = factory(item, index);
992
+ console.log(`[CustomOptionPool] Created new component for index ${index}`);
993
+ // Add to pool if under limit
994
+ const pool = this._pool.get(factoryKey) || [];
995
+ if (pool.length < this._maxPoolSize) {
996
+ pool.push({
997
+ instance: component,
998
+ inUse: true,
999
+ lastUsedIndex: index
1000
+ });
1001
+ this._pool.set(factoryKey, pool);
1002
+ }
1003
+ }
1004
+ catch (error) {
1005
+ console.error(`[CustomOptionPool] Failed to create component:`, error);
1006
+ throw error;
1007
+ }
1008
+ }
1009
+ // Mount the component
1010
+ try {
1011
+ component.mountOption(container, context);
1012
+ this._activeComponents.set(index, component);
1013
+ }
1014
+ catch (error) {
1015
+ console.error(`[CustomOptionPool] Failed to mount component at index ${index}:`, error);
1016
+ throw error;
1017
+ }
1018
+ return component;
1019
+ }
1020
+ /**
1021
+ * Release a component back to the pool
1022
+ *
1023
+ * @param index - The index of the component to release
1024
+ */
1025
+ release(index) {
1026
+ const component = this._activeComponents.get(index);
1027
+ if (!component)
1028
+ return;
1029
+ try {
1030
+ component.unmountOption();
1031
+ }
1032
+ catch (error) {
1033
+ console.error(`[CustomOptionPool] Failed to unmount component at index ${index}:`, error);
1034
+ }
1035
+ this._activeComponents.delete(index);
1036
+ // Mark as available in pool
1037
+ for (const pool of this._pool.values()) {
1038
+ const pooled = pool.find(p => p.instance === component);
1039
+ if (pooled) {
1040
+ pooled.inUse = false;
1041
+ console.log(`[CustomOptionPool] Released component from index ${index}`);
1042
+ break;
1043
+ }
1044
+ }
1045
+ }
1046
+ /**
1047
+ * Release all active components
1048
+ */
1049
+ releaseAll() {
1050
+ console.log(`[CustomOptionPool] Releasing ${this._activeComponents.size} active components`);
1051
+ const indices = Array.from(this._activeComponents.keys());
1052
+ indices.forEach(index => this.release(index));
1053
+ }
1054
+ /**
1055
+ * Update selection state for a component
1056
+ *
1057
+ * @param index - The index of the component
1058
+ * @param selected - Whether it's selected
1059
+ */
1060
+ updateSelection(index, selected) {
1061
+ const component = this._activeComponents.get(index);
1062
+ if (component) {
1063
+ component.updateSelected(selected);
1064
+ }
1065
+ }
1066
+ /**
1067
+ * Update focused state for a component
1068
+ *
1069
+ * @param index - The index of the component
1070
+ * @param focused - Whether it has keyboard focus
1071
+ */
1072
+ updateFocused(index, focused) {
1073
+ const component = this._activeComponents.get(index);
1074
+ if (component && component.updateFocused) {
1075
+ component.updateFocused(focused);
1076
+ }
1077
+ }
1078
+ /**
1079
+ * Get active component at index
1080
+ *
1081
+ * @param index - The option index
1082
+ * @returns The component instance or undefined
1083
+ */
1084
+ getComponent(index) {
1085
+ return this._activeComponents.get(index);
1086
+ }
1087
+ /**
1088
+ * Clear the entire pool
1089
+ */
1090
+ clear() {
1091
+ this.releaseAll();
1092
+ this._pool.clear();
1093
+ console.log('[CustomOptionPool] Pool cleared');
1094
+ }
1095
+ /**
1096
+ * Get pool statistics for debugging
1097
+ */
1098
+ getStats() {
1099
+ let totalPooled = 0;
1100
+ let availableComponents = 0;
1101
+ for (const pool of this._pool.values()) {
1102
+ totalPooled += pool.length;
1103
+ availableComponents += pool.filter(p => !p.inUse).length;
1104
+ }
1105
+ return {
1106
+ totalPooled,
1107
+ activeComponents: this._activeComponents.size,
1108
+ availableComponents
1109
+ };
1110
+ }
1111
+ /**
1112
+ * Find an available component in the pool
1113
+ */
1114
+ _findAvailableComponent(factoryKey) {
1115
+ const pool = this._pool.get(factoryKey);
1116
+ if (!pool)
1117
+ return undefined;
1118
+ return pool.find(p => !p.inUse);
1119
+ }
1120
+ /**
1121
+ * Generate a unique key for a factory function
1122
+ */
1123
+ _getFactoryKey(factory) {
1124
+ // Use function name or create a symbol
1125
+ return factory.name || `factory_${factory.toString().slice(0, 50)}`;
1126
+ }
1127
+ }
1128
+
1129
+ /**
1130
+ * Option Renderer
1131
+ *
1132
+ * Unified renderer that handles both lightweight (label/value) and
1133
+ * custom component rendering with consistent performance characteristics.
1134
+ */
1135
+ /**
1136
+ * Manages rendering of both lightweight and custom component options
1137
+ */
1138
+ class OptionRenderer {
1139
+ constructor(config) {
1140
+ this._mountedElements = new Map();
1141
+ this._config = config;
1142
+ this._pool = new CustomOptionPool(config.maxPoolSize);
1143
+ }
1144
+ /**
1145
+ * Render an option (lightweight or custom component)
1146
+ *
1147
+ * @param item - The data item
1148
+ * @param index - The option index
1149
+ * @param isSelected - Whether the option is selected
1150
+ * @param isFocused - Whether the option has keyboard focus
1151
+ * @param uniqueId - Unique ID for the select instance
1152
+ * @returns The rendered DOM element
1153
+ */
1154
+ render(item, index, isSelected, isFocused, uniqueId) {
1155
+ const extendedItem = item;
1156
+ const value = this._config.getValue(item);
1157
+ const label = this._config.getLabel(item);
1158
+ const isDisabled = this._config.getDisabled ? this._config.getDisabled(item) : false;
1159
+ // Determine if this is a custom component or lightweight option
1160
+ const hasCustomComponent = extendedItem.optionComponent && typeof extendedItem.optionComponent === 'function';
1161
+ if (hasCustomComponent) {
1162
+ return this._renderCustomComponent(item, index, value, label, isSelected, isFocused, isDisabled, uniqueId, extendedItem.optionComponent);
1163
+ }
1164
+ else {
1165
+ return this._renderLightweightOption(item, index, value, label, isSelected, isFocused, isDisabled, uniqueId);
1166
+ }
1167
+ }
1168
+ /**
1169
+ * Update selection state for an option
1170
+ *
1171
+ * @param index - The option index
1172
+ * @param selected - Whether it's selected
1173
+ */
1174
+ updateSelection(index, selected) {
1175
+ const element = this._mountedElements.get(index);
1176
+ if (!element)
1177
+ return;
1178
+ // Check if this is a custom component
1179
+ const component = this._pool.getComponent(index);
1180
+ if (component) {
1181
+ component.updateSelected(selected);
1182
+ }
1183
+ else {
1184
+ // Update lightweight option
1185
+ if (selected) {
1186
+ element.classList.add('selected');
1187
+ element.setAttribute('aria-selected', 'true');
1188
+ }
1189
+ else {
1190
+ element.classList.remove('selected');
1191
+ element.setAttribute('aria-selected', 'false');
1192
+ }
1193
+ }
1194
+ }
1195
+ /**
1196
+ * Update focused state for an option
1197
+ *
1198
+ * @param index - The option index
1199
+ * @param focused - Whether it has keyboard focus
1200
+ */
1201
+ updateFocused(index, focused) {
1202
+ const element = this._mountedElements.get(index);
1203
+ if (!element)
1204
+ return;
1205
+ // Check if this is a custom component
1206
+ const component = this._pool.getComponent(index);
1207
+ if (component) {
1208
+ if (component.updateFocused) {
1209
+ component.updateFocused(focused);
1210
+ }
1211
+ // Also update the element's focused class for styling
1212
+ element.classList.toggle('focused', focused);
1213
+ }
1214
+ else {
1215
+ // Update lightweight option
1216
+ element.classList.toggle('focused', focused);
1217
+ }
1218
+ }
1219
+ /**
1220
+ * Unmount and cleanup an option
1221
+ *
1222
+ * @param index - The option index
1223
+ */
1224
+ unmount(index) {
1225
+ // Release custom component if exists
1226
+ this._pool.release(index);
1227
+ // Remove from mounted elements
1228
+ this._mountedElements.delete(index);
1229
+ }
1230
+ /**
1231
+ * Unmount all options
1232
+ */
1233
+ unmountAll() {
1234
+ this._pool.releaseAll();
1235
+ this._mountedElements.clear();
1236
+ }
1237
+ /**
1238
+ * Get pool statistics
1239
+ */
1240
+ getStats() {
1241
+ return this._pool.getStats();
1242
+ }
1243
+ /**
1244
+ * Render a lightweight option (traditional label/value)
1245
+ */
1246
+ _renderLightweightOption(item, index, value, label, isSelected, isFocused, isDisabled, uniqueId) {
1247
+ const option = document.createElement('div');
1248
+ option.className = 'option';
1249
+ if (isSelected)
1250
+ option.classList.add('selected');
1251
+ if (isFocused)
1252
+ option.classList.add('focused');
1253
+ if (isDisabled)
1254
+ option.classList.add('disabled');
1255
+ option.id = `${uniqueId}-option-${index}`;
1256
+ option.textContent = label;
1257
+ option.dataset.value = String(value);
1258
+ option.dataset.index = String(index);
1259
+ option.dataset.mode = 'lightweight';
1260
+ option.setAttribute('role', 'option');
1261
+ option.setAttribute('aria-selected', String(isSelected));
1262
+ if (isDisabled) {
1263
+ option.setAttribute('aria-disabled', 'true');
1264
+ }
1265
+ // Click handler
1266
+ if (!isDisabled) {
1267
+ option.addEventListener('click', () => {
1268
+ this._config.onSelect(index);
1269
+ });
1270
+ }
1271
+ this._mountedElements.set(index, option);
1272
+ console.log(`[OptionRenderer] Rendered lightweight option ${index}: ${label}`);
1273
+ return option;
1274
+ }
1275
+ /**
1276
+ * Render a custom component option
1277
+ */
1278
+ _renderCustomComponent(item, index, value, label, isSelected, isFocused, isDisabled, uniqueId, factory) {
1279
+ // Create wrapper container for the custom component
1280
+ const wrapper = document.createElement('div');
1281
+ wrapper.className = 'option option-custom';
1282
+ if (isSelected)
1283
+ wrapper.classList.add('selected');
1284
+ if (isFocused)
1285
+ wrapper.classList.add('focused');
1286
+ if (isDisabled)
1287
+ wrapper.classList.add('disabled');
1288
+ wrapper.id = `${uniqueId}-option-${index}`;
1289
+ wrapper.dataset.value = String(value);
1290
+ wrapper.dataset.index = String(index);
1291
+ wrapper.dataset.mode = 'component';
1292
+ wrapper.setAttribute('role', 'option');
1293
+ wrapper.setAttribute('aria-selected', String(isSelected));
1294
+ wrapper.setAttribute('aria-label', label); // Accessibility fallback
1295
+ if (isDisabled) {
1296
+ wrapper.setAttribute('aria-disabled', 'true');
1297
+ }
1298
+ // Create context for the custom component
1299
+ const context = {
1300
+ item,
1301
+ index,
1302
+ value,
1303
+ label,
1304
+ isSelected,
1305
+ isFocused,
1306
+ isDisabled,
1307
+ onSelect: (idx) => {
1308
+ if (!isDisabled) {
1309
+ this._config.onSelect(idx);
1310
+ }
1311
+ },
1312
+ onCustomEvent: (eventName, data) => {
1313
+ if (this._config.onCustomEvent) {
1314
+ this._config.onCustomEvent(index, eventName, data);
1315
+ }
1316
+ }
1317
+ };
1318
+ // Acquire component from pool and mount it
1319
+ try {
1320
+ const component = this._pool.acquire(factory, item, index, context, wrapper);
1321
+ // Get the component's root element and attach click handler to wrapper
1322
+ const componentElement = component.getElement();
1323
+ if (!isDisabled) {
1324
+ // Use event delegation on the wrapper
1325
+ wrapper.addEventListener('click', (e) => {
1326
+ // Only trigger if clicking within the component
1327
+ if (wrapper.contains(e.target)) {
1328
+ this._config.onSelect(index);
1329
+ }
1330
+ });
1331
+ }
1332
+ console.log(`[OptionRenderer] Rendered custom component option ${index}: ${label}`);
1333
+ }
1334
+ catch (error) {
1335
+ console.error(`[OptionRenderer] Failed to render custom component at index ${index}:`, error);
1336
+ // Fallback to lightweight rendering on error
1337
+ wrapper.innerHTML = '';
1338
+ wrapper.textContent = label;
1339
+ wrapper.classList.add('component-error');
1340
+ if (this._config.onError) {
1341
+ this._config.onError(index, error);
1342
+ }
1343
+ }
1344
+ this._mountedElements.set(index, wrapper);
1345
+ return wrapper;
1346
+ }
1347
+ }
1348
+
951
1349
  /**
952
1350
  * Enhanced Select Component
953
1351
  * Implements all advanced features: infinite scroll, load more, busy state,
@@ -1006,6 +1404,9 @@ class EnhancedSelect extends HTMLElement {
1006
1404
  // Initialize styles BEFORE assembling DOM (order matters in shadow DOM)
1007
1405
  this._initializeStyles();
1008
1406
  console.log('[EnhancedSelect] Styles initialized');
1407
+ // Initialize option renderer
1408
+ this._initializeOptionRenderer();
1409
+ console.log('[EnhancedSelect] Option renderer initialized');
1009
1410
  this._assembleDOM();
1010
1411
  console.log('[EnhancedSelect] DOM assembled');
1011
1412
  this._attachEventListeners();
@@ -1042,6 +1443,11 @@ class EnhancedSelect extends HTMLElement {
1042
1443
  clearTimeout(this._typeTimeout);
1043
1444
  if (this._searchTimeout)
1044
1445
  clearTimeout(this._searchTimeout);
1446
+ // Cleanup option renderer
1447
+ if (this._optionRenderer) {
1448
+ this._optionRenderer.unmountAll();
1449
+ console.log('[EnhancedSelect] Option renderer cleaned up');
1450
+ }
1045
1451
  // Cleanup arrow click listener
1046
1452
  if (this._boundArrowClick && this._arrowContainer) {
1047
1453
  this._arrowContainer.removeEventListener('click', this._boundArrowClick);
@@ -1581,6 +1987,40 @@ class EnhancedSelect extends HTMLElement {
1581
1987
  }, { threshold: 0.1 });
1582
1988
  }
1583
1989
  }
1990
+ _initializeOptionRenderer() {
1991
+ const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
1992
+ const getLabel = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
1993
+ const getDisabled = (item) => item?.disabled ?? false;
1994
+ const rendererConfig = {
1995
+ enableRecycling: true,
1996
+ maxPoolSize: 100,
1997
+ getValue,
1998
+ getLabel,
1999
+ getDisabled,
2000
+ onSelect: (index) => {
2001
+ this._selectOption(index);
2002
+ },
2003
+ onCustomEvent: (index, eventName, data) => {
2004
+ console.log(`[EnhancedSelect] Custom event from option ${index}: ${eventName}`, data);
2005
+ // Emit as a generic event since these aren't in the standard event map
2006
+ this.dispatchEvent(new CustomEvent('option:custom-event', {
2007
+ detail: { index, eventName, data },
2008
+ bubbles: true,
2009
+ composed: true
2010
+ }));
2011
+ },
2012
+ onError: (index, error) => {
2013
+ console.error(`[EnhancedSelect] Error in option ${index}:`, error);
2014
+ this.dispatchEvent(new CustomEvent('option:mount-error', {
2015
+ detail: { index, error },
2016
+ bubbles: true,
2017
+ composed: true
2018
+ }));
2019
+ }
2020
+ };
2021
+ this._optionRenderer = new OptionRenderer(rendererConfig);
2022
+ console.log('[EnhancedSelect] Option renderer initialized with config:', rendererConfig);
2023
+ }
1584
2024
  async _loadInitialSelectedItems() {
1585
2025
  if (!this._config.serverSide.fetchSelectedItems || !this._config.serverSide.initialSelectedValues) {
1586
2026
  return;
@@ -2301,6 +2741,11 @@ class EnhancedSelect extends HTMLElement {
2301
2741
  if (this._loadMoreTrigger && this._intersectionObserver) {
2302
2742
  this._intersectionObserver.unobserve(this._loadMoreTrigger);
2303
2743
  }
2744
+ // Cleanup all rendered options (including custom components)
2745
+ if (this._optionRenderer) {
2746
+ this._optionRenderer.unmountAll();
2747
+ console.log('[EnhancedSelect] Unmounted all option components');
2748
+ }
2304
2749
  // Clear options container
2305
2750
  console.log('[EnhancedSelect] Clearing options container, previous children:', this._optionsContainer.children.length);
2306
2751
  this._optionsContainer.innerHTML = '';
@@ -2417,28 +2862,23 @@ class EnhancedSelect extends HTMLElement {
2417
2862
  console.log('[EnhancedSelect] _renderOptions complete, optionsContainer children:', this._optionsContainer.children.length);
2418
2863
  }
2419
2864
  _renderSingleOption(item, index, getValue, getLabel) {
2420
- const option = document.createElement('div');
2421
- option.className = 'option';
2422
- option.id = `${this._uniqueId}-option-${index}`;
2423
- const value = getValue(item);
2424
- const label = getLabel(item);
2425
- console.log('[EnhancedSelect] Rendering option', index, ':', { value, label });
2426
- option.textContent = label;
2427
- option.dataset.value = String(value);
2428
- option.dataset.index = String(index); // Also useful for debugging/selectors
2429
- // Check if selected using selectedItems map
2430
- const isSelected = this._state.selectedIndices.has(index);
2431
- if (isSelected) {
2432
- option.classList.add('selected');
2433
- option.setAttribute('aria-selected', 'true');
2434
- }
2435
- else {
2436
- option.setAttribute('aria-selected', 'false');
2865
+ if (!this._optionRenderer) {
2866
+ console.error('[EnhancedSelect] Option renderer not initialized');
2867
+ return;
2437
2868
  }
2438
- option.addEventListener('click', () => {
2439
- this._selectOption(index);
2869
+ // Check if selected
2870
+ const isSelected = this._state.selectedIndices.has(index);
2871
+ const isFocused = this._state.activeIndex === index;
2872
+ console.log('[EnhancedSelect] Rendering option', index, ':', {
2873
+ value: getValue(item),
2874
+ label: getLabel(item),
2875
+ isSelected,
2876
+ isFocused,
2877
+ hasCustomComponent: !!item.optionComponent
2440
2878
  });
2441
- this._optionsContainer.appendChild(option);
2879
+ // Use the OptionRenderer to render both lightweight and custom component options
2880
+ const optionElement = this._optionRenderer.render(item, index, isSelected, isFocused, this._uniqueId);
2881
+ this._optionsContainer.appendChild(optionElement);
2442
2882
  console.log('[EnhancedSelect] Option', index, 'appended to optionsContainer');
2443
2883
  }
2444
2884
  _addLoadMoreTrigger() {
@@ -2476,920 +2916,6 @@ if (!customElements.get('enhanced-select')) {
2476
2916
  customElements.define('enhanced-select', EnhancedSelect);
2477
2917
  }
2478
2918
 
2479
- /**
2480
- * Angular-Optimized Enhanced Select Component
2481
- *
2482
- * This is a specialized variant that uses light DOM instead of shadow DOM
2483
- * to ensure perfect compatibility with Angular's rendering pipeline and
2484
- * view encapsulation system.
2485
- *
2486
- * Key differences from standard EnhancedSelect:
2487
- * - Uses light DOM with scoped CSS classes
2488
- * - Integrates seamlessly with Angular's change detection
2489
- * - Maintains all core features (virtualization, accessibility, performance)
2490
- * - Uses unique class prefixes to avoid style conflicts
2491
- *
2492
- * @performance Optimized for Angular's zone.js and rendering cycle
2493
- * @accessibility Full WCAG 2.1 AAA compliance maintained
2494
- */
2495
- /**
2496
- * Angular-Enhanced Select Web Component
2497
- * Uses light DOM for Angular compatibility
2498
- */
2499
- class AngularEnhancedSelect extends HTMLElement {
2500
- constructor() {
2501
- super();
2502
- this._pageCache = {};
2503
- this._typeBuffer = '';
2504
- this._hasError = false;
2505
- this._errorMessage = '';
2506
- this._boundArrowClick = null;
2507
- this._isReady = false;
2508
- // Unique class prefix to avoid conflicts
2509
- this.PREFIX = 'smilodon-ang-';
2510
- console.log('[AngularEnhancedSelect] Constructor called');
2511
- this._uniqueId = `angular-select-${Math.random().toString(36).substr(2, 9)}`;
2512
- // Merge global config
2513
- this._config = selectConfig.getConfig();
2514
- // Initialize state
2515
- this._state = {
2516
- isOpen: false,
2517
- isBusy: false,
2518
- isSearching: false,
2519
- currentPage: this._config.infiniteScroll.initialPage || 1,
2520
- totalPages: 1,
2521
- selectedIndices: new Set(),
2522
- selectedItems: new Map(),
2523
- activeIndex: -1,
2524
- searchQuery: '',
2525
- loadedItems: [],
2526
- groupedItems: [],
2527
- preserveScrollPosition: false,
2528
- lastScrollPosition: 0,
2529
- lastNotifiedQuery: null,
2530
- lastNotifiedResultCount: 0,
2531
- isExpanded: false,
2532
- };
2533
- // Create DOM structure in light DOM
2534
- this._initializeStyles();
2535
- this._container = this._createContainer();
2536
- this._inputContainer = this._createInputContainer();
2537
- this._input = this._createInput();
2538
- this._arrowContainer = this._createArrowContainer();
2539
- this._dropdown = this._createDropdown();
2540
- this._optionsContainer = this._createOptionsContainer();
2541
- this._liveRegion = this._createLiveRegion();
2542
- this._assembleDOM();
2543
- this._attachEventListeners();
2544
- this._initializeObservers();
2545
- }
2546
- connectedCallback() {
2547
- console.log('[AngularEnhancedSelect] connectedCallback called');
2548
- // Ensure host has proper layout
2549
- if (!this.style.display) {
2550
- this.style.display = 'block';
2551
- }
2552
- if (!this.style.position) {
2553
- this.style.position = 'relative';
2554
- }
2555
- // Load initial data if server-side is enabled
2556
- if (this._config.serverSide.enabled && this._config.serverSide.initialSelectedValues) {
2557
- this._loadInitialSelectedItems();
2558
- }
2559
- // Mark element as ready
2560
- this._isReady = true;
2561
- console.log('[AngularEnhancedSelect] Element is now ready');
2562
- }
2563
- disconnectedCallback() {
2564
- // Cleanup observers
2565
- this._resizeObserver?.disconnect();
2566
- this._intersectionObserver?.disconnect();
2567
- if (this._busyTimeout)
2568
- clearTimeout(this._busyTimeout);
2569
- if (this._typeTimeout)
2570
- clearTimeout(this._typeTimeout);
2571
- if (this._searchTimeout)
2572
- clearTimeout(this._searchTimeout);
2573
- // Cleanup arrow click listener
2574
- if (this._boundArrowClick && this._arrowContainer) {
2575
- this._arrowContainer.removeEventListener('click', this._boundArrowClick);
2576
- }
2577
- // Remove style element
2578
- if (this._styleElement && this._styleElement.parentNode) {
2579
- this._styleElement.parentNode.removeChild(this._styleElement);
2580
- }
2581
- }
2582
- _initializeStyles() {
2583
- // Check if styles already exist for this component type
2584
- const existingStyle = document.head.querySelector('style[data-component="angular-enhanced-select-shared"]');
2585
- if (existingStyle) {
2586
- // Styles already injected, reuse the existing one
2587
- this._styleElement = existingStyle;
2588
- return;
2589
- }
2590
- // Create scoped styles for this component type (shared across all instances)
2591
- this._styleElement = document.createElement('style');
2592
- this._styleElement.setAttribute('data-component', 'angular-enhanced-select-shared');
2593
- const p = this.PREFIX; // shorthand
2594
- this._styleElement.textContent = `
2595
- /* Host styles - applied to <angular-enhanced-select> */
2596
- angular-enhanced-select {
2597
- display: block;
2598
- position: relative;
2599
- width: 100%;
2600
- min-height: 44px;
2601
- box-sizing: border-box;
2602
- }
2603
-
2604
- /* Container */
2605
- .${p}container {
2606
- position: relative;
2607
- width: 100%;
2608
- min-height: 44px;
2609
- box-sizing: border-box;
2610
- }
2611
-
2612
- /* Input Container */
2613
- .${p}input-container {
2614
- position: relative;
2615
- width: 100%;
2616
- display: flex;
2617
- align-items: center;
2618
- flex-wrap: wrap;
2619
- gap: 6px;
2620
- padding: 6px 52px 6px 8px;
2621
- min-height: 44px;
2622
- background: white;
2623
- border: 1px solid #d1d5db;
2624
- border-radius: 6px;
2625
- box-sizing: border-box;
2626
- transition: all 0.2s ease;
2627
- }
2628
-
2629
- .${p}input-container:focus-within {
2630
- border-color: #667eea;
2631
- box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
2632
- }
2633
-
2634
- /* Gradient separator before arrow */
2635
- .${p}input-container::after {
2636
- content: '';
2637
- position: absolute;
2638
- top: 50%;
2639
- right: 40px;
2640
- transform: translateY(-50%);
2641
- width: 1px;
2642
- height: 60%;
2643
- background: linear-gradient(
2644
- to bottom,
2645
- transparent 0%,
2646
- rgba(0, 0, 0, 0.1) 20%,
2647
- rgba(0, 0, 0, 0.1) 80%,
2648
- transparent 100%
2649
- );
2650
- pointer-events: none;
2651
- z-index: 1;
2652
- }
2653
-
2654
- /* Dropdown Arrow Container */
2655
- .${p}arrow-container {
2656
- position: absolute;
2657
- top: 0;
2658
- right: 0;
2659
- bottom: 0;
2660
- width: 40px;
2661
- display: flex;
2662
- align-items: center;
2663
- justify-content: center;
2664
- cursor: pointer;
2665
- transition: background-color 0.2s ease;
2666
- border-radius: 0 4px 4px 0;
2667
- z-index: 2;
2668
- }
2669
-
2670
- .${p}arrow-container:hover {
2671
- background-color: rgba(102, 126, 234, 0.08);
2672
- }
2673
-
2674
- .${p}arrow {
2675
- width: 16px;
2676
- height: 16px;
2677
- color: #667eea;
2678
- transition: transform 0.2s ease, color 0.2s ease;
2679
- transform: translateY(0);
2680
- }
2681
-
2682
- .${p}arrow-container:hover .${p}arrow {
2683
- color: #667eea;
2684
- }
2685
-
2686
- .${p}arrow.${p}open {
2687
- transform: rotate(180deg);
2688
- }
2689
-
2690
- /* Input */
2691
- .${p}input {
2692
- flex: 1;
2693
- min-width: 120px;
2694
- padding: 4px;
2695
- border: none;
2696
- font-size: 14px;
2697
- line-height: 1.5;
2698
- color: #1f2937;
2699
- background: transparent;
2700
- box-sizing: border-box;
2701
- outline: none;
2702
- }
2703
-
2704
- .${p}input::placeholder {
2705
- color: #9ca3af;
2706
- }
2707
-
2708
- /* Selection Badges */
2709
- .${p}badge {
2710
- display: inline-flex;
2711
- align-items: center;
2712
- gap: 4px;
2713
- padding: 4px 8px;
2714
- margin: 2px;
2715
- background: #667eea;
2716
- color: white;
2717
- border-radius: 4px;
2718
- font-size: 13px;
2719
- line-height: 1;
2720
- }
2721
-
2722
- .${p}badge-remove {
2723
- display: inline-flex;
2724
- align-items: center;
2725
- justify-content: center;
2726
- width: 16px;
2727
- height: 16px;
2728
- padding: 0;
2729
- margin-left: 4px;
2730
- background: rgba(255, 255, 255, 0.3);
2731
- border: none;
2732
- border-radius: 50%;
2733
- color: white;
2734
- font-size: 16px;
2735
- line-height: 1;
2736
- cursor: pointer;
2737
- transition: background 0.2s;
2738
- }
2739
-
2740
- .${p}badge-remove:hover {
2741
- background: rgba(255, 255, 255, 0.5);
2742
- }
2743
-
2744
- /* Dropdown */
2745
- .${p}dropdown {
2746
- position: absolute;
2747
- scroll-behavior: smooth;
2748
- top: 100%;
2749
- left: 0;
2750
- right: 0;
2751
- margin-top: 4px;
2752
- max-height: 300px;
2753
- overflow: hidden;
2754
- background: white;
2755
- border: 1px solid #ccc;
2756
- border-radius: 4px;
2757
- box-shadow: 0 4px 6px rgba(0,0,0,0.1);
2758
- z-index: 1000;
2759
- box-sizing: border-box;
2760
- }
2761
-
2762
- .${p}dropdown[style*="display: none"] {
2763
- display: none !important;
2764
- }
2765
-
2766
- /* Options Container */
2767
- .${p}options-container {
2768
- position: relative;
2769
- max-height: 300px;
2770
- overflow: auto;
2771
- transition: opacity 0.2s ease-in-out;
2772
- }
2773
-
2774
- /* Option */
2775
- .${p}option {
2776
- padding: 8px 12px;
2777
- cursor: pointer;
2778
- color: inherit;
2779
- transition: background-color 0.15s ease;
2780
- user-select: none;
2781
- }
2782
-
2783
- .${p}option:hover {
2784
- background-color: #f3f4f6;
2785
- }
2786
-
2787
- .${p}option.${p}selected {
2788
- background-color: #e0e7ff;
2789
- color: #4338ca;
2790
- font-weight: 500;
2791
- }
2792
-
2793
- .${p}option.${p}active {
2794
- background-color: #f3f4f6;
2795
- }
2796
-
2797
- /* Load More */
2798
- .${p}load-more-container {
2799
- padding: 12px;
2800
- text-align: center;
2801
- border-top: 1px solid #e0e0e0;
2802
- }
2803
-
2804
- .${p}load-more-button {
2805
- padding: 8px 16px;
2806
- border: 1px solid #1976d2;
2807
- background: white;
2808
- color: #1976d2;
2809
- border-radius: 4px;
2810
- cursor: pointer;
2811
- font-size: 14px;
2812
- transition: all 0.2s ease;
2813
- }
2814
-
2815
- .${p}load-more-button:hover {
2816
- background: #1976d2;
2817
- color: white;
2818
- }
2819
-
2820
- .${p}load-more-button:disabled {
2821
- opacity: 0.5;
2822
- cursor: not-allowed;
2823
- }
2824
-
2825
- /* Busy State */
2826
- .${p}busy-bucket {
2827
- padding: 16px;
2828
- text-align: center;
2829
- color: #666;
2830
- }
2831
-
2832
- .${p}spinner {
2833
- display: inline-block;
2834
- width: 20px;
2835
- height: 20px;
2836
- border: 2px solid #ccc;
2837
- border-top-color: #1976d2;
2838
- border-radius: 50%;
2839
- animation: ${p}spin 0.6s linear infinite;
2840
- }
2841
-
2842
- @keyframes ${p}spin {
2843
- to { transform: rotate(360deg); }
2844
- }
2845
-
2846
- /* Empty State */
2847
- .${p}empty-state {
2848
- padding: 24px;
2849
- text-align: center;
2850
- color: #999;
2851
- }
2852
-
2853
- /* Searching State */
2854
- .${p}searching-state {
2855
- padding: 24px;
2856
- text-align: center;
2857
- color: #667eea;
2858
- font-style: italic;
2859
- animation: ${p}pulse 1.5s ease-in-out infinite;
2860
- }
2861
-
2862
- @keyframes ${p}pulse {
2863
- 0%, 100% { opacity: 1; }
2864
- 50% { opacity: 0.5; }
2865
- }
2866
-
2867
- /* Error states */
2868
- .${p}input[aria-invalid="true"] {
2869
- border-color: #dc2626;
2870
- }
2871
-
2872
- .${p}input[aria-invalid="true"]:focus {
2873
- border-color: #dc2626;
2874
- box-shadow: 0 0 0 2px rgba(220, 38, 38, 0.1);
2875
- outline-color: #dc2626;
2876
- }
2877
-
2878
- /* Live Region (Screen reader only) */
2879
- .${p}live-region {
2880
- position: absolute;
2881
- left: -10000px;
2882
- width: 1px;
2883
- height: 1px;
2884
- overflow: hidden;
2885
- clip: rect(0, 0, 0, 0);
2886
- white-space: nowrap;
2887
- border-width: 0;
2888
- }
2889
-
2890
- /* Accessibility: Reduced motion */
2891
- @media (prefers-reduced-motion: reduce) {
2892
- .${p}arrow,
2893
- .${p}badge-remove,
2894
- .${p}option,
2895
- .${p}dropdown {
2896
- animation-duration: 0.01ms !important;
2897
- animation-iteration-count: 1 !important;
2898
- transition-duration: 0.01ms !important;
2899
- }
2900
- }
2901
-
2902
- /* Touch targets (WCAG 2.5.5) */
2903
- .${p}load-more-button,
2904
- .${p}option {
2905
- min-height: 44px;
2906
- }
2907
- `;
2908
- // Safely append to document head (check if document is ready and not already appended)
2909
- if (document.head && !this._styleElement.parentNode) {
2910
- try {
2911
- document.head.appendChild(this._styleElement);
2912
- }
2913
- catch (e) {
2914
- console.warn('[AngularEnhancedSelect] Could not inject styles:', e);
2915
- // Fallback: inject after a delay
2916
- setTimeout(() => {
2917
- try {
2918
- if (this._styleElement && !this._styleElement.parentNode) {
2919
- document.head.appendChild(this._styleElement);
2920
- }
2921
- }
2922
- catch (err) {
2923
- console.error('[AngularEnhancedSelect] Style injection failed:', err);
2924
- }
2925
- }, 0);
2926
- }
2927
- }
2928
- }
2929
- _createContainer() {
2930
- const container = document.createElement('div');
2931
- container.className = `${this.PREFIX}container`;
2932
- return container;
2933
- }
2934
- _createInputContainer() {
2935
- const container = document.createElement('div');
2936
- container.className = `${this.PREFIX}input-container`;
2937
- return container;
2938
- }
2939
- _createInput() {
2940
- const input = document.createElement('input');
2941
- input.type = 'text';
2942
- input.className = `${this.PREFIX}input`;
2943
- input.placeholder = this.getAttribute('placeholder') || 'Select an option...';
2944
- input.setAttribute('readonly', '');
2945
- input.setAttribute('role', 'combobox');
2946
- input.setAttribute('aria-expanded', 'false');
2947
- input.setAttribute('aria-haspopup', 'listbox');
2948
- input.setAttribute('aria-autocomplete', 'none');
2949
- input.setAttribute('aria-controls', `${this._uniqueId}-listbox`);
2950
- input.setAttribute('aria-owns', `${this._uniqueId}-listbox`);
2951
- input.tabIndex = 0;
2952
- return input;
2953
- }
2954
- _createArrowContainer() {
2955
- const container = document.createElement('div');
2956
- container.className = `${this.PREFIX}arrow-container`;
2957
- const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
2958
- svg.setAttribute('class', `${this.PREFIX}arrow`);
2959
- svg.setAttribute('width', '16');
2960
- svg.setAttribute('height', '16');
2961
- svg.setAttribute('viewBox', '0 0 16 16');
2962
- svg.setAttribute('fill', 'none');
2963
- const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
2964
- path.setAttribute('d', 'M4 6l4 4 4-4');
2965
- path.setAttribute('stroke', 'currentColor');
2966
- path.setAttribute('stroke-width', '2');
2967
- path.setAttribute('stroke-linecap', 'round');
2968
- path.setAttribute('stroke-linejoin', 'round');
2969
- svg.appendChild(path);
2970
- container.appendChild(svg);
2971
- return container;
2972
- }
2973
- _createDropdown() {
2974
- const dropdown = document.createElement('div');
2975
- dropdown.id = `${this._uniqueId}-listbox`;
2976
- dropdown.className = `${this.PREFIX}dropdown`;
2977
- dropdown.style.display = 'none';
2978
- dropdown.setAttribute('role', 'listbox');
2979
- return dropdown;
2980
- }
2981
- _createOptionsContainer() {
2982
- const container = document.createElement('div');
2983
- container.className = `${this.PREFIX}options-container`;
2984
- return container;
2985
- }
2986
- _createLiveRegion() {
2987
- const region = document.createElement('div');
2988
- region.className = `${this.PREFIX}live-region`;
2989
- region.setAttribute('role', 'status');
2990
- region.setAttribute('aria-live', 'polite');
2991
- region.setAttribute('aria-atomic', 'true');
2992
- return region;
2993
- }
2994
- _assembleDOM() {
2995
- // Assemble in light DOM
2996
- this._inputContainer.appendChild(this._input);
2997
- this._inputContainer.appendChild(this._arrowContainer);
2998
- this._container.appendChild(this._inputContainer);
2999
- this._dropdown.appendChild(this._optionsContainer);
3000
- this._container.appendChild(this._dropdown);
3001
- this._container.appendChild(this._liveRegion);
3002
- this.appendChild(this._container);
3003
- }
3004
- _attachEventListeners() {
3005
- // Arrow click handler
3006
- if (this._arrowContainer) {
3007
- this._boundArrowClick = (e) => {
3008
- e.stopPropagation();
3009
- e.preventDefault();
3010
- const wasOpen = this._state.isOpen;
3011
- this._state.isOpen = !this._state.isOpen;
3012
- this._updateDropdownVisibility();
3013
- this._updateArrowRotation();
3014
- if (this._state.isOpen && this._config.callbacks.onOpen) {
3015
- this._config.callbacks.onOpen();
3016
- }
3017
- else if (!this._state.isOpen && this._config.callbacks.onClose) {
3018
- this._config.callbacks.onClose();
3019
- }
3020
- if (!wasOpen && this._state.isOpen && this._state.selectedIndices.size > 0) {
3021
- setTimeout(() => this._scrollToSelected(), 50);
3022
- }
3023
- };
3024
- this._arrowContainer.addEventListener('click', this._boundArrowClick);
3025
- }
3026
- // Input focus handler
3027
- this._input.addEventListener('focus', () => {
3028
- if (!this._state.isOpen) {
3029
- this._state.isOpen = true;
3030
- this._updateDropdownVisibility();
3031
- this._updateArrowRotation();
3032
- if (this._config.callbacks.onOpen) {
3033
- this._config.callbacks.onOpen();
3034
- }
3035
- }
3036
- });
3037
- // Input keyboard handler
3038
- this._input.addEventListener('keydown', (e) => this._handleKeydown(e));
3039
- // Click outside to close
3040
- document.addEventListener('click', (e) => {
3041
- if (!this.contains(e.target) && this._state.isOpen) {
3042
- this._state.isOpen = false;
3043
- this._updateDropdownVisibility();
3044
- this._updateArrowRotation();
3045
- if (this._config.callbacks.onClose) {
3046
- this._config.callbacks.onClose();
3047
- }
3048
- }
3049
- });
3050
- // Search handler
3051
- if (this.hasAttribute('searchable')) {
3052
- this._input.removeAttribute('readonly');
3053
- this._input.addEventListener('input', (e) => {
3054
- const query = e.target.value;
3055
- this._handleSearch(query);
3056
- });
3057
- }
3058
- }
3059
- _initializeObservers() {
3060
- // Resize observer for dropdown positioning
3061
- if (typeof ResizeObserver !== 'undefined') {
3062
- this._resizeObserver = new ResizeObserver(() => {
3063
- if (this._state.isOpen) {
3064
- this._updateDropdownPosition();
3065
- }
3066
- });
3067
- this._resizeObserver.observe(this);
3068
- }
3069
- }
3070
- _updateDropdownVisibility() {
3071
- if (this._state.isOpen) {
3072
- this._dropdown.style.display = 'block';
3073
- this._input.setAttribute('aria-expanded', 'true');
3074
- this._updateDropdownPosition();
3075
- }
3076
- else {
3077
- this._dropdown.style.display = 'none';
3078
- this._input.setAttribute('aria-expanded', 'false');
3079
- }
3080
- }
3081
- _updateDropdownPosition() {
3082
- // Ensure dropdown is positioned correctly relative to input
3083
- const rect = this._inputContainer.getBoundingClientRect();
3084
- const viewportHeight = window.innerHeight;
3085
- const spaceBelow = viewportHeight - rect.bottom;
3086
- const spaceAbove = rect.top;
3087
- // Auto placement
3088
- if (spaceBelow < 300 && spaceAbove > spaceBelow) {
3089
- // Open upward
3090
- this._dropdown.style.top = 'auto';
3091
- this._dropdown.style.bottom = '100%';
3092
- this._dropdown.style.marginTop = '0';
3093
- this._dropdown.style.marginBottom = '4px';
3094
- }
3095
- else {
3096
- // Open downward (default)
3097
- this._dropdown.style.top = '100%';
3098
- this._dropdown.style.bottom = 'auto';
3099
- this._dropdown.style.marginTop = '4px';
3100
- this._dropdown.style.marginBottom = '0';
3101
- }
3102
- }
3103
- _updateArrowRotation() {
3104
- const arrow = this._arrowContainer?.querySelector(`.${this.PREFIX}arrow`);
3105
- if (arrow) {
3106
- if (this._state.isOpen) {
3107
- arrow.classList.add(`${this.PREFIX}open`);
3108
- }
3109
- else {
3110
- arrow.classList.remove(`${this.PREFIX}open`);
3111
- }
3112
- }
3113
- }
3114
- _handleKeydown(e) {
3115
- // Implement keyboard navigation
3116
- switch (e.key) {
3117
- case 'ArrowDown':
3118
- e.preventDefault();
3119
- if (!this._state.isOpen) {
3120
- this._state.isOpen = true;
3121
- this._updateDropdownVisibility();
3122
- this._updateArrowRotation();
3123
- }
3124
- else {
3125
- this._moveActive(1);
3126
- }
3127
- break;
3128
- case 'ArrowUp':
3129
- e.preventDefault();
3130
- if (this._state.isOpen) {
3131
- this._moveActive(-1);
3132
- }
3133
- break;
3134
- case 'Enter':
3135
- e.preventDefault();
3136
- if (this._state.isOpen && this._state.activeIndex >= 0) {
3137
- this._selectByIndex(this._state.activeIndex);
3138
- }
3139
- else {
3140
- this._state.isOpen = true;
3141
- this._updateDropdownVisibility();
3142
- this._updateArrowRotation();
3143
- }
3144
- break;
3145
- case 'Escape':
3146
- e.preventDefault();
3147
- if (this._state.isOpen) {
3148
- this._state.isOpen = false;
3149
- this._updateDropdownVisibility();
3150
- this._updateArrowRotation();
3151
- }
3152
- break;
3153
- case 'Tab':
3154
- if (this._state.isOpen) {
3155
- this._state.isOpen = false;
3156
- this._updateDropdownVisibility();
3157
- this._updateArrowRotation();
3158
- }
3159
- break;
3160
- }
3161
- }
3162
- _moveActive(direction) {
3163
- const options = this._optionsContainer.querySelectorAll(`.${this.PREFIX}option`);
3164
- if (options.length === 0)
3165
- return;
3166
- let newIndex = this._state.activeIndex + direction;
3167
- if (newIndex < 0)
3168
- newIndex = 0;
3169
- if (newIndex >= options.length)
3170
- newIndex = options.length - 1;
3171
- this._state.activeIndex = newIndex;
3172
- // Update visual active state
3173
- options.forEach((opt, idx) => {
3174
- if (idx === newIndex) {
3175
- opt.classList.add(`${this.PREFIX}active`);
3176
- opt.scrollIntoView({ block: 'nearest' });
3177
- }
3178
- else {
3179
- opt.classList.remove(`${this.PREFIX}active`);
3180
- }
3181
- });
3182
- }
3183
- _selectByIndex(index) {
3184
- const item = this._state.loadedItems[index];
3185
- if (!item)
3186
- return;
3187
- const isMultiple = this.hasAttribute('multiple');
3188
- if (isMultiple) {
3189
- // Toggle selection
3190
- if (this._state.selectedIndices.has(index)) {
3191
- this._state.selectedIndices.delete(index);
3192
- this._state.selectedItems.delete(index);
3193
- }
3194
- else {
3195
- this._state.selectedIndices.add(index);
3196
- this._state.selectedItems.set(index, item);
3197
- }
3198
- }
3199
- else {
3200
- // Single selection
3201
- this._state.selectedIndices.clear();
3202
- this._state.selectedItems.clear();
3203
- this._state.selectedIndices.add(index);
3204
- this._state.selectedItems.set(index, item);
3205
- // Close dropdown
3206
- this._state.isOpen = false;
3207
- this._updateDropdownVisibility();
3208
- this._updateArrowRotation();
3209
- }
3210
- this._updateInputDisplay();
3211
- this._renderOptions();
3212
- this._emitChangeEvent();
3213
- }
3214
- _updateInputDisplay() {
3215
- const selectedItems = Array.from(this._state.selectedItems.values());
3216
- const isMultiple = this.hasAttribute('multiple');
3217
- if (isMultiple) {
3218
- // Clear input, show badges
3219
- this._input.value = '';
3220
- // Remove existing badges
3221
- this._inputContainer.querySelectorAll(`.${this.PREFIX}badge`).forEach(badge => badge.remove());
3222
- // Add new badges
3223
- selectedItems.forEach((item, idx) => {
3224
- const badge = document.createElement('span');
3225
- badge.className = `${this.PREFIX}badge`;
3226
- badge.textContent = item.label;
3227
- const removeBtn = document.createElement('button');
3228
- removeBtn.className = `${this.PREFIX}badge-remove`;
3229
- removeBtn.textContent = '×';
3230
- removeBtn.addEventListener('click', (e) => {
3231
- e.stopPropagation();
3232
- const itemIndex = Array.from(this._state.selectedItems.keys())[idx];
3233
- this._state.selectedIndices.delete(itemIndex);
3234
- this._state.selectedItems.delete(itemIndex);
3235
- this._updateInputDisplay();
3236
- this._renderOptions();
3237
- this._emitChangeEvent();
3238
- });
3239
- badge.appendChild(removeBtn);
3240
- this._inputContainer.insertBefore(badge, this._input);
3241
- });
3242
- }
3243
- else {
3244
- // Single selection - show label in input
3245
- if (selectedItems.length > 0) {
3246
- this._input.value = selectedItems[0].label;
3247
- }
3248
- else {
3249
- this._input.value = '';
3250
- }
3251
- }
3252
- }
3253
- _renderOptions() {
3254
- // Clear existing options
3255
- this._optionsContainer.innerHTML = '';
3256
- const items = this._state.loadedItems;
3257
- if (items.length === 0) {
3258
- const emptyDiv = document.createElement('div');
3259
- emptyDiv.className = `${this.PREFIX}empty-state`;
3260
- emptyDiv.textContent = 'No options available';
3261
- this._optionsContainer.appendChild(emptyDiv);
3262
- return;
3263
- }
3264
- // Render options
3265
- items.forEach((item, index) => {
3266
- const optionDiv = document.createElement('div');
3267
- optionDiv.className = `${this.PREFIX}option`;
3268
- optionDiv.textContent = item.label;
3269
- optionDiv.setAttribute('role', 'option');
3270
- optionDiv.setAttribute('data-index', String(index));
3271
- if (this._state.selectedIndices.has(index)) {
3272
- optionDiv.classList.add(`${this.PREFIX}selected`);
3273
- optionDiv.setAttribute('aria-selected', 'true');
3274
- }
3275
- if (item.disabled) {
3276
- optionDiv.style.opacity = '0.5';
3277
- optionDiv.style.cursor = 'not-allowed';
3278
- }
3279
- else {
3280
- optionDiv.addEventListener('click', () => {
3281
- this._selectByIndex(index);
3282
- });
3283
- }
3284
- this._optionsContainer.appendChild(optionDiv);
3285
- });
3286
- }
3287
- _handleSearch(query) {
3288
- this._state.searchQuery = query;
3289
- // Filter items based on search
3290
- const allItems = this._state.loadedItems;
3291
- const filtered = allItems.filter(item => item.label.toLowerCase().includes(query.toLowerCase()));
3292
- // Temporarily replace loaded items with filtered
3293
- this._state.loadedItems;
3294
- this._state.loadedItems = filtered;
3295
- this._renderOptions();
3296
- // Emit search event
3297
- this.dispatchEvent(new CustomEvent('search', {
3298
- detail: { query },
3299
- bubbles: true,
3300
- composed: true,
3301
- }));
3302
- }
3303
- _emitChangeEvent() {
3304
- const selectedItems = Array.from(this._state.selectedItems.values());
3305
- const selectedValues = selectedItems.map(item => item.value);
3306
- const selectedIndices = Array.from(this._state.selectedIndices);
3307
- this.dispatchEvent(new CustomEvent('change', {
3308
- detail: { selectedItems, selectedValues, selectedIndices },
3309
- bubbles: true,
3310
- composed: true,
3311
- }));
3312
- }
3313
- _scrollToSelected() {
3314
- const firstSelected = this._optionsContainer.querySelector(`.${this.PREFIX}selected`);
3315
- if (firstSelected) {
3316
- firstSelected.scrollIntoView({ block: 'nearest' });
3317
- }
3318
- }
3319
- _loadInitialSelectedItems() {
3320
- // Placeholder for server-side data loading
3321
- }
3322
- _announce(message) {
3323
- if (this._liveRegion) {
3324
- this._liveRegion.textContent = message;
3325
- setTimeout(() => {
3326
- if (this._liveRegion)
3327
- this._liveRegion.textContent = '';
3328
- }, 1000);
3329
- }
3330
- }
3331
- // Public API methods
3332
- isReady() {
3333
- return this._isReady;
3334
- }
3335
- setItems(items) {
3336
- this._state.loadedItems = items;
3337
- this._renderOptions();
3338
- }
3339
- setGroupedItems(groups) {
3340
- this._state.groupedItems = groups;
3341
- // Flatten for now
3342
- const items = [];
3343
- groups.forEach(group => {
3344
- if (group.items) {
3345
- items.push(...group.items);
3346
- }
3347
- });
3348
- this.setItems(items);
3349
- }
3350
- setSelectedValues(values) {
3351
- this._state.selectedIndices.clear();
3352
- this._state.selectedItems.clear();
3353
- values.forEach(value => {
3354
- const index = this._state.loadedItems.findIndex(item => item.value === value);
3355
- if (index >= 0) {
3356
- this._state.selectedIndices.add(index);
3357
- this._state.selectedItems.set(index, this._state.loadedItems[index]);
3358
- }
3359
- });
3360
- this._updateInputDisplay();
3361
- this._renderOptions();
3362
- }
3363
- getSelectedValues() {
3364
- return Array.from(this._state.selectedItems.values()).map(item => item.value);
3365
- }
3366
- updateConfig(config) {
3367
- this._config = { ...this._config, ...config };
3368
- }
3369
- setError(message) {
3370
- this._hasError = true;
3371
- this._errorMessage = message;
3372
- this._input.setAttribute('aria-invalid', 'true');
3373
- this._announce(`Error: ${message}`);
3374
- }
3375
- clearError() {
3376
- this._hasError = false;
3377
- this._errorMessage = '';
3378
- this._input.removeAttribute('aria-invalid');
3379
- }
3380
- }
3381
- // Register the custom element
3382
- console.log('[AngularEnhancedSelect] Attempting to register custom element...');
3383
- console.log('[AngularEnhancedSelect] customElements available:', typeof customElements !== 'undefined');
3384
- console.log('[AngularEnhancedSelect] Already registered:', customElements?.get('angular-enhanced-select'));
3385
- if (typeof customElements !== 'undefined' && !customElements.get('angular-enhanced-select')) {
3386
- customElements.define('angular-enhanced-select', AngularEnhancedSelect);
3387
- console.log('[AngularEnhancedSelect] Successfully registered custom element');
3388
- }
3389
- else if (customElements?.get('angular-enhanced-select')) {
3390
- console.log('[AngularEnhancedSelect] Custom element already registered');
3391
- }
3392
-
3393
2919
  /**
3394
2920
  * Independent Option Component
3395
2921
  * High cohesion, low coupling - handles its own selection state and events
@@ -4652,12 +4178,13 @@ function warnCSPViolation(feature, fallback) {
4652
4178
  }
4653
4179
  }
4654
4180
 
4655
- exports.AngularEnhancedSelect = AngularEnhancedSelect;
4656
4181
  exports.CSPFeatures = CSPFeatures;
4182
+ exports.CustomOptionPool = CustomOptionPool;
4657
4183
  exports.DOMPool = DOMPool;
4658
4184
  exports.EnhancedSelect = EnhancedSelect;
4659
4185
  exports.FenwickTree = FenwickTree;
4660
4186
  exports.NativeSelectElement = NativeSelectElement;
4187
+ exports.OptionRenderer = OptionRenderer;
4661
4188
  exports.PerformanceTelemetry = PerformanceTelemetry;
4662
4189
  exports.SelectOption = SelectOption;
4663
4190
  exports.Virtualizer = Virtualizer;