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