@smilodon/core 1.9.2 → 1.10.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.
Files changed (52) hide show
  1. package/README.md +10 -6
  2. package/dist/index.cjs +2488 -436
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.js +2473 -437
  5. package/dist/index.js.map +1 -1
  6. package/dist/index.min.js +1 -1
  7. package/dist/index.min.js.map +1 -1
  8. package/dist/index.umd.js +2488 -436
  9. package/dist/index.umd.js.map +1 -1
  10. package/dist/index.umd.min.js +1 -1
  11. package/dist/index.umd.min.js.map +1 -1
  12. package/dist/types/src/components/enhanced-select.d.ts +114 -1
  13. package/dist/types/src/components/native-select.d.ts +2 -1
  14. package/dist/types/src/config/global-config.d.ts +2 -2
  15. package/dist/types/src/engine/accessibility.d.ts +109 -0
  16. package/dist/types/src/engine/contracts.d.ts +4 -0
  17. package/dist/types/src/engine/index.d.ts +9 -0
  18. package/dist/types/src/engine/item-adapter.d.ts +23 -0
  19. package/dist/types/src/engine/item-registry.d.ts +31 -0
  20. package/dist/types/src/engine/select-effects.d.ts +20 -0
  21. package/dist/types/src/engine/select-events.d.ts +55 -0
  22. package/dist/types/src/engine/select-machine.d.ts +9 -0
  23. package/dist/types/src/engine/select-state.d.ts +17 -0
  24. package/dist/types/src/engine/selection-policy.d.ts +33 -0
  25. package/dist/types/src/engine/selectors.d.ts +10 -0
  26. package/dist/types/src/engine/virtualization.d.ts +56 -0
  27. package/dist/types/src/index.d.ts +4 -0
  28. package/dist/types/src/platform/web/accessibility-effects.d.ts +19 -0
  29. package/dist/types/src/platform/web/index.d.ts +2 -0
  30. package/dist/types/src/platform/web/select-effect-runner.d.ts +15 -0
  31. package/dist/types/src/platform/web/select-engine-bridge.d.ts +10 -0
  32. package/dist/types/src/utils/custom-option-pool.d.ts +3 -4
  33. package/dist/types/src/utils/data-source.d.ts +7 -2
  34. package/dist/types/src/utils/dom-pool.d.ts +1 -0
  35. package/dist/types/src/utils/telemetry.d.ts +2 -2
  36. package/dist/types/src/utils/virtualizer.d.ts +50 -1
  37. package/dist/types/tests/accessibility-contract.spec.d.ts +1 -0
  38. package/dist/types/tests/enhanced-select-accessibility-integration.spec.d.ts +1 -0
  39. package/dist/types/tests/enhanced-select-active-authority.spec.d.ts +1 -0
  40. package/dist/types/tests/enhanced-select-active-parity.spec.d.ts +1 -0
  41. package/dist/types/tests/enhanced-select-authority.spec.d.ts +1 -0
  42. package/dist/types/tests/enhanced-select-compatibility-projection.spec.d.ts +1 -0
  43. package/dist/types/tests/enhanced-select-selection-parity.spec.d.ts +1 -0
  44. package/dist/types/tests/enhanced-select-virtualization-integration.spec.d.ts +1 -0
  45. package/dist/types/tests/item-adapter.spec.d.ts +1 -0
  46. package/dist/types/tests/item-registry.spec.d.ts +1 -0
  47. package/dist/types/tests/memory-lifecycle.spec.d.ts +1 -0
  48. package/dist/types/tests/select-accessibility.spec.d.ts +1 -0
  49. package/dist/types/tests/select-selection.spec.d.ts +1 -0
  50. package/dist/types/tests/virtualization-contract.spec.d.ts +1 -0
  51. package/dist/types/tests/web-accessibility-effects.spec.d.ts +1 -0
  52. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -40,6 +40,530 @@ function renderTemplate(container, items, optionTemplate) {
40
40
  container.replaceChildren(frag);
41
41
  }
42
42
 
43
+ const objectKeyCache = new WeakMap();
44
+ let generatedObjectKeyId = 0;
45
+ function isObjectRecord(value) {
46
+ return value !== null && (typeof value === 'object' || typeof value === 'function');
47
+ }
48
+ function readField(item, field) {
49
+ if (!field || !isObjectRecord(item))
50
+ return undefined;
51
+ return item[field];
52
+ }
53
+ function toSelectKey(value) {
54
+ if (typeof value === 'string' || typeof value === 'number') {
55
+ return value;
56
+ }
57
+ if (typeof value === 'boolean' || typeof value === 'bigint' || typeof value === 'symbol') {
58
+ return String(value);
59
+ }
60
+ return null;
61
+ }
62
+ function objectIdentityKey(item) {
63
+ const cached = objectKeyCache.get(item);
64
+ if (cached)
65
+ return cached;
66
+ generatedObjectKeyId += 1;
67
+ const key = `__smilodon-object-${generatedObjectKeyId}`;
68
+ objectKeyCache.set(item, key);
69
+ return key;
70
+ }
71
+ function indexFallbackKey(index, warn) {
72
+ const env = globalThis.process?.env?.NODE_ENV;
73
+ if (env !== 'production') {
74
+ const message = '[Smilodon Phase2] Using index as key is unstable under filtering/sorting. Provide getKey/valueField for stable selection.';
75
+ if (warn) {
76
+ warn(message);
77
+ }
78
+ else {
79
+ console.warn(message);
80
+ }
81
+ }
82
+ return `__smilodon-index-${index}`;
83
+ }
84
+ /** Generated reference keys survive reorder, but not replacement with new objects. */
85
+ function createDefaultItemAdapter(options = {}) {
86
+ return {
87
+ getKey(item, index) {
88
+ if (options.getKey) {
89
+ return options.getKey(item, index);
90
+ }
91
+ if (isObjectRecord(item)) {
92
+ const directKey = toSelectKey(item.id)
93
+ ?? toSelectKey(item.key)
94
+ ?? toSelectKey(item.value)
95
+ ?? toSelectKey(readField(item, options.valueField));
96
+ if (directKey !== null) {
97
+ return directKey;
98
+ }
99
+ if (options.getValue) {
100
+ const configuredValueKey = toSelectKey(options.getValue(item, index));
101
+ if (configuredValueKey !== null) {
102
+ return configuredValueKey;
103
+ }
104
+ }
105
+ return options.keyFallback === 'index'
106
+ ? indexFallbackKey(index, options.onIndexFallback)
107
+ : objectIdentityKey(item);
108
+ }
109
+ return String(item);
110
+ },
111
+ getValue(item, index) {
112
+ if (options.getValue) {
113
+ return options.getValue(item, index);
114
+ }
115
+ const fieldValue = readField(item, options.valueField);
116
+ if (fieldValue !== undefined) {
117
+ return fieldValue;
118
+ }
119
+ return isObjectRecord(item) && item.value !== undefined ? item.value : item;
120
+ },
121
+ getLabel(item, index) {
122
+ if (options.getLabel) {
123
+ return options.getLabel(item, index);
124
+ }
125
+ const fieldLabel = readField(item, options.labelField);
126
+ if (fieldLabel !== undefined) {
127
+ return String(fieldLabel);
128
+ }
129
+ if (isObjectRecord(item) && item.label !== undefined) {
130
+ return String(item.label);
131
+ }
132
+ if (isObjectRecord(item) && item.text !== undefined) {
133
+ return String(item.text);
134
+ }
135
+ return String(item);
136
+ },
137
+ isDisabled(item, index) {
138
+ if (options.isDisabled) {
139
+ return options.isDisabled(item, index);
140
+ }
141
+ return Boolean(isObjectRecord(item) && item.disabled);
142
+ },
143
+ getGroupKey(item, index) {
144
+ if (options.getGroupKey) {
145
+ return options.getGroupKey(item, index);
146
+ }
147
+ if (!isObjectRecord(item) || item.group === undefined) {
148
+ return null;
149
+ }
150
+ return item.group == null ? null : String(item.group);
151
+ },
152
+ };
153
+ }
154
+
155
+ function getDefaultDuplicateKeyPolicy() {
156
+ const env = globalThis.process?.env?.NODE_ENV;
157
+ return env === 'production' ? 'warn' : 'throw';
158
+ }
159
+ function createItemRegistry(items, adapter, options = {}) {
160
+ const duplicateKeyPolicy = options.duplicateKeyPolicy ?? getDefaultDuplicateKeyPolicy();
161
+ const records = [];
162
+ const keyToRecord = new Map();
163
+ const indexToKey = new Map();
164
+ const keyToIndex = new Map();
165
+ const firstIndexByKey = new Map();
166
+ const duplicateKeys = [];
167
+ items.forEach((item, index) => {
168
+ const key = adapter.getKey(item, index);
169
+ const firstIndex = firstIndexByKey.get(key);
170
+ const record = {
171
+ key,
172
+ item,
173
+ index,
174
+ label: adapter.getLabel(item, index),
175
+ value: adapter.getValue(item, index),
176
+ disabled: adapter.isDisabled?.(item, index) === true,
177
+ groupKey: adapter.getGroupKey?.(item, index) ?? null,
178
+ };
179
+ records.push(record);
180
+ indexToKey.set(index, key);
181
+ if (firstIndex !== undefined) {
182
+ const diagnostic = {
183
+ key,
184
+ firstIndex,
185
+ duplicateIndex: index,
186
+ };
187
+ duplicateKeys.push(diagnostic);
188
+ if (duplicateKeyPolicy === 'throw') {
189
+ throw new Error(duplicateKeyMessage(diagnostic));
190
+ }
191
+ if (duplicateKeyPolicy === 'warn') {
192
+ if (options.onDuplicateKey) {
193
+ options.onDuplicateKey(diagnostic);
194
+ }
195
+ else {
196
+ console.warn(duplicateKeyMessage(diagnostic));
197
+ }
198
+ return;
199
+ }
200
+ if (duplicateKeyPolicy === 'first-wins') {
201
+ return;
202
+ }
203
+ }
204
+ else {
205
+ firstIndexByKey.set(key, index);
206
+ }
207
+ keyToRecord.set(key, record);
208
+ keyToIndex.set(key, index);
209
+ });
210
+ return {
211
+ records,
212
+ keyToRecord,
213
+ indexToKey,
214
+ keyToIndex,
215
+ duplicateKeys,
216
+ };
217
+ }
218
+ function duplicateKeyMessage(diagnostic) {
219
+ return `[Smilodon Phase2] Duplicate item key "${String(diagnostic.key)}" at indexes ${diagnostic.firstIndex} and ${diagnostic.duplicateIndex}. Provide stable unique keys for selection.`;
220
+ }
221
+
222
+ /** Pure key policy. Visibility does not constrain selection; disabled keys do. */
223
+ function applySelectionRequest(selectedKeys, request, config) {
224
+ let next;
225
+ switch (request.type) {
226
+ case 'select':
227
+ next = selectKey(selectedKeys, request.key, config);
228
+ break;
229
+ case 'deselect':
230
+ next = deselectKey(selectedKeys, request.key, config);
231
+ break;
232
+ case 'toggle':
233
+ if (!selectedKeys.has(request.key)) {
234
+ next = selectKey(selectedKeys, request.key, config);
235
+ }
236
+ else if (config.multiple || config.allowDeselect) {
237
+ next = deselectKey(selectedKeys, request.key, config);
238
+ }
239
+ else {
240
+ next = selectedKeys;
241
+ }
242
+ break;
243
+ case 'clear':
244
+ next = config.required && selectedKeys.size > 0
245
+ ? selectedKeys
246
+ : new Set();
247
+ break;
248
+ case 'replace':
249
+ next = replaceKeys(selectedKeys, request.keys, config);
250
+ break;
251
+ }
252
+ // Set membership is authoritative. Reordering the same keys is not a change.
253
+ return next.size === selectedKeys.size && [...next].every((key) => selectedKeys.has(key))
254
+ ? selectedKeys
255
+ : next;
256
+ }
257
+ function selectKey(selectedKeys, key, config) {
258
+ if (config.disabledKeys.has(key)) {
259
+ return selectedKeys;
260
+ }
261
+ if (!config.multiple) {
262
+ return new Set([key]);
263
+ }
264
+ if (selectedKeys.has(key)) {
265
+ return selectedKeys;
266
+ }
267
+ const maxSelections = config.maxSelections ?? 0;
268
+ if (maxSelections > 0 && selectedKeys.size >= maxSelections) {
269
+ return selectedKeys;
270
+ }
271
+ return new Set([...selectedKeys, key]);
272
+ }
273
+ function deselectKey(selectedKeys, key, config) {
274
+ if (!selectedKeys.has(key) || config.disabledKeys.has(key)) {
275
+ return selectedKeys;
276
+ }
277
+ if (config.required && selectedKeys.size <= 1) {
278
+ return selectedKeys;
279
+ }
280
+ const next = new Set(selectedKeys);
281
+ next.delete(key);
282
+ return next;
283
+ }
284
+ function replaceKeys(selectedKeys, keys, config) {
285
+ const next = normalizeKeys(keys, config);
286
+ if (config.required && next.size === 0 && selectedKeys.size > 0) {
287
+ // Required preserves a valid selection, but cannot keep newly disabled keys.
288
+ return normalizeKeys(selectedKeys, config);
289
+ }
290
+ return next;
291
+ }
292
+ function normalizeKeys(keys, config) {
293
+ const seen = new Set();
294
+ const maxSelections = config.maxSelections ?? 0;
295
+ for (const key of keys) {
296
+ if (config.disabledKeys.has(key) || seen.has(key)) {
297
+ continue;
298
+ }
299
+ seen.add(key);
300
+ if (!config.multiple || (maxSelections > 0 && seen.size >= maxSelections)) {
301
+ break;
302
+ }
303
+ }
304
+ return seen;
305
+ }
306
+
307
+ function transition(state, event) {
308
+ switch (event.type) {
309
+ case 'CONNECT':
310
+ return { state: { ...state, lifecycle: 'connected' }, effects: [] };
311
+ case 'DISCONNECT': {
312
+ const effects = state.popup === 'open'
313
+ ? [{ type: 'POPUP_CLOSED', reason: 'disconnect' }, { type: 'SYNC_ARIA' }]
314
+ : [];
315
+ return {
316
+ state: { ...state, lifecycle: 'disconnected', popup: 'closed', focused: false },
317
+ effects,
318
+ };
319
+ }
320
+ case 'OPEN_REQUEST':
321
+ if (state.lifecycle !== 'connected' || state.disabled || state.popup === 'open') {
322
+ return { state: enforceInvariants(state), effects: [] };
323
+ }
324
+ return {
325
+ state: { ...state, popup: 'open' },
326
+ effects: [{ type: 'POPUP_OPENED' }, { type: 'FOCUS_TRIGGER' }, { type: 'SYNC_ARIA' }],
327
+ };
328
+ case 'CLOSE_REQUEST':
329
+ if (state.popup === 'closed') {
330
+ return { state, effects: [] };
331
+ }
332
+ return {
333
+ state: { ...state, popup: 'closed' },
334
+ effects: [{ type: 'POPUP_CLOSED', reason: event.reason }, { type: 'SYNC_ARIA' }],
335
+ };
336
+ case 'TOGGLE_REQUEST':
337
+ return transition(state, state.popup === 'open'
338
+ ? { type: 'CLOSE_REQUEST', reason: 'programmatic' }
339
+ : { type: 'OPEN_REQUEST' });
340
+ case 'FOCUS_GAINED':
341
+ return state.focused
342
+ ? { state, effects: [] }
343
+ : { state: { ...state, focused: true }, effects: [{ type: 'SYNC_ARIA' }] };
344
+ case 'FOCUS_LOST':
345
+ return state.focused
346
+ ? { state: { ...state, focused: false }, effects: [{ type: 'SYNC_ARIA' }] }
347
+ : { state, effects: [] };
348
+ case 'DISABLED_CHANGED': {
349
+ if (state.disabled === event.disabled) {
350
+ return { state: enforceInvariants(state), effects: [] };
351
+ }
352
+ const nextState = enforceInvariants({ ...state, disabled: event.disabled });
353
+ const effects = [];
354
+ if (event.disabled && state.popup === 'open') {
355
+ effects.push({ type: 'POPUP_CLOSED', reason: 'disabled' });
356
+ }
357
+ effects.push({ type: 'SYNC_ARIA' });
358
+ return {
359
+ state: nextState,
360
+ effects,
361
+ };
362
+ }
363
+ case 'ITEMS_REGISTERED': {
364
+ const registeredKeys = new Set(event.keys);
365
+ const disabledKeys = new Set(event.disabledKeys ?? []);
366
+ const selection = { ...state.selection, disabledKeys };
367
+ const activeKey = resolveActiveKey(state.activeKey, registeredKeys, disabledKeys);
368
+ const selectedKeys = applySelectionRequest(state.selectedKeys, { type: 'replace', keys: Array.from(state.selectedKeys)}, selection);
369
+ const nextState = {
370
+ ...state,
371
+ activeKey,
372
+ selectedKeys,
373
+ registeredKeys,
374
+ selection,
375
+ };
376
+ const effects = [];
377
+ if (!keysEqual(activeKey, state.activeKey)) {
378
+ effects.push({ type: 'ACTIVE_KEY_CHANGED', activeKey, reason: 'programmatic' });
379
+ }
380
+ if (!setsEqual(selectedKeys, state.selectedKeys)) {
381
+ effects.push({ type: 'SELECTION_CHANGED', selectedKeys: Array.from(selectedKeys), reason: 'programmatic' });
382
+ }
383
+ if (effects.length > 0) {
384
+ effects.push({ type: 'SYNC_ARIA' });
385
+ }
386
+ return { state: nextState, effects };
387
+ }
388
+ case 'SELECTION_CONFIG_CHANGED': {
389
+ const selection = {
390
+ ...state.selection,
391
+ multiple: event.multiple ?? state.selection.multiple,
392
+ required: event.required ?? state.selection.required,
393
+ allowDeselect: event.allowDeselect ?? state.selection.allowDeselect,
394
+ maxSelections: event.maxSelections ?? state.selection.maxSelections,
395
+ disabledKeys: event.disabledKeys ? new Set(event.disabledKeys) : state.selection.disabledKeys,
396
+ };
397
+ const selectedKeys = applySelectionRequest(state.selectedKeys, { type: 'replace', keys: Array.from(state.selectedKeys)}, selection);
398
+ const activeKey = resolveActiveKey(state.activeKey, state.registeredKeys, selection.disabledKeys);
399
+ const nextState = { ...state, selection, selectedKeys, activeKey };
400
+ const effects = [];
401
+ if (!keysEqual(activeKey, state.activeKey)) {
402
+ effects.push({ type: 'ACTIVE_KEY_CHANGED', activeKey, reason: 'programmatic' });
403
+ }
404
+ if (!setsEqual(selectedKeys, state.selectedKeys)) {
405
+ effects.push({ type: 'SELECTION_CHANGED', selectedKeys: Array.from(selectedKeys), reason: 'programmatic' });
406
+ }
407
+ if (effects.length > 0) {
408
+ effects.push({ type: 'SYNC_ARIA' });
409
+ }
410
+ return { state: nextState, effects };
411
+ }
412
+ case 'ACTIVE_KEY_CHANGED': {
413
+ if (event.key !== null
414
+ && (!state.registeredKeys.has(event.key) || state.selection.disabledKeys.has(event.key))) {
415
+ return { state, effects: [] };
416
+ }
417
+ if (keysEqual(state.activeKey, event.key)) {
418
+ return { state, effects: [] };
419
+ }
420
+ return {
421
+ state: { ...state, activeKey: event.key },
422
+ effects: [
423
+ { type: 'ACTIVE_KEY_CHANGED', activeKey: event.key, reason: event.reason },
424
+ { type: 'SYNC_ARIA' },
425
+ ],
426
+ };
427
+ }
428
+ case 'SELECT_KEY_REQUEST':
429
+ case 'DESELECT_KEY_REQUEST':
430
+ case 'TOGGLE_KEY_REQUEST':
431
+ case 'CLEAR_SELECTION_REQUEST':
432
+ case 'REPLACE_SELECTION_REQUEST': {
433
+ const selectedKeys = applySelectionRequest(state.selectedKeys, selectionRequestFromEvent(event), state.selection);
434
+ if (setsEqual(selectedKeys, state.selectedKeys)) {
435
+ return { state, effects: [] };
436
+ }
437
+ return {
438
+ state: { ...state, selectedKeys },
439
+ effects: [
440
+ { type: 'SELECTION_CHANGED', selectedKeys: Array.from(selectedKeys), reason: event.reason },
441
+ { type: 'SYNC_ARIA' },
442
+ ],
443
+ };
444
+ }
445
+ default:
446
+ return { state, effects: [] };
447
+ }
448
+ }
449
+ function selectionRequestFromEvent(event) {
450
+ switch (event.type) {
451
+ case 'SELECT_KEY_REQUEST':
452
+ return { type: 'select', key: event.key, reason: event.reason };
453
+ case 'DESELECT_KEY_REQUEST':
454
+ return { type: 'deselect', key: event.key, reason: event.reason };
455
+ case 'TOGGLE_KEY_REQUEST':
456
+ return { type: 'toggle', key: event.key, reason: event.reason };
457
+ case 'CLEAR_SELECTION_REQUEST':
458
+ return { type: 'clear', reason: event.reason };
459
+ case 'REPLACE_SELECTION_REQUEST':
460
+ return { type: 'replace', keys: event.keys, reason: event.reason };
461
+ }
462
+ }
463
+ function enforceInvariants(state) {
464
+ if (state.lifecycle === 'disconnected' || state.disabled) {
465
+ return state.popup === 'closed' ? state : { ...state, popup: 'closed' };
466
+ }
467
+ return state;
468
+ }
469
+ function resolveActiveKey(key, registeredKeys, disabledKeys) {
470
+ return key !== null && registeredKeys.has(key) && !disabledKeys.has(key) ? key : null;
471
+ }
472
+ function setsEqual(left, right) {
473
+ if (left.size !== right.size)
474
+ return false;
475
+ for (const value of left) {
476
+ if (!right.has(value))
477
+ return false;
478
+ }
479
+ return true;
480
+ }
481
+ /** Match Map/Set identity, including NaN and signed zero. */
482
+ function keysEqual(left, right) {
483
+ return left === right || Object.is(left, right);
484
+ }
485
+
486
+ function createInitialSelectState() {
487
+ return {
488
+ lifecycle: 'disconnected',
489
+ popup: 'closed',
490
+ disabled: false,
491
+ focused: false,
492
+ query: '',
493
+ activeKey: null,
494
+ selectedKeys: new Set(),
495
+ registeredKeys: new Set(),
496
+ selection: {
497
+ multiple: false,
498
+ required: false,
499
+ allowDeselect: false,
500
+ disabledKeys: new Set(),
501
+ maxSelections: 0,
502
+ },
503
+ dataStatus: 'idle',
504
+ };
505
+ }
506
+
507
+ function isOpen(state) {
508
+ return state.popup === 'open';
509
+ }
510
+ function isDisabled(state) {
511
+ return state.disabled;
512
+ }
513
+ function isFocused(state) {
514
+ return state.focused;
515
+ }
516
+ function hasSelection(state) {
517
+ return state.selectedKeys.size > 0;
518
+ }
519
+ function isSelected(state, key) {
520
+ return state.selectedKeys.has(key);
521
+ }
522
+ function getSelectedKeys(state) {
523
+ return Array.from(state.selectedKeys);
524
+ }
525
+ function getActiveKey(state) {
526
+ return state.activeKey;
527
+ }
528
+ function isRegisteredKey(state, key) {
529
+ return state.registeredKeys.has(key);
530
+ }
531
+
532
+ class SelectEngineBridge {
533
+ constructor(initialState = createInitialSelectState()) {
534
+ this._state = initialState;
535
+ }
536
+ get state() {
537
+ return this._state;
538
+ }
539
+ dispatch(event) {
540
+ const result = transition(this._state, event);
541
+ this._state = result.state;
542
+ return result.effects;
543
+ }
544
+ }
545
+
546
+ class DefaultSelectEffectRunner {
547
+ run(effects, context) {
548
+ for (const effect of effects) {
549
+ switch (effect.type) {
550
+ case 'FOCUS_TRIGGER':
551
+ context.focusTrigger?.();
552
+ break;
553
+ case 'SYNC_ARIA':
554
+ context.syncAria?.();
555
+ break;
556
+ case 'POPUP_OPENED':
557
+ context.onPopupOpened?.();
558
+ break;
559
+ case 'POPUP_CLOSED':
560
+ context.onPopupClosed?.(effect.reason);
561
+ break;
562
+ }
563
+ }
564
+ }
565
+ }
566
+
43
567
  /**
44
568
  * Fenwick Tree (Binary Indexed Tree) for O(log n) prefix sum queries and updates.
45
569
  * Used for cumulative height calculations in variable-height virtualization.
@@ -243,6 +767,10 @@ class DOMPool {
243
767
  if (poolNode) {
244
768
  poolNode.inUse = false;
245
769
  poolNode.lastUsed = performance.now();
770
+ if (this.pool.length > this.maxSize) {
771
+ this.removePoolNode(poolNode);
772
+ return;
773
+ }
246
774
  // Aggressive cleanup
247
775
  this.reset(poolNode.node);
248
776
  }
@@ -263,12 +791,19 @@ class DOMPool {
263
791
  }
264
792
  }
265
793
  if (lruIndex >= 0) {
266
- const evicted = this.pool.splice(lruIndex, 1)[0];
267
- // Full cleanup before GC
268
- this.deepCleanup(evicted.node);
794
+ this.removePoolNode(this.pool[lruIndex]);
269
795
  if (this.telemetry)
270
796
  this.evictions++;
797
+ return true;
271
798
  }
799
+ return false;
800
+ }
801
+ removePoolNode(poolNode) {
802
+ const index = this.pool.indexOf(poolNode);
803
+ if (index < 0)
804
+ return;
805
+ const [removed] = this.pool.splice(index, 1);
806
+ this.deepCleanup(removed.node);
272
807
  }
273
808
  /**
274
809
  * Default reset: clear content, remove inline styles, remove attributes
@@ -318,7 +853,8 @@ class DOMPool {
318
853
  this.maxSize = size;
319
854
  // Evict excess nodes
320
855
  while (this.pool.length > this.maxSize) {
321
- this.evictLRU();
856
+ if (!this.evictLRU())
857
+ break;
322
858
  }
323
859
  }
324
860
  /**
@@ -353,11 +889,17 @@ class DOMPool {
353
889
  class Virtualizer {
354
890
  constructor(container, itemsLength, itemGetter, options) {
355
891
  this.measuredHeights = new Map();
892
+ this.measuredHeightTotal = 0;
356
893
  this.activeNodes = new Map(); // index -> node mapping
894
+ this.destroyed = false;
895
+ this.recycleRafId = 0;
896
+ this.intendedScrollTop = 0;
897
+ this.currentWindow = null;
357
898
  this.container = container;
358
899
  this.itemsLength = itemsLength;
359
900
  this.itemGetter = itemGetter;
360
901
  this.options = options;
902
+ this.estimatedItemHeight = options.estimatedItemHeight;
361
903
  this.averageHeight = options.estimatedItemHeight;
362
904
  // Initialize DOM pool with LRU eviction
363
905
  const maxPoolSize = Math.ceil((options.buffer * 2 + 10) * 1.5) + (options.maxPoolExtra ?? 32);
@@ -378,39 +920,121 @@ class Virtualizer {
378
920
  },
379
921
  telemetry: options.enableTelemetry || false,
380
922
  });
381
- // Use Fenwick tree for large lists (>5000 items)
382
- if (itemsLength > 5000) {
383
- this.fenwick = new FenwickTree(itemsLength);
384
- // Initialize with estimated heights
385
- for (let i = 0; i < itemsLength; i++) {
386
- this.fenwick.add(i, options.estimatedItemHeight);
387
- }
388
- }
923
+ // One prefix index keeps offset, window, and scroll calculations on the
924
+ // same measured-height policy at every list size.
925
+ this.fenwick = this.createFenwickTree(itemsLength);
389
926
  this.container.style.willChange = 'transform';
390
927
  }
391
928
  computeWindow(scrollTop, viewportHeight) {
392
929
  const { buffer } = this.options;
393
- const startIndex = Math.max(Math.floor(scrollTop / this.averageHeight) - buffer, 0);
394
- const endIndex = Math.min(Math.ceil((scrollTop + viewportHeight) / this.averageHeight) + buffer, this.itemsLength - 1);
930
+ const visibleStartIndex = this.indexAtOffset(scrollTop);
931
+ const calculatedStartIndex = visibleStartIndex - buffer;
932
+ const startIndex = this.itemsLength > 0
933
+ ? Math.max(0, Math.min(this.itemsLength - 1, calculatedStartIndex))
934
+ : 0;
935
+ const viewportEnd = Math.max(0, scrollTop + viewportHeight);
936
+ let visibleEndIndex = this.indexAtOffset(viewportEnd);
937
+ // The item beginning exactly at the viewport's lower edge is not visible.
938
+ // indexAtOffset deliberately advances across exact boundaries for the
939
+ // viewport start, so reverse that choice here when the viewport has height.
940
+ if (viewportHeight > 0
941
+ && visibleEndIndex > visibleStartIndex
942
+ && this.cumulativeOffset(visibleEndIndex) === viewportEnd) {
943
+ visibleEndIndex -= 1;
944
+ }
945
+ const calculatedEndIndex = Math.max(visibleStartIndex, visibleEndIndex) + buffer;
946
+ const endIndex = this.itemsLength > 0
947
+ ? Math.max(0, Math.min(this.itemsLength - 1, calculatedEndIndex))
948
+ : -1;
395
949
  const windowSize = Math.max(0, endIndex - startIndex + 1);
396
950
  // Adjust pool size dynamically based on window
397
951
  const newPoolSize = windowSize + (this.options.maxPoolExtra ?? 32);
398
952
  this.pool.setMaxSize(newPoolSize);
399
953
  return { startIndex, endIndex, windowSize };
400
954
  }
401
- cumulativeOffset(index) {
402
- if (index <= 0)
955
+ /** Computes and records a scroll-derived window without installing listeners. */
956
+ updateWindow(scrollTop, viewportHeight) {
957
+ if (this.destroyed)
958
+ return null;
959
+ const safeScrollTop = Number.isFinite(scrollTop) ? Math.max(0, scrollTop) : 0;
960
+ const safeViewportHeight = Number.isFinite(viewportHeight) && viewportHeight >= 0
961
+ ? viewportHeight
962
+ : 0;
963
+ const nextWindow = this.computeWindow(safeScrollTop, safeViewportHeight);
964
+ const changed = this.currentWindow === null
965
+ || this.currentWindow.startIndex !== nextWindow.startIndex
966
+ || this.currentWindow.endIndex !== nextWindow.endIndex
967
+ || this.currentWindow.windowSize !== nextWindow.windowSize;
968
+ this.currentWindow = { ...nextWindow };
969
+ return {
970
+ window: { ...nextWindow },
971
+ changed,
972
+ scrollTop: safeScrollTop,
973
+ viewportHeight: safeViewportHeight,
974
+ };
975
+ }
976
+ /** Returns a copy of the last recorded window, or null before the first update. */
977
+ getCurrentWindow() {
978
+ return this.currentWindow ? { ...this.currentWindow } : null;
979
+ }
980
+ /** Finds the item containing an offset, advancing past exact item boundaries. */
981
+ indexAtOffset(offset) {
982
+ if (this.itemsLength <= 0)
403
983
  return 0;
404
- // Use Fenwick tree for O(log n) prefix sum
405
- if (this.fenwick) {
406
- return this.fenwick.sum(index - 1);
984
+ const target = Math.max(0, offset);
985
+ let index = Math.max(0, Math.min(this.itemsLength - 1, this.fenwick.lowerBound(target)));
986
+ // FenwickTree.lowerBound returns the preceding item when the target lands
987
+ // exactly on an item boundary. For the viewport start, select the next item.
988
+ while (index < this.itemsLength - 1 && this.cumulativeOffset(index + 1) <= target) {
989
+ index += 1;
407
990
  }
408
- // Fallback: approximate using average height with sparse adjustments
409
- let total = 0;
410
- for (let i = 0; i < index; i++) {
411
- total += this.measuredHeights.get(i) ?? this.averageHeight;
991
+ return index;
992
+ }
993
+ cumulativeOffset(index) {
994
+ if (!Number.isFinite(index)) {
995
+ return index === Number.POSITIVE_INFINITY && this.itemsLength > 0
996
+ ? this.fenwick.sum(this.itemsLength - 1)
997
+ : 0;
412
998
  }
413
- return total;
999
+ const boundedIndex = Math.max(0, Math.min(this.itemsLength, Math.trunc(index)));
1000
+ if (boundedIndex === 0)
1001
+ return 0;
1002
+ return this.fenwick.sum(boundedIndex - 1);
1003
+ }
1004
+ /**
1005
+ * Calculates and records the intended scroll position for an item without
1006
+ * mutating the container. The caller may apply the returned scrollTop.
1007
+ * Returns null after destruction or when there are no items to target.
1008
+ */
1009
+ scrollToIndex(index) {
1010
+ if (this.destroyed || this.itemsLength <= 0)
1011
+ return null;
1012
+ const requestedIndex = Number.isFinite(index) ? Math.trunc(index) : 0;
1013
+ const targetIndex = Math.max(0, Math.min(this.itemsLength - 1, requestedIndex));
1014
+ const offset = this.cumulativeOffset(targetIndex);
1015
+ this.intendedScrollTop = offset;
1016
+ return { index: targetIndex, offset, scrollTop: offset };
1017
+ }
1018
+ /**
1019
+ * Resolves a stable key against the caller's current data identity, then
1020
+ * delegates to scrollToIndex(). Invalid or out-of-range resolutions are
1021
+ * rejected rather than clamped to a different item's position.
1022
+ */
1023
+ scrollToKey(key, resolveIndex) {
1024
+ if (this.destroyed || this.itemsLength <= 0)
1025
+ return null;
1026
+ const index = resolveIndex(key);
1027
+ if (typeof index !== 'number'
1028
+ || !Number.isInteger(index)
1029
+ || index < 0
1030
+ || index >= this.itemsLength) {
1031
+ return null;
1032
+ }
1033
+ return this.scrollToIndex(index);
1034
+ }
1035
+ /** Returns the last scroll position requested through scrollToIndex(). */
1036
+ getIntendedScrollTop() {
1037
+ return this.intendedScrollTop;
414
1038
  }
415
1039
  acquireNode(index) {
416
1040
  // Check if we already have this node active (reuse)
@@ -439,6 +1063,8 @@ class Virtualizer {
439
1063
  }
440
1064
  }
441
1065
  render(startIndex, endIndex, updateNode) {
1066
+ if (this.destroyed)
1067
+ return;
442
1068
  const frag = document.createDocumentFragment();
443
1069
  const activeIndices = new Set();
444
1070
  for (let i = startIndex; i <= endIndex; i++) {
@@ -447,31 +1073,51 @@ class Virtualizer {
447
1073
  frag.appendChild(node);
448
1074
  activeIndices.add(i);
449
1075
  // Measure on appear (deferred)
450
- queueMicrotask(() => this.measureOnAppear(node, i));
1076
+ queueMicrotask(() => {
1077
+ if (!this.destroyed) {
1078
+ this.measureOnAppear(node, i);
1079
+ }
1080
+ });
451
1081
  }
452
1082
  // Translate container by cumulative offset of startIndex
453
1083
  const topOffset = this.cumulativeOffset(startIndex);
454
1084
  this.container.style.transform = `translate3d(0, ${Math.round(topOffset * 100) / 100}px, 0)`;
455
1085
  this.container.replaceChildren(frag);
456
1086
  // Recycle nodes not in use
457
- requestAnimationFrame(() => this.releaseExcess(activeIndices));
1087
+ if (this.recycleRafId) {
1088
+ cancelAnimationFrame(this.recycleRafId);
1089
+ }
1090
+ this.recycleRafId = requestAnimationFrame(() => {
1091
+ this.recycleRafId = 0;
1092
+ if (!this.destroyed) {
1093
+ this.releaseExcess(activeIndices);
1094
+ }
1095
+ });
458
1096
  }
459
1097
  measureOnAppear(node, index) {
460
- const h = node.offsetHeight;
1098
+ this.measureItem(index, node.offsetHeight);
1099
+ }
1100
+ /** Records a validated measured height and updates the virtual offset index. */
1101
+ measureItem(index, height) {
1102
+ if (this.destroyed
1103
+ || !Number.isInteger(index)
1104
+ || index < 0
1105
+ || index >= this.itemsLength
1106
+ || !Number.isFinite(height)
1107
+ || height <= 0)
1108
+ return false;
461
1109
  const prev = this.measuredHeights.get(index);
462
1110
  const threshold = this.options.measurementThreshold ?? 5;
463
- if (prev === undefined || Math.abs(prev - h) > threshold) {
464
- const oldValue = prev ?? this.averageHeight;
465
- this.measuredHeights.set(index, h);
1111
+ if (prev === undefined || Math.abs(prev - height) > threshold) {
1112
+ const oldValue = prev ?? this.estimatedItemHeight;
1113
+ this.measuredHeights.set(index, height);
1114
+ this.measuredHeightTotal += height - (prev ?? 0);
466
1115
  // Update Fenwick tree with new measurement
467
- if (this.fenwick) {
468
- this.fenwick.update(index, oldValue, h);
469
- }
470
- // Update running average (weighted by measured count)
471
- const count = this.measuredHeights.size;
472
- const total = Array.from(this.measuredHeights.values()).reduce((a, b) => a + b, 0);
473
- this.averageHeight = Math.round((total / count) * 100) / 100;
1116
+ this.fenwick.update(index, oldValue, height);
1117
+ this.updateAverageHeight();
1118
+ return true;
474
1119
  }
1120
+ return false;
475
1121
  }
476
1122
  /**
477
1123
  * Get pool statistics (if telemetry enabled)
@@ -483,29 +1129,63 @@ class Virtualizer {
483
1129
  * Update items length and resize Fenwick tree if needed
484
1130
  */
485
1131
  setItemsLength(newLength) {
1132
+ const previousLength = this.itemsLength;
486
1133
  this.itemsLength = newLength;
487
- if (this.fenwick) {
488
- this.fenwick.resize(newLength);
1134
+ if (newLength !== previousLength)
1135
+ this.currentWindow = null;
1136
+ let removedMeasurement = false;
1137
+ for (const [index, height] of this.measuredHeights) {
1138
+ if (index >= newLength) {
1139
+ this.measuredHeightTotal -= height;
1140
+ this.measuredHeights.delete(index);
1141
+ removedMeasurement = true;
1142
+ }
489
1143
  }
490
- else if (newLength > 5000 && !this.fenwick) {
491
- // Activate Fenwick tree when crossing threshold
492
- this.fenwick = new FenwickTree(newLength);
493
- // Populate with existing measurements
494
- for (const [index, height] of this.measuredHeights) {
495
- this.fenwick.update(index, this.averageHeight, height);
1144
+ if (removedMeasurement)
1145
+ this.updateAverageHeight();
1146
+ for (const index of Array.from(this.activeNodes.keys())) {
1147
+ if (index >= newLength) {
1148
+ this.releaseNode(index);
496
1149
  }
497
1150
  }
1151
+ if (newLength !== previousLength) {
1152
+ this.fenwick = this.createFenwickTree(newLength);
1153
+ }
498
1154
  }
499
1155
  /**
500
1156
  * Cleanup resources
501
1157
  */
502
1158
  destroy() {
1159
+ this.destroyed = true;
1160
+ if (this.recycleRafId) {
1161
+ cancelAnimationFrame(this.recycleRafId);
1162
+ this.recycleRafId = 0;
1163
+ }
503
1164
  this.pool.clear();
504
1165
  this.activeNodes.clear();
505
1166
  this.measuredHeights.clear();
506
- if (this.fenwick) {
507
- this.fenwick.reset();
1167
+ this.measuredHeightTotal = 0;
1168
+ this.averageHeight = this.estimatedItemHeight;
1169
+ this.currentWindow = null;
1170
+ this.fenwick.reset();
1171
+ }
1172
+ updateAverageHeight() {
1173
+ const count = this.measuredHeights.size;
1174
+ this.averageHeight = count > 0
1175
+ ? Math.round((this.measuredHeightTotal / count) * 100) / 100
1176
+ : this.estimatedItemHeight;
1177
+ }
1178
+ createFenwickTree(size) {
1179
+ const tree = new FenwickTree(size);
1180
+ for (let index = 0; index < size; index++) {
1181
+ tree.add(index, this.estimatedItemHeight);
1182
+ }
1183
+ for (const [index, height] of this.measuredHeights) {
1184
+ if (index < size) {
1185
+ tree.update(index, this.estimatedItemHeight, height);
1186
+ }
508
1187
  }
1188
+ return tree;
509
1189
  }
510
1190
  }
511
1191
 
@@ -535,30 +1215,18 @@ class CustomOptionPool {
535
1215
  * @returns Component instance
536
1216
  */
537
1217
  acquire(factory, item, index, context, container) {
538
- const factoryKey = this._getFactoryKey(factory);
1218
+ this.release(index);
539
1219
  // Try to find an available component in the pool
540
- const pooled = this._findAvailableComponent(factoryKey);
1220
+ const pooled = this._findAvailableComponent(factory);
541
1221
  let component;
542
1222
  if (pooled) {
543
1223
  // Reuse pooled component
544
1224
  component = pooled.instance;
545
- pooled.inUse = true;
546
- pooled.lastUsedIndex = index;
547
1225
  }
548
1226
  else {
549
1227
  // Create new component
550
1228
  try {
551
1229
  component = factory(item, index);
552
- // Add to pool if under limit
553
- const pool = this._pool.get(factoryKey) || [];
554
- if (pool.length < this._maxPoolSize) {
555
- pool.push({
556
- instance: component,
557
- inUse: true,
558
- lastUsedIndex: index
559
- });
560
- this._pool.set(factoryKey, pool);
561
- }
562
1230
  }
563
1231
  catch (error) {
564
1232
  console.error(`[CustomOptionPool] Failed to create component:`, error);
@@ -568,9 +1236,25 @@ class CustomOptionPool {
568
1236
  // Mount the component
569
1237
  try {
570
1238
  component.mountOption(container, context);
1239
+ if (pooled) {
1240
+ pooled.inUse = true;
1241
+ pooled.lastUsedIndex = index;
1242
+ }
1243
+ else {
1244
+ this._addToPool(factory, component, index);
1245
+ }
571
1246
  this._activeComponents.set(index, component);
572
1247
  }
573
1248
  catch (error) {
1249
+ if (pooled) {
1250
+ pooled.inUse = false;
1251
+ }
1252
+ try {
1253
+ component.unmountOption();
1254
+ }
1255
+ catch {
1256
+ // ignore cleanup failures after a mount failure
1257
+ }
574
1258
  console.error(`[CustomOptionPool] Failed to mount component at index ${index}:`, error);
575
1259
  throw error;
576
1260
  }
@@ -667,18 +1351,44 @@ class CustomOptionPool {
667
1351
  /**
668
1352
  * Find an available component in the pool
669
1353
  */
670
- _findAvailableComponent(factoryKey) {
671
- const pool = this._pool.get(factoryKey);
1354
+ _findAvailableComponent(factory) {
1355
+ const pool = this._pool.get(factory);
672
1356
  if (!pool)
673
1357
  return undefined;
674
1358
  return pool.find(p => !p.inUse);
675
1359
  }
676
- /**
677
- * Generate a unique key for a factory function
678
- */
679
- _getFactoryKey(factory) {
680
- // Use function name or create a symbol
681
- return factory.name || `factory_${factory.toString().slice(0, 50)}`;
1360
+ _addToPool(factory, component, index) {
1361
+ while (this._getTotalPooled() >= this._maxPoolSize) {
1362
+ if (!this._evictAvailableComponent())
1363
+ return;
1364
+ }
1365
+ const pool = this._pool.get(factory) || [];
1366
+ pool.push({
1367
+ instance: component,
1368
+ inUse: true,
1369
+ lastUsedIndex: index
1370
+ });
1371
+ this._pool.set(factory, pool);
1372
+ }
1373
+ _evictAvailableComponent() {
1374
+ for (const [factory, pool] of this._pool.entries()) {
1375
+ const index = pool.findIndex(p => !p.inUse);
1376
+ if (index < 0)
1377
+ continue;
1378
+ pool.splice(index, 1);
1379
+ if (pool.length === 0) {
1380
+ this._pool.delete(factory);
1381
+ }
1382
+ return true;
1383
+ }
1384
+ return false;
1385
+ }
1386
+ _getTotalPooled() {
1387
+ let total = 0;
1388
+ for (const pool of this._pool.values()) {
1389
+ total += pool.length;
1390
+ }
1391
+ return total;
682
1392
  }
683
1393
  }
684
1394
 
@@ -712,6 +1422,7 @@ class OptionRenderer {
712
1422
  const value = this._config.getValue(item);
713
1423
  const label = this._config.getLabel(item);
714
1424
  const isDisabled = this._config.getDisabled ? this._config.getDisabled(item) : false;
1425
+ this.unmount(index);
715
1426
  // Determine if this is a custom component or lightweight option
716
1427
  const hasCustomComponent = extendedItem.optionComponent && typeof extendedItem.optionComponent === 'function';
717
1428
  if (hasCustomComponent) {
@@ -902,7 +1613,7 @@ class OptionRenderer {
902
1613
 
903
1614
  class NativeSelectElement extends HTMLElement {
904
1615
  static get observedAttributes() {
905
- return ['placement', 'strategy', 'portal'];
1616
+ return ["placement", "strategy", "portal"];
906
1617
  }
907
1618
  constructor() {
908
1619
  super();
@@ -913,22 +1624,23 @@ class NativeSelectElement extends HTMLElement {
913
1624
  this._selectedItems = new Map(); // index -> item
914
1625
  this._activeIndex = -1;
915
1626
  this._multi = false;
916
- this._typeBuffer = '';
917
- this._shadow = this.attachShadow({ mode: 'open' });
918
- this._listRoot = document.createElement('div');
919
- this._listRoot.setAttribute('role', 'listbox');
920
- this._listRoot.setAttribute('tabindex', '0');
1627
+ this._typeBuffer = "";
1628
+ this._shadow = this.attachShadow({ mode: "open" });
1629
+ this._listRoot = document.createElement("div");
1630
+ this._listRoot.setAttribute("role", "listbox");
1631
+ this._listRoot.setAttribute("tabindex", "0");
921
1632
  this._shadow.appendChild(this._listRoot);
922
1633
  // Live region for screen reader announcements
923
- this._liveRegion = document.createElement('div');
924
- this._liveRegion.setAttribute('role', 'status');
925
- this._liveRegion.setAttribute('aria-live', 'polite');
926
- this._liveRegion.style.cssText = 'position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden;';
1634
+ this._liveRegion = document.createElement("div");
1635
+ this._liveRegion.setAttribute("role", "status");
1636
+ this._liveRegion.setAttribute("aria-live", "polite");
1637
+ this._liveRegion.style.cssText =
1638
+ "position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden;";
927
1639
  this._shadow.appendChild(this._liveRegion);
928
1640
  this._helpers = createRendererHelpers((item, index) => this._onSelect(item, index));
929
1641
  // Delegated click
930
- this._listRoot.addEventListener('click', (e) => {
931
- const el = e.target.closest('[data-selectable]');
1642
+ this._listRoot.addEventListener("click", (e) => {
1643
+ const el = e.target.closest("[data-selectable]");
932
1644
  if (!el)
933
1645
  return;
934
1646
  const idx = Number(el.dataset.index);
@@ -936,28 +1648,33 @@ class NativeSelectElement extends HTMLElement {
936
1648
  this._onSelect(item, idx);
937
1649
  });
938
1650
  // Keyboard navigation
939
- this._listRoot.addEventListener('keydown', (e) => this._onKeydown(e));
1651
+ this._listRoot.addEventListener("keydown", (e) => this._onKeydown(e));
940
1652
  }
941
1653
  connectedCallback() {
942
1654
  // Initialize ARIA roles and open event
943
- this._listRoot.setAttribute('role', 'listbox');
944
- this._listRoot.setAttribute('aria-label', 'Options list');
1655
+ this._listRoot.setAttribute("role", "listbox");
1656
+ this._listRoot.setAttribute("aria-label", "Options list");
945
1657
  if (this._multi)
946
- this._listRoot.setAttribute('aria-multiselectable', 'true');
1658
+ this._listRoot.setAttribute("aria-multiselectable", "true");
947
1659
  this._initializeOptionRenderer();
948
- this._emit('open', {});
1660
+ this._emit("open", {});
949
1661
  }
950
1662
  disconnectedCallback() {
951
- this._emit('close', {});
1663
+ this._emit("close", {});
952
1664
  // Cleanup unified renderer
953
1665
  if (this._unifiedRenderer) {
954
1666
  this._unifiedRenderer.unmountAll();
955
1667
  }
1668
+ this._virtualizer?.destroy();
1669
+ this._virtualizer = undefined;
956
1670
  // Cleanup: remove listeners if any were added outside constructor
957
1671
  if (this._typeTimeout)
958
1672
  window.clearTimeout(this._typeTimeout);
1673
+ if (this._announceTimeout)
1674
+ window.clearTimeout(this._announceTimeout);
959
1675
  }
960
1676
  _initializeOptionRenderer() {
1677
+ this._unifiedRenderer?.unmountAll();
961
1678
  const getValue = (item) => item?.value ?? item;
962
1679
  const getLabel = (item) => item?.label ?? String(item);
963
1680
  const getDisabled = (item) => item?.disabled ?? false;
@@ -973,39 +1690,43 @@ class NativeSelectElement extends HTMLElement {
973
1690
  },
974
1691
  onCustomEvent: (index, eventName, data) => {
975
1692
  // Emit custom events from option components
976
- this.dispatchEvent(new CustomEvent('option:custom-event', {
1693
+ this.dispatchEvent(new CustomEvent("option:custom-event", {
977
1694
  detail: { index, eventName, data },
978
1695
  bubbles: true,
979
- composed: true
1696
+ composed: true,
980
1697
  }));
981
1698
  },
982
1699
  onError: (index, error) => {
983
1700
  console.error(`[NativeSelect] Error in option ${index}:`, error);
984
- this.dispatchEvent(new CustomEvent('option:mount-error', {
1701
+ this.dispatchEvent(new CustomEvent("option:mount-error", {
985
1702
  detail: { index, error },
986
1703
  bubbles: true,
987
- composed: true
1704
+ composed: true,
988
1705
  }));
989
- }
1706
+ },
990
1707
  };
991
1708
  this._unifiedRenderer = new OptionRenderer(rendererConfig);
992
1709
  }
993
1710
  attributeChangedCallback(name, _oldValue, newValue) {
994
1711
  switch (name) {
995
- case 'placement':
996
- this._options.placement = (newValue ?? undefined);
1712
+ case "placement":
1713
+ this._options.placement = (newValue ??
1714
+ undefined);
997
1715
  break;
998
- case 'strategy':
999
- this._options.strategy = (newValue ?? undefined);
1716
+ case "strategy":
1717
+ this._options.strategy = (newValue ??
1718
+ undefined);
1000
1719
  break;
1001
- case 'portal':
1002
- this._options.portal = newValue === 'true' ? true : newValue === 'false' ? false : undefined;
1720
+ case "portal":
1721
+ this._options.portal =
1722
+ newValue === "true" ? true : newValue === "false" ? false : undefined;
1003
1723
  break;
1004
1724
  }
1005
1725
  }
1006
1726
  set items(items) {
1007
1727
  this._items = items ?? [];
1008
1728
  // initialize virtualizer with estimated height (default 48) and buffer
1729
+ this._virtualizer?.destroy();
1009
1730
  this._virtualizer = new Virtualizer(this._listRoot, this._items.length, (i) => this._items[i], { estimatedItemHeight: 48, buffer: 5 });
1010
1731
  this.render();
1011
1732
  }
@@ -1015,10 +1736,10 @@ class NativeSelectElement extends HTMLElement {
1015
1736
  set multi(value) {
1016
1737
  this._multi = value;
1017
1738
  if (value) {
1018
- this._listRoot.setAttribute('aria-multiselectable', 'true');
1739
+ this._listRoot.setAttribute("aria-multiselectable", "true");
1019
1740
  }
1020
1741
  else {
1021
- this._listRoot.removeAttribute('aria-multiselectable');
1742
+ this._listRoot.removeAttribute("aria-multiselectable");
1022
1743
  }
1023
1744
  }
1024
1745
  get multi() {
@@ -1054,7 +1775,7 @@ class NativeSelectElement extends HTMLElement {
1054
1775
  * For multi-select: adds to selection if not already selected
1055
1776
  */
1056
1777
  setValue(value) {
1057
- if (value === null || value === undefined || value === '') {
1778
+ if (value === null || value === undefined || value === "") {
1058
1779
  // Clear selection
1059
1780
  this._selectedSet.clear();
1060
1781
  this._selectedItems.clear();
@@ -1063,8 +1784,8 @@ class NativeSelectElement extends HTMLElement {
1063
1784
  return;
1064
1785
  }
1065
1786
  // Find item by value
1066
- const index = this._items.findIndex(item => {
1067
- if (typeof item === 'object' && item !== null && 'value' in item) {
1787
+ const index = this._items.findIndex((item) => {
1788
+ if (typeof item === "object" && item !== null && "value" in item) {
1068
1789
  return item.value === value;
1069
1790
  }
1070
1791
  return item === value;
@@ -1090,7 +1811,7 @@ class NativeSelectElement extends HTMLElement {
1090
1811
  // Optimized: single-pass iteration, no intermediate arrays
1091
1812
  const values = [];
1092
1813
  for (const item of this._selectedItems.values()) {
1093
- if (typeof item === 'object' && item !== null && 'value' in item) {
1814
+ if (typeof item === "object" && item !== null && "value" in item) {
1094
1815
  values.push(item.value);
1095
1816
  }
1096
1817
  else {
@@ -1105,16 +1826,16 @@ class NativeSelectElement extends HTMLElement {
1105
1826
  const scrollTop = this.scrollTop || 0;
1106
1827
  // Update aria-activedescendant
1107
1828
  if (this._activeIndex >= 0) {
1108
- this._listRoot.setAttribute('aria-activedescendant', `option-${this._activeIndex}`);
1829
+ this._listRoot.setAttribute("aria-activedescendant", `option-${this._activeIndex}`);
1109
1830
  }
1110
1831
  else {
1111
- this._listRoot.removeAttribute('aria-activedescendant');
1832
+ this._listRoot.removeAttribute("aria-activedescendant");
1112
1833
  }
1113
1834
  // Check if any items have custom components
1114
- const hasCustomComponents = this._items.some(item => typeof item === 'object' &&
1835
+ const hasCustomComponents = this._items.some((item) => typeof item === "object" &&
1115
1836
  item !== null &&
1116
- Object.prototype.hasOwnProperty.call(item, 'optionComponent') &&
1117
- typeof item.optionComponent === 'function');
1837
+ Object.prototype.hasOwnProperty.call(item, "optionComponent") &&
1838
+ typeof item.optionComponent === "function");
1118
1839
  // Use unified renderer if we have custom components
1119
1840
  if (hasCustomComponents && this._unifiedRenderer) {
1120
1841
  this._listRoot.replaceChildren(); // Clear existing content
@@ -1123,7 +1844,7 @@ class NativeSelectElement extends HTMLElement {
1123
1844
  const item = this._items[i];
1124
1845
  const isSelected = this._selectedSet.has(i);
1125
1846
  const isFocused = this._activeIndex === i;
1126
- const optionElement = this._unifiedRenderer.render(item, i, isSelected, isFocused, `native-${this.getAttribute('id') || 'default'}`);
1847
+ const optionElement = this._unifiedRenderer.render(item, i, isSelected, isFocused, `native-${this.getAttribute("id") || "default"}`);
1127
1848
  frag.appendChild(optionElement);
1128
1849
  }
1129
1850
  this._listRoot.appendChild(frag);
@@ -1140,14 +1861,14 @@ class NativeSelectElement extends HTMLElement {
1140
1861
  node.replaceChildren(el);
1141
1862
  }
1142
1863
  else if (optionTemplate) {
1143
- const wrapper = document.createElement('div');
1864
+ const wrapper = document.createElement("div");
1144
1865
  wrapper.innerHTML = optionTemplate(item, i);
1145
1866
  const el = wrapper.firstElementChild;
1146
1867
  node.replaceChildren(el ?? document.createTextNode(String(item)));
1147
1868
  }
1148
1869
  else {
1149
1870
  // Handle {label, value} objects or primitives
1150
- const displayText = (typeof item === 'object' && item !== null && 'label' in item)
1871
+ const displayText = typeof item === "object" && item !== null && "label" in item
1151
1872
  ? String(item.label)
1152
1873
  : String(item);
1153
1874
  node.textContent = displayText;
@@ -1160,9 +1881,9 @@ class NativeSelectElement extends HTMLElement {
1160
1881
  const item = this._items[i];
1161
1882
  if (optionRenderer) {
1162
1883
  const el = optionRenderer(item, i, this._helpers);
1163
- if (!el.hasAttribute('data-selectable')) {
1164
- el.setAttribute('data-selectable', '');
1165
- el.setAttribute('data-index', String(i));
1884
+ if (!el.hasAttribute("data-selectable")) {
1885
+ el.setAttribute("data-selectable", "");
1886
+ el.setAttribute("data-index", String(i));
1166
1887
  }
1167
1888
  this._applyOptionAttrs(el, i);
1168
1889
  frag.appendChild(el);
@@ -1175,14 +1896,14 @@ class NativeSelectElement extends HTMLElement {
1175
1896
  return; // rendering complete
1176
1897
  }
1177
1898
  else {
1178
- const el = document.createElement('div');
1899
+ const el = document.createElement("div");
1179
1900
  // Handle {label, value} objects or primitives
1180
- const displayText = (typeof item === 'object' && item !== null && 'label' in item)
1901
+ const displayText = typeof item === "object" && item !== null && "label" in item
1181
1902
  ? String(item.label)
1182
1903
  : String(item);
1183
1904
  el.textContent = displayText;
1184
- el.setAttribute('data-selectable', '');
1185
- el.setAttribute('data-index', String(i));
1905
+ el.setAttribute("data-selectable", "");
1906
+ el.setAttribute("data-index", String(i));
1186
1907
  this._applyOptionAttrs(el, i);
1187
1908
  frag.appendChild(el);
1188
1909
  }
@@ -1190,13 +1911,13 @@ class NativeSelectElement extends HTMLElement {
1190
1911
  this._listRoot.replaceChildren(frag);
1191
1912
  }
1192
1913
  _applyOptionAttrs(node, index) {
1193
- node.setAttribute('role', 'option');
1914
+ node.setAttribute("role", "option");
1194
1915
  node.id = `option-${index}`;
1195
1916
  if (this._selectedSet.has(index)) {
1196
- node.setAttribute('aria-selected', 'true');
1917
+ node.setAttribute("aria-selected", "true");
1197
1918
  }
1198
1919
  else {
1199
- node.setAttribute('aria-selected', 'false');
1920
+ node.setAttribute("aria-selected", "false");
1200
1921
  }
1201
1922
  }
1202
1923
  _applyAriaToAll() {
@@ -1234,13 +1955,13 @@ class NativeSelectElement extends HTMLElement {
1234
1955
  const selected = this._selectedSet.has(index);
1235
1956
  const value = item?.value ?? item;
1236
1957
  const label = item?.label ?? String(item);
1237
- this._emit('select', {
1958
+ this._emit("select", {
1238
1959
  item,
1239
1960
  index,
1240
1961
  value,
1241
1962
  label,
1242
1963
  selected,
1243
- multi: this._multi
1964
+ multi: this._multi,
1244
1965
  });
1245
1966
  // Optimized: single-pass iteration for change event data
1246
1967
  const selectedItems = [];
@@ -1250,50 +1971,50 @@ class NativeSelectElement extends HTMLElement {
1250
1971
  selectedValues.push(item?.value ?? item);
1251
1972
  }
1252
1973
  // Emit 'change' event for better React compatibility
1253
- this._emit('change', {
1974
+ this._emit("change", {
1254
1975
  selectedItems,
1255
1976
  selectedValues,
1256
- selectedIndices: Array.from(this._selectedSet)
1977
+ selectedIndices: Array.from(this._selectedSet),
1257
1978
  });
1258
1979
  this._announce(`Selected ${label}`);
1259
1980
  }
1260
1981
  _onKeydown(e) {
1261
1982
  switch (e.key) {
1262
- case 'ArrowDown':
1983
+ case "ArrowDown":
1263
1984
  e.preventDefault();
1264
1985
  this._moveActive(1);
1265
1986
  break;
1266
- case 'ArrowUp':
1987
+ case "ArrowUp":
1267
1988
  e.preventDefault();
1268
1989
  this._moveActive(-1);
1269
1990
  break;
1270
- case 'Home':
1991
+ case "Home":
1271
1992
  e.preventDefault();
1272
1993
  this._setActive(0);
1273
1994
  break;
1274
- case 'End':
1995
+ case "End":
1275
1996
  e.preventDefault();
1276
1997
  this._setActive(this._items.length - 1);
1277
1998
  break;
1278
- case 'PageDown':
1999
+ case "PageDown":
1279
2000
  e.preventDefault();
1280
2001
  this._moveActive(10);
1281
2002
  break;
1282
- case 'PageUp':
2003
+ case "PageUp":
1283
2004
  e.preventDefault();
1284
2005
  this._moveActive(-10);
1285
2006
  break;
1286
- case 'Enter':
1287
- case ' ':
2007
+ case "Enter":
2008
+ case " ":
1288
2009
  e.preventDefault();
1289
2010
  if (this._activeIndex >= 0) {
1290
2011
  const item = this._items[this._activeIndex];
1291
2012
  this._onSelect(item, this._activeIndex);
1292
2013
  }
1293
2014
  break;
1294
- case 'Escape':
2015
+ case "Escape":
1295
2016
  e.preventDefault();
1296
- this._emit('close', {});
2017
+ this._emit("close", {});
1297
2018
  break;
1298
2019
  default:
1299
2020
  // Type-ahead buffer
@@ -1315,14 +2036,14 @@ class NativeSelectElement extends HTMLElement {
1315
2036
  }
1316
2037
  _scrollToActive() {
1317
2038
  const el = this._shadow.getElementById(`option-${this._activeIndex}`);
1318
- el?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
2039
+ el?.scrollIntoView({ block: "nearest", inline: "nearest" });
1319
2040
  }
1320
2041
  _onType(char) {
1321
2042
  if (this._typeTimeout)
1322
2043
  window.clearTimeout(this._typeTimeout);
1323
2044
  this._typeBuffer += char.toLowerCase();
1324
2045
  this._typeTimeout = window.setTimeout(() => {
1325
- this._typeBuffer = '';
2046
+ this._typeBuffer = "";
1326
2047
  }, 400);
1327
2048
  // Find first matching item
1328
2049
  const match = this._items.findIndex((item) => String(item).toLowerCase().startsWith(this._typeBuffer));
@@ -1333,9 +2054,12 @@ class NativeSelectElement extends HTMLElement {
1333
2054
  _announce(msg) {
1334
2055
  if (this._liveRegion) {
1335
2056
  this._liveRegion.textContent = msg;
1336
- setTimeout(() => {
2057
+ if (this._announceTimeout)
2058
+ window.clearTimeout(this._announceTimeout);
2059
+ this._announceTimeout = window.setTimeout(() => {
2060
+ this._announceTimeout = undefined;
1337
2061
  if (this._liveRegion)
1338
- this._liveRegion.textContent = '';
2062
+ this._liveRegion.textContent = "";
1339
2063
  }, 1000);
1340
2064
  }
1341
2065
  }
@@ -1344,7 +2068,9 @@ class NativeSelectElement extends HTMLElement {
1344
2068
  this._listRoot.focus();
1345
2069
  }
1346
2070
  }
1347
- customElements.define('smilodon-select', NativeSelectElement);
2071
+ if (!customElements.get("smilodon-select")) {
2072
+ customElements.define("smilodon-select", NativeSelectElement);
2073
+ }
1348
2074
 
1349
2075
  /**
1350
2076
  * Global Configuration System for Select Components
@@ -1521,6 +2247,222 @@ function resetSelectConfig() {
1521
2247
  selectConfig.resetConfig();
1522
2248
  }
1523
2249
 
2250
+ /** Returns whether a selected key remains in the filtered result set. */
2251
+ /**
2252
+ * Returns keys in the half-open index range [startIndex, endIndex), clamped to
2253
+ * the source. Bounds are truncated to integers; an end before start is empty.
2254
+ */
2255
+ function computeWindowKeys(filteredKeys, startIndex, endIndex) {
2256
+ const start = Math.max(0, Math.min(filteredKeys.length, Math.trunc(startIndex)));
2257
+ const end = Math.max(start, Math.min(filteredKeys.length, Math.trunc(endIndex)));
2258
+ return filteredKeys.slice(start, end);
2259
+ }
2260
+
2261
+ /** Projects existing engine state into accessibility semantics without DOM data. */
2262
+ function deriveAccessibilityState(state, context = {}) {
2263
+ const required = state.selection.required;
2264
+ const invalid = context.invalid ?? false;
2265
+ return {
2266
+ expanded: state.popup === 'open',
2267
+ disabled: state.disabled,
2268
+ readonly: context.readonly ?? false,
2269
+ searchable: context.searchable ?? false,
2270
+ multiple: state.selection.multiple,
2271
+ required,
2272
+ invalid,
2273
+ busy: state.dataStatus === 'loading',
2274
+ activeKey: state.activeKey,
2275
+ selectedKeys: state.selectedKeys,
2276
+ disabledKeys: state.selection.disabledKeys,
2277
+ popupRole: 'listbox',
2278
+ label: context.label ?? {},
2279
+ validation: {
2280
+ required,
2281
+ invalid,
2282
+ errorMessage: context.errorMessage ?? null,
2283
+ errorDescriptionId: context.errorDescriptionId ?? null,
2284
+ },
2285
+ };
2286
+ }
2287
+ function uniqueIds(ids) {
2288
+ return [...new Set(ids.filter((id) => Boolean(id)))];
2289
+ }
2290
+ function getLabelledBy(label) {
2291
+ return uniqueIds([label.labelId, ...(label.labelledBy ?? [])]);
2292
+ }
2293
+ function getDescribedBy(state) {
2294
+ return uniqueIds([
2295
+ ...(state.label.describedBy ?? []),
2296
+ state.validation.errorDescriptionId,
2297
+ ]);
2298
+ }
2299
+ /** Computes combobox semantics without reading from or writing to the DOM. */
2300
+ function computeComboboxAccessibility(state, controlsId = null) {
2301
+ return {
2302
+ role: 'combobox',
2303
+ expanded: state.expanded,
2304
+ disabled: state.disabled,
2305
+ readonly: state.readonly,
2306
+ autocomplete: state.searchable ? 'list' : 'none',
2307
+ multiple: state.multiple,
2308
+ required: state.required,
2309
+ invalid: state.invalid,
2310
+ activeKey: state.activeKey,
2311
+ controlsId,
2312
+ labelledBy: getLabelledBy(state.label),
2313
+ describedBy: getDescribedBy(state),
2314
+ ariaLabel: state.label.ariaLabel ?? null,
2315
+ ariaDescription: state.label.ariaDescription ?? null,
2316
+ };
2317
+ }
2318
+ /** Computes listbox semantics; the supplied label IDs remain caller-owned data. */
2319
+ function computeListboxAccessibility(state) {
2320
+ return {
2321
+ role: state.popupRole,
2322
+ multiple: state.multiple,
2323
+ busy: state.busy,
2324
+ labelledBy: getLabelledBy(state.label),
2325
+ ariaLabel: state.label.ariaLabel ?? null,
2326
+ };
2327
+ }
2328
+ /** Computes one option's semantic state from stable identity, never its index. */
2329
+ function computeOptionAccessibility(state, key) {
2330
+ const disabled = state.disabled || state.disabledKeys.has(key);
2331
+ return {
2332
+ key,
2333
+ selected: state.selectedKeys.has(key),
2334
+ disabled,
2335
+ active: !disabled && state.activeKey === key,
2336
+ };
2337
+ }
2338
+ /**
2339
+ * Produces semantic accessibility effects. IDs and rendered option keys are
2340
+ * caller inputs; this function does not inspect the DOM or perform side effects.
2341
+ */
2342
+ function computeAccessibilityEffects(state, options) {
2343
+ return [
2344
+ {
2345
+ type: 'SYNC_COMBOBOX_ARIA',
2346
+ ...computeComboboxAccessibility(state, options.controlsId ?? null),
2347
+ },
2348
+ {
2349
+ type: 'SYNC_LISTBOX_ARIA',
2350
+ ...computeListboxAccessibility(state),
2351
+ },
2352
+ ...options.optionKeys.map((key) => ({
2353
+ type: 'SYNC_OPTION_ARIA',
2354
+ ...computeOptionAccessibility(state, key),
2355
+ })),
2356
+ ...(options.announcements ?? []).map((announcement) => ({
2357
+ type: 'ANNOUNCE',
2358
+ ...announcement,
2359
+ })),
2360
+ ...(options.focusIntents ?? []).map((focusIntent) => ({
2361
+ type: 'FOCUS_INTENT',
2362
+ ...focusIntent,
2363
+ })),
2364
+ ];
2365
+ }
2366
+
2367
+ function setBooleanAttribute(element, name, value) {
2368
+ element.setAttribute(name, String(value));
2369
+ }
2370
+ function setOptionalAttribute(element, name, value) {
2371
+ if (value) {
2372
+ element.setAttribute(name, value);
2373
+ }
2374
+ else {
2375
+ element.removeAttribute(name);
2376
+ }
2377
+ }
2378
+ function setIdListAttribute(element, name, ids) {
2379
+ setOptionalAttribute(element, name, ids.length > 0 ? ids.join(' ') : null);
2380
+ }
2381
+ function applyCombobox(effect, targets) {
2382
+ const combobox = targets.combobox;
2383
+ if (!combobox)
2384
+ return;
2385
+ combobox.setAttribute('role', effect.role);
2386
+ setBooleanAttribute(combobox, 'aria-expanded', effect.expanded);
2387
+ setBooleanAttribute(combobox, 'aria-disabled', effect.disabled);
2388
+ setBooleanAttribute(combobox, 'aria-readonly', effect.readonly);
2389
+ setBooleanAttribute(combobox, 'aria-required', effect.required);
2390
+ setBooleanAttribute(combobox, 'aria-invalid', effect.invalid);
2391
+ combobox.setAttribute('aria-autocomplete', effect.autocomplete);
2392
+ setOptionalAttribute(combobox, 'aria-controls', effect.controlsId);
2393
+ setIdListAttribute(combobox, 'aria-labelledby', effect.labelledBy);
2394
+ setIdListAttribute(combobox, 'aria-describedby', effect.describedBy);
2395
+ setOptionalAttribute(combobox, 'aria-label', effect.ariaLabel);
2396
+ setOptionalAttribute(combobox, 'aria-description', effect.ariaDescription);
2397
+ const activeOption = effect.activeKey == null
2398
+ ? null
2399
+ : targets.getOptionByKey?.(effect.activeKey) ?? null;
2400
+ setOptionalAttribute(combobox, 'aria-activedescendant', activeOption?.id || null);
2401
+ }
2402
+ function applyListbox(effect, targets) {
2403
+ const listbox = targets.listbox;
2404
+ if (!listbox)
2405
+ return;
2406
+ listbox.setAttribute('role', effect.role);
2407
+ if (effect.multiple)
2408
+ listbox.setAttribute('aria-multiselectable', 'true');
2409
+ else
2410
+ listbox.removeAttribute('aria-multiselectable');
2411
+ if (effect.busy)
2412
+ listbox.setAttribute('aria-busy', 'true');
2413
+ else
2414
+ listbox.removeAttribute('aria-busy');
2415
+ setIdListAttribute(listbox, 'aria-labelledby', effect.labelledBy);
2416
+ setOptionalAttribute(listbox, 'aria-label', effect.ariaLabel);
2417
+ }
2418
+ function applyOption(effect, targets) {
2419
+ const option = targets.getOptionByKey?.(effect.key);
2420
+ if (!option)
2421
+ return;
2422
+ option.setAttribute('role', 'option');
2423
+ setBooleanAttribute(option, 'aria-selected', effect.selected);
2424
+ if (effect.disabled)
2425
+ option.setAttribute('aria-disabled', 'true');
2426
+ else
2427
+ option.removeAttribute('aria-disabled');
2428
+ }
2429
+ function applyFocusIntent(target, targets, options) {
2430
+ if (!options.applyFocus || target === 'none')
2431
+ return;
2432
+ const focusTarget = target === 'input'
2433
+ ? targets.focusTargets?.input
2434
+ : target === 'clear-button'
2435
+ ? targets.focusTargets?.clearButton
2436
+ : targets.focusTargets?.getActiveOption?.();
2437
+ focusTarget?.focus();
2438
+ }
2439
+ /** Applies engine accessibility effects to caller-owned web DOM targets. */
2440
+ function applyAccessibilityEffects(effects, targets, options = {}) {
2441
+ for (const effect of effects) {
2442
+ switch (effect.type) {
2443
+ case 'SYNC_COMBOBOX_ARIA':
2444
+ applyCombobox(effect, targets);
2445
+ break;
2446
+ case 'SYNC_LISTBOX_ARIA':
2447
+ applyListbox(effect, targets);
2448
+ break;
2449
+ case 'SYNC_OPTION_ARIA':
2450
+ applyOption(effect, targets);
2451
+ break;
2452
+ case 'ANNOUNCE':
2453
+ if (targets.liveRegion) {
2454
+ targets.liveRegion.setAttribute('aria-live', effect.politeness);
2455
+ targets.liveRegion.setAttribute('aria-atomic', 'true');
2456
+ targets.liveRegion.textContent = effect.message;
2457
+ }
2458
+ break;
2459
+ case 'FOCUS_INTENT':
2460
+ applyFocusIntent(effect.target, targets, options);
2461
+ break;
2462
+ }
2463
+ }
2464
+ }
2465
+
1524
2466
  /**
1525
2467
  * Independent Option Component
1526
2468
  * High cohesion, low coupling - handles its own selection state and events
@@ -2111,13 +3053,19 @@ function arraysEqualByValue(a, b) {
2111
3053
  * Implements all advanced features: infinite scroll, load more, busy state,
2112
3054
  * server-side selection, and full customization
2113
3055
  *
2114
- * ✨ Redesigned with formal elegance, refined microinteractions, and polished UX
3056
+ * Redesigned with formal elegance, refined microinteractions, and polished UX
2115
3057
  */
2116
3058
  class EnhancedSelect extends HTMLElement {
3059
+ static get observedAttributes() {
3060
+ return ['aria-label', 'aria-description'];
3061
+ }
2117
3062
  get classMap() {
2118
3063
  return this._classMap;
2119
3064
  }
2120
3065
  set classMap(map) {
3066
+ if (this._areClassMapsEqual(this._classMap, map))
3067
+ return;
3068
+ this._invalidateGuardedMeasurements();
2121
3069
  this._classMap = map;
2122
3070
  this._setGlobalStylesMirroring(Boolean(this._optionRenderer || map || this._groupHeaderRenderer));
2123
3071
  this._track('style', 'classMapChanged', {
@@ -2137,6 +3085,8 @@ class EnhancedSelect extends HTMLElement {
2137
3085
  return this._groupHeaderRenderer;
2138
3086
  }
2139
3087
  set groupHeaderRenderer(renderer) {
3088
+ if (this._groupHeaderRenderer === renderer)
3089
+ return;
2140
3090
  this._groupHeaderRenderer = renderer;
2141
3091
  this._setGlobalStylesMirroring(Boolean(this._optionRenderer || this._classMap || renderer));
2142
3092
  this._track('style', 'groupHeaderRendererChanged', { enabled: Boolean(renderer) });
@@ -2146,6 +3096,48 @@ class EnhancedSelect extends HTMLElement {
2146
3096
  }
2147
3097
  constructor() {
2148
3098
  super();
3099
+ this._engine = new SelectEngineBridge();
3100
+ this._virtualizationScope = {
3101
+ dataKeys: [],
3102
+ filteredKeys: [],
3103
+ registeredKeys: [],
3104
+ windowKeys: [],
3105
+ mountedKeys: [],
3106
+ selectedKeys: new Set(),
3107
+ activeKey: null,
3108
+ };
3109
+ this._renderPlan = {
3110
+ mode: 'legacy-full',
3111
+ filteredIndices: [],
3112
+ filteredKeys: [],
3113
+ intendedRenderKeys: [],
3114
+ filteredIndexByKey: new Map(),
3115
+ };
3116
+ // Null keeps the public/default renderer on its legacy full path. This
3117
+ // private state is only used by guarded virtualization integration.
3118
+ this._guardedVirtualWindow = null;
3119
+ this._guardedVirtualizer = null;
3120
+ this._guardedVirtualizationRequested = false;
3121
+ this._guardedVirtualizerKeys = [];
3122
+ this._guardedMeasurementQuery = null;
3123
+ this._guardedOptionResizeObserver = null;
3124
+ this._guardedObservedOptions = new Set();
3125
+ this._guardedObserverSeenOptions = new WeakSet();
3126
+ this._guardedOptionMeasurements = new WeakMap();
3127
+ this._guardedMeasurementGeneration = 0;
3128
+ this._guardedVirtualScrollTop = 0;
3129
+ this._guardedVirtualViewportHeight = 0;
3130
+ this._guardedVirtualOverscan = 0;
3131
+ this._guardedVirtualWindowRafId = null;
3132
+ this._guardedScrollListenerAttached = false;
3133
+ this._onGuardedVirtualScroll = () => this._scheduleGuardedVirtualWindowUpdate();
3134
+ this._effectRunner = new DefaultSelectEffectRunner();
3135
+ this._itemAdapter = this._createEngineItemAdapter();
3136
+ this._itemRegistry = createItemRegistry([], this._itemAdapter);
3137
+ // Engine selectedKeys owns identity. The registry resolves current records;
3138
+ // this cache keeps the last known record available while a selected key is detached.
3139
+ this._selectedRecordsByKey = new Map();
3140
+ this._registryItemsRef = [];
2149
3141
  this._pageCache = {};
2150
3142
  this._typeBuffer = '';
2151
3143
  this._hasError = false;
@@ -2155,11 +3147,17 @@ class EnhancedSelect extends HTMLElement {
2155
3147
  this._pendingSearchRenderMark = false;
2156
3148
  this._rangeAnchorIndex = null;
2157
3149
  this._customOptionBoundElements = new WeakSet();
3150
+ this._customOptionNormalizedIds = new WeakMap();
3151
+ this._customOptionNormalizedLabels = new WeakMap();
2158
3152
  this._mirrorGlobalStylesForCustomOptions = false;
2159
3153
  this._globalStylesObserver = null;
2160
3154
  this._globalStylesContainer = null;
2161
3155
  this._themeContextObserver = null;
2162
3156
  this._globalStylesSyncToken = 0;
3157
+ this._asyncGeneration = 0;
3158
+ this._lifecycleTimers = new Set();
3159
+ this._lifecycleRafs = new Set();
3160
+ this._keyboardActiveChangeGeneration = 0;
2163
3161
  this._tracking = { events: [], styles: [], limitations: [] };
2164
3162
  this._suppressBlurClose = false;
2165
3163
  this._renderCycleId = 0;
@@ -2173,14 +3171,54 @@ class EnhancedSelect extends HTMLElement {
2173
3171
  startScrollLeft: 0,
2174
3172
  };
2175
3173
  this._liftedAncestors = [];
3174
+ this._onDocumentPointerDown = (e) => {
3175
+ const path = (e.composedPath && e.composedPath()) || [];
3176
+ let clickedInside = false;
3177
+ for (const node of path) {
3178
+ if (node === this || node === this._container) {
3179
+ clickedInside = true;
3180
+ break;
3181
+ }
3182
+ if (node instanceof Node) {
3183
+ try {
3184
+ if (this._shadow && this._shadow.contains(node)) {
3185
+ clickedInside = true;
3186
+ break;
3187
+ }
3188
+ }
3189
+ catch (err) {
3190
+ // ignore
3191
+ }
3192
+ }
3193
+ if (node instanceof Element) {
3194
+ try {
3195
+ if (node.matches('[data-sm-selectable], [data-selectable], [data-sm-state], .input-container, .select-container, .dropdown-arrow-container, .clear-control-button')) {
3196
+ clickedInside = true;
3197
+ break;
3198
+ }
3199
+ }
3200
+ catch (err) {
3201
+ // ignore
3202
+ }
3203
+ }
3204
+ }
3205
+ if (!clickedInside) {
3206
+ this._handleClose('outside-pointer');
3207
+ }
3208
+ };
2176
3209
  this._shadow = this.attachShadow({ mode: 'open' });
2177
3210
  this._uniqueId = `enhanced-select-${Math.random().toString(36).substr(2, 9)}`;
2178
3211
  this._rendererHelpers = this._buildRendererHelpers();
2179
3212
  // Merge global config with component-level config
2180
3213
  this._config = selectConfig.getConfig();
3214
+ this._engine.dispatch({ type: 'DISABLED_CHANGED', disabled: !this._config.enabled });
3215
+ this._syncEngineSelectionConfig();
2181
3216
  // Initialize state
3217
+ const host = this;
2182
3218
  this._state = {
2183
- isOpen: false,
3219
+ get isOpen() {
3220
+ return host._engine.state.popup === 'open';
3221
+ },
2184
3222
  isBusy: false,
2185
3223
  isSearching: false,
2186
3224
  currentPage: this._config.infiniteScroll.initialPage || 1,
@@ -2207,6 +3245,7 @@ class EnhancedSelect extends HTMLElement {
2207
3245
  this._dropdown = this._createDropdown();
2208
3246
  this._optionsContainer = this._createOptionsContainer();
2209
3247
  this._liveRegion = this._createLiveRegion();
3248
+ this._errorDescription = this._createErrorDescription();
2210
3249
  // Initialize styles BEFORE assembling DOM (order matters in shadow DOM)
2211
3250
  this._initializeStyles();
2212
3251
  this._syncStyleConfigVariables();
@@ -2215,17 +3254,27 @@ class EnhancedSelect extends HTMLElement {
2215
3254
  this._assembleDOM();
2216
3255
  this._attachEventListeners();
2217
3256
  this._initializeObservers();
3257
+ this._syncComboboxAccessibility();
3258
+ this._syncListboxAccessibility();
2218
3259
  }
2219
3260
  connectedCallback() {
2220
3261
  // register instance
2221
3262
  EnhancedSelect._instances.add(this);
3263
+ this._runEngineEffects(this._engine.dispatch({ type: 'CONNECT' }));
3264
+ this._runEngineEffects(this._engine.dispatch({ type: 'DISABLED_CHANGED', disabled: !this._config.enabled }));
3265
+ this._connectionController?.abort();
3266
+ this._connectionController = new AbortController();
3267
+ document.addEventListener('pointerdown', this._onDocumentPointerDown, {
3268
+ signal: this._connectionController.signal,
3269
+ });
2222
3270
  // WORKAROUND: Force display style on host element for Angular compatibility
2223
3271
  // Angular's rendering seems to not apply :host styles correctly in some cases
2224
3272
  // Must be done in connectedCallback when element is attached to DOM
2225
3273
  this.style.display = 'block';
2226
3274
  // Sync direction attribute (must be in connectedCallback, not constructor)
2227
3275
  this._syncDirectionConfig();
2228
- if (this._optionRenderer) {
3276
+ this._syncComboboxAccessibility();
3277
+ if (this._optionRenderer || this._classMap || this._groupHeaderRenderer) {
2229
3278
  this._setGlobalStylesMirroring(true);
2230
3279
  }
2231
3280
  // Load initial data if server-side is enabled
@@ -2243,9 +3292,33 @@ class EnhancedSelect extends HTMLElement {
2243
3292
  this._config.callbacks.onOpen();
2244
3293
  }
2245
3294
  }
3295
+ attributeChangedCallback(name, oldValue, newValue) {
3296
+ if (oldValue === newValue || (name !== 'aria-label' && name !== 'aria-description'))
3297
+ return;
3298
+ this._syncComboboxAccessibility();
3299
+ if (name === 'aria-label')
3300
+ this._syncListboxAccessibility();
3301
+ }
2246
3302
  disconnectedCallback() {
2247
3303
  // unregister instance
2248
3304
  EnhancedSelect._instances.delete(this);
3305
+ if (this._state.isOpen) {
3306
+ this._handleClose('disconnect');
3307
+ }
3308
+ this._runEngineEffects(this._engine.dispatch({ type: 'DISCONNECT' }));
3309
+ this._connectionController?.abort();
3310
+ this._connectionController = undefined;
3311
+ this._asyncGeneration += 1;
3312
+ this._cancelGuardedVirtualWindowUpdate();
3313
+ this._clearLifecycleTasks();
3314
+ this._destroyGuardedVirtualizer(true);
3315
+ this._virtualizationScope = {
3316
+ ...this._virtualizationScope,
3317
+ mountedKeys: [],
3318
+ };
3319
+ Array.from(this._optionsContainer.children)
3320
+ .filter((element) => element.hasAttribute('data-index') || element.hasAttribute('data-virtual-spacer'))
3321
+ .forEach((element) => element.remove());
2249
3322
  // Cleanup observers
2250
3323
  this._resizeObserver?.disconnect();
2251
3324
  this._intersectionObserver?.disconnect();
@@ -2265,8 +3338,8 @@ class EnhancedSelect extends HTMLElement {
2265
3338
  }
2266
3339
  _setGlobalStylesMirroring(enabled) {
2267
3340
  if (this._mirrorGlobalStylesForCustomOptions === enabled) {
2268
- if (enabled) {
2269
- this._mirrorDocumentStylesIntoShadow();
3341
+ if (enabled && this.isConnected && !this._globalStylesObserver) {
3342
+ this._setupGlobalStylesMirroring();
2270
3343
  }
2271
3344
  return;
2272
3345
  }
@@ -2279,6 +3352,36 @@ class EnhancedSelect extends HTMLElement {
2279
3352
  this._teardownGlobalStylesMirroring();
2280
3353
  }
2281
3354
  }
3355
+ _setLifecycleTimeout(callback, delay = 0) {
3356
+ const id = window.setTimeout(() => {
3357
+ this._lifecycleTimers.delete(id);
3358
+ if (!this.isConnected)
3359
+ return;
3360
+ callback();
3361
+ }, delay);
3362
+ this._lifecycleTimers.add(id);
3363
+ return id;
3364
+ }
3365
+ _requestLifecycleFrame(callback) {
3366
+ const id = requestAnimationFrame(() => {
3367
+ this._lifecycleRafs.delete(id);
3368
+ if (!this.isConnected)
3369
+ return;
3370
+ callback();
3371
+ });
3372
+ this._lifecycleRafs.add(id);
3373
+ return id;
3374
+ }
3375
+ _clearLifecycleTasks() {
3376
+ for (const id of this._lifecycleTimers) {
3377
+ clearTimeout(id);
3378
+ }
3379
+ this._lifecycleTimers.clear();
3380
+ for (const id of this._lifecycleRafs) {
3381
+ cancelAnimationFrame(id);
3382
+ }
3383
+ this._lifecycleRafs.clear();
3384
+ }
2282
3385
  _setupGlobalStylesMirroring() {
2283
3386
  if (typeof document === 'undefined')
2284
3387
  return;
@@ -2390,23 +3493,64 @@ class EnhancedSelect extends HTMLElement {
2390
3493
  return this._buildScopedStyleElement(node.textContent || '', String(index));
2391
3494
  }
2392
3495
  if (node instanceof HTMLLinkElement && node.href) {
2393
- try {
2394
- const response = await fetch(node.href, {
2395
- credentials: node.crossOrigin === 'use-credentials' ? 'include' : 'same-origin',
2396
- mode: 'cors',
2397
- });
2398
- if (!response.ok) {
2399
- return null;
2400
- }
2401
- const cssText = await response.text();
2402
- return this._buildScopedStyleElement(cssText, String(index));
3496
+ const credentials = node.crossOrigin === 'use-credentials' ? 'include' : 'same-origin';
3497
+ const cacheKey = `${node.href}|${credentials}`;
3498
+ let cacheEntry = EnhancedSelect._mirroredStylesheetTextCache.get(cacheKey);
3499
+ if (!cacheEntry) {
3500
+ cacheEntry = {
3501
+ promise: fetch(node.href, {
3502
+ credentials,
3503
+ mode: 'cors',
3504
+ })
3505
+ .then((response) => {
3506
+ if (!response.ok)
3507
+ return null;
3508
+ return response.text();
3509
+ })
3510
+ .catch(() => null),
3511
+ lastUsed: Date.now(),
3512
+ };
3513
+ EnhancedSelect._mirroredStylesheetTextCache.set(cacheKey, cacheEntry);
3514
+ EnhancedSelect._pruneMirroredStylesheetTextCache();
3515
+ }
3516
+ else {
3517
+ cacheEntry.lastUsed = Date.now();
2403
3518
  }
2404
- catch (_error) {
3519
+ const cssText = await cacheEntry.promise;
3520
+ if (cssText === null) {
3521
+ EnhancedSelect._mirroredStylesheetTextCache.delete(cacheKey);
2405
3522
  return null;
2406
3523
  }
3524
+ return this._buildScopedStyleElement(cssText, String(index));
2407
3525
  }
2408
3526
  return null;
2409
3527
  }
3528
+ static _pruneMirroredStylesheetTextCache() {
3529
+ while (EnhancedSelect._mirroredStylesheetTextCache.size > EnhancedSelect._MIRRORED_STYLESHEET_CACHE_LIMIT) {
3530
+ let lruKey;
3531
+ let oldest = Infinity;
3532
+ for (const [key, entry] of EnhancedSelect._mirroredStylesheetTextCache.entries()) {
3533
+ if (entry.lastUsed < oldest) {
3534
+ oldest = entry.lastUsed;
3535
+ lruKey = key;
3536
+ }
3537
+ }
3538
+ if (!lruKey)
3539
+ return;
3540
+ EnhancedSelect._mirroredStylesheetTextCache.delete(lruKey);
3541
+ }
3542
+ }
3543
+ _areClassMapsEqual(left, right) {
3544
+ if (left === right)
3545
+ return true;
3546
+ if (!left || !right)
3547
+ return false;
3548
+ const leftKeys = Object.keys(left);
3549
+ const rightKeys = Object.keys(right);
3550
+ if (leftKeys.length !== rightKeys.length)
3551
+ return false;
3552
+ return leftKeys.every((key) => left[key] === right[key]);
3553
+ }
2410
3554
  _buildScopedStyleElement(cssText, id) {
2411
3555
  const scopedCss = this._scopeMirroredCssText(cssText);
2412
3556
  if (!scopedCss.trim())
@@ -2551,8 +3695,16 @@ class EnhancedSelect extends HTMLElement {
2551
3695
  return scopedSelector;
2552
3696
  }
2553
3697
  _normalizeCustomOptionAccessibility(optionEl, meta) {
2554
- if (!optionEl.hasAttribute('aria-label') && !optionEl.hasAttribute('aria-labelledby')) {
3698
+ const previousNormalizedLabel = this._customOptionNormalizedLabels.get(optionEl);
3699
+ const currentAriaLabel = optionEl.getAttribute('aria-label');
3700
+ const canRefreshNormalizedLabel = previousNormalizedLabel !== undefined
3701
+ && currentAriaLabel === previousNormalizedLabel;
3702
+ if (!optionEl.hasAttribute('aria-labelledby') && (!currentAriaLabel || canRefreshNormalizedLabel)) {
2555
3703
  optionEl.setAttribute('aria-label', meta.label);
3704
+ this._customOptionNormalizedLabels.set(optionEl, meta.label);
3705
+ }
3706
+ else {
3707
+ this._customOptionNormalizedLabels.delete(optionEl);
2556
3708
  }
2557
3709
  const nestedFocusableSelectors = [
2558
3710
  'a[href]',
@@ -2654,8 +3806,241 @@ class EnhancedSelect extends HTMLElement {
2654
3806
  _isOptionSelectionBlocked(item) {
2655
3807
  return Boolean(item?.disabled) && !this._isDisabledOptionSelectable(item);
2656
3808
  }
3809
+ _isPhase2DevRuntime() {
3810
+ const env = globalThis.process?.env?.NODE_ENV;
3811
+ return env !== 'production';
3812
+ }
3813
+ _getDuplicateKeyPolicy() {
3814
+ return this._isPhase2DevRuntime() ? 'throw' : 'warn';
3815
+ }
3816
+ _warnPhase2(message) {
3817
+ if (this._isPhase2DevRuntime() && typeof console !== 'undefined') {
3818
+ console.warn(message);
3819
+ }
3820
+ }
3821
+ _getItemValue(item) {
3822
+ return this._config.serverSide.getValueFromItem?.(item) ?? item?.value ?? item;
3823
+ }
3824
+ _getItemLabel(item) {
3825
+ return this._config.serverSide.getLabelFromItem?.(item) ?? item?.label ?? String(item);
3826
+ }
3827
+ _createEngineItemAdapter() {
3828
+ return createDefaultItemAdapter({
3829
+ getValue: (item) => this._getItemValue(item),
3830
+ getLabel: (item) => this._getItemLabel(item),
3831
+ isDisabled: (item) => Boolean(item?.disabled),
3832
+ getGroupKey: (item) => {
3833
+ const group = item?.group;
3834
+ return group == null ? null : String(group);
3835
+ },
3836
+ onIndexFallback: (message) => this._warnPhase2(message),
3837
+ });
3838
+ }
3839
+ _getBlockedDisabledKeys() {
3840
+ const keys = this._itemRegistry.records
3841
+ .filter((record) => record.disabled && this._isOptionSelectionBlocked(record.item))
3842
+ .map((record) => record.key);
3843
+ for (const entry of this._getSelectedEntries()) {
3844
+ if (this._isOptionSelectionBlocked(entry.item))
3845
+ keys.push(entry.key);
3846
+ }
3847
+ return keys;
3848
+ }
3849
+ _syncEngineSelectionConfig() {
3850
+ const required = Boolean(this._input?.hasAttribute('required'));
3851
+ const disabledKeys = this._getBlockedDisabledKeys();
3852
+ this._engine.dispatch({
3853
+ type: 'SELECTION_CONFIG_CHANGED',
3854
+ multiple: this._config.selection.mode === 'multi',
3855
+ required,
3856
+ allowDeselect: this._config.selection.allowDeselect === true,
3857
+ maxSelections: this._config.selection.maxSelections ?? 0,
3858
+ disabledKeys,
3859
+ });
3860
+ if (this._state) {
3861
+ this._syncLegacySelectionFromEngine();
3862
+ this._syncLegacyActiveFromEngine();
3863
+ this._assertSelectionProjection('selection config');
3864
+ this._assertActiveProjection('selection config');
3865
+ }
3866
+ }
3867
+ _rebuildItemRegistry(items = this._state.loadedItems) {
3868
+ // Build first so duplicate-key rejection leaves the previous runtime intact.
3869
+ const registry = createItemRegistry(items, this._itemAdapter, {
3870
+ duplicateKeyPolicy: this._getDuplicateKeyPolicy(),
3871
+ });
3872
+ const activeKey = this._engine.state.activeKey;
3873
+ const anchorKey = this._rangeAnchorIndex === null ? undefined : this._itemRegistry.indexToKey.get(this._rangeAnchorIndex);
3874
+ this._itemRegistry = registry;
3875
+ this._state.loadedItems = items;
3876
+ this._registryItemsRef = items;
3877
+ const disabledKeys = this._getBlockedDisabledKeys();
3878
+ this._rangeAnchorIndex = anchorKey === undefined ? null : registry.keyToIndex.get(anchorKey) ?? null;
3879
+ this._engine.dispatch({
3880
+ type: 'ITEMS_REGISTERED',
3881
+ keys: registry.records.map((record) => record.key),
3882
+ disabledKeys,
3883
+ });
3884
+ if (activeKey !== null && registry.keyToRecord.get(activeKey)?.disabled) {
3885
+ this._dispatchActiveKey(null, 'programmatic', 'items registered with disabled active key');
3886
+ }
3887
+ else {
3888
+ this._syncLegacyActiveFromEngine();
3889
+ }
3890
+ this._syncLegacySelectionFromEngine();
3891
+ this._syncEngineSelectionConfig();
3892
+ this._assertSelectionProjection('items registered');
3893
+ }
3894
+ _ensureRegistryCurrent() {
3895
+ if (this._registryItemsRef !== this._state.loadedItems
3896
+ || this._itemRegistry.records.length !== this._state.loadedItems.length
3897
+ || this._itemRegistry.records.some((record, index) => record.item !== this._state.loadedItems[index])) {
3898
+ this._rebuildItemRegistry();
3899
+ return;
3900
+ }
3901
+ this._syncLegacySelectionFromEngine();
3902
+ this._syncLegacyActiveFromEngine();
3903
+ this._assertSelectionProjection('registry read');
3904
+ this._assertActiveProjection('registry read');
3905
+ }
3906
+ _getRecordByIndex(index) {
3907
+ const key = this._itemRegistry.indexToKey.get(index);
3908
+ return key === undefined ? null : this._itemRegistry.keyToRecord.get(key) ?? null;
3909
+ }
3910
+ _getSelectedEntries() {
3911
+ const entries = [];
3912
+ if (!this._state)
3913
+ return entries;
3914
+ for (const key of this._engine.state.selectedKeys) {
3915
+ const record = this._itemRegistry.keyToRecord.get(key) ?? this._selectedRecordsByKey.get(key);
3916
+ if (record)
3917
+ entries.push({ key, index: record.index, item: record.item });
3918
+ }
3919
+ return entries;
3920
+ }
3921
+ _syncLegacySelectionFromEngine() {
3922
+ const selectedIndices = new Set();
3923
+ const selectedItems = new Map();
3924
+ const selectedKeys = this._engine.state.selectedKeys;
3925
+ for (const key of [...this._selectedRecordsByKey.keys()]) {
3926
+ if (!selectedKeys.has(key))
3927
+ this._selectedRecordsByKey.delete(key);
3928
+ }
3929
+ for (const key of selectedKeys) {
3930
+ const record = this._itemRegistry.keyToRecord.get(key);
3931
+ if (record)
3932
+ this._selectedRecordsByKey.set(key, record);
3933
+ if (!record)
3934
+ continue;
3935
+ selectedIndices.add(record.index);
3936
+ selectedItems.set(record.index, record.item);
3937
+ }
3938
+ this._state.selectedIndices = selectedIndices;
3939
+ this._state.selectedItems = selectedItems;
3940
+ }
3941
+ _projectedSelectedKeysSnapshot() {
3942
+ return new Set([...this._state.selectedIndices]
3943
+ .map((index) => this._itemRegistry.indexToKey.get(index))
3944
+ .filter((key) => key !== undefined));
3945
+ }
3946
+ _assertSelectionProjection(context) {
3947
+ if (!this._isPhase2DevRuntime())
3948
+ return;
3949
+ const legacyKeys = this._projectedSelectedKeysSnapshot();
3950
+ const engineKeys = this._engine.state.selectedKeys;
3951
+ if (this._state.selectedItems.size !== this._state.selectedIndices.size
3952
+ || [...this._state.selectedIndices].some((index) => !this._state.selectedItems.has(index))
3953
+ || [...engineKeys].some((key) => this._itemRegistry.keyToRecord.has(key) && !legacyKeys.has(key))
3954
+ || [...legacyKeys].some((key) => !engineKeys.has(key))) {
3955
+ throw new Error(`[Smilodon Phase2] Selection projection failed in ${context}: compatibility=${JSON.stringify([...legacyKeys])}, engine=${JSON.stringify([...engineKeys])}`);
3956
+ }
3957
+ }
3958
+ _projectedActiveKeySnapshot() {
3959
+ return this._state.activeIndex < 0
3960
+ ? null
3961
+ : this._itemRegistry.indexToKey.get(this._state.activeIndex) ?? null;
3962
+ }
3963
+ _syncLegacyActiveFromEngine() {
3964
+ const activeKey = this._engine.state.activeKey;
3965
+ this._state.activeIndex = activeKey === null
3966
+ ? -1
3967
+ : this._itemRegistry.keyToIndex.get(activeKey) ?? -1;
3968
+ this._syncLegacyActiveAria();
3969
+ }
3970
+ _assertActiveProjection(context) {
3971
+ if (!this._isPhase2DevRuntime())
3972
+ return;
3973
+ const legacyKey = this._projectedActiveKeySnapshot();
3974
+ const engineKey = this._engine.state.activeKey;
3975
+ if (legacyKey !== engineKey && !Object.is(legacyKey, engineKey)) {
3976
+ throw new Error(`[Smilodon Phase2] Active projection failed in ${context}: compatibility=${String(legacyKey)}, engine=${String(engineKey)}`);
3977
+ }
3978
+ }
3979
+ _dispatchActiveKey(key, reason, context) {
3980
+ const effects = this._engine.dispatch({ type: 'ACTIVE_KEY_CHANGED', key, reason });
3981
+ this._runEngineEffects(effects);
3982
+ this._syncLegacyActiveFromEngine();
3983
+ this._assertActiveProjection(context);
3984
+ }
3985
+ _clearDisabledEngineActive(context) {
3986
+ const activeKey = this._engine.state.activeKey;
3987
+ if (activeKey !== null && this._itemRegistry.keyToRecord.get(activeKey)?.disabled) {
3988
+ this._dispatchActiveKey(null, 'programmatic', context);
3989
+ }
3990
+ else {
3991
+ this._syncLegacyActiveFromEngine();
3992
+ this._assertActiveProjection(context);
3993
+ }
3994
+ }
3995
+ /**
3996
+ * @deprecated Test/backward-compatibility shim. Production active-state authority is engine.activeKey.
3997
+ * Kept for existing renderer tests; component mutation paths dispatch by key.
3998
+ */
3999
+ _mirrorLegacyActive(reason, context) {
4000
+ this._dispatchActiveKey(this._projectedActiveKeySnapshot(), reason, context);
4001
+ }
4002
+ _dispatchSelection(event, context) {
4003
+ this._engine.dispatch(event);
4004
+ this._syncLegacySelectionFromEngine();
4005
+ this._assertSelectionProjection(context);
4006
+ }
4007
+ /**
4008
+ * @deprecated Test/backward-compatibility shim. Production selection authority is engine.selectedKeys.
4009
+ * Kept for existing styling tests; dispatches to engine authority.
4010
+ */
4011
+ _mirrorLegacySelection(event, context) {
4012
+ this._dispatchSelection(event, context);
4013
+ }
4014
+ _requestSelectionReplacement(entries, reason, context) {
4015
+ for (const entry of entries) {
4016
+ const record = this._itemRegistry.keyToRecord.get(entry.key) ?? this._selectedRecordsByKey.get(entry.key);
4017
+ this._selectedRecordsByKey.set(entry.key, record ?? {
4018
+ key: entry.key,
4019
+ item: entry.item,
4020
+ index: entry.index,
4021
+ label: this._getItemLabel(entry.item),
4022
+ value: this._getItemValue(entry.item),
4023
+ disabled: Boolean(entry.item?.disabled),
4024
+ groupKey: entry.item?.group == null
4025
+ ? null
4026
+ : String(entry.item.group),
4027
+ });
4028
+ }
4029
+ this._dispatchSelection({ type: 'REPLACE_SELECTION_REQUEST', keys: entries.map(({ key }) => key), reason }, context);
4030
+ }
4031
+ _registerShadowItems(indices) {
4032
+ const keys = indices.map((index) => this._itemRegistry.indexToKey.get(index)).filter((key) => key !== undefined);
4033
+ this._engine.dispatch({ type: 'ITEMS_REGISTERED', keys, disabledKeys: this._getBlockedDisabledKeys() });
4034
+ this._clearDisabledEngineActive('visible items');
4035
+ this._assertSelectionProjection('visible items');
4036
+ }
4037
+ _syncLegacyActiveAria() {
4038
+ this._syncComboboxAccessibility();
4039
+ }
2657
4040
  _syncStyleConfigVariables() {
2658
4041
  const styles = this._config.styles;
4042
+ if (!styles)
4043
+ return;
2659
4044
  this._applyStyleVariableMap(styles.option, {
2660
4045
  background: '--select-option-bg',
2661
4046
  backgroundColor: '--select-option-bg',
@@ -3070,10 +4455,7 @@ class EnhancedSelect extends HTMLElement {
3070
4455
  delete inputStyles.maxHeight;
3071
4456
  Object.assign(input.style, inputStyles);
3072
4457
  }
3073
- input.setAttribute('role', 'combobox');
3074
- input.setAttribute('aria-expanded', 'false');
3075
4458
  input.setAttribute('aria-haspopup', 'listbox');
3076
- input.setAttribute('aria-autocomplete', this._config.searchable ? 'list' : 'none');
3077
4459
  return input;
3078
4460
  }
3079
4461
  _createDropdown() {
@@ -3087,11 +4469,6 @@ class EnhancedSelect extends HTMLElement {
3087
4469
  if (this._config.styles.dropdown) {
3088
4470
  Object.assign(dropdown.style, this._config.styles.dropdown);
3089
4471
  }
3090
- dropdown.setAttribute('role', 'listbox');
3091
- dropdown.setAttribute('aria-labelledby', `${this._uniqueId}-input`);
3092
- if (this._config.selection.mode === 'multi') {
3093
- dropdown.setAttribute('aria-multiselectable', 'true');
3094
- }
3095
4472
  return dropdown;
3096
4473
  }
3097
4474
  _createOptionsContainer() {
@@ -3107,6 +4484,12 @@ class EnhancedSelect extends HTMLElement {
3107
4484
  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;';
3108
4485
  return liveRegion;
3109
4486
  }
4487
+ _createErrorDescription() {
4488
+ const description = document.createElement('div');
4489
+ description.id = `${this._uniqueId}-error`;
4490
+ description.style.cssText = 'position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0;';
4491
+ return description;
4492
+ }
3110
4493
  _createArrowContainer() {
3111
4494
  const container = document.createElement('div');
3112
4495
  container.className = 'dropdown-arrow-container';
@@ -3153,10 +4536,12 @@ class EnhancedSelect extends HTMLElement {
3153
4536
  if (this._liveRegion) {
3154
4537
  this._shadow.appendChild(this._liveRegion);
3155
4538
  }
4539
+ if (this._errorDescription) {
4540
+ this._shadow.appendChild(this._errorDescription);
4541
+ }
3156
4542
  // Set ARIA relationships
3157
4543
  const listboxId = `${this._uniqueId}-listbox`;
3158
4544
  this._dropdown.id = listboxId;
3159
- this._input.setAttribute('aria-controls', listboxId);
3160
4545
  this._input.setAttribute('aria-owns', listboxId);
3161
4546
  this._syncInputContainerMode();
3162
4547
  this._syncClearControlState();
@@ -4006,7 +5391,7 @@ class EnhancedSelect extends HTMLElement {
4006
5391
  margin: var(--select-group-header-margin, 0 calc(var(--select-options-padding, 6px) * -1));
4007
5392
  font-weight: var(--select-group-header-weight, 600);
4008
5393
  color: var(--select-group-header-color, var(--select-text-muted));
4009
- background: var(--select-group-header-bg, #ffffff);
5394
+ background: var(--select-group-header-bg, #f3f4f6);
4010
5395
  text-align: var(--select-group-header-text-align, left);
4011
5396
  font-size: var(--select-group-header-font-size, 0.7333em);
4012
5397
  text-transform: var(--select-group-header-text-transform, uppercase);
@@ -4513,6 +5898,25 @@ class EnhancedSelect extends HTMLElement {
4513
5898
  box-shadow: var(--select-group-header-shadow, 0 1px 2px rgba(0, 0, 0, 0.3));
4514
5899
  }
4515
5900
 
5901
+ :host(.dark-mode) .group-header,
5902
+ :host([dark-mode]) .group-header,
5903
+ :host([darkmode]) .group-header,
5904
+ :host([data-theme="dark"]) .group-header,
5905
+ :host([theme="dark"]) .group-header {
5906
+ color: var(--select-dark-group-header-color, var(--select-group-header-dark-color, #9ca3af));
5907
+ background: var(--select-dark-group-header-bg, var(--select-group-header-dark-bg, #1a1a2e));
5908
+ border-bottom: var(--select-group-header-border-bottom, 1px solid rgba(255, 255, 255, 0.08));
5909
+ box-shadow: var(--select-group-header-shadow, 0 1px 2px rgba(0, 0, 0, 0.3));
5910
+ }
5911
+
5912
+ :host(.dark-mode) .group-header:not(:first-child),
5913
+ :host([dark-mode]) .group-header:not(:first-child),
5914
+ :host([darkmode]) .group-header:not(:first-child),
5915
+ :host([data-theme="dark"]) .group-header:not(:first-child),
5916
+ :host([theme="dark"]) .group-header:not(:first-child) {
5917
+ border-top-color: var(--select-border);
5918
+ }
5919
+
4516
5920
  :host(.dark-mode) .option.selected::before,
4517
5921
  :host([dark-mode]) .option.selected::before,
4518
5922
  :host([darkmode]) .option.selected::before,
@@ -4610,7 +6014,7 @@ class EnhancedSelect extends HTMLElement {
4610
6014
  this._handleOpen();
4611
6015
  }
4612
6016
  // Focus the input (do not prevent default behavior for input itself)
4613
- this._input.focus();
6017
+ this._applyFocusIntent('input', 'input-container-trigger');
4614
6018
  // If we just opened the dropdown, transfer pointer capture to the
4615
6019
  // options container so the subsequent pointerup lands there instead of
4616
6020
  // staying with the input container (which would swallow the event).
@@ -4647,7 +6051,7 @@ class EnhancedSelect extends HTMLElement {
4647
6051
  if (!this._state.isOpen) {
4648
6052
  this._handleOpen();
4649
6053
  }
4650
- this._input.focus();
6054
+ this._applyFocusIntent('input', 'input-container-activation');
4651
6055
  });
4652
6056
  this._inputContent.addEventListener('pointermove', (e) => {
4653
6057
  this._updateMultiScrollDrag(e);
@@ -4673,7 +6077,10 @@ class EnhancedSelect extends HTMLElement {
4673
6077
  e.stopPropagation();
4674
6078
  });
4675
6079
  // Input focus/blur
4676
- this._input.addEventListener('focus', () => this._handleOpen());
6080
+ this._input.addEventListener('focus', () => {
6081
+ this._runEngineEffects(this._engine.dispatch({ type: 'FOCUS_GAINED' }));
6082
+ this._handleOpen();
6083
+ });
4677
6084
  // When the input loses focus we normally close the dropdown, but
4678
6085
  // clicking an option will blur the input before the option's click
4679
6086
  // handler executes. To avoid the blur timer closing the dropdown
@@ -4681,12 +6088,13 @@ class EnhancedSelect extends HTMLElement {
4681
6088
  // interacting with the options container. The close callback checks this
4682
6089
  // flag and skips closing if the user is about to click an option.
4683
6090
  this._input.addEventListener('blur', (e) => {
6091
+ this._runEngineEffects(this._engine.dispatch({ type: 'FOCUS_LOST' }));
4684
6092
  const related = e.relatedTarget;
4685
6093
  if (related && (this._shadow.contains(related) || this._container.contains(related))) {
4686
6094
  return;
4687
6095
  }
4688
6096
  // Delay to allow option click/focus transitions
4689
- setTimeout(() => {
6097
+ this._setLifecycleTimeout(() => {
4690
6098
  if (this._suppressBlurClose) {
4691
6099
  // another pointerdown inside options is in progress; keep open
4692
6100
  return;
@@ -4695,7 +6103,7 @@ class EnhancedSelect extends HTMLElement {
4695
6103
  if (active && (this._shadow.contains(active) || this._container.contains(active))) {
4696
6104
  return;
4697
6105
  }
4698
- this._handleClose();
6106
+ this._handleClose('blur');
4699
6107
  }, 150);
4700
6108
  });
4701
6109
  // Input search
@@ -4711,7 +6119,7 @@ class EnhancedSelect extends HTMLElement {
4711
6119
  // sufficient.
4712
6120
  this._optionsContainer.addEventListener('pointerdown', () => {
4713
6121
  this._suppressBlurClose = true;
4714
- setTimeout(() => {
6122
+ this._setLifecycleTimeout(() => {
4715
6123
  this._suppressBlurClose = false;
4716
6124
  }, 150); // Increased timeout to ensure click finishes before blur checks
4717
6125
  });
@@ -4746,42 +6154,6 @@ class EnhancedSelect extends HTMLElement {
4746
6154
  this._optionsContainer.addEventListener('click', handleOptionEvent);
4747
6155
  // Keyboard navigation
4748
6156
  this._input.addEventListener('keydown', (e) => this._handleKeydown(e));
4749
- // Click outside to close — robust detection across shadow DOM and custom renderers
4750
- document.addEventListener('pointerdown', (e) => {
4751
- const path = (e.composedPath && e.composedPath()) || [];
4752
- let clickedInside = false;
4753
- for (const node of path) {
4754
- if (node === this || node === this._container) {
4755
- clickedInside = true;
4756
- break;
4757
- }
4758
- if (node instanceof Node) {
4759
- try {
4760
- if (this._shadow && this._shadow.contains(node)) {
4761
- clickedInside = true;
4762
- break;
4763
- }
4764
- }
4765
- catch (err) {
4766
- // ignore
4767
- }
4768
- }
4769
- if (node instanceof Element) {
4770
- try {
4771
- if (node.matches('[data-sm-selectable], [data-selectable], [data-sm-state], .input-container, .select-container, .dropdown-arrow-container, .clear-control-button')) {
4772
- clickedInside = true;
4773
- break;
4774
- }
4775
- }
4776
- catch (err) {
4777
- // ignore
4778
- }
4779
- }
4780
- }
4781
- if (!clickedInside) {
4782
- this._handleClose();
4783
- }
4784
- });
4785
6157
  }
4786
6158
  _initializeObservers() {
4787
6159
  // Disconnect existing observer if any
@@ -4807,41 +6179,143 @@ class EnhancedSelect extends HTMLElement {
4807
6179
  return;
4808
6180
  }
4809
6181
  this._setBusy(true);
6182
+ const generation = ++this._asyncGeneration;
4810
6183
  try {
4811
6184
  const items = await this._config.serverSide.fetchSelectedItems(this._config.serverSide.initialSelectedValues);
4812
- // Add to state
4813
- items.forEach((item, index) => {
4814
- this._state.selectedItems.set(index, item);
4815
- this._state.selectedIndices.add(index);
6185
+ if (generation !== this._asyncGeneration || !this.isConnected)
6186
+ return;
6187
+ const fetchedRegistry = createItemRegistry(items, this._itemAdapter, {
6188
+ duplicateKeyPolicy: this._getDuplicateKeyPolicy(),
4816
6189
  });
6190
+ this._requestSelectionReplacement(fetchedRegistry.records, 'external-value-sync', 'initial selected items');
4817
6191
  this._updateInputDisplay();
4818
6192
  }
4819
6193
  catch (error) {
6194
+ if (generation !== this._asyncGeneration || !this.isConnected)
6195
+ return;
4820
6196
  this._handleError(error);
4821
6197
  }
4822
6198
  finally {
4823
- this._setBusy(false);
6199
+ if (generation === this._asyncGeneration && this.isConnected) {
6200
+ this._setBusy(false);
6201
+ }
4824
6202
  }
4825
6203
  }
6204
+ _runEngineEffects(effects) {
6205
+ this._effectRunner.run(effects, {
6206
+ focusTrigger: () => {
6207
+ this._applyFocusIntent('input', 'engine-focus-trigger');
6208
+ },
6209
+ syncAria: () => {
6210
+ this._syncPopupAria();
6211
+ },
6212
+ });
6213
+ }
6214
+ _syncPopupAria() {
6215
+ if (!this._input)
6216
+ return;
6217
+ this._syncComboboxAccessibility();
6218
+ }
6219
+ _syncComboboxAccessibility() {
6220
+ if (!this._input || !this._engine || !this._state)
6221
+ return;
6222
+ const accessibilityState = deriveAccessibilityState(this._engine.state, {
6223
+ searchable: this._config.searchable,
6224
+ readonly: !this._config.searchable,
6225
+ invalid: this._hasError,
6226
+ label: {
6227
+ ariaLabel: this.getAttribute('aria-label')?.trim() || null,
6228
+ ariaDescription: this.getAttribute('aria-description')?.trim() || null,
6229
+ },
6230
+ errorMessage: this._errorMessage,
6231
+ errorDescriptionId: this._hasError && this._errorMessage ? this._errorDescription?.id ?? null : null,
6232
+ });
6233
+ const effects = computeAccessibilityEffects(accessibilityState, {
6234
+ controlsId: this._dropdown?.id || null,
6235
+ optionKeys: [],
6236
+ }).filter((effect) => effect.type === 'SYNC_COMBOBOX_ARIA');
6237
+ applyAccessibilityEffects(effects, {
6238
+ combobox: this._input,
6239
+ getOptionByKey: (key) => {
6240
+ if (!this._state.isOpen)
6241
+ return null;
6242
+ const index = this._itemRegistry.keyToIndex.get(key);
6243
+ return index === undefined ? null : this._getOptionElementByIndex(index);
6244
+ },
6245
+ });
6246
+ }
6247
+ _syncListboxAccessibility() {
6248
+ if (!this._dropdown || !this._engine || !this._state)
6249
+ return;
6250
+ const derivedState = deriveAccessibilityState(this._engine.state, {
6251
+ label: { ariaLabel: this.getAttribute('aria-label')?.trim() || null },
6252
+ });
6253
+ const accessibilityState = {
6254
+ ...derivedState,
6255
+ // The component's existing busy lifecycle is not yet mirrored to engine dataStatus.
6256
+ busy: this._state.isBusy,
6257
+ };
6258
+ const effects = computeAccessibilityEffects(accessibilityState, {
6259
+ controlsId: this._dropdown.id || null,
6260
+ optionKeys: [],
6261
+ }).filter((effect) => effect.type === 'SYNC_LISTBOX_ARIA');
6262
+ applyAccessibilityEffects(effects, { listbox: this._dropdown });
6263
+ }
6264
+ _syncRenderedOptionAccessibility() {
6265
+ if (!this._optionsContainer || !this._engine || !this._state)
6266
+ return;
6267
+ const optionTargets = new Map();
6268
+ this._optionsContainer.querySelectorAll('[data-index]').forEach((option) => {
6269
+ const index = Number(option.getAttribute('data-index'));
6270
+ if (!Number.isFinite(index))
6271
+ return;
6272
+ const key = this._itemRegistry.indexToKey.get(index);
6273
+ if (key !== undefined)
6274
+ optionTargets.set(key, option);
6275
+ });
6276
+ if (optionTargets.size === 0)
6277
+ return;
6278
+ const effects = computeAccessibilityEffects(deriveAccessibilityState(this._engine.state), {
6279
+ controlsId: this._dropdown?.id || null,
6280
+ optionKeys: [...optionTargets.keys()],
6281
+ }).filter((effect) => effect.type === 'SYNC_OPTION_ARIA');
6282
+ applyAccessibilityEffects(effects, {
6283
+ getOptionByKey: (key) => optionTargets.get(key) ?? null,
6284
+ });
6285
+ }
6286
+ _applyFocusIntent(target, reason, focusTarget) {
6287
+ const effects = computeAccessibilityEffects(deriveAccessibilityState(this._engine.state), {
6288
+ optionKeys: [],
6289
+ focusIntents: [{ target, reason }],
6290
+ }).filter((effect) => effect.type === 'FOCUS_INTENT');
6291
+ applyAccessibilityEffects(effects, {
6292
+ focusTargets: {
6293
+ input: target === 'input' ? this._input : null,
6294
+ clearButton: target === 'clear-button' ? this._clearControl : null,
6295
+ getActiveOption: () => target === 'active-option' ? focusTarget ?? null : null,
6296
+ },
6297
+ }, { applyFocus: true });
6298
+ }
4826
6299
  _handleOpen() {
4827
- if (!this._config.enabled || this._state.isOpen)
6300
+ if (!this._config.enabled) {
6301
+ this._runEngineEffects(this._engine.dispatch({ type: 'DISABLED_CHANGED', disabled: true }));
6302
+ return;
6303
+ }
6304
+ if (this._state.isOpen)
4828
6305
  return;
4829
6306
  // close any other open selects before proceeding
4830
6307
  EnhancedSelect._instances.forEach(inst => {
4831
6308
  if (inst !== this)
4832
6309
  inst._handleClose();
4833
6310
  });
4834
- // Always focus the input when opening so callers (arrow click,
4835
- // programmatic `open()`, etc.) get the keyboard cursor. This was a
4836
- // frequent source of confusion in #14 where people opened the dropdown
4837
- // but the text field never received focus.
4838
- this._input.focus();
6311
+ const effects = this._engine.dispatch({ type: 'OPEN_REQUEST' });
6312
+ if (!effects.some((effect) => effect.type === 'POPUP_OPENED'))
6313
+ return;
6314
+ this._runEngineEffects(effects);
4839
6315
  this._markOpenStart();
4840
- this._state.isOpen = true;
4841
6316
  this.setAttribute('data-open', 'true');
4842
6317
  this._liftStackingAncestors();
4843
6318
  this._dropdown.style.display = 'block';
4844
- this._input.setAttribute('aria-expanded', 'true');
4845
6319
  this._updateArrowRotation();
4846
6320
  // Render options when opening
4847
6321
  this._renderOptions();
@@ -4852,26 +6326,32 @@ class EnhancedSelect extends HTMLElement {
4852
6326
  this._announce('Options expanded');
4853
6327
  // Scroll to selected if configured
4854
6328
  if (this._config.scrollToSelected.enabled) {
6329
+ const keyboardActiveChangeGeneration = this._keyboardActiveChangeGeneration;
6330
+ const canRestoreOpenSelection = () => this._state.isOpen
6331
+ && this._keyboardActiveChangeGeneration === keyboardActiveChangeGeneration;
4855
6332
  // Use requestAnimationFrame for better timing after render
4856
- requestAnimationFrame(() => {
6333
+ this._requestLifecycleFrame(() => {
6334
+ if (!canRestoreOpenSelection())
6335
+ return;
4857
6336
  // Double RAF to ensure layout is complete
4858
- requestAnimationFrame(() => {
6337
+ this._requestLifecycleFrame(() => {
6338
+ if (!canRestoreOpenSelection())
6339
+ return;
4859
6340
  this._scrollToSelected();
4860
6341
  });
4861
6342
  });
4862
6343
  }
4863
6344
  }
4864
- _handleClose() {
4865
- if (!this._state.isOpen)
6345
+ _handleClose(reason = 'programmatic') {
6346
+ const effects = this._engine.dispatch({ type: 'CLOSE_REQUEST', reason });
6347
+ if (!effects.some((effect) => effect.type === 'POPUP_CLOSED'))
4866
6348
  return;
4867
- this._state.isOpen = false;
4868
6349
  this.removeAttribute('data-open');
4869
6350
  this._restoreLiftedAncestors();
4870
6351
  this._dropdown.style.display = 'none';
4871
6352
  this._dropdown.setAttribute('data-placement', this._resolvedDropdownPlacement);
4872
- this._input.setAttribute('aria-expanded', 'false');
4873
- this._input.removeAttribute('aria-activedescendant');
4874
6353
  this._updateArrowRotation();
6354
+ this._runEngineEffects(effects);
4875
6355
  this._emit('close', {});
4876
6356
  this._config.callbacks.onClose?.();
4877
6357
  this._announce('Options collapsed');
@@ -4882,14 +6362,13 @@ class EnhancedSelect extends HTMLElement {
4882
6362
  this._liftStackingAncestors();
4883
6363
  this._dropdown.style.display = 'block';
4884
6364
  this._syncDropdownPlacement();
4885
- this._input.setAttribute('aria-expanded', 'true');
4886
6365
  }
4887
6366
  else {
4888
6367
  this.removeAttribute('data-open');
4889
6368
  this._restoreLiftedAncestors();
4890
6369
  this._dropdown.style.display = 'none';
4891
- this._input.setAttribute('aria-expanded', 'false');
4892
6370
  }
6371
+ this._syncComboboxAccessibility();
4893
6372
  }
4894
6373
  _liftStackingAncestors() {
4895
6374
  this._restoreLiftedAncestors();
@@ -4977,6 +6456,9 @@ class EnhancedSelect extends HTMLElement {
4977
6456
  if (!this._isPerfEnabled())
4978
6457
  return;
4979
6458
  performance.measure(name, start, end);
6459
+ performance.clearMarks(start);
6460
+ performance.clearMarks(end);
6461
+ performance.clearMeasures(name);
4980
6462
  }
4981
6463
  _markOpenStart() {
4982
6464
  if (!this._isPerfEnabled())
@@ -5074,7 +6556,7 @@ class EnhancedSelect extends HTMLElement {
5074
6556
  this._state.lastNotifiedQuery = query;
5075
6557
  this._state.lastNotifiedResultCount = count;
5076
6558
  // Use setTimeout to avoid synchronous state updates during render
5077
- setTimeout(() => {
6559
+ this._setLifecycleTimeout(() => {
5078
6560
  this._emit('search', { query, results: filteredItems, count });
5079
6561
  this._config.callbacks.onSearch?.(query);
5080
6562
  }, 0);
@@ -5146,13 +6628,17 @@ class EnhancedSelect extends HTMLElement {
5146
6628
  if (!this._state.isOpen) {
5147
6629
  this._handleOpen();
5148
6630
  }
5149
- else if (this._state.activeIndex >= 0) {
5150
- this._selectOption(this._state.activeIndex, { shiftKey: e.shiftKey, toggleKey: e.ctrlKey || e.metaKey });
6631
+ else {
6632
+ const activeKey = this._engine.state.activeKey;
6633
+ const currentIndex = activeKey === null ? -1 : this._itemRegistry.keyToIndex.get(activeKey) ?? -1;
6634
+ if (currentIndex >= 0) {
6635
+ this._selectOption(currentIndex, { shiftKey: e.shiftKey, toggleKey: e.ctrlKey || e.metaKey, reason: 'keyboard' });
6636
+ }
5151
6637
  }
5152
6638
  break;
5153
6639
  case 'Escape':
5154
6640
  e.preventDefault();
5155
- this._handleClose();
6641
+ this._handleClose('escape');
5156
6642
  break;
5157
6643
  case 'Tab':
5158
6644
  if (this._state.isOpen) {
@@ -5178,7 +6664,9 @@ class EnhancedSelect extends HTMLElement {
5178
6664
  const selectableIndices = this._getSelectableOptionIndices();
5179
6665
  if (selectableIndices.length === 0)
5180
6666
  return;
5181
- const currentPosition = selectableIndices.indexOf(this._state.activeIndex);
6667
+ const activeKey = this._engine.state.activeKey;
6668
+ const currentIndex = activeKey === null ? -1 : this._itemRegistry.keyToIndex.get(activeKey) ?? -1;
6669
+ const currentPosition = selectableIndices.indexOf(currentIndex);
5182
6670
  const basePosition = currentPosition >= 0
5183
6671
  ? currentPosition
5184
6672
  : delta >= 0
@@ -5188,7 +6676,7 @@ class EnhancedSelect extends HTMLElement {
5188
6676
  const next = selectableIndices[nextPosition];
5189
6677
  this._setActive(next);
5190
6678
  if (this._config.selection.mode === 'multi' && opts?.shiftKey) {
5191
- const anchor = this._rangeAnchorIndex ?? this._state.activeIndex;
6679
+ const anchor = this._rangeAnchorIndex ?? currentIndex;
5192
6680
  const anchorIndex = anchor >= 0 ? anchor : next;
5193
6681
  if (this._rangeAnchorIndex === null) {
5194
6682
  this._rangeAnchorIndex = anchorIndex;
@@ -5196,14 +6684,26 @@ class EnhancedSelect extends HTMLElement {
5196
6684
  this._selectRange(anchorIndex, next, { clear: !opts?.toggleKey });
5197
6685
  }
5198
6686
  }
5199
- _setActive(index) {
5200
- const option = this._getOptionElementByIndex(index);
5201
- if (!option || (option.getAttribute('aria-disabled') === 'true' && !option.classList.contains('smilodon-option--disabled-focusable'))) {
6687
+ _setActive(index, reason = 'keyboard') {
6688
+ this._ensureRegistryCurrent();
6689
+ const record = this._getRecordByIndex(index);
6690
+ let option = this._getOptionElementByIndex(index);
6691
+ if (!option && record && this._guardedVirtualizer) {
6692
+ this._materializeGuardedVirtualKey(record.key);
6693
+ option = this._getOptionElementByIndex(index);
6694
+ }
6695
+ if (!record || record.disabled || !option || option.getAttribute('aria-disabled') === 'true') {
5202
6696
  return;
5203
6697
  }
6698
+ if (reason === 'keyboard')
6699
+ this._keyboardActiveChangeGeneration += 1;
6700
+ const previousIndex = this._state.activeIndex;
6701
+ this._dispatchActiveKey(record.key, reason, 'set active');
6702
+ if (this._state.activeIndex !== index)
6703
+ return;
5204
6704
  // Clear previous active state
5205
- if (this._state.activeIndex >= 0) {
5206
- const prevOption = this._getOptionElementByIndex(this._state.activeIndex);
6705
+ if (previousIndex >= 0 && previousIndex !== index) {
6706
+ const prevOption = this._getOptionElementByIndex(previousIndex);
5207
6707
  if (prevOption) {
5208
6708
  // Check if it's a custom SelectOption or a lightweight DOM element
5209
6709
  if ('setActive' in prevOption && typeof prevOption.setActive === 'function') {
@@ -5211,11 +6711,10 @@ class EnhancedSelect extends HTMLElement {
5211
6711
  }
5212
6712
  else {
5213
6713
  // Lightweight option - remove active class
5214
- prevOption.classList.remove('smilodon-option--active');
6714
+ prevOption.classList.remove('active', 'smilodon-option--active');
5215
6715
  }
5216
6716
  }
5217
6717
  }
5218
- this._state.activeIndex = index;
5219
6718
  // Set new active state
5220
6719
  if (option) {
5221
6720
  // Check if it's a custom SelectOption or a lightweight DOM element
@@ -5224,7 +6723,7 @@ class EnhancedSelect extends HTMLElement {
5224
6723
  }
5225
6724
  else {
5226
6725
  // Lightweight option - add active class
5227
- option.classList.add('smilodon-option--active');
6726
+ option.classList.add('active', 'smilodon-option--active');
5228
6727
  }
5229
6728
  if (typeof option.scrollIntoView === 'function') {
5230
6729
  // Don't scroll wildly when just opening with pre-selections
@@ -5234,8 +6733,7 @@ class EnhancedSelect extends HTMLElement {
5234
6733
  const total = this._state.loadedItems.length;
5235
6734
  this._announce(`Item ${index + 1} of ${total}`);
5236
6735
  // Update aria-activedescendant using the actual option id when available
5237
- const optionId = option.id || `${this._uniqueId}-option-${index}`;
5238
- this._input.setAttribute('aria-activedescendant', optionId);
6736
+ this._syncLegacyActiveAria();
5239
6737
  }
5240
6738
  }
5241
6739
  _getOptionElementByIndex(index) {
@@ -5246,10 +6744,16 @@ class EnhancedSelect extends HTMLElement {
5246
6744
  // Only return elements with data-index or data-sm-selectable attributes
5247
6745
  return Array.from(this._optionsContainer.children).filter((child) => {
5248
6746
  return (child.hasAttribute('data-index') || child.hasAttribute('data-sm-selectable'))
5249
- && (child.getAttribute('aria-disabled') !== 'true' || child.classList.contains('smilodon-option--disabled-focusable'));
6747
+ && child.getAttribute('aria-disabled') !== 'true';
5250
6748
  });
5251
6749
  }
5252
6750
  _getSelectableOptionIndices() {
6751
+ if (this._guardedVirtualizer) {
6752
+ return this._renderPlan.filteredKeys.flatMap((key) => {
6753
+ const record = this._itemRegistry.keyToRecord.get(key);
6754
+ return record && !record.disabled ? [record.index] : [];
6755
+ });
6756
+ }
5253
6757
  return this._getSelectableOptions()
5254
6758
  .map((option) => Number(option.getAttribute('data-sm-index') ?? option.getAttribute('data-index')))
5255
6759
  .filter((index) => Number.isFinite(index));
@@ -5267,7 +6771,7 @@ class EnhancedSelect extends HTMLElement {
5267
6771
  keyboardFocus: (index) => {
5268
6772
  this._setActive(index);
5269
6773
  const el = this._getOptionElementByIndex(index);
5270
- el?.focus?.();
6774
+ this._applyFocusIntent('active-option', 'renderer-keyboard-focus', el);
5271
6775
  },
5272
6776
  };
5273
6777
  }
@@ -5282,43 +6786,25 @@ class EnhancedSelect extends HTMLElement {
5282
6786
  const getValue = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
5283
6787
  const matchIndex = this._state.loadedItems.findIndex((item) => getValue(item).toLowerCase().startsWith(this._typeBuffer));
5284
6788
  if (matchIndex >= 0) {
5285
- this._setActive(matchIndex);
6789
+ this._setActive(matchIndex, 'search');
5286
6790
  }
5287
6791
  }
5288
6792
  _selectAll() {
5289
6793
  if (this._config.selection.mode !== 'multi')
5290
6794
  return;
6795
+ this._ensureRegistryCurrent();
5291
6796
  const options = this._getSelectableOptions();
5292
- const maxSelections = this._config.selection.maxSelections || 0;
6797
+ const entries = this._getSelectedEntries();
5293
6798
  options.forEach((option) => {
5294
6799
  const optionIndex = Number(option.getAttribute('data-sm-index') ?? option.getAttribute('data-index'));
5295
6800
  if (!Number.isFinite(optionIndex))
5296
6801
  return;
5297
- if (maxSelections > 0 && this._state.selectedIndices.size >= maxSelections) {
5298
- return;
5299
- }
5300
- if (!this._state.selectedIndices.has(optionIndex)) {
5301
- // Check if it's a custom SelectOption or a lightweight DOM element
5302
- if ('getConfig' in option && typeof option.getConfig === 'function') {
5303
- const config = option.getConfig();
5304
- if (this._isOptionSelectionBlocked(config.item))
5305
- return;
5306
- this._state.selectedIndices.add(optionIndex);
5307
- this._state.selectedItems.set(optionIndex, config.item);
5308
- option.setSelected(true);
5309
- }
5310
- else {
5311
- // Lightweight option - get item from data attribute or state
5312
- const item = this._state.loadedItems[optionIndex];
5313
- if (item && !this._isOptionSelectionBlocked(item)) {
5314
- this._state.selectedIndices.add(optionIndex);
5315
- this._state.selectedItems.set(optionIndex, item);
5316
- option.classList.add('smilodon-option--selected');
5317
- option.setAttribute('aria-selected', 'true');
5318
- }
5319
- }
5320
- }
6802
+ const record = this._getRecordByIndex(optionIndex);
6803
+ if (record && !this._isOptionSelectionBlocked(record.item))
6804
+ entries.push(record);
5321
6805
  });
6806
+ this._requestSelectionReplacement(entries, 'keyboard', 'select all');
6807
+ this._renderOptions();
5322
6808
  this._updateInputDisplay();
5323
6809
  this._emitChange();
5324
6810
  this._announce(`Selected all ${options.length} items`);
@@ -5326,82 +6812,101 @@ class EnhancedSelect extends HTMLElement {
5326
6812
  _selectRange(start, end, opts) {
5327
6813
  if (this._config.selection.mode !== 'multi')
5328
6814
  return;
5329
- const maxSelections = this._config.selection.maxSelections || 0;
6815
+ this._ensureRegistryCurrent();
5330
6816
  const [min, max] = start < end ? [start, end] : [end, start];
5331
- if (opts?.clear) {
5332
- this._state.selectedIndices.clear();
5333
- this._state.selectedItems.clear();
5334
- }
6817
+ const selectedEntries = this._getSelectedEntries();
6818
+ const entries = opts?.clear
6819
+ ? selectedEntries.filter((entry) => !this._itemRegistry.keyToRecord.has(entry.key))
6820
+ : selectedEntries;
5335
6821
  for (let i = min; i <= max; i += 1) {
5336
- if (maxSelections > 0 && this._state.selectedIndices.size >= maxSelections)
5337
- break;
5338
- const item = this._state.loadedItems[i];
6822
+ const record = this._getRecordByIndex(i);
5339
6823
  const optionEl = this._getOptionElementByIndex(i);
5340
6824
  if (optionEl?.getAttribute('aria-disabled') === 'true' && !optionEl.classList.contains('smilodon-option--disabled-selectable'))
5341
6825
  continue;
5342
- if (!item)
5343
- continue;
5344
- if (this._isOptionSelectionBlocked(item))
6826
+ if (!record || this._isOptionSelectionBlocked(record.item))
5345
6827
  continue;
5346
- this._state.selectedIndices.add(i);
5347
- this._state.selectedItems.set(i, item);
6828
+ entries.push(record);
5348
6829
  }
6830
+ this._requestSelectionReplacement(entries, opts?.reason ?? 'keyboard', 'select range');
5349
6831
  this._renderOptions();
5350
6832
  this._updateInputDisplay();
6833
+ const target = this._getRecordByIndex(end);
6834
+ const selectDetail = target ? this._getSelectEventDetail(target) : null;
6835
+ if (selectDetail)
6836
+ this._emit('select', selectDetail);
5351
6837
  this._emitChange();
5352
6838
  this._announce(`${this._state.selectedIndices.size} items selected`);
6839
+ if (selectDetail)
6840
+ this._config.callbacks.onSelect?.(selectDetail);
6841
+ }
6842
+ _getSelectEventDetail(record) {
6843
+ const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
6844
+ const getLabel = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
6845
+ return {
6846
+ item: record.item,
6847
+ index: record.index,
6848
+ value: getValue(record.item),
6849
+ label: getLabel(record.item),
6850
+ selected: this._engine.state.selectedKeys.has(record.key),
6851
+ multi: this._config.selection.mode === 'multi',
6852
+ };
5353
6853
  }
5354
6854
  _setInitialActiveOption() {
5355
6855
  const selectableIndices = this._getSelectableOptionIndices();
5356
- if (selectableIndices.length === 0)
5357
- return;
5358
6856
  const selected = Array.from(this._state.selectedIndices).sort((a, b) => a - b);
5359
- if (this._config.selection.mode === 'multi' && selected.length === 0) {
5360
- this._state.activeIndex = -1;
5361
- this._input.removeAttribute('aria-activedescendant');
6857
+ if (selectableIndices.length === 0 || (this._config.selection.mode === 'multi' && selected.length === 0)) {
6858
+ this._dispatchActiveKey(null, 'open', 'initial active option');
5362
6859
  return;
5363
6860
  }
5364
6861
  const target = selected.find((index) => selectableIndices.includes(index)) ?? selectableIndices[0];
5365
- this._setActive(target);
6862
+ this._setActive(target, 'open');
5366
6863
  }
5367
6864
  _announce(message) {
5368
- if (this._liveRegion) {
5369
- this._liveRegion.textContent = message;
5370
- setTimeout(() => {
5371
- if (this._liveRegion)
5372
- this._liveRegion.textContent = '';
5373
- }, 1000);
5374
- }
6865
+ const effects = computeAccessibilityEffects(deriveAccessibilityState(this._engine.state), {
6866
+ optionKeys: [],
6867
+ announcements: [{ politeness: 'polite', message }],
6868
+ }).filter((effect) => effect.type === 'ANNOUNCE');
6869
+ applyAccessibilityEffects(effects, { liveRegion: this._liveRegion });
6870
+ if (!this._liveRegion)
6871
+ return;
6872
+ this._setLifecycleTimeout(() => {
6873
+ const clearEffects = computeAccessibilityEffects(deriveAccessibilityState(this._engine.state), {
6874
+ optionKeys: [],
6875
+ announcements: [{ politeness: 'polite', message: '' }],
6876
+ }).filter((effect) => effect.type === 'ANNOUNCE');
6877
+ applyAccessibilityEffects(clearEffects, { liveRegion: this._liveRegion });
6878
+ }, 1000);
5375
6879
  }
5376
6880
  _selectOption(index, opts) {
5377
6881
  // FIX: Do not rely on this._optionsContainer.children[index] because filtering changes the children
5378
6882
  // Instead, use the index to update state directly
5379
- const item = this._state.loadedItems[index];
5380
- if (!item) {
6883
+ this._ensureRegistryCurrent();
6884
+ const record = this._getRecordByIndex(index);
6885
+ if (!record)
5381
6886
  return;
5382
- }
6887
+ index = record.index;
6888
+ const item = record.item;
5383
6889
  if (this._isOptionSelectionBlocked(item)) {
5384
6890
  return;
5385
6891
  }
5386
- const isCurrentlySelected = this._state.selectedIndices.has(index);
6892
+ const isCurrentlySelected = this._engine.state.selectedKeys.has(record.key);
6893
+ const reason = opts?.reason ?? 'pointer';
5387
6894
  // Keep active/focus styling aligned with the most recently interacted option.
5388
6895
  // Without this, a previously selected item may retain active classes/styles
5389
6896
  // after selecting a different option.
5390
- this._state.activeIndex = index;
6897
+ if (!record.disabled) {
6898
+ this._dispatchActiveKey(record.key, reason === 'keyboard' ? 'keyboard' : 'pointer', 'option selection');
6899
+ }
5391
6900
  if (this._config.selection.mode === 'single') {
5392
- // Single select: clear previous and select new
5393
- const wasSelected = this._state.selectedIndices.has(index);
5394
- this._state.selectedIndices.clear();
5395
- this._state.selectedItems.clear();
5396
- if (!wasSelected || !this._config.selection.allowDeselect) {
5397
- // Select this option
5398
- this._state.selectedIndices.add(index);
5399
- this._state.selectedItems.set(index, item);
5400
- }
6901
+ this._dispatchSelection({
6902
+ type: isCurrentlySelected && this._config.selection.allowDeselect ? 'TOGGLE_KEY_REQUEST' : 'SELECT_KEY_REQUEST',
6903
+ key: record.key,
6904
+ reason,
6905
+ }, 'single option selection');
5401
6906
  // Re-render to update all option styles
5402
6907
  this._renderOptions();
5403
6908
  if (this._config.selection.closeOnSelect) {
5404
- this._handleClose();
6909
+ this._handleClose('selection');
5405
6910
  }
5406
6911
  }
5407
6912
  else {
@@ -5409,35 +6914,27 @@ class EnhancedSelect extends HTMLElement {
5409
6914
  const shiftKey = Boolean(opts?.shiftKey);
5410
6915
  if (shiftKey) {
5411
6916
  const anchor = this._rangeAnchorIndex ?? index;
5412
- this._selectRange(anchor, index, { clear: !toggleKey });
6917
+ this._selectRange(anchor, index, { clear: !toggleKey, reason });
5413
6918
  this._rangeAnchorIndex = anchor;
5414
6919
  return;
5415
6920
  }
5416
6921
  // Multi select with toggle
5417
6922
  const maxSelections = this._config.selection.maxSelections || 0;
5418
- if (isCurrentlySelected) {
5419
- // Deselect (toggle off)
5420
- this._state.selectedIndices.delete(index);
5421
- this._state.selectedItems.delete(index);
5422
- }
5423
- else {
5424
- // Select (toggle on)
5425
- if (maxSelections > 0 && this._state.selectedIndices.size >= maxSelections) {
5426
- this._announce(`Maximum ${maxSelections} selections allowed`);
5427
- return; // Max selections reached
5428
- }
5429
- this._state.selectedIndices.add(index);
5430
- this._state.selectedItems.set(index, item);
6923
+ if (!isCurrentlySelected && maxSelections > 0 && this._engine.state.selectedKeys.size >= maxSelections) {
6924
+ this._announce(`Maximum ${maxSelections} selections allowed`);
6925
+ this._renderOptions();
6926
+ return;
5431
6927
  }
6928
+ this._dispatchSelection({ type: 'TOGGLE_KEY_REQUEST', key: record.key, reason }, 'multi option selection');
5432
6929
  // Re-render to update styles (safer than trying to find the element in filtered list)
5433
6930
  this._renderOptions();
5434
6931
  }
5435
6932
  this._rangeAnchorIndex = index;
5436
6933
  this._updateInputDisplay();
6934
+ const selectDetail = this._getSelectEventDetail(record);
6935
+ this._emit('select', selectDetail);
5437
6936
  this._emitChange();
5438
- const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
5439
- const getLabel = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
5440
- const label = getLabel(item);
6937
+ const label = selectDetail.label;
5441
6938
  if (this._config.selection.mode === 'single') {
5442
6939
  this._announce(`Selected ${label}`);
5443
6940
  }
@@ -5446,25 +6943,34 @@ class EnhancedSelect extends HTMLElement {
5446
6943
  const action = isCurrentlySelected ? 'Deselected' : 'Selected';
5447
6944
  this._announce(`${action} ${label}. ${selectedCount} selected`);
5448
6945
  }
5449
- this._config.callbacks.onSelect?.({
5450
- item: item,
5451
- index,
5452
- value: getValue(item),
5453
- label: getLabel(item),
5454
- selected: this._state.selectedIndices.has(index),
5455
- });
6946
+ this._config.callbacks.onSelect?.(selectDetail);
5456
6947
  }
5457
- _handleOptionRemove(index) {
5458
- const item = this._state.selectedItems.get(index);
5459
- const option = this._getOptionElementByIndex(index);
5460
- this._state.selectedIndices.delete(index);
5461
- this._state.selectedItems.delete(index);
6948
+ _handleOptionRemove(index, key) {
6949
+ this._ensureRegistryCurrent();
6950
+ const entry = this._getSelectedEntries().find((selected) => key === undefined
6951
+ ? selected.index === index
6952
+ : selected.key === key);
6953
+ if (!entry)
6954
+ return;
6955
+ const item = entry.item;
6956
+ const activeElement = this._shadow.activeElement;
6957
+ const focusedBadge = activeElement instanceof HTMLButtonElement
6958
+ && activeElement.getAttribute('part') === 'chip-remove'
6959
+ ? activeElement.closest('.selection-badge')
6960
+ : null;
6961
+ const hadFocusedChipRemove = focusedBadge !== null;
6962
+ const focusedBadgeIndex = focusedBadge
6963
+ ? Array.from(this._inputContent.querySelectorAll('.selection-badge')).indexOf(focusedBadge)
6964
+ : -1;
6965
+ const option = this._itemRegistry.keyToRecord.has(entry.key)
6966
+ ? this._getOptionElementByIndex(entry.index)
6967
+ : null;
6968
+ this._dispatchSelection({ type: 'DESELECT_KEY_REQUEST', key: entry.key, reason: 'pointer' }, 'remove selected item');
5462
6969
  if (option && 'setSelected' in option && typeof option.setSelected === 'function') {
5463
6970
  option.setSelected(false);
5464
6971
  }
5465
6972
  else if (option) {
5466
6973
  option.classList.remove('selected', 'sm-selected', 'smilodon-option--selected');
5467
- option.setAttribute('aria-selected', 'false');
5468
6974
  const stateTokens = (option.dataset.smState || '')
5469
6975
  .split(' ')
5470
6976
  .map(token => token.trim())
@@ -5479,13 +6985,24 @@ class EnhancedSelect extends HTMLElement {
5479
6985
  this._updateInputDisplay();
5480
6986
  this._renderOptions();
5481
6987
  this._emitChange();
6988
+ if (hadFocusedChipRemove && this.isConnected) {
6989
+ const removeButtons = this._inputContent.querySelectorAll('[part="chip-remove"]');
6990
+ if (removeButtons.length > 0) {
6991
+ const nextFocusIndex = Math.min(Math.max(focusedBadgeIndex, 0), removeButtons.length - 1);
6992
+ removeButtons[nextFocusIndex].focus();
6993
+ }
6994
+ else {
6995
+ this._applyFocusIntent('input', 'selected-chip-removed');
6996
+ }
6997
+ }
5482
6998
  const config = option && 'getConfig' in option && typeof option.getConfig === 'function'
5483
6999
  ? option.getConfig()
5484
7000
  : undefined;
5485
- this._emit('remove', { item: config?.item ?? item, index });
7001
+ this._emit('remove', { item: config?.item ?? item, index: entry.index });
5486
7002
  }
5487
7003
  _updateInputDisplay() {
5488
- const selectedItems = Array.from(this._state.selectedItems.values());
7004
+ const selectedEntries = this._getSelectedEntries();
7005
+ const selectedItems = selectedEntries.map(({ item }) => item);
5489
7006
  const getLabel = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
5490
7007
  if (selectedItems.length === 0) {
5491
7008
  this._input.value = '';
@@ -5505,8 +7022,7 @@ class EnhancedSelect extends HTMLElement {
5505
7022
  const existingBadges = this._inputContent.querySelectorAll('.selection-badge');
5506
7023
  existingBadges.forEach(badge => badge.remove());
5507
7024
  // Create badges for each selected item
5508
- const selectedEntries = Array.from(this._state.selectedItems.entries());
5509
- selectedEntries.forEach(([index, item]) => {
7025
+ selectedEntries.forEach(({ key, index, item }) => {
5510
7026
  const badge = document.createElement('span');
5511
7027
  badge.className = 'selection-badge';
5512
7028
  if (this._config.styles.classNames?.badge) {
@@ -5549,7 +7065,7 @@ class EnhancedSelect extends HTMLElement {
5549
7065
  removeBtn.addEventListener('click', (e) => {
5550
7066
  e.stopPropagation();
5551
7067
  e.preventDefault();
5552
- this._handleOptionRemove(index);
7068
+ this._handleOptionRemove(index, key);
5553
7069
  });
5554
7070
  badge.appendChild(removeBtn);
5555
7071
  }
@@ -5562,7 +7078,7 @@ class EnhancedSelect extends HTMLElement {
5562
7078
  // Add fade-out animation
5563
7079
  this._optionsContainer.style.opacity = '0';
5564
7080
  this._optionsContainer.style.transition = 'opacity 0.15s ease-out';
5565
- setTimeout(() => {
7081
+ this._setLifecycleTimeout(() => {
5566
7082
  this._renderOptions();
5567
7083
  // Fade back in
5568
7084
  this._optionsContainer.style.opacity = '1';
@@ -5573,7 +7089,9 @@ class EnhancedSelect extends HTMLElement {
5573
7089
  if (this._state.selectedIndices.size === 0)
5574
7090
  return;
5575
7091
  const target = this._config.scrollToSelected.multiSelectTarget;
5576
- const indices = Array.from(this._state.selectedIndices).sort((a, b) => a - b);
7092
+ const indices = Array.from(this._state.selectedIndices).filter((index) => index >= 0).sort((a, b) => a - b);
7093
+ if (indices.length === 0)
7094
+ return;
5577
7095
  // For multi-select, find the closest selected item to the current scroll position
5578
7096
  let targetIndex;
5579
7097
  if (this._config.selection.mode === 'multi' && indices.length > 1) {
@@ -5601,7 +7119,14 @@ class EnhancedSelect extends HTMLElement {
5601
7119
  targetIndex = target === 'first' ? indices[0] : indices[indices.length - 1];
5602
7120
  }
5603
7121
  // Find and scroll to the target option
5604
- const option = this._getOptionElementByIndex(targetIndex);
7122
+ let option = this._getOptionElementByIndex(targetIndex);
7123
+ if (!option && this._guardedVirtualizer) {
7124
+ const targetKey = this._itemRegistry.indexToKey.get(targetIndex);
7125
+ if (targetKey !== undefined) {
7126
+ this._materializeGuardedVirtualKey(targetKey);
7127
+ option = this._getOptionElementByIndex(targetIndex);
7128
+ }
7129
+ }
5605
7130
  if (option) {
5606
7131
  // Use smooth scrolling with center alignment for better UX
5607
7132
  if (typeof option.scrollIntoView === 'function') {
@@ -5611,7 +7136,7 @@ class EnhancedSelect extends HTMLElement {
5611
7136
  });
5612
7137
  }
5613
7138
  // Also set it as active for keyboard navigation
5614
- this._setActive(targetIndex);
7139
+ this._setActive(targetIndex, 'programmatic');
5615
7140
  }
5616
7141
  }
5617
7142
  async _loadMoreItems() {
@@ -5643,12 +7168,7 @@ class EnhancedSelect extends HTMLElement {
5643
7168
  }
5644
7169
  _setBusy(busy) {
5645
7170
  this._state.isBusy = busy;
5646
- if (busy) {
5647
- this._dropdown.setAttribute('aria-busy', 'true');
5648
- }
5649
- else {
5650
- this._dropdown.removeAttribute('aria-busy');
5651
- }
7171
+ this._syncListboxAccessibility();
5652
7172
  // Trigger re-render to show/hide busy indicator
5653
7173
  // We use _renderOptions to handle the UI update
5654
7174
  this._renderOptions();
@@ -5817,10 +7337,11 @@ class EnhancedSelect extends HTMLElement {
5817
7337
  };
5818
7338
  }
5819
7339
  _emitChange() {
5820
- const selectedItems = Array.from(this._state.selectedItems.values());
7340
+ const selectedEntries = this._getSelectedEntries();
7341
+ const selectedItems = selectedEntries.map(({ item }) => item);
5821
7342
  const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
5822
7343
  const selectedValues = selectedItems.map(getValue);
5823
- const selectedIndices = Array.from(this._state.selectedIndices);
7344
+ const selectedIndices = selectedEntries.map(({ index }) => index).filter((index) => index >= 0);
5824
7345
  this._emit('change', { selectedItems, selectedValues, selectedIndices });
5825
7346
  this._config.callbacks.onChange?.(selectedItems, selectedValues);
5826
7347
  }
@@ -5829,8 +7350,11 @@ class EnhancedSelect extends HTMLElement {
5829
7350
  return this._optionRenderer;
5830
7351
  }
5831
7352
  set optionRenderer(renderer) {
7353
+ if (this._optionRenderer === renderer)
7354
+ return;
7355
+ this._invalidateGuardedMeasurements();
5832
7356
  this._optionRenderer = renderer;
5833
- this._setGlobalStylesMirroring(Boolean(renderer || this._classMap));
7357
+ this._setGlobalStylesMirroring(Boolean(renderer || this._classMap || this._groupHeaderRenderer));
5834
7358
  this._track('style', 'optionRendererChanged', { enabled: Boolean(renderer) });
5835
7359
  this._renderOptions();
5836
7360
  }
@@ -5838,12 +7362,12 @@ class EnhancedSelect extends HTMLElement {
5838
7362
  * Set items to display in the select
5839
7363
  */
5840
7364
  setItems(items) {
7365
+ this._invalidateGuardedMeasurements();
5841
7366
  const previousLength = this._state.loadedItems.length;
5842
- this._state.loadedItems = items;
5843
- // If grouped items exist, flatten them to items
5844
- if (this._state.groupedItems.length > 0) {
5845
- this._state.loadedItems = this._state.groupedItems.flatMap(group => group.options);
5846
- }
7367
+ this._rebuildItemRegistry(items);
7368
+ this._state.groupedItems = this._groupItemsByProperty(items);
7369
+ if (!this._state.searchQuery)
7370
+ this._updateInputDisplay();
5847
7371
  const newLength = this._state.loadedItems.length;
5848
7372
  // When infinite scroll is active (preserveScrollPosition = true),
5849
7373
  // we need to maintain scroll position during the update
@@ -5859,7 +7383,7 @@ class EnhancedSelect extends HTMLElement {
5859
7383
  // new ones simply appear below.
5860
7384
  this._dropdown.scrollTop = targetScrollTop;
5861
7385
  // Ensure it sticks after layout
5862
- requestAnimationFrame(() => {
7386
+ this._requestLifecycleFrame(() => {
5863
7387
  if (this._dropdown) {
5864
7388
  this._dropdown.scrollTop = targetScrollTop;
5865
7389
  }
@@ -5875,19 +7399,42 @@ class EnhancedSelect extends HTMLElement {
5875
7399
  this._renderOptions();
5876
7400
  }
5877
7401
  }
7402
+ _groupItemsByProperty(items) {
7403
+ const hasGroupData = items.some((item, index) => this._itemAdapter.getGroupKey?.(item, index) !== null);
7404
+ if (!hasGroupData) {
7405
+ return [];
7406
+ }
7407
+ const groups = new Map();
7408
+ items.forEach((item, index) => {
7409
+ const rawGroup = this._itemAdapter.getGroupKey?.(item, index);
7410
+ const label = rawGroup == null ? 'Ungrouped' : String(rawGroup);
7411
+ const options = groups.get(label);
7412
+ if (options) {
7413
+ options.push(item);
7414
+ }
7415
+ else {
7416
+ groups.set(label, [item]);
7417
+ }
7418
+ });
7419
+ return Array.from(groups.entries()).map(([label, options]) => ({ label, options }));
7420
+ }
5878
7421
  /**
5879
7422
  * Set grouped items
5880
7423
  */
5881
7424
  setGroupedItems(groupedItems) {
7425
+ this._destroyGuardedVirtualizer();
7426
+ this._rebuildItemRegistry(groupedItems.flatMap(group => group.options));
5882
7427
  this._state.groupedItems = groupedItems;
5883
- this._state.loadedItems = groupedItems.flatMap(group => group.options);
5884
7428
  this._renderOptions();
7429
+ if (!this._state.searchQuery)
7430
+ this._updateInputDisplay();
5885
7431
  }
5886
7432
  /**
5887
7433
  * Get currently selected items
5888
7434
  */
5889
7435
  getSelectedItems() {
5890
- return Array.from(this._state.selectedItems.values());
7436
+ this._ensureRegistryCurrent();
7437
+ return this._getSelectedEntries().map((entry) => entry.item);
5891
7438
  }
5892
7439
  /**
5893
7440
  * Get all loaded items
@@ -5899,8 +7446,7 @@ class EnhancedSelect extends HTMLElement {
5899
7446
  * Get currently selected values
5900
7447
  */
5901
7448
  getSelectedValues() {
5902
- const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
5903
- return this.getSelectedItems().map(getValue);
7449
+ return this.getSelectedItems().map((item) => this._getItemValue(item));
5904
7450
  }
5905
7451
  /**
5906
7452
  * Set selected items by value
@@ -5910,16 +7456,10 @@ class EnhancedSelect extends HTMLElement {
5910
7456
  await this._loadSelectedItemsByValues(values);
5911
7457
  }
5912
7458
  else {
5913
- // Select from loaded items
5914
- const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
5915
- this._state.selectedIndices.clear();
5916
- this._state.selectedItems.clear();
5917
- this._state.loadedItems.forEach((item, index) => {
5918
- if (arrayIncludesValue(values, getValue(item)) && !this._isOptionSelectionBlocked(item)) {
5919
- this._state.selectedIndices.add(index);
5920
- this._state.selectedItems.set(index, item);
5921
- }
5922
- });
7459
+ this._ensureRegistryCurrent();
7460
+ const selected = this._itemRegistry.records
7461
+ .filter((record) => arrayIncludesValue(values, record.value) && !this._isOptionSelectionBlocked(record.item));
7462
+ this._requestSelectionReplacement(selected, 'external-value-sync', 'setSelectedValues');
5923
7463
  this._renderOptions();
5924
7464
  this._updateInputDisplay();
5925
7465
  this._emitChange();
@@ -5932,16 +7472,15 @@ class EnhancedSelect extends HTMLElement {
5932
7472
  if (!this._config.serverSide.fetchSelectedItems)
5933
7473
  return;
5934
7474
  this._setBusy(true);
7475
+ const generation = ++this._asyncGeneration;
5935
7476
  try {
5936
7477
  const items = await this._config.serverSide.fetchSelectedItems(values);
5937
- this._state.selectedIndices.clear();
5938
- this._state.selectedItems.clear();
5939
- items.forEach((item, index) => {
5940
- if (this._isOptionSelectionBlocked(item))
5941
- return;
5942
- this._state.selectedIndices.add(index);
5943
- this._state.selectedItems.set(index, item);
7478
+ if (generation !== this._asyncGeneration || !this.isConnected)
7479
+ return;
7480
+ const fetchedRegistry = createItemRegistry(items, this._itemAdapter, {
7481
+ duplicateKeyPolicy: this._getDuplicateKeyPolicy(),
5944
7482
  });
7483
+ this._requestSelectionReplacement(fetchedRegistry.records, 'external-value-sync', 'fetched selected items');
5945
7484
  this._renderOptions();
5946
7485
  this._updateInputDisplay();
5947
7486
  this._emitChange();
@@ -5951,18 +7490,22 @@ class EnhancedSelect extends HTMLElement {
5951
7490
  }
5952
7491
  }
5953
7492
  catch (error) {
7493
+ if (generation !== this._asyncGeneration || !this.isConnected)
7494
+ return;
5954
7495
  this._handleError(error);
5955
7496
  }
5956
7497
  finally {
5957
- this._setBusy(false);
7498
+ if (generation === this._asyncGeneration && this.isConnected) {
7499
+ this._setBusy(false);
7500
+ }
5958
7501
  }
5959
7502
  }
5960
7503
  /**
5961
7504
  * Clear all selections
5962
7505
  */
5963
7506
  clear() {
5964
- this._state.selectedIndices.clear();
5965
- this._state.selectedItems.clear();
7507
+ this._ensureRegistryCurrent();
7508
+ this._dispatchSelection({ type: 'CLEAR_SELECTION_REQUEST', reason: 'programmatic' }, 'clear');
5966
7509
  this._renderOptions();
5967
7510
  this._updateInputDisplay();
5968
7511
  this._emitChange();
@@ -5998,8 +7541,17 @@ class EnhancedSelect extends HTMLElement {
5998
7541
  * Update component configuration
5999
7542
  */
6000
7543
  updateConfig(config) {
7544
+ this._invalidateGuardedMeasurements();
6001
7545
  const previousMode = this._config.selection.mode;
7546
+ const previousEnabled = this._config.enabled;
6002
7547
  this._config = this._mergeConfig(this._config, config);
7548
+ this._rebuildItemRegistry();
7549
+ if (previousEnabled !== this._config.enabled) {
7550
+ if (!this._config.enabled && this._state.isOpen) {
7551
+ this._handleClose('disabled');
7552
+ }
7553
+ this._runEngineEffects(this._engine.dispatch({ type: 'DISABLED_CHANGED', disabled: !this._config.enabled }));
7554
+ }
6003
7555
  if (previousMode !== this._config.selection.mode &&
6004
7556
  this._config.limitations?.autoMitigateRuntimeModeSwitch) {
6005
7557
  this.clear();
@@ -6017,7 +7569,7 @@ class EnhancedSelect extends HTMLElement {
6017
7569
  // Update input state based on new config
6018
7570
  if (this._input) {
6019
7571
  this._input.readOnly = !this._config.searchable;
6020
- this._input.setAttribute('aria-autocomplete', this._config.searchable ? 'list' : 'none');
7572
+ this._syncComboboxAccessibility();
6021
7573
  if (this._state.selectedIndices.size === 0) {
6022
7574
  this._input.placeholder = this._config.placeholder || 'Select an option...';
6023
7575
  }
@@ -6035,14 +7587,7 @@ class EnhancedSelect extends HTMLElement {
6035
7587
  }
6036
7588
  }
6037
7589
  this._syncStyleConfigVariables();
6038
- if (this._dropdown) {
6039
- if (this._config.selection.mode === 'multi') {
6040
- this._dropdown.setAttribute('aria-multiselectable', 'true');
6041
- }
6042
- else {
6043
- this._dropdown.removeAttribute('aria-multiselectable');
6044
- }
6045
- }
7590
+ this._syncListboxAccessibility();
6046
7591
  if (this.isConnected) {
6047
7592
  this._syncDirectionConfig();
6048
7593
  this._syncInputContainerMode();
@@ -6070,6 +7615,8 @@ class EnhancedSelect extends HTMLElement {
6070
7615
  if (!Object.prototype.hasOwnProperty.call(source, key))
6071
7616
  continue;
6072
7617
  const sourceValue = source[key];
7618
+ if (sourceValue === undefined)
7619
+ continue;
6073
7620
  const targetValue = result[key];
6074
7621
  // Optional adapter props are commonly forwarded as undefined. Preserve
6075
7622
  // the existing/default config in that case instead of erasing a section.
@@ -6103,7 +7650,7 @@ class EnhancedSelect extends HTMLElement {
6103
7650
  clearedSelection: shouldClearSelection && hadSelection,
6104
7651
  clearedSearch: shouldClearSearch && hadSearch,
6105
7652
  });
6106
- this._input.focus();
7653
+ this._applyFocusIntent('input', 'clear-control-complete');
6107
7654
  }
6108
7655
  _syncClearControlState() {
6109
7656
  if (!this._clearControl || !this._inputContainer || !this._arrowContainer)
@@ -6129,7 +7676,9 @@ class EnhancedSelect extends HTMLElement {
6129
7676
  setError(message) {
6130
7677
  this._hasError = true;
6131
7678
  this._errorMessage = message;
6132
- this._input.setAttribute('aria-invalid', 'true');
7679
+ if (this._errorDescription)
7680
+ this._errorDescription.textContent = message;
7681
+ this._syncComboboxAccessibility();
6133
7682
  this._announce(`Error: ${message}`);
6134
7683
  }
6135
7684
  /**
@@ -6138,20 +7687,22 @@ class EnhancedSelect extends HTMLElement {
6138
7687
  clearError() {
6139
7688
  this._hasError = false;
6140
7689
  this._errorMessage = '';
6141
- this._input.removeAttribute('aria-invalid');
7690
+ if (this._errorDescription)
7691
+ this._errorDescription.textContent = '';
7692
+ this._syncComboboxAccessibility();
6142
7693
  }
6143
7694
  /**
6144
7695
  * Set required state
6145
7696
  */
6146
7697
  setRequired(required) {
6147
7698
  if (required) {
6148
- this._input.setAttribute('aria-required', 'true');
6149
7699
  this._input.setAttribute('required', '');
6150
7700
  }
6151
7701
  else {
6152
- this._input.removeAttribute('aria-required');
6153
7702
  this._input.removeAttribute('required');
6154
7703
  }
7704
+ this._syncEngineSelectionConfig();
7705
+ this._syncComboboxAccessibility();
6155
7706
  }
6156
7707
  /**
6157
7708
  * Validate selection (for required fields)
@@ -6168,15 +7719,414 @@ class EnhancedSelect extends HTMLElement {
6168
7719
  /**
6169
7720
  * Render options based on current state
6170
7721
  */
7722
+ _deriveVirtualizationScope(filteredIndices) {
7723
+ const keyForIndex = (index) => this._itemRegistry.indexToKey.get(index);
7724
+ const filteredKeys = filteredIndices
7725
+ .map(keyForIndex)
7726
+ .filter((key) => key !== undefined);
7727
+ return {
7728
+ dataKeys: this._itemRegistry.records.map((record) => record.key),
7729
+ filteredKeys,
7730
+ registeredKeys: Array.from(this._engine.state.registeredKeys),
7731
+ // The current chunked path schedules all filtered items for rendering;
7732
+ // this scaffold records that target set until bounded windows are wired.
7733
+ windowKeys: this._renderPlan.intendedRenderKeys.slice(),
7734
+ mountedKeys: this._getMountedVirtualizationKeys(this._optionsContainer.children),
7735
+ selectedKeys: new Set(this._engine.state.selectedKeys),
7736
+ activeKey: this._engine.state.activeKey,
7737
+ };
7738
+ }
7739
+ _getMountedVirtualizationKeys(targets) {
7740
+ const keyForIndex = (index) => this._itemRegistry.indexToKey.get(index);
7741
+ return Array.from(targets)
7742
+ .filter((target) => target instanceof HTMLElement
7743
+ && (target.hasAttribute('data-sm-selectable') || target.hasAttribute('data-selectable')))
7744
+ .map((target) => Number(target.getAttribute('data-sm-index') ?? target.getAttribute('data-index')))
7745
+ .filter(Number.isInteger)
7746
+ .map(keyForIndex)
7747
+ .filter((key) => key !== undefined);
7748
+ }
7749
+ _refreshMountedVirtualizationScope() {
7750
+ this._virtualizationScope = {
7751
+ ...this._virtualizationScope,
7752
+ mountedKeys: this._getMountedVirtualizationKeys(this._optionsContainer.children),
7753
+ registeredKeys: Array.from(this._engine.state.registeredKeys),
7754
+ selectedKeys: new Set(this._engine.state.selectedKeys),
7755
+ activeKey: this._engine.state.activeKey,
7756
+ };
7757
+ }
7758
+ _appendMountedVirtualizationTargets(targets) {
7759
+ const mountedKeys = this._getMountedVirtualizationKeys(targets);
7760
+ this._virtualizationScope = {
7761
+ ...this._virtualizationScope,
7762
+ mountedKeys: [...new Set([...this._virtualizationScope.mountedKeys, ...mountedKeys])],
7763
+ registeredKeys: Array.from(this._engine.state.registeredKeys),
7764
+ selectedKeys: new Set(this._engine.state.selectedKeys),
7765
+ activeKey: this._engine.state.activeKey,
7766
+ };
7767
+ }
7768
+ _createLegacyRenderPlan(filteredIndices) {
7769
+ const indices = [...filteredIndices];
7770
+ const filteredKeys = indices
7771
+ .map((index) => this._itemRegistry.indexToKey.get(index))
7772
+ .filter((key) => key !== undefined);
7773
+ const filteredIndexByKey = new Map();
7774
+ filteredKeys.forEach((key, filteredIndex) => filteredIndexByKey.set(key, filteredIndex));
7775
+ return {
7776
+ mode: 'legacy-full',
7777
+ filteredIndices: indices,
7778
+ filteredKeys,
7779
+ intendedRenderKeys: filteredKeys.slice(),
7780
+ filteredIndexByKey,
7781
+ };
7782
+ }
7783
+ _createVirtualRenderPlan(startIndex, endIndex) {
7784
+ const filteredKeys = this._renderPlan.filteredKeys.slice();
7785
+ const intendedRenderKeys = computeWindowKeys(filteredKeys, startIndex, endIndex);
7786
+ const filteredIndices = intendedRenderKeys
7787
+ .map((key) => this._itemRegistry.keyToIndex.get(key))
7788
+ .filter((index) => index !== undefined);
7789
+ return {
7790
+ mode: 'virtual-window',
7791
+ filteredIndices,
7792
+ filteredKeys,
7793
+ intendedRenderKeys,
7794
+ filteredIndexByKey: new Map(this._renderPlan.filteredIndexByKey),
7795
+ };
7796
+ }
7797
+ _ensureGuardedVirtualizer(filteredKeys) {
7798
+ const keysChanged = this._guardedVirtualizer !== null && (filteredKeys.length !== this._guardedVirtualizerKeys.length
7799
+ || filteredKeys.some((key, index) => !Object.is(key, this._guardedVirtualizerKeys[index])));
7800
+ if (keysChanged)
7801
+ this._destroyGuardedVirtualizer(true);
7802
+ if (!this._guardedVirtualizer) {
7803
+ // The controller only calculates ranges and scroll intents. Give it a
7804
+ // detached container so its internal styling never touches rendered UI.
7805
+ this._guardedVirtualizer = new Virtualizer(document.createElement('div'), filteredKeys.length, (index) => this._renderPlan.filteredKeys[index], {
7806
+ estimatedItemHeight: this._resolveGuardedEstimatedItemHeight(),
7807
+ buffer: 0,
7808
+ measurementThreshold: 0,
7809
+ });
7810
+ this._guardedVirtualScrollTop = this._optionsContainer.scrollTop;
7811
+ this._guardedVirtualViewportHeight = this._resolveGuardedViewportHeight();
7812
+ this._optionsContainer.addEventListener('scroll', this._onGuardedVirtualScroll, { passive: true });
7813
+ this._guardedScrollListenerAttached = true;
7814
+ }
7815
+ this._guardedVirtualizerKeys = [...filteredKeys];
7816
+ return this._guardedVirtualizer;
7817
+ }
7818
+ _resolveGuardedEstimatedItemHeight() {
7819
+ const configuredHeight = this._config.estimatedItemHeight;
7820
+ if (typeof configuredHeight === 'number' && Number.isFinite(configuredHeight) && configuredHeight > 0) {
7821
+ return configuredHeight;
7822
+ }
7823
+ const renderedOption = this._optionsContainer.querySelector('[part="option"]');
7824
+ const measuredHeight = renderedOption?.getBoundingClientRect().height || renderedOption?.offsetHeight;
7825
+ if (typeof measuredHeight === 'number' && Number.isFinite(measuredHeight) && measuredHeight > 0) {
7826
+ return measuredHeight;
7827
+ }
7828
+ return 48;
7829
+ }
7830
+ _resolveGuardedViewportHeight() {
7831
+ const candidates = [
7832
+ this._optionsContainer.clientHeight,
7833
+ this._optionsContainer.getBoundingClientRect().height,
7834
+ ];
7835
+ return candidates.find((height) => Number.isFinite(height) && height > 0) ?? 0;
7836
+ }
7837
+ _clampGuardedScrollPosition(itemCount, viewportHeight) {
7838
+ if (!this._guardedVirtualizer)
7839
+ return 0;
7840
+ const totalHeight = this._guardedVirtualizer.cumulativeOffset(itemCount);
7841
+ const maxScrollTop = Math.max(0, totalHeight - viewportHeight);
7842
+ const scrollTop = Math.min(Math.max(0, this._guardedVirtualScrollTop), maxScrollTop);
7843
+ this._guardedVirtualScrollTop = scrollTop;
7844
+ if (this._optionsContainer.scrollTop !== scrollTop) {
7845
+ this._optionsContainer.scrollTop = scrollTop;
7846
+ }
7847
+ return scrollTop;
7848
+ }
7849
+ _createGuardedSpacer(position, height) {
7850
+ const spacer = document.createElement('div');
7851
+ spacer.setAttribute('data-virtual-spacer', position);
7852
+ spacer.setAttribute('aria-hidden', 'true');
7853
+ spacer.setAttribute('role', 'presentation');
7854
+ spacer.style.height = `${Number.isFinite(height) ? Math.max(0, height) : 0}px`;
7855
+ spacer.style.minHeight = '0';
7856
+ spacer.style.flex = '0 0 auto';
7857
+ spacer.style.pointerEvents = 'none';
7858
+ return spacer;
7859
+ }
7860
+ _appendGuardedTopSpacer() {
7861
+ const virtualizer = this._guardedVirtualizer;
7862
+ const window = this._guardedVirtualWindow;
7863
+ if (!virtualizer || !window)
7864
+ return;
7865
+ this._optionsContainer.appendChild(this._createGuardedSpacer('top', virtualizer.cumulativeOffset(window.startIndex)));
7866
+ }
7867
+ _appendGuardedBottomSpacer() {
7868
+ const virtualizer = this._guardedVirtualizer;
7869
+ const window = this._guardedVirtualWindow;
7870
+ if (!virtualizer || !window)
7871
+ return;
7872
+ const totalHeight = virtualizer.cumulativeOffset(this._renderPlan.filteredKeys.length);
7873
+ const endOffset = virtualizer.cumulativeOffset(window.endIndex);
7874
+ this._optionsContainer.appendChild(this._createGuardedSpacer('bottom', Math.max(0, totalHeight - endOffset)));
7875
+ }
7876
+ _resolveGuardedOverscan() {
7877
+ return 2;
7878
+ }
7879
+ _applyGuardedWindowUpdate(update, overscan = 0) {
7880
+ if (!this._guardedVirtualizer)
7881
+ return false;
7882
+ this._guardedVirtualScrollTop = update.scrollTop;
7883
+ this._guardedVirtualViewportHeight = update.viewportHeight;
7884
+ const itemCount = this._renderPlan.filteredKeys.length;
7885
+ const nextWindow = {
7886
+ startIndex: Math.max(0, update.window.startIndex - overscan),
7887
+ endIndex: Math.min(itemCount, update.window.endIndex + 1 + overscan),
7888
+ };
7889
+ const changed = this._guardedVirtualWindow?.startIndex !== nextWindow.startIndex
7890
+ || this._guardedVirtualWindow?.endIndex !== nextWindow.endIndex;
7891
+ this._guardedVirtualWindow = nextWindow;
7892
+ return changed;
7893
+ }
7894
+ _scheduleGuardedVirtualWindowUpdate() {
7895
+ if (!this._guardedVirtualizer || this._guardedVirtualWindowRafId !== null)
7896
+ return;
7897
+ this._guardedVirtualWindowRafId = this._requestLifecycleFrame(() => {
7898
+ this._guardedVirtualWindowRafId = null;
7899
+ const virtualizer = this._guardedVirtualizer;
7900
+ if (!virtualizer)
7901
+ return;
7902
+ const update = virtualizer.updateWindow(this._optionsContainer.scrollTop, this._resolveGuardedViewportHeight());
7903
+ this._guardedVirtualOverscan = this._resolveGuardedOverscan();
7904
+ if (update && this._applyGuardedWindowUpdate(update, this._guardedVirtualOverscan)) {
7905
+ this._renderOptions();
7906
+ }
7907
+ });
7908
+ }
7909
+ _cancelGuardedVirtualWindowUpdate() {
7910
+ if (this._guardedVirtualWindowRafId === null)
7911
+ return;
7912
+ cancelAnimationFrame(this._guardedVirtualWindowRafId);
7913
+ this._lifecycleRafs.delete(this._guardedVirtualWindowRafId);
7914
+ this._guardedVirtualWindowRafId = null;
7915
+ }
7916
+ _applyGuardedScrollResult(result) {
7917
+ if (!result || !this._guardedVirtualizer)
7918
+ return false;
7919
+ this._guardedVirtualScrollTop = result.scrollTop;
7920
+ this._optionsContainer.scrollTop = result.scrollTop;
7921
+ const update = this._guardedVirtualizer.updateWindow(this._guardedVirtualScrollTop, this._guardedVirtualViewportHeight);
7922
+ if (!update)
7923
+ return false;
7924
+ this._guardedVirtualWindow = {
7925
+ startIndex: update.window.startIndex,
7926
+ endIndex: update.window.endIndex + 1,
7927
+ };
7928
+ this._guardedVirtualOverscan = 0;
7929
+ return true;
7930
+ }
7931
+ _updateGuardedVirtualWindow(scrollTop, viewportHeight) {
7932
+ this._guardedVirtualizationRequested = true;
7933
+ const virtualizer = this._ensureGuardedVirtualizer(this._renderPlan.filteredKeys);
7934
+ this._guardedVirtualScrollTop = scrollTop;
7935
+ this._guardedVirtualViewportHeight = viewportHeight;
7936
+ const update = virtualizer.updateWindow(scrollTop, viewportHeight);
7937
+ if (!update)
7938
+ return false;
7939
+ this._guardedVirtualOverscan = 0;
7940
+ this._applyGuardedWindowUpdate(update, this._guardedVirtualOverscan);
7941
+ this._optionsContainer.scrollTop = update.scrollTop;
7942
+ return true;
7943
+ }
7944
+ _destroyGuardedVirtualizer(preserveRequestedMode = false) {
7945
+ this._cancelGuardedVirtualWindowUpdate();
7946
+ this._guardedMeasurementGeneration += 1;
7947
+ if (this._guardedScrollListenerAttached) {
7948
+ this._optionsContainer.removeEventListener('scroll', this._onGuardedVirtualScroll);
7949
+ this._guardedScrollListenerAttached = false;
7950
+ }
7951
+ this._guardedVirtualizer?.destroy();
7952
+ this._guardedVirtualizer = null;
7953
+ this._teardownGuardedOptionResizeObserver();
7954
+ if (!preserveRequestedMode)
7955
+ this._guardedVirtualizationRequested = false;
7956
+ this._guardedVirtualizerKeys = [];
7957
+ this._guardedVirtualWindow = null;
7958
+ this._guardedVirtualScrollTop = 0;
7959
+ this._guardedVirtualViewportHeight = 0;
7960
+ this._guardedVirtualOverscan = 0;
7961
+ }
7962
+ _invalidateGuardedMeasurements() {
7963
+ if (this._guardedVirtualizer)
7964
+ this._destroyGuardedVirtualizer(true);
7965
+ }
7966
+ _createGuardedOptionResizeObserver(generation) {
7967
+ if (typeof ResizeObserver === 'undefined')
7968
+ return;
7969
+ this._guardedOptionResizeObserver = new ResizeObserver((entries) => {
7970
+ if (generation !== this._guardedMeasurementGeneration
7971
+ || !this._guardedVirtualizer
7972
+ || !this._guardedVirtualizationRequested
7973
+ || !this.isConnected)
7974
+ return;
7975
+ const virtualizer = this._guardedVirtualizer;
7976
+ const scrollTop = this._optionsContainer.scrollTop;
7977
+ const viewportHeight = this._resolveGuardedViewportHeight();
7978
+ const anchor = this._captureGuardedScrollAnchor(virtualizer, scrollTop, viewportHeight);
7979
+ let changed = false;
7980
+ for (const entry of entries) {
7981
+ const option = entry.target;
7982
+ if (!(option instanceof HTMLElement) || !this._guardedObservedOptions.has(option))
7983
+ continue;
7984
+ if (!option.isConnected || !this._optionsContainer.contains(option))
7985
+ continue;
7986
+ const meta = this._guardedOptionMeasurements.get(option);
7987
+ if (!meta || meta.generation !== generation)
7988
+ continue;
7989
+ const dataIndex = Number(option.getAttribute('data-index'));
7990
+ if (!Number.isInteger(dataIndex) || !Object.is(this._itemRegistry.indexToKey.get(dataIndex), meta.key))
7991
+ continue;
7992
+ const currentIndex = this._renderPlan.filteredIndexByKey.get(meta.key);
7993
+ if (currentIndex === undefined || currentIndex !== meta.index)
7994
+ continue;
7995
+ const reportedHeight = entry.borderBoxSize?.[0]?.blockSize;
7996
+ const height = typeof reportedHeight === 'number' ? reportedHeight : entry.contentRect.height;
7997
+ if (!Number.isFinite(height) || height <= 0)
7998
+ continue;
7999
+ changed = virtualizer.measureItem(meta.index, height) || changed;
8000
+ }
8001
+ if (!changed)
8002
+ return;
8003
+ if (anchor) {
8004
+ const currentAnchorIndex = this._renderPlan.filteredIndexByKey.get(anchor.key);
8005
+ if (currentAnchorIndex !== undefined) {
8006
+ const anchoredScrollTop = Math.max(0, virtualizer.cumulativeOffset(currentAnchorIndex) + anchor.offset);
8007
+ this._guardedVirtualScrollTop = anchoredScrollTop;
8008
+ this._optionsContainer.scrollTop = anchoredScrollTop;
8009
+ }
8010
+ }
8011
+ const update = virtualizer.updateWindow(this._optionsContainer.scrollTop, viewportHeight);
8012
+ if (update)
8013
+ this._applyGuardedWindowUpdate(update, this._guardedVirtualOverscan);
8014
+ this._renderOptions();
8015
+ });
8016
+ }
8017
+ _captureGuardedScrollAnchor(virtualizer, scrollTop, viewportHeight) {
8018
+ const viewportTop = this._optionsContainer.getBoundingClientRect().top + this._optionsContainer.clientTop;
8019
+ const viewportBottom = viewportTop + viewportHeight;
8020
+ const visible = Array.from(this._guardedObservedOptions)
8021
+ .map((option) => ({ option, rect: option.getBoundingClientRect() }))
8022
+ .filter(({ rect }) => rect.height > 0 && rect.bottom > viewportTop && rect.top < viewportBottom)
8023
+ .sort((left, right) => left.rect.top - right.rect.top)[0];
8024
+ const visibleMeta = visible ? this._guardedOptionMeasurements.get(visible.option) : undefined;
8025
+ if (visibleMeta && visibleMeta.generation === this._guardedMeasurementGeneration) {
8026
+ return {
8027
+ key: visibleMeta.key,
8028
+ offset: scrollTop - virtualizer.cumulativeOffset(visibleMeta.index),
8029
+ };
8030
+ }
8031
+ if (this._renderPlan.filteredKeys.length === 0)
8032
+ return null;
8033
+ const index = virtualizer.computeWindow(scrollTop, 0).startIndex;
8034
+ const key = this._renderPlan.filteredKeys[index];
8035
+ return key === undefined ? null : {
8036
+ key,
8037
+ offset: scrollTop - virtualizer.cumulativeOffset(index),
8038
+ };
8039
+ }
8040
+ _syncGuardedOptionResizeTargets() {
8041
+ const virtualizer = this._guardedVirtualizer;
8042
+ if (!virtualizer || !this._guardedVirtualizationRequested || !this.isConnected)
8043
+ return;
8044
+ const candidates = [];
8045
+ for (const child of Array.from(this._optionsContainer.children)) {
8046
+ if (!(child instanceof HTMLElement) || !child.hasAttribute('data-index'))
8047
+ continue;
8048
+ const dataIndex = Number(child.getAttribute('data-index'));
8049
+ if (!Number.isInteger(dataIndex))
8050
+ continue;
8051
+ const key = this._itemRegistry.indexToKey.get(dataIndex);
8052
+ const index = key === undefined ? undefined : this._renderPlan.filteredIndexByKey.get(key);
8053
+ if (key === undefined || index === undefined)
8054
+ continue;
8055
+ candidates.push({ option: child, key, index });
8056
+ }
8057
+ const reusedTarget = candidates.some(({ option }) => this._guardedObserverSeenOptions.has(option));
8058
+ if (reusedTarget && this._guardedOptionResizeObserver) {
8059
+ this._guardedMeasurementGeneration += 1;
8060
+ this._teardownGuardedOptionResizeObserver();
8061
+ }
8062
+ if (!this._guardedOptionResizeObserver) {
8063
+ this._createGuardedOptionResizeObserver(this._guardedMeasurementGeneration);
8064
+ }
8065
+ const observer = this._guardedOptionResizeObserver;
8066
+ if (!observer)
8067
+ return;
8068
+ const current = new Set();
8069
+ for (const { option, key, index } of candidates) {
8070
+ current.add(option);
8071
+ this._guardedOptionMeasurements.set(option, {
8072
+ key,
8073
+ index,
8074
+ generation: this._guardedMeasurementGeneration,
8075
+ });
8076
+ if (!this._guardedObservedOptions.has(option)) {
8077
+ observer.observe(option);
8078
+ this._guardedObserverSeenOptions.add(option);
8079
+ }
8080
+ }
8081
+ for (const previous of this._guardedObservedOptions) {
8082
+ if (!current.has(previous))
8083
+ observer.unobserve(previous);
8084
+ }
8085
+ this._guardedObservedOptions = current;
8086
+ }
8087
+ _teardownGuardedOptionResizeObserver() {
8088
+ for (const option of this._guardedObservedOptions) {
8089
+ this._guardedOptionResizeObserver?.unobserve(option);
8090
+ }
8091
+ this._guardedObservedOptions.clear();
8092
+ this._guardedObserverSeenOptions = new WeakSet();
8093
+ this._guardedOptionResizeObserver?.disconnect();
8094
+ this._guardedOptionResizeObserver = null;
8095
+ this._guardedOptionMeasurements = new WeakMap();
8096
+ }
8097
+ _materializeGuardedVirtualKey(key) {
8098
+ if (!this._guardedVirtualizer)
8099
+ return false;
8100
+ const targetIndex = this._renderPlan.filteredIndexByKey.get(key);
8101
+ if (targetIndex === undefined)
8102
+ return false;
8103
+ this._ensureGuardedVirtualizer(this._renderPlan.filteredKeys);
8104
+ const result = this._guardedVirtualizer.scrollToKey(key, (candidate) => this._renderPlan.filteredIndexByKey.get(candidate));
8105
+ if (!this._applyGuardedScrollResult(result))
8106
+ return false;
8107
+ this._renderOptions();
8108
+ return true;
8109
+ }
8110
+ _refreshVirtualizationScope(filteredIndices) {
8111
+ this._virtualizationScope = this._deriveVirtualizationScope(filteredIndices);
8112
+ }
6171
8113
  _renderOptions() {
8114
+ this._ensureRegistryCurrent();
8115
+ const scrollTopBeforeRender = this._optionsContainer.scrollTop;
6172
8116
  this._renderCycleId += 1;
6173
8117
  const renderCycleId = this._renderCycleId;
8118
+ if (this._guardedVirtualizer) {
8119
+ this._guardedVirtualScrollTop = this._optionsContainer.scrollTop;
8120
+ }
6174
8121
  // Cleanup observer
6175
8122
  if (this._loadMoreTrigger && this._intersectionObserver) {
6176
8123
  this._intersectionObserver.unobserve(this._loadMoreTrigger);
6177
8124
  }
8125
+ this._unobserveGuardedOptionResizeTargets();
6178
8126
  // Clear options container
6179
8127
  this._optionsContainer.innerHTML = '';
8128
+ let filteredIndicesForScope = [];
8129
+ let guardedScrollTopToRestore = null;
6180
8130
  // Ensure dropdown only contains options container (cleanup legacy direct children)
6181
8131
  // We need to preserve optionsContainer, so we can't just clear dropdown.innerHTML
6182
8132
  // But we can check if there are other children and remove them
@@ -6191,6 +8141,10 @@ class EnhancedSelect extends HTMLElement {
6191
8141
  }
6192
8142
  // Show searching state (exclusive state)
6193
8143
  if (this._state.isSearching) {
8144
+ this._registerShadowItems([]);
8145
+ this._renderPlan = this._createLegacyRenderPlan([]);
8146
+ this._refreshVirtualizationScope(filteredIndicesForScope);
8147
+ this._syncLegacyActiveAria();
6194
8148
  const searching = document.createElement('div');
6195
8149
  searching.className = 'searching-state';
6196
8150
  searching.setAttribute('part', 'loading');
@@ -6202,8 +8156,17 @@ class EnhancedSelect extends HTMLElement {
6202
8156
  const getLabel = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
6203
8157
  // Filter items by search query
6204
8158
  const query = this._state.searchQuery.toLowerCase();
8159
+ if (this._guardedMeasurementQuery !== null && this._guardedMeasurementQuery !== query) {
8160
+ this._invalidateGuardedMeasurements();
8161
+ }
8162
+ this._guardedMeasurementQuery = query;
6205
8163
  // Handle Grouped Items Rendering (when no search query)
6206
8164
  if (this._state.groupedItems.length > 0 && !query) {
8165
+ this._destroyGuardedVirtualizer();
8166
+ this._renderPlan = this._createLegacyRenderPlan(this._itemRegistry.records.map((record) => record.index));
8167
+ filteredIndicesForScope = this._renderPlan.filteredIndices;
8168
+ this._registerShadowItems(filteredIndicesForScope);
8169
+ this._refreshVirtualizationScope(filteredIndicesForScope);
6207
8170
  this._state.groupedItems.forEach((group, groupIndex) => {
6208
8171
  let header;
6209
8172
  if (this.groupHeaderRenderer) {
@@ -6241,7 +8204,7 @@ class EnhancedSelect extends HTMLElement {
6241
8204
  }
6242
8205
  else {
6243
8206
  // Normal rendering (flat list or filtered)
6244
- const filteredIndices = [];
8207
+ const computedFilteredIndices = [];
6245
8208
  this._state.loadedItems.forEach((item, index) => {
6246
8209
  if (query) {
6247
8210
  try {
@@ -6253,8 +8216,40 @@ class EnhancedSelect extends HTMLElement {
6253
8216
  return;
6254
8217
  }
6255
8218
  }
6256
- filteredIndices.push(index);
8219
+ computedFilteredIndices.push(index);
6257
8220
  });
8221
+ this._renderPlan = this._createLegacyRenderPlan(computedFilteredIndices);
8222
+ filteredIndicesForScope = this._renderPlan.filteredIndices;
8223
+ this._registerShadowItems(filteredIndicesForScope);
8224
+ if (this._guardedVirtualizationRequested && !this._guardedVirtualizer) {
8225
+ this._ensureGuardedVirtualizer(this._renderPlan.filteredKeys);
8226
+ this._guardedVirtualViewportHeight = this._resolveGuardedViewportHeight();
8227
+ // A data reorder/filter may have invalidated the old virtualizer, but
8228
+ // the physical position is still available before the DOM is cleared.
8229
+ this._guardedVirtualScrollTop = scrollTopBeforeRender;
8230
+ }
8231
+ if (this._guardedVirtualizer) {
8232
+ const virtualizer = this._ensureGuardedVirtualizer(this._renderPlan.filteredKeys);
8233
+ const measuredViewportHeight = this._resolveGuardedViewportHeight();
8234
+ if (measuredViewportHeight > 0) {
8235
+ this._guardedVirtualViewportHeight = measuredViewportHeight;
8236
+ }
8237
+ const scrollTop = this._clampGuardedScrollPosition(this._renderPlan.filteredKeys.length, this._guardedVirtualViewportHeight);
8238
+ guardedScrollTopToRestore = scrollTop;
8239
+ const update = virtualizer.updateWindow(scrollTop, this._guardedVirtualViewportHeight);
8240
+ if (update) {
8241
+ this._applyGuardedWindowUpdate(update, this._guardedVirtualOverscan);
8242
+ }
8243
+ else {
8244
+ this._guardedVirtualWindow = null;
8245
+ }
8246
+ }
8247
+ if (this._guardedVirtualWindow) {
8248
+ this._renderPlan = this._createVirtualRenderPlan(this._guardedVirtualWindow.startIndex, this._guardedVirtualWindow.endIndex);
8249
+ }
8250
+ const filteredIndices = this._renderPlan.filteredIndices;
8251
+ this._refreshVirtualizationScope(filteredIndicesForScope);
8252
+ this._appendGuardedTopSpacer();
6258
8253
  if (filteredIndices.length === 0 && !this._state.isBusy) {
6259
8254
  const empty = document.createElement('div');
6260
8255
  empty.setAttribute('part', 'no-results');
@@ -6268,7 +8263,8 @@ class EnhancedSelect extends HTMLElement {
6268
8263
  this._optionsContainer.appendChild(empty);
6269
8264
  }
6270
8265
  else {
6271
- const shouldIncrementalRender = this._config.virtualize !== false
8266
+ const shouldIncrementalRender = !this._guardedVirtualizer
8267
+ && this._config.virtualize !== false
6272
8268
  && this._state.groupedItems.length === 0
6273
8269
  && filteredIndices.length > 300;
6274
8270
  if (shouldIncrementalRender) {
@@ -6276,7 +8272,7 @@ class EnhancedSelect extends HTMLElement {
6276
8272
  let cursor = 0;
6277
8273
  let maxRenderTarget = 0;
6278
8274
  if (this._state.selectedIndices.size > 0 && this._config.scrollToSelected.enabled) {
6279
- const indices = Array.from(this._state.selectedIndices).sort((a, b) => a - b);
8275
+ const indices = Array.from(this._state.selectedIndices).filter((index) => index >= 0).sort((a, b) => a - b);
6280
8276
  const targetIndex = this._config.scrollToSelected.multiSelectTarget === 'first' ? indices[0] : indices[indices.length - 1];
6281
8277
  const filteredPos = filteredIndices.indexOf(targetIndex);
6282
8278
  if (filteredPos !== -1) {
@@ -6294,9 +8290,13 @@ class EnhancedSelect extends HTMLElement {
6294
8290
  const item = this._state.loadedItems[itemIndex];
6295
8291
  this._renderSingleOption(item, itemIndex, getValue, getLabel, fragment);
6296
8292
  }
8293
+ const renderedTargets = Array.from(fragment.children);
6297
8294
  this._optionsContainer.appendChild(fragment);
8295
+ this._appendMountedVirtualizationTargets(renderedTargets);
8296
+ this._syncRenderedOptionAccessibility();
8297
+ this._syncLegacyActiveAria();
6298
8298
  if (cursor < filteredIndices.length) {
6299
- requestAnimationFrame(renderChunk);
8299
+ this._requestLifecycleFrame(renderChunk);
6300
8300
  }
6301
8301
  else {
6302
8302
  if (renderCycleId !== this._renderCycleId)
@@ -6315,7 +8315,9 @@ class EnhancedSelect extends HTMLElement {
6315
8315
  this._renderSingleOption(item, itemIndex, getValue, getLabel);
6316
8316
  });
6317
8317
  }
8318
+ this._appendGuardedBottomSpacer();
6318
8319
  }
8320
+ this._refreshMountedVirtualizationScope();
6319
8321
  // Append Busy Indicator if busy
6320
8322
  if (this._state.isBusy && this._config.busyBucket.enabled) {
6321
8323
  const busyBucket = document.createElement('div');
@@ -6337,8 +8339,23 @@ class EnhancedSelect extends HTMLElement {
6337
8339
  else if ((this._config.loadMore.enabled || this._config.infiniteScroll.enabled) && this._state.loadedItems.length > 0) {
6338
8340
  this._addLoadMoreTrigger();
6339
8341
  }
8342
+ // Rebuilding the list temporarily removes its spacer geometry. Browsers
8343
+ // clamp scrollTop during that interval, so restore the logical position
8344
+ // only after the new top/bottom spacers and mounted rows are present.
8345
+ if (guardedScrollTopToRestore !== null) {
8346
+ this._optionsContainer.scrollTop = guardedScrollTopToRestore;
8347
+ }
8348
+ this._syncRenderedOptionAccessibility();
8349
+ this._syncLegacyActiveAria();
8350
+ this._syncGuardedOptionResizeTargets();
6340
8351
  this._finalizePerfMarks();
6341
8352
  }
8353
+ _unobserveGuardedOptionResizeTargets() {
8354
+ for (const option of this._guardedObservedOptions) {
8355
+ this._guardedOptionResizeObserver?.unobserve(option);
8356
+ }
8357
+ this._guardedObservedOptions.clear();
8358
+ }
6342
8359
  _renderSingleOption(item, index, getValue, getLabel, targetContainer = this._optionsContainer) {
6343
8360
  const isSelected = this._state.selectedIndices.has(index);
6344
8361
  const isDisabled = Boolean(item?.disabled);
@@ -6374,16 +8391,16 @@ class EnhancedSelect extends HTMLElement {
6374
8391
  showRemoveButton: this._config.selection.mode === 'multi' && this._config.selection.showRemoveButton,
6375
8392
  removeButtonIcon: this._config.selection.removeButtonIcon,
6376
8393
  classMap: this.classMap,
6377
- className: this._config.styles.classNames?.option,
8394
+ className: this._config.styles?.classNames?.option,
6378
8395
  });
6379
- if (this._config.styles.classNames?.option) {
8396
+ if (this._config.styles?.classNames?.option) {
6380
8397
  option.classList.add(...this._config.styles.classNames.option.split(' ').filter(Boolean));
6381
8398
  }
6382
8399
  option.setAttribute('dir', this._config.direction ?? 'ltr');
6383
- if (isSelected && this._config.styles.classNames?.selectedOption) {
8400
+ if (isSelected && this._config.styles?.classNames?.selectedOption) {
6384
8401
  option.classList.add(...this._config.styles.classNames.selectedOption.split(' ').filter(Boolean));
6385
8402
  }
6386
- if (this._state.activeIndex === index && this._config.styles.classNames?.activeOption) {
8403
+ if (this._state.activeIndex === index && this._config.styles?.classNames?.activeOption) {
6387
8404
  option.classList.add(...this._config.styles.classNames.activeOption.split(' ').filter(Boolean));
6388
8405
  }
6389
8406
  if (isDisabled && this._config.styles.classNames?.disabledOption) {
@@ -6513,16 +8530,18 @@ class EnhancedSelect extends HTMLElement {
6513
8530
  if (meta.value != null) {
6514
8531
  optionEl.dataset.smValue = String(meta.value);
6515
8532
  }
6516
- optionEl.id = optionEl.id || meta.id;
6517
- if (!optionEl.getAttribute('role')) {
6518
- optionEl.setAttribute('role', 'option');
8533
+ else {
8534
+ delete optionEl.dataset.smValue;
6519
8535
  }
6520
- optionEl.setAttribute('aria-selected', String(meta.selected));
6521
- if (meta.disabled && !meta.disabledBehavior.selectable) {
6522
- optionEl.setAttribute('aria-disabled', 'true');
8536
+ // Refresh component-generated IDs when a renderer reuses an option node,
8537
+ // while preserving an ID that the renderer supplied itself.
8538
+ const previousNormalizedId = this._customOptionNormalizedIds.get(optionEl);
8539
+ if (!optionEl.id || (previousNormalizedId !== undefined && optionEl.id === previousNormalizedId)) {
8540
+ optionEl.id = meta.id;
8541
+ this._customOptionNormalizedIds.set(optionEl, meta.id);
6523
8542
  }
6524
8543
  else {
6525
- optionEl.removeAttribute('aria-disabled');
8544
+ this._customOptionNormalizedIds.delete(optionEl);
6526
8545
  }
6527
8546
  if (!optionEl.hasAttribute('tabindex')) {
6528
8547
  optionEl.tabIndex = -1;
@@ -6572,6 +8591,8 @@ class EnhancedSelect extends HTMLElement {
6572
8591
  /** live set of all connected instances; used to auto-close siblings */
6573
8592
  EnhancedSelect._instances = new Set();
6574
8593
  EnhancedSelect._MIRRORED_STYLES_SCOPE_CLASS = 'smilodon-mirrored-styles-scope';
8594
+ EnhancedSelect._MIRRORED_STYLESHEET_CACHE_LIMIT = 32;
8595
+ EnhancedSelect._mirroredStylesheetTextCache = new Map();
6575
8596
  // Register custom element
6576
8597
  if (!customElements.get('enhanced-select')) {
6577
8598
  customElements.define('enhanced-select', EnhancedSelect);
@@ -6929,7 +8950,8 @@ class PerformanceTelemetry {
6929
8950
  this.rafId = 0;
6930
8951
  this.measuring = false;
6931
8952
  this.observer = null;
6932
- this.workTimes = [];
8953
+ this.workTotal = 0;
8954
+ this.workCount = 0;
6933
8955
  /**
6934
8956
  * Measure frame timing via requestAnimationFrame
6935
8957
  */
@@ -6946,7 +8968,6 @@ class PerformanceTelemetry {
6946
8968
  this.lastFrameTime = now;
6947
8969
  this.rafId = requestAnimationFrame(this.measureFrame);
6948
8970
  };
6949
- this.setupObserver();
6950
8971
  }
6951
8972
  /**
6952
8973
  * Setup PerformanceObserver for long tasks
@@ -6956,12 +8977,15 @@ class PerformanceTelemetry {
6956
8977
  return;
6957
8978
  try {
6958
8979
  this.observer = new PerformanceObserver((list) => {
8980
+ if (!this.measuring)
8981
+ return;
6959
8982
  for (const entry of list.getEntries()) {
6960
8983
  if (entry.entryType === 'longtask' && entry.duration > 50) {
6961
8984
  this.longTasks++;
6962
8985
  }
6963
8986
  if (entry.entryType === 'measure') {
6964
- this.workTimes.push(entry.duration);
8987
+ this.workTotal += entry.duration;
8988
+ this.workCount += 1;
6965
8989
  }
6966
8990
  }
6967
8991
  });
@@ -6986,9 +9010,11 @@ class PerformanceTelemetry {
6986
9010
  return;
6987
9011
  this.measuring = true;
6988
9012
  this.frameTimes = [];
6989
- this.workTimes = [];
9013
+ this.workTotal = 0;
9014
+ this.workCount = 0;
6990
9015
  this.longTasks = 0;
6991
9016
  this.lastFrameTime = performance.now();
9017
+ this.setupObserver();
6992
9018
  this.measureFrame();
6993
9019
  }
6994
9020
  /**
@@ -7000,6 +9026,10 @@ class PerformanceTelemetry {
7000
9026
  cancelAnimationFrame(this.rafId);
7001
9027
  this.rafId = 0;
7002
9028
  }
9029
+ if (this.observer) {
9030
+ this.observer.disconnect();
9031
+ this.observer = null;
9032
+ }
7003
9033
  }
7004
9034
  /**
7005
9035
  * Mark start of work for custom measurement
@@ -7011,10 +9041,15 @@ class PerformanceTelemetry {
7011
9041
  * Mark end of work and measure duration
7012
9042
  */
7013
9043
  markEnd(label) {
7014
- performance.mark(`${label}-end`);
7015
- performance.measure(label, `${label}-start`, `${label}-end`);
7016
- const measure = performance.getEntriesByName(label, 'measure')[0];
7017
- return measure ? measure.duration : 0;
9044
+ const startMark = `${label}-start`;
9045
+ const endMark = `${label}-end`;
9046
+ performance.mark(endMark);
9047
+ const measure = performance.measure(label, startMark, endMark);
9048
+ const duration = measure ? measure.duration : 0;
9049
+ performance.clearMarks(startMark);
9050
+ performance.clearMarks(endMark);
9051
+ performance.clearMeasures(label);
9052
+ return duration;
7018
9053
  }
7019
9054
  /**
7020
9055
  * Get current metrics snapshot
@@ -7026,8 +9061,8 @@ class PerformanceTelemetry {
7026
9061
  const fps = avgFrameTime > 0 ? 1000 / avgFrameTime : 0;
7027
9062
  const longFrames = this.frameTimes.filter(t => t > 16.67).length;
7028
9063
  const droppedFrames = this.frameTimes.filter(t => t > 33.33).length; // > 2 frames
7029
- const avgMainThreadWork = this.workTimes.length > 0
7030
- ? this.workTimes.reduce((a, b) => a + b, 0) / this.workTimes.length
9064
+ const avgMainThreadWork = this.workCount > 0
9065
+ ? this.workTotal / this.workCount
7031
9066
  : 0;
7032
9067
  const metrics = {
7033
9068
  frames: {
@@ -7086,7 +9121,8 @@ class PerformanceTelemetry {
7086
9121
  */
7087
9122
  reset() {
7088
9123
  this.frameTimes = [];
7089
- this.workTimes = [];
9124
+ this.workTotal = 0;
9125
+ this.workCount = 0;
7090
9126
  this.longTasks = 0;
7091
9127
  }
7092
9128
  /**
@@ -7588,5 +9624,5 @@ function warnCSPViolation(feature, fallback) {
7588
9624
  }
7589
9625
  }
7590
9626
 
7591
- export { CSPFeatures, CustomOptionPool, DOMPool, EnhancedSelect, FenwickTree, NativeSelectElement, OptionRenderer, PerformanceTelemetry, SelectOption, Virtualizer, WorkerManager, applyClasses, applyDefaultTheme, arrayIncludesValue, arraysEqualByValue, configureSelect, containsSuspiciousPatterns, createElement, createRendererHelpers, createTextNode, defaultTheme, detectEnvironment, escapeAttribute, escapeHTML, getCustomProperty, getHTMLSanitizer, getTelemetry, getWorkerManager, hasOverflowHiddenAncestor, injectShadowStyles, measureAsync, measureSync, removeCustomProperty, renderTemplate, resetSelectConfig, sanitizeHTML, selectConfig, setCSSProperties, setCustomProperties, setHTMLSanitizer, setTextContent, shadowDOMStyles, toggleClass, validateTemplate, valuesEqual, warnCSPViolation };
9627
+ export { CSPFeatures, CustomOptionPool, DOMPool, DefaultSelectEffectRunner, EnhancedSelect, FenwickTree, NativeSelectElement, OptionRenderer, PerformanceTelemetry, SelectEngineBridge, SelectOption, Virtualizer, WorkerManager, applyClasses, applyDefaultTheme, applySelectionRequest, arrayIncludesValue, arraysEqualByValue, configureSelect, containsSuspiciousPatterns, createDefaultItemAdapter, createElement, createInitialSelectState, createItemRegistry, createRendererHelpers, createTextNode, defaultTheme, detectEnvironment, escapeAttribute, escapeHTML, getActiveKey, getCustomProperty, getDefaultDuplicateKeyPolicy, getHTMLSanitizer, getSelectedKeys, getTelemetry, getWorkerManager, hasOverflowHiddenAncestor, hasSelection, injectShadowStyles, isDisabled, isFocused, isOpen, isRegisteredKey, isSelected, measureAsync, measureSync, removeCustomProperty, renderTemplate, resetSelectConfig, sanitizeHTML, selectConfig, setCSSProperties, setCustomProperties, setHTMLSanitizer, setTextContent, shadowDOMStyles, toggleClass, transition, validateTemplate, valuesEqual, warnCSPViolation };
7592
9628
  //# sourceMappingURL=index.js.map