@smilodon/core 1.9.3 → 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 (46) hide show
  1. package/README.md +10 -6
  2. package/dist/index.cjs +2101 -266
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.js +2086 -267
  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 +2101 -266
  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 +102 -1
  13. package/dist/types/src/config/global-config.d.ts +2 -2
  14. package/dist/types/src/engine/accessibility.d.ts +109 -0
  15. package/dist/types/src/engine/contracts.d.ts +4 -0
  16. package/dist/types/src/engine/index.d.ts +9 -0
  17. package/dist/types/src/engine/item-adapter.d.ts +23 -0
  18. package/dist/types/src/engine/item-registry.d.ts +31 -0
  19. package/dist/types/src/engine/select-effects.d.ts +20 -0
  20. package/dist/types/src/engine/select-events.d.ts +55 -0
  21. package/dist/types/src/engine/select-machine.d.ts +9 -0
  22. package/dist/types/src/engine/select-state.d.ts +17 -0
  23. package/dist/types/src/engine/selection-policy.d.ts +33 -0
  24. package/dist/types/src/engine/selectors.d.ts +10 -0
  25. package/dist/types/src/engine/virtualization.d.ts +56 -0
  26. package/dist/types/src/index.d.ts +4 -0
  27. package/dist/types/src/platform/web/accessibility-effects.d.ts +19 -0
  28. package/dist/types/src/platform/web/index.d.ts +2 -0
  29. package/dist/types/src/platform/web/select-effect-runner.d.ts +15 -0
  30. package/dist/types/src/platform/web/select-engine-bridge.d.ts +10 -0
  31. package/dist/types/src/utils/virtualizer.d.ts +48 -1
  32. package/dist/types/tests/accessibility-contract.spec.d.ts +1 -0
  33. package/dist/types/tests/enhanced-select-accessibility-integration.spec.d.ts +1 -0
  34. package/dist/types/tests/enhanced-select-active-authority.spec.d.ts +1 -0
  35. package/dist/types/tests/enhanced-select-active-parity.spec.d.ts +1 -0
  36. package/dist/types/tests/enhanced-select-authority.spec.d.ts +1 -0
  37. package/dist/types/tests/enhanced-select-compatibility-projection.spec.d.ts +1 -0
  38. package/dist/types/tests/enhanced-select-selection-parity.spec.d.ts +1 -0
  39. package/dist/types/tests/enhanced-select-virtualization-integration.spec.d.ts +1 -0
  40. package/dist/types/tests/item-adapter.spec.d.ts +1 -0
  41. package/dist/types/tests/item-registry.spec.d.ts +1 -0
  42. package/dist/types/tests/select-accessibility.spec.d.ts +1 -0
  43. package/dist/types/tests/select-selection.spec.d.ts +1 -0
  44. package/dist/types/tests/virtualization-contract.spec.d.ts +1 -0
  45. package/dist/types/tests/web-accessibility-effects.spec.d.ts +1 -0
  46. package/package.json +1 -1
package/dist/index.umd.js CHANGED
@@ -46,6 +46,530 @@
46
46
  container.replaceChildren(frag);
47
47
  }
48
48
 
49
+ const objectKeyCache = new WeakMap();
50
+ let generatedObjectKeyId = 0;
51
+ function isObjectRecord(value) {
52
+ return value !== null && (typeof value === 'object' || typeof value === 'function');
53
+ }
54
+ function readField(item, field) {
55
+ if (!field || !isObjectRecord(item))
56
+ return undefined;
57
+ return item[field];
58
+ }
59
+ function toSelectKey(value) {
60
+ if (typeof value === 'string' || typeof value === 'number') {
61
+ return value;
62
+ }
63
+ if (typeof value === 'boolean' || typeof value === 'bigint' || typeof value === 'symbol') {
64
+ return String(value);
65
+ }
66
+ return null;
67
+ }
68
+ function objectIdentityKey(item) {
69
+ const cached = objectKeyCache.get(item);
70
+ if (cached)
71
+ return cached;
72
+ generatedObjectKeyId += 1;
73
+ const key = `__smilodon-object-${generatedObjectKeyId}`;
74
+ objectKeyCache.set(item, key);
75
+ return key;
76
+ }
77
+ function indexFallbackKey(index, warn) {
78
+ const env = globalThis.process?.env?.NODE_ENV;
79
+ if (env !== 'production') {
80
+ const message = '[Smilodon Phase2] Using index as key is unstable under filtering/sorting. Provide getKey/valueField for stable selection.';
81
+ if (warn) {
82
+ warn(message);
83
+ }
84
+ else {
85
+ console.warn(message);
86
+ }
87
+ }
88
+ return `__smilodon-index-${index}`;
89
+ }
90
+ /** Generated reference keys survive reorder, but not replacement with new objects. */
91
+ function createDefaultItemAdapter(options = {}) {
92
+ return {
93
+ getKey(item, index) {
94
+ if (options.getKey) {
95
+ return options.getKey(item, index);
96
+ }
97
+ if (isObjectRecord(item)) {
98
+ const directKey = toSelectKey(item.id)
99
+ ?? toSelectKey(item.key)
100
+ ?? toSelectKey(item.value)
101
+ ?? toSelectKey(readField(item, options.valueField));
102
+ if (directKey !== null) {
103
+ return directKey;
104
+ }
105
+ if (options.getValue) {
106
+ const configuredValueKey = toSelectKey(options.getValue(item, index));
107
+ if (configuredValueKey !== null) {
108
+ return configuredValueKey;
109
+ }
110
+ }
111
+ return options.keyFallback === 'index'
112
+ ? indexFallbackKey(index, options.onIndexFallback)
113
+ : objectIdentityKey(item);
114
+ }
115
+ return String(item);
116
+ },
117
+ getValue(item, index) {
118
+ if (options.getValue) {
119
+ return options.getValue(item, index);
120
+ }
121
+ const fieldValue = readField(item, options.valueField);
122
+ if (fieldValue !== undefined) {
123
+ return fieldValue;
124
+ }
125
+ return isObjectRecord(item) && item.value !== undefined ? item.value : item;
126
+ },
127
+ getLabel(item, index) {
128
+ if (options.getLabel) {
129
+ return options.getLabel(item, index);
130
+ }
131
+ const fieldLabel = readField(item, options.labelField);
132
+ if (fieldLabel !== undefined) {
133
+ return String(fieldLabel);
134
+ }
135
+ if (isObjectRecord(item) && item.label !== undefined) {
136
+ return String(item.label);
137
+ }
138
+ if (isObjectRecord(item) && item.text !== undefined) {
139
+ return String(item.text);
140
+ }
141
+ return String(item);
142
+ },
143
+ isDisabled(item, index) {
144
+ if (options.isDisabled) {
145
+ return options.isDisabled(item, index);
146
+ }
147
+ return Boolean(isObjectRecord(item) && item.disabled);
148
+ },
149
+ getGroupKey(item, index) {
150
+ if (options.getGroupKey) {
151
+ return options.getGroupKey(item, index);
152
+ }
153
+ if (!isObjectRecord(item) || item.group === undefined) {
154
+ return null;
155
+ }
156
+ return item.group == null ? null : String(item.group);
157
+ },
158
+ };
159
+ }
160
+
161
+ function getDefaultDuplicateKeyPolicy() {
162
+ const env = globalThis.process?.env?.NODE_ENV;
163
+ return env === 'production' ? 'warn' : 'throw';
164
+ }
165
+ function createItemRegistry(items, adapter, options = {}) {
166
+ const duplicateKeyPolicy = options.duplicateKeyPolicy ?? getDefaultDuplicateKeyPolicy();
167
+ const records = [];
168
+ const keyToRecord = new Map();
169
+ const indexToKey = new Map();
170
+ const keyToIndex = new Map();
171
+ const firstIndexByKey = new Map();
172
+ const duplicateKeys = [];
173
+ items.forEach((item, index) => {
174
+ const key = adapter.getKey(item, index);
175
+ const firstIndex = firstIndexByKey.get(key);
176
+ const record = {
177
+ key,
178
+ item,
179
+ index,
180
+ label: adapter.getLabel(item, index),
181
+ value: adapter.getValue(item, index),
182
+ disabled: adapter.isDisabled?.(item, index) === true,
183
+ groupKey: adapter.getGroupKey?.(item, index) ?? null,
184
+ };
185
+ records.push(record);
186
+ indexToKey.set(index, key);
187
+ if (firstIndex !== undefined) {
188
+ const diagnostic = {
189
+ key,
190
+ firstIndex,
191
+ duplicateIndex: index,
192
+ };
193
+ duplicateKeys.push(diagnostic);
194
+ if (duplicateKeyPolicy === 'throw') {
195
+ throw new Error(duplicateKeyMessage(diagnostic));
196
+ }
197
+ if (duplicateKeyPolicy === 'warn') {
198
+ if (options.onDuplicateKey) {
199
+ options.onDuplicateKey(diagnostic);
200
+ }
201
+ else {
202
+ console.warn(duplicateKeyMessage(diagnostic));
203
+ }
204
+ return;
205
+ }
206
+ if (duplicateKeyPolicy === 'first-wins') {
207
+ return;
208
+ }
209
+ }
210
+ else {
211
+ firstIndexByKey.set(key, index);
212
+ }
213
+ keyToRecord.set(key, record);
214
+ keyToIndex.set(key, index);
215
+ });
216
+ return {
217
+ records,
218
+ keyToRecord,
219
+ indexToKey,
220
+ keyToIndex,
221
+ duplicateKeys,
222
+ };
223
+ }
224
+ function duplicateKeyMessage(diagnostic) {
225
+ return `[Smilodon Phase2] Duplicate item key "${String(diagnostic.key)}" at indexes ${diagnostic.firstIndex} and ${diagnostic.duplicateIndex}. Provide stable unique keys for selection.`;
226
+ }
227
+
228
+ /** Pure key policy. Visibility does not constrain selection; disabled keys do. */
229
+ function applySelectionRequest(selectedKeys, request, config) {
230
+ let next;
231
+ switch (request.type) {
232
+ case 'select':
233
+ next = selectKey(selectedKeys, request.key, config);
234
+ break;
235
+ case 'deselect':
236
+ next = deselectKey(selectedKeys, request.key, config);
237
+ break;
238
+ case 'toggle':
239
+ if (!selectedKeys.has(request.key)) {
240
+ next = selectKey(selectedKeys, request.key, config);
241
+ }
242
+ else if (config.multiple || config.allowDeselect) {
243
+ next = deselectKey(selectedKeys, request.key, config);
244
+ }
245
+ else {
246
+ next = selectedKeys;
247
+ }
248
+ break;
249
+ case 'clear':
250
+ next = config.required && selectedKeys.size > 0
251
+ ? selectedKeys
252
+ : new Set();
253
+ break;
254
+ case 'replace':
255
+ next = replaceKeys(selectedKeys, request.keys, config);
256
+ break;
257
+ }
258
+ // Set membership is authoritative. Reordering the same keys is not a change.
259
+ return next.size === selectedKeys.size && [...next].every((key) => selectedKeys.has(key))
260
+ ? selectedKeys
261
+ : next;
262
+ }
263
+ function selectKey(selectedKeys, key, config) {
264
+ if (config.disabledKeys.has(key)) {
265
+ return selectedKeys;
266
+ }
267
+ if (!config.multiple) {
268
+ return new Set([key]);
269
+ }
270
+ if (selectedKeys.has(key)) {
271
+ return selectedKeys;
272
+ }
273
+ const maxSelections = config.maxSelections ?? 0;
274
+ if (maxSelections > 0 && selectedKeys.size >= maxSelections) {
275
+ return selectedKeys;
276
+ }
277
+ return new Set([...selectedKeys, key]);
278
+ }
279
+ function deselectKey(selectedKeys, key, config) {
280
+ if (!selectedKeys.has(key) || config.disabledKeys.has(key)) {
281
+ return selectedKeys;
282
+ }
283
+ if (config.required && selectedKeys.size <= 1) {
284
+ return selectedKeys;
285
+ }
286
+ const next = new Set(selectedKeys);
287
+ next.delete(key);
288
+ return next;
289
+ }
290
+ function replaceKeys(selectedKeys, keys, config) {
291
+ const next = normalizeKeys(keys, config);
292
+ if (config.required && next.size === 0 && selectedKeys.size > 0) {
293
+ // Required preserves a valid selection, but cannot keep newly disabled keys.
294
+ return normalizeKeys(selectedKeys, config);
295
+ }
296
+ return next;
297
+ }
298
+ function normalizeKeys(keys, config) {
299
+ const seen = new Set();
300
+ const maxSelections = config.maxSelections ?? 0;
301
+ for (const key of keys) {
302
+ if (config.disabledKeys.has(key) || seen.has(key)) {
303
+ continue;
304
+ }
305
+ seen.add(key);
306
+ if (!config.multiple || (maxSelections > 0 && seen.size >= maxSelections)) {
307
+ break;
308
+ }
309
+ }
310
+ return seen;
311
+ }
312
+
313
+ function transition(state, event) {
314
+ switch (event.type) {
315
+ case 'CONNECT':
316
+ return { state: { ...state, lifecycle: 'connected' }, effects: [] };
317
+ case 'DISCONNECT': {
318
+ const effects = state.popup === 'open'
319
+ ? [{ type: 'POPUP_CLOSED', reason: 'disconnect' }, { type: 'SYNC_ARIA' }]
320
+ : [];
321
+ return {
322
+ state: { ...state, lifecycle: 'disconnected', popup: 'closed', focused: false },
323
+ effects,
324
+ };
325
+ }
326
+ case 'OPEN_REQUEST':
327
+ if (state.lifecycle !== 'connected' || state.disabled || state.popup === 'open') {
328
+ return { state: enforceInvariants(state), effects: [] };
329
+ }
330
+ return {
331
+ state: { ...state, popup: 'open' },
332
+ effects: [{ type: 'POPUP_OPENED' }, { type: 'FOCUS_TRIGGER' }, { type: 'SYNC_ARIA' }],
333
+ };
334
+ case 'CLOSE_REQUEST':
335
+ if (state.popup === 'closed') {
336
+ return { state, effects: [] };
337
+ }
338
+ return {
339
+ state: { ...state, popup: 'closed' },
340
+ effects: [{ type: 'POPUP_CLOSED', reason: event.reason }, { type: 'SYNC_ARIA' }],
341
+ };
342
+ case 'TOGGLE_REQUEST':
343
+ return transition(state, state.popup === 'open'
344
+ ? { type: 'CLOSE_REQUEST', reason: 'programmatic' }
345
+ : { type: 'OPEN_REQUEST' });
346
+ case 'FOCUS_GAINED':
347
+ return state.focused
348
+ ? { state, effects: [] }
349
+ : { state: { ...state, focused: true }, effects: [{ type: 'SYNC_ARIA' }] };
350
+ case 'FOCUS_LOST':
351
+ return state.focused
352
+ ? { state: { ...state, focused: false }, effects: [{ type: 'SYNC_ARIA' }] }
353
+ : { state, effects: [] };
354
+ case 'DISABLED_CHANGED': {
355
+ if (state.disabled === event.disabled) {
356
+ return { state: enforceInvariants(state), effects: [] };
357
+ }
358
+ const nextState = enforceInvariants({ ...state, disabled: event.disabled });
359
+ const effects = [];
360
+ if (event.disabled && state.popup === 'open') {
361
+ effects.push({ type: 'POPUP_CLOSED', reason: 'disabled' });
362
+ }
363
+ effects.push({ type: 'SYNC_ARIA' });
364
+ return {
365
+ state: nextState,
366
+ effects,
367
+ };
368
+ }
369
+ case 'ITEMS_REGISTERED': {
370
+ const registeredKeys = new Set(event.keys);
371
+ const disabledKeys = new Set(event.disabledKeys ?? []);
372
+ const selection = { ...state.selection, disabledKeys };
373
+ const activeKey = resolveActiveKey(state.activeKey, registeredKeys, disabledKeys);
374
+ const selectedKeys = applySelectionRequest(state.selectedKeys, { type: 'replace', keys: Array.from(state.selectedKeys)}, selection);
375
+ const nextState = {
376
+ ...state,
377
+ activeKey,
378
+ selectedKeys,
379
+ registeredKeys,
380
+ selection,
381
+ };
382
+ const effects = [];
383
+ if (!keysEqual(activeKey, state.activeKey)) {
384
+ effects.push({ type: 'ACTIVE_KEY_CHANGED', activeKey, reason: 'programmatic' });
385
+ }
386
+ if (!setsEqual(selectedKeys, state.selectedKeys)) {
387
+ effects.push({ type: 'SELECTION_CHANGED', selectedKeys: Array.from(selectedKeys), reason: 'programmatic' });
388
+ }
389
+ if (effects.length > 0) {
390
+ effects.push({ type: 'SYNC_ARIA' });
391
+ }
392
+ return { state: nextState, effects };
393
+ }
394
+ case 'SELECTION_CONFIG_CHANGED': {
395
+ const selection = {
396
+ ...state.selection,
397
+ multiple: event.multiple ?? state.selection.multiple,
398
+ required: event.required ?? state.selection.required,
399
+ allowDeselect: event.allowDeselect ?? state.selection.allowDeselect,
400
+ maxSelections: event.maxSelections ?? state.selection.maxSelections,
401
+ disabledKeys: event.disabledKeys ? new Set(event.disabledKeys) : state.selection.disabledKeys,
402
+ };
403
+ const selectedKeys = applySelectionRequest(state.selectedKeys, { type: 'replace', keys: Array.from(state.selectedKeys)}, selection);
404
+ const activeKey = resolveActiveKey(state.activeKey, state.registeredKeys, selection.disabledKeys);
405
+ const nextState = { ...state, selection, selectedKeys, activeKey };
406
+ const effects = [];
407
+ if (!keysEqual(activeKey, state.activeKey)) {
408
+ effects.push({ type: 'ACTIVE_KEY_CHANGED', activeKey, reason: 'programmatic' });
409
+ }
410
+ if (!setsEqual(selectedKeys, state.selectedKeys)) {
411
+ effects.push({ type: 'SELECTION_CHANGED', selectedKeys: Array.from(selectedKeys), reason: 'programmatic' });
412
+ }
413
+ if (effects.length > 0) {
414
+ effects.push({ type: 'SYNC_ARIA' });
415
+ }
416
+ return { state: nextState, effects };
417
+ }
418
+ case 'ACTIVE_KEY_CHANGED': {
419
+ if (event.key !== null
420
+ && (!state.registeredKeys.has(event.key) || state.selection.disabledKeys.has(event.key))) {
421
+ return { state, effects: [] };
422
+ }
423
+ if (keysEqual(state.activeKey, event.key)) {
424
+ return { state, effects: [] };
425
+ }
426
+ return {
427
+ state: { ...state, activeKey: event.key },
428
+ effects: [
429
+ { type: 'ACTIVE_KEY_CHANGED', activeKey: event.key, reason: event.reason },
430
+ { type: 'SYNC_ARIA' },
431
+ ],
432
+ };
433
+ }
434
+ case 'SELECT_KEY_REQUEST':
435
+ case 'DESELECT_KEY_REQUEST':
436
+ case 'TOGGLE_KEY_REQUEST':
437
+ case 'CLEAR_SELECTION_REQUEST':
438
+ case 'REPLACE_SELECTION_REQUEST': {
439
+ const selectedKeys = applySelectionRequest(state.selectedKeys, selectionRequestFromEvent(event), state.selection);
440
+ if (setsEqual(selectedKeys, state.selectedKeys)) {
441
+ return { state, effects: [] };
442
+ }
443
+ return {
444
+ state: { ...state, selectedKeys },
445
+ effects: [
446
+ { type: 'SELECTION_CHANGED', selectedKeys: Array.from(selectedKeys), reason: event.reason },
447
+ { type: 'SYNC_ARIA' },
448
+ ],
449
+ };
450
+ }
451
+ default:
452
+ return { state, effects: [] };
453
+ }
454
+ }
455
+ function selectionRequestFromEvent(event) {
456
+ switch (event.type) {
457
+ case 'SELECT_KEY_REQUEST':
458
+ return { type: 'select', key: event.key, reason: event.reason };
459
+ case 'DESELECT_KEY_REQUEST':
460
+ return { type: 'deselect', key: event.key, reason: event.reason };
461
+ case 'TOGGLE_KEY_REQUEST':
462
+ return { type: 'toggle', key: event.key, reason: event.reason };
463
+ case 'CLEAR_SELECTION_REQUEST':
464
+ return { type: 'clear', reason: event.reason };
465
+ case 'REPLACE_SELECTION_REQUEST':
466
+ return { type: 'replace', keys: event.keys, reason: event.reason };
467
+ }
468
+ }
469
+ function enforceInvariants(state) {
470
+ if (state.lifecycle === 'disconnected' || state.disabled) {
471
+ return state.popup === 'closed' ? state : { ...state, popup: 'closed' };
472
+ }
473
+ return state;
474
+ }
475
+ function resolveActiveKey(key, registeredKeys, disabledKeys) {
476
+ return key !== null && registeredKeys.has(key) && !disabledKeys.has(key) ? key : null;
477
+ }
478
+ function setsEqual(left, right) {
479
+ if (left.size !== right.size)
480
+ return false;
481
+ for (const value of left) {
482
+ if (!right.has(value))
483
+ return false;
484
+ }
485
+ return true;
486
+ }
487
+ /** Match Map/Set identity, including NaN and signed zero. */
488
+ function keysEqual(left, right) {
489
+ return left === right || Object.is(left, right);
490
+ }
491
+
492
+ function createInitialSelectState() {
493
+ return {
494
+ lifecycle: 'disconnected',
495
+ popup: 'closed',
496
+ disabled: false,
497
+ focused: false,
498
+ query: '',
499
+ activeKey: null,
500
+ selectedKeys: new Set(),
501
+ registeredKeys: new Set(),
502
+ selection: {
503
+ multiple: false,
504
+ required: false,
505
+ allowDeselect: false,
506
+ disabledKeys: new Set(),
507
+ maxSelections: 0,
508
+ },
509
+ dataStatus: 'idle',
510
+ };
511
+ }
512
+
513
+ function isOpen(state) {
514
+ return state.popup === 'open';
515
+ }
516
+ function isDisabled(state) {
517
+ return state.disabled;
518
+ }
519
+ function isFocused(state) {
520
+ return state.focused;
521
+ }
522
+ function hasSelection(state) {
523
+ return state.selectedKeys.size > 0;
524
+ }
525
+ function isSelected(state, key) {
526
+ return state.selectedKeys.has(key);
527
+ }
528
+ function getSelectedKeys(state) {
529
+ return Array.from(state.selectedKeys);
530
+ }
531
+ function getActiveKey(state) {
532
+ return state.activeKey;
533
+ }
534
+ function isRegisteredKey(state, key) {
535
+ return state.registeredKeys.has(key);
536
+ }
537
+
538
+ class SelectEngineBridge {
539
+ constructor(initialState = createInitialSelectState()) {
540
+ this._state = initialState;
541
+ }
542
+ get state() {
543
+ return this._state;
544
+ }
545
+ dispatch(event) {
546
+ const result = transition(this._state, event);
547
+ this._state = result.state;
548
+ return result.effects;
549
+ }
550
+ }
551
+
552
+ class DefaultSelectEffectRunner {
553
+ run(effects, context) {
554
+ for (const effect of effects) {
555
+ switch (effect.type) {
556
+ case 'FOCUS_TRIGGER':
557
+ context.focusTrigger?.();
558
+ break;
559
+ case 'SYNC_ARIA':
560
+ context.syncAria?.();
561
+ break;
562
+ case 'POPUP_OPENED':
563
+ context.onPopupOpened?.();
564
+ break;
565
+ case 'POPUP_CLOSED':
566
+ context.onPopupClosed?.(effect.reason);
567
+ break;
568
+ }
569
+ }
570
+ }
571
+ }
572
+
49
573
  /**
50
574
  * Fenwick Tree (Binary Indexed Tree) for O(log n) prefix sum queries and updates.
51
575
  * Used for cumulative height calculations in variable-height virtualization.
@@ -371,13 +895,17 @@
371
895
  class Virtualizer {
372
896
  constructor(container, itemsLength, itemGetter, options) {
373
897
  this.measuredHeights = new Map();
898
+ this.measuredHeightTotal = 0;
374
899
  this.activeNodes = new Map(); // index -> node mapping
375
900
  this.destroyed = false;
376
901
  this.recycleRafId = 0;
902
+ this.intendedScrollTop = 0;
903
+ this.currentWindow = null;
377
904
  this.container = container;
378
905
  this.itemsLength = itemsLength;
379
906
  this.itemGetter = itemGetter;
380
907
  this.options = options;
908
+ this.estimatedItemHeight = options.estimatedItemHeight;
381
909
  this.averageHeight = options.estimatedItemHeight;
382
910
  // Initialize DOM pool with LRU eviction
383
911
  const maxPoolSize = Math.ceil((options.buffer * 2 + 10) * 1.5) + (options.maxPoolExtra ?? 32);
@@ -398,39 +926,121 @@
398
926
  },
399
927
  telemetry: options.enableTelemetry || false,
400
928
  });
401
- // Use Fenwick tree for large lists (>5000 items)
402
- if (itemsLength > 5000) {
403
- this.fenwick = new FenwickTree(itemsLength);
404
- // Initialize with estimated heights
405
- for (let i = 0; i < itemsLength; i++) {
406
- this.fenwick.add(i, options.estimatedItemHeight);
407
- }
408
- }
929
+ // One prefix index keeps offset, window, and scroll calculations on the
930
+ // same measured-height policy at every list size.
931
+ this.fenwick = this.createFenwickTree(itemsLength);
409
932
  this.container.style.willChange = 'transform';
410
933
  }
411
934
  computeWindow(scrollTop, viewportHeight) {
412
935
  const { buffer } = this.options;
413
- const startIndex = Math.max(Math.floor(scrollTop / this.averageHeight) - buffer, 0);
414
- const endIndex = Math.min(Math.ceil((scrollTop + viewportHeight) / this.averageHeight) + buffer, this.itemsLength - 1);
936
+ const visibleStartIndex = this.indexAtOffset(scrollTop);
937
+ const calculatedStartIndex = visibleStartIndex - buffer;
938
+ const startIndex = this.itemsLength > 0
939
+ ? Math.max(0, Math.min(this.itemsLength - 1, calculatedStartIndex))
940
+ : 0;
941
+ const viewportEnd = Math.max(0, scrollTop + viewportHeight);
942
+ let visibleEndIndex = this.indexAtOffset(viewportEnd);
943
+ // The item beginning exactly at the viewport's lower edge is not visible.
944
+ // indexAtOffset deliberately advances across exact boundaries for the
945
+ // viewport start, so reverse that choice here when the viewport has height.
946
+ if (viewportHeight > 0
947
+ && visibleEndIndex > visibleStartIndex
948
+ && this.cumulativeOffset(visibleEndIndex) === viewportEnd) {
949
+ visibleEndIndex -= 1;
950
+ }
951
+ const calculatedEndIndex = Math.max(visibleStartIndex, visibleEndIndex) + buffer;
952
+ const endIndex = this.itemsLength > 0
953
+ ? Math.max(0, Math.min(this.itemsLength - 1, calculatedEndIndex))
954
+ : -1;
415
955
  const windowSize = Math.max(0, endIndex - startIndex + 1);
416
956
  // Adjust pool size dynamically based on window
417
957
  const newPoolSize = windowSize + (this.options.maxPoolExtra ?? 32);
418
958
  this.pool.setMaxSize(newPoolSize);
419
959
  return { startIndex, endIndex, windowSize };
420
960
  }
421
- cumulativeOffset(index) {
422
- if (index <= 0)
961
+ /** Computes and records a scroll-derived window without installing listeners. */
962
+ updateWindow(scrollTop, viewportHeight) {
963
+ if (this.destroyed)
964
+ return null;
965
+ const safeScrollTop = Number.isFinite(scrollTop) ? Math.max(0, scrollTop) : 0;
966
+ const safeViewportHeight = Number.isFinite(viewportHeight) && viewportHeight >= 0
967
+ ? viewportHeight
968
+ : 0;
969
+ const nextWindow = this.computeWindow(safeScrollTop, safeViewportHeight);
970
+ const changed = this.currentWindow === null
971
+ || this.currentWindow.startIndex !== nextWindow.startIndex
972
+ || this.currentWindow.endIndex !== nextWindow.endIndex
973
+ || this.currentWindow.windowSize !== nextWindow.windowSize;
974
+ this.currentWindow = { ...nextWindow };
975
+ return {
976
+ window: { ...nextWindow },
977
+ changed,
978
+ scrollTop: safeScrollTop,
979
+ viewportHeight: safeViewportHeight,
980
+ };
981
+ }
982
+ /** Returns a copy of the last recorded window, or null before the first update. */
983
+ getCurrentWindow() {
984
+ return this.currentWindow ? { ...this.currentWindow } : null;
985
+ }
986
+ /** Finds the item containing an offset, advancing past exact item boundaries. */
987
+ indexAtOffset(offset) {
988
+ if (this.itemsLength <= 0)
423
989
  return 0;
424
- // Use Fenwick tree for O(log n) prefix sum
425
- if (this.fenwick) {
426
- return this.fenwick.sum(index - 1);
990
+ const target = Math.max(0, offset);
991
+ let index = Math.max(0, Math.min(this.itemsLength - 1, this.fenwick.lowerBound(target)));
992
+ // FenwickTree.lowerBound returns the preceding item when the target lands
993
+ // exactly on an item boundary. For the viewport start, select the next item.
994
+ while (index < this.itemsLength - 1 && this.cumulativeOffset(index + 1) <= target) {
995
+ index += 1;
427
996
  }
428
- // Fallback: approximate using average height with sparse adjustments
429
- let total = 0;
430
- for (let i = 0; i < index; i++) {
431
- total += this.measuredHeights.get(i) ?? this.averageHeight;
997
+ return index;
998
+ }
999
+ cumulativeOffset(index) {
1000
+ if (!Number.isFinite(index)) {
1001
+ return index === Number.POSITIVE_INFINITY && this.itemsLength > 0
1002
+ ? this.fenwick.sum(this.itemsLength - 1)
1003
+ : 0;
432
1004
  }
433
- return total;
1005
+ const boundedIndex = Math.max(0, Math.min(this.itemsLength, Math.trunc(index)));
1006
+ if (boundedIndex === 0)
1007
+ return 0;
1008
+ return this.fenwick.sum(boundedIndex - 1);
1009
+ }
1010
+ /**
1011
+ * Calculates and records the intended scroll position for an item without
1012
+ * mutating the container. The caller may apply the returned scrollTop.
1013
+ * Returns null after destruction or when there are no items to target.
1014
+ */
1015
+ scrollToIndex(index) {
1016
+ if (this.destroyed || this.itemsLength <= 0)
1017
+ return null;
1018
+ const requestedIndex = Number.isFinite(index) ? Math.trunc(index) : 0;
1019
+ const targetIndex = Math.max(0, Math.min(this.itemsLength - 1, requestedIndex));
1020
+ const offset = this.cumulativeOffset(targetIndex);
1021
+ this.intendedScrollTop = offset;
1022
+ return { index: targetIndex, offset, scrollTop: offset };
1023
+ }
1024
+ /**
1025
+ * Resolves a stable key against the caller's current data identity, then
1026
+ * delegates to scrollToIndex(). Invalid or out-of-range resolutions are
1027
+ * rejected rather than clamped to a different item's position.
1028
+ */
1029
+ scrollToKey(key, resolveIndex) {
1030
+ if (this.destroyed || this.itemsLength <= 0)
1031
+ return null;
1032
+ const index = resolveIndex(key);
1033
+ if (typeof index !== 'number'
1034
+ || !Number.isInteger(index)
1035
+ || index < 0
1036
+ || index >= this.itemsLength) {
1037
+ return null;
1038
+ }
1039
+ return this.scrollToIndex(index);
1040
+ }
1041
+ /** Returns the last scroll position requested through scrollToIndex(). */
1042
+ getIntendedScrollTop() {
1043
+ return this.intendedScrollTop;
434
1044
  }
435
1045
  acquireNode(index) {
436
1046
  // Check if we already have this node active (reuse)
@@ -491,23 +1101,29 @@
491
1101
  });
492
1102
  }
493
1103
  measureOnAppear(node, index) {
494
- if (this.destroyed || index >= this.itemsLength)
495
- return;
496
- const h = node.offsetHeight;
1104
+ this.measureItem(index, node.offsetHeight);
1105
+ }
1106
+ /** Records a validated measured height and updates the virtual offset index. */
1107
+ measureItem(index, height) {
1108
+ if (this.destroyed
1109
+ || !Number.isInteger(index)
1110
+ || index < 0
1111
+ || index >= this.itemsLength
1112
+ || !Number.isFinite(height)
1113
+ || height <= 0)
1114
+ return false;
497
1115
  const prev = this.measuredHeights.get(index);
498
1116
  const threshold = this.options.measurementThreshold ?? 5;
499
- if (prev === undefined || Math.abs(prev - h) > threshold) {
500
- const oldValue = prev ?? this.averageHeight;
501
- this.measuredHeights.set(index, h);
1117
+ if (prev === undefined || Math.abs(prev - height) > threshold) {
1118
+ const oldValue = prev ?? this.estimatedItemHeight;
1119
+ this.measuredHeights.set(index, height);
1120
+ this.measuredHeightTotal += height - (prev ?? 0);
502
1121
  // Update Fenwick tree with new measurement
503
- if (this.fenwick) {
504
- this.fenwick.update(index, oldValue, h);
505
- }
506
- // Update running average (weighted by measured count)
507
- const count = this.measuredHeights.size;
508
- const total = Array.from(this.measuredHeights.values()).reduce((a, b) => a + b, 0);
509
- this.averageHeight = Math.round((total / count) * 100) / 100;
1122
+ this.fenwick.update(index, oldValue, height);
1123
+ this.updateAverageHeight();
1124
+ return true;
510
1125
  }
1126
+ return false;
511
1127
  }
512
1128
  /**
513
1129
  * Get pool statistics (if telemetry enabled)
@@ -519,27 +1135,27 @@
519
1135
  * Update items length and resize Fenwick tree if needed
520
1136
  */
521
1137
  setItemsLength(newLength) {
1138
+ const previousLength = this.itemsLength;
522
1139
  this.itemsLength = newLength;
523
- for (const index of Array.from(this.measuredHeights.keys())) {
1140
+ if (newLength !== previousLength)
1141
+ this.currentWindow = null;
1142
+ let removedMeasurement = false;
1143
+ for (const [index, height] of this.measuredHeights) {
524
1144
  if (index >= newLength) {
1145
+ this.measuredHeightTotal -= height;
525
1146
  this.measuredHeights.delete(index);
1147
+ removedMeasurement = true;
526
1148
  }
527
1149
  }
1150
+ if (removedMeasurement)
1151
+ this.updateAverageHeight();
528
1152
  for (const index of Array.from(this.activeNodes.keys())) {
529
1153
  if (index >= newLength) {
530
1154
  this.releaseNode(index);
531
1155
  }
532
1156
  }
533
- if (this.fenwick) {
534
- this.fenwick.resize(newLength);
535
- }
536
- else if (newLength > 5000 && !this.fenwick) {
537
- // Activate Fenwick tree when crossing threshold
538
- this.fenwick = new FenwickTree(newLength);
539
- // Populate with existing measurements
540
- for (const [index, height] of this.measuredHeights) {
541
- this.fenwick.update(index, this.averageHeight, height);
542
- }
1157
+ if (newLength !== previousLength) {
1158
+ this.fenwick = this.createFenwickTree(newLength);
543
1159
  }
544
1160
  }
545
1161
  /**
@@ -554,9 +1170,28 @@
554
1170
  this.pool.clear();
555
1171
  this.activeNodes.clear();
556
1172
  this.measuredHeights.clear();
557
- if (this.fenwick) {
558
- this.fenwick.reset();
1173
+ this.measuredHeightTotal = 0;
1174
+ this.averageHeight = this.estimatedItemHeight;
1175
+ this.currentWindow = null;
1176
+ this.fenwick.reset();
1177
+ }
1178
+ updateAverageHeight() {
1179
+ const count = this.measuredHeights.size;
1180
+ this.averageHeight = count > 0
1181
+ ? Math.round((this.measuredHeightTotal / count) * 100) / 100
1182
+ : this.estimatedItemHeight;
1183
+ }
1184
+ createFenwickTree(size) {
1185
+ const tree = new FenwickTree(size);
1186
+ for (let index = 0; index < size; index++) {
1187
+ tree.add(index, this.estimatedItemHeight);
1188
+ }
1189
+ for (const [index, height] of this.measuredHeights) {
1190
+ if (index < size) {
1191
+ tree.update(index, this.estimatedItemHeight, height);
1192
+ }
559
1193
  }
1194
+ return tree;
560
1195
  }
561
1196
  }
562
1197
 
@@ -1618,6 +2253,222 @@
1618
2253
  selectConfig.resetConfig();
1619
2254
  }
1620
2255
 
2256
+ /** Returns whether a selected key remains in the filtered result set. */
2257
+ /**
2258
+ * Returns keys in the half-open index range [startIndex, endIndex), clamped to
2259
+ * the source. Bounds are truncated to integers; an end before start is empty.
2260
+ */
2261
+ function computeWindowKeys(filteredKeys, startIndex, endIndex) {
2262
+ const start = Math.max(0, Math.min(filteredKeys.length, Math.trunc(startIndex)));
2263
+ const end = Math.max(start, Math.min(filteredKeys.length, Math.trunc(endIndex)));
2264
+ return filteredKeys.slice(start, end);
2265
+ }
2266
+
2267
+ /** Projects existing engine state into accessibility semantics without DOM data. */
2268
+ function deriveAccessibilityState(state, context = {}) {
2269
+ const required = state.selection.required;
2270
+ const invalid = context.invalid ?? false;
2271
+ return {
2272
+ expanded: state.popup === 'open',
2273
+ disabled: state.disabled,
2274
+ readonly: context.readonly ?? false,
2275
+ searchable: context.searchable ?? false,
2276
+ multiple: state.selection.multiple,
2277
+ required,
2278
+ invalid,
2279
+ busy: state.dataStatus === 'loading',
2280
+ activeKey: state.activeKey,
2281
+ selectedKeys: state.selectedKeys,
2282
+ disabledKeys: state.selection.disabledKeys,
2283
+ popupRole: 'listbox',
2284
+ label: context.label ?? {},
2285
+ validation: {
2286
+ required,
2287
+ invalid,
2288
+ errorMessage: context.errorMessage ?? null,
2289
+ errorDescriptionId: context.errorDescriptionId ?? null,
2290
+ },
2291
+ };
2292
+ }
2293
+ function uniqueIds(ids) {
2294
+ return [...new Set(ids.filter((id) => Boolean(id)))];
2295
+ }
2296
+ function getLabelledBy(label) {
2297
+ return uniqueIds([label.labelId, ...(label.labelledBy ?? [])]);
2298
+ }
2299
+ function getDescribedBy(state) {
2300
+ return uniqueIds([
2301
+ ...(state.label.describedBy ?? []),
2302
+ state.validation.errorDescriptionId,
2303
+ ]);
2304
+ }
2305
+ /** Computes combobox semantics without reading from or writing to the DOM. */
2306
+ function computeComboboxAccessibility(state, controlsId = null) {
2307
+ return {
2308
+ role: 'combobox',
2309
+ expanded: state.expanded,
2310
+ disabled: state.disabled,
2311
+ readonly: state.readonly,
2312
+ autocomplete: state.searchable ? 'list' : 'none',
2313
+ multiple: state.multiple,
2314
+ required: state.required,
2315
+ invalid: state.invalid,
2316
+ activeKey: state.activeKey,
2317
+ controlsId,
2318
+ labelledBy: getLabelledBy(state.label),
2319
+ describedBy: getDescribedBy(state),
2320
+ ariaLabel: state.label.ariaLabel ?? null,
2321
+ ariaDescription: state.label.ariaDescription ?? null,
2322
+ };
2323
+ }
2324
+ /** Computes listbox semantics; the supplied label IDs remain caller-owned data. */
2325
+ function computeListboxAccessibility(state) {
2326
+ return {
2327
+ role: state.popupRole,
2328
+ multiple: state.multiple,
2329
+ busy: state.busy,
2330
+ labelledBy: getLabelledBy(state.label),
2331
+ ariaLabel: state.label.ariaLabel ?? null,
2332
+ };
2333
+ }
2334
+ /** Computes one option's semantic state from stable identity, never its index. */
2335
+ function computeOptionAccessibility(state, key) {
2336
+ const disabled = state.disabled || state.disabledKeys.has(key);
2337
+ return {
2338
+ key,
2339
+ selected: state.selectedKeys.has(key),
2340
+ disabled,
2341
+ active: !disabled && state.activeKey === key,
2342
+ };
2343
+ }
2344
+ /**
2345
+ * Produces semantic accessibility effects. IDs and rendered option keys are
2346
+ * caller inputs; this function does not inspect the DOM or perform side effects.
2347
+ */
2348
+ function computeAccessibilityEffects(state, options) {
2349
+ return [
2350
+ {
2351
+ type: 'SYNC_COMBOBOX_ARIA',
2352
+ ...computeComboboxAccessibility(state, options.controlsId ?? null),
2353
+ },
2354
+ {
2355
+ type: 'SYNC_LISTBOX_ARIA',
2356
+ ...computeListboxAccessibility(state),
2357
+ },
2358
+ ...options.optionKeys.map((key) => ({
2359
+ type: 'SYNC_OPTION_ARIA',
2360
+ ...computeOptionAccessibility(state, key),
2361
+ })),
2362
+ ...(options.announcements ?? []).map((announcement) => ({
2363
+ type: 'ANNOUNCE',
2364
+ ...announcement,
2365
+ })),
2366
+ ...(options.focusIntents ?? []).map((focusIntent) => ({
2367
+ type: 'FOCUS_INTENT',
2368
+ ...focusIntent,
2369
+ })),
2370
+ ];
2371
+ }
2372
+
2373
+ function setBooleanAttribute(element, name, value) {
2374
+ element.setAttribute(name, String(value));
2375
+ }
2376
+ function setOptionalAttribute(element, name, value) {
2377
+ if (value) {
2378
+ element.setAttribute(name, value);
2379
+ }
2380
+ else {
2381
+ element.removeAttribute(name);
2382
+ }
2383
+ }
2384
+ function setIdListAttribute(element, name, ids) {
2385
+ setOptionalAttribute(element, name, ids.length > 0 ? ids.join(' ') : null);
2386
+ }
2387
+ function applyCombobox(effect, targets) {
2388
+ const combobox = targets.combobox;
2389
+ if (!combobox)
2390
+ return;
2391
+ combobox.setAttribute('role', effect.role);
2392
+ setBooleanAttribute(combobox, 'aria-expanded', effect.expanded);
2393
+ setBooleanAttribute(combobox, 'aria-disabled', effect.disabled);
2394
+ setBooleanAttribute(combobox, 'aria-readonly', effect.readonly);
2395
+ setBooleanAttribute(combobox, 'aria-required', effect.required);
2396
+ setBooleanAttribute(combobox, 'aria-invalid', effect.invalid);
2397
+ combobox.setAttribute('aria-autocomplete', effect.autocomplete);
2398
+ setOptionalAttribute(combobox, 'aria-controls', effect.controlsId);
2399
+ setIdListAttribute(combobox, 'aria-labelledby', effect.labelledBy);
2400
+ setIdListAttribute(combobox, 'aria-describedby', effect.describedBy);
2401
+ setOptionalAttribute(combobox, 'aria-label', effect.ariaLabel);
2402
+ setOptionalAttribute(combobox, 'aria-description', effect.ariaDescription);
2403
+ const activeOption = effect.activeKey == null
2404
+ ? null
2405
+ : targets.getOptionByKey?.(effect.activeKey) ?? null;
2406
+ setOptionalAttribute(combobox, 'aria-activedescendant', activeOption?.id || null);
2407
+ }
2408
+ function applyListbox(effect, targets) {
2409
+ const listbox = targets.listbox;
2410
+ if (!listbox)
2411
+ return;
2412
+ listbox.setAttribute('role', effect.role);
2413
+ if (effect.multiple)
2414
+ listbox.setAttribute('aria-multiselectable', 'true');
2415
+ else
2416
+ listbox.removeAttribute('aria-multiselectable');
2417
+ if (effect.busy)
2418
+ listbox.setAttribute('aria-busy', 'true');
2419
+ else
2420
+ listbox.removeAttribute('aria-busy');
2421
+ setIdListAttribute(listbox, 'aria-labelledby', effect.labelledBy);
2422
+ setOptionalAttribute(listbox, 'aria-label', effect.ariaLabel);
2423
+ }
2424
+ function applyOption(effect, targets) {
2425
+ const option = targets.getOptionByKey?.(effect.key);
2426
+ if (!option)
2427
+ return;
2428
+ option.setAttribute('role', 'option');
2429
+ setBooleanAttribute(option, 'aria-selected', effect.selected);
2430
+ if (effect.disabled)
2431
+ option.setAttribute('aria-disabled', 'true');
2432
+ else
2433
+ option.removeAttribute('aria-disabled');
2434
+ }
2435
+ function applyFocusIntent(target, targets, options) {
2436
+ if (!options.applyFocus || target === 'none')
2437
+ return;
2438
+ const focusTarget = target === 'input'
2439
+ ? targets.focusTargets?.input
2440
+ : target === 'clear-button'
2441
+ ? targets.focusTargets?.clearButton
2442
+ : targets.focusTargets?.getActiveOption?.();
2443
+ focusTarget?.focus();
2444
+ }
2445
+ /** Applies engine accessibility effects to caller-owned web DOM targets. */
2446
+ function applyAccessibilityEffects(effects, targets, options = {}) {
2447
+ for (const effect of effects) {
2448
+ switch (effect.type) {
2449
+ case 'SYNC_COMBOBOX_ARIA':
2450
+ applyCombobox(effect, targets);
2451
+ break;
2452
+ case 'SYNC_LISTBOX_ARIA':
2453
+ applyListbox(effect, targets);
2454
+ break;
2455
+ case 'SYNC_OPTION_ARIA':
2456
+ applyOption(effect, targets);
2457
+ break;
2458
+ case 'ANNOUNCE':
2459
+ if (targets.liveRegion) {
2460
+ targets.liveRegion.setAttribute('aria-live', effect.politeness);
2461
+ targets.liveRegion.setAttribute('aria-atomic', 'true');
2462
+ targets.liveRegion.textContent = effect.message;
2463
+ }
2464
+ break;
2465
+ case 'FOCUS_INTENT':
2466
+ applyFocusIntent(effect.target, targets, options);
2467
+ break;
2468
+ }
2469
+ }
2470
+ }
2471
+
1621
2472
  /**
1622
2473
  * Independent Option Component
1623
2474
  * High cohesion, low coupling - handles its own selection state and events
@@ -2208,15 +3059,19 @@
2208
3059
  * Implements all advanced features: infinite scroll, load more, busy state,
2209
3060
  * server-side selection, and full customization
2210
3061
  *
2211
- * ✨ Redesigned with formal elegance, refined microinteractions, and polished UX
3062
+ * Redesigned with formal elegance, refined microinteractions, and polished UX
2212
3063
  */
2213
3064
  class EnhancedSelect extends HTMLElement {
3065
+ static get observedAttributes() {
3066
+ return ['aria-label', 'aria-description'];
3067
+ }
2214
3068
  get classMap() {
2215
3069
  return this._classMap;
2216
3070
  }
2217
3071
  set classMap(map) {
2218
3072
  if (this._areClassMapsEqual(this._classMap, map))
2219
3073
  return;
3074
+ this._invalidateGuardedMeasurements();
2220
3075
  this._classMap = map;
2221
3076
  this._setGlobalStylesMirroring(Boolean(this._optionRenderer || map || this._groupHeaderRenderer));
2222
3077
  this._track('style', 'classMapChanged', {
@@ -2247,6 +3102,48 @@
2247
3102
  }
2248
3103
  constructor() {
2249
3104
  super();
3105
+ this._engine = new SelectEngineBridge();
3106
+ this._virtualizationScope = {
3107
+ dataKeys: [],
3108
+ filteredKeys: [],
3109
+ registeredKeys: [],
3110
+ windowKeys: [],
3111
+ mountedKeys: [],
3112
+ selectedKeys: new Set(),
3113
+ activeKey: null,
3114
+ };
3115
+ this._renderPlan = {
3116
+ mode: 'legacy-full',
3117
+ filteredIndices: [],
3118
+ filteredKeys: [],
3119
+ intendedRenderKeys: [],
3120
+ filteredIndexByKey: new Map(),
3121
+ };
3122
+ // Null keeps the public/default renderer on its legacy full path. This
3123
+ // private state is only used by guarded virtualization integration.
3124
+ this._guardedVirtualWindow = null;
3125
+ this._guardedVirtualizer = null;
3126
+ this._guardedVirtualizationRequested = false;
3127
+ this._guardedVirtualizerKeys = [];
3128
+ this._guardedMeasurementQuery = null;
3129
+ this._guardedOptionResizeObserver = null;
3130
+ this._guardedObservedOptions = new Set();
3131
+ this._guardedObserverSeenOptions = new WeakSet();
3132
+ this._guardedOptionMeasurements = new WeakMap();
3133
+ this._guardedMeasurementGeneration = 0;
3134
+ this._guardedVirtualScrollTop = 0;
3135
+ this._guardedVirtualViewportHeight = 0;
3136
+ this._guardedVirtualOverscan = 0;
3137
+ this._guardedVirtualWindowRafId = null;
3138
+ this._guardedScrollListenerAttached = false;
3139
+ this._onGuardedVirtualScroll = () => this._scheduleGuardedVirtualWindowUpdate();
3140
+ this._effectRunner = new DefaultSelectEffectRunner();
3141
+ this._itemAdapter = this._createEngineItemAdapter();
3142
+ this._itemRegistry = createItemRegistry([], this._itemAdapter);
3143
+ // Engine selectedKeys owns identity. The registry resolves current records;
3144
+ // this cache keeps the last known record available while a selected key is detached.
3145
+ this._selectedRecordsByKey = new Map();
3146
+ this._registryItemsRef = [];
2250
3147
  this._pageCache = {};
2251
3148
  this._typeBuffer = '';
2252
3149
  this._hasError = false;
@@ -2256,6 +3153,8 @@
2256
3153
  this._pendingSearchRenderMark = false;
2257
3154
  this._rangeAnchorIndex = null;
2258
3155
  this._customOptionBoundElements = new WeakSet();
3156
+ this._customOptionNormalizedIds = new WeakMap();
3157
+ this._customOptionNormalizedLabels = new WeakMap();
2259
3158
  this._mirrorGlobalStylesForCustomOptions = false;
2260
3159
  this._globalStylesObserver = null;
2261
3160
  this._globalStylesContainer = null;
@@ -2264,6 +3163,7 @@
2264
3163
  this._asyncGeneration = 0;
2265
3164
  this._lifecycleTimers = new Set();
2266
3165
  this._lifecycleRafs = new Set();
3166
+ this._keyboardActiveChangeGeneration = 0;
2267
3167
  this._tracking = { events: [], styles: [], limitations: [] };
2268
3168
  this._suppressBlurClose = false;
2269
3169
  this._renderCycleId = 0;
@@ -2309,7 +3209,7 @@
2309
3209
  }
2310
3210
  }
2311
3211
  if (!clickedInside) {
2312
- this._handleClose();
3212
+ this._handleClose('outside-pointer');
2313
3213
  }
2314
3214
  };
2315
3215
  this._shadow = this.attachShadow({ mode: 'open' });
@@ -2317,9 +3217,14 @@
2317
3217
  this._rendererHelpers = this._buildRendererHelpers();
2318
3218
  // Merge global config with component-level config
2319
3219
  this._config = selectConfig.getConfig();
3220
+ this._engine.dispatch({ type: 'DISABLED_CHANGED', disabled: !this._config.enabled });
3221
+ this._syncEngineSelectionConfig();
2320
3222
  // Initialize state
3223
+ const host = this;
2321
3224
  this._state = {
2322
- isOpen: false,
3225
+ get isOpen() {
3226
+ return host._engine.state.popup === 'open';
3227
+ },
2323
3228
  isBusy: false,
2324
3229
  isSearching: false,
2325
3230
  currentPage: this._config.infiniteScroll.initialPage || 1,
@@ -2346,6 +3251,7 @@
2346
3251
  this._dropdown = this._createDropdown();
2347
3252
  this._optionsContainer = this._createOptionsContainer();
2348
3253
  this._liveRegion = this._createLiveRegion();
3254
+ this._errorDescription = this._createErrorDescription();
2349
3255
  // Initialize styles BEFORE assembling DOM (order matters in shadow DOM)
2350
3256
  this._initializeStyles();
2351
3257
  this._syncStyleConfigVariables();
@@ -2354,10 +3260,14 @@
2354
3260
  this._assembleDOM();
2355
3261
  this._attachEventListeners();
2356
3262
  this._initializeObservers();
3263
+ this._syncComboboxAccessibility();
3264
+ this._syncListboxAccessibility();
2357
3265
  }
2358
3266
  connectedCallback() {
2359
3267
  // register instance
2360
3268
  EnhancedSelect._instances.add(this);
3269
+ this._runEngineEffects(this._engine.dispatch({ type: 'CONNECT' }));
3270
+ this._runEngineEffects(this._engine.dispatch({ type: 'DISABLED_CHANGED', disabled: !this._config.enabled }));
2361
3271
  this._connectionController?.abort();
2362
3272
  this._connectionController = new AbortController();
2363
3273
  document.addEventListener('pointerdown', this._onDocumentPointerDown, {
@@ -2369,6 +3279,7 @@
2369
3279
  this.style.display = 'block';
2370
3280
  // Sync direction attribute (must be in connectedCallback, not constructor)
2371
3281
  this._syncDirectionConfig();
3282
+ this._syncComboboxAccessibility();
2372
3283
  if (this._optionRenderer || this._classMap || this._groupHeaderRenderer) {
2373
3284
  this._setGlobalStylesMirroring(true);
2374
3285
  }
@@ -2387,13 +3298,33 @@
2387
3298
  this._config.callbacks.onOpen();
2388
3299
  }
2389
3300
  }
3301
+ attributeChangedCallback(name, oldValue, newValue) {
3302
+ if (oldValue === newValue || (name !== 'aria-label' && name !== 'aria-description'))
3303
+ return;
3304
+ this._syncComboboxAccessibility();
3305
+ if (name === 'aria-label')
3306
+ this._syncListboxAccessibility();
3307
+ }
2390
3308
  disconnectedCallback() {
2391
3309
  // unregister instance
2392
3310
  EnhancedSelect._instances.delete(this);
3311
+ if (this._state.isOpen) {
3312
+ this._handleClose('disconnect');
3313
+ }
3314
+ this._runEngineEffects(this._engine.dispatch({ type: 'DISCONNECT' }));
2393
3315
  this._connectionController?.abort();
2394
3316
  this._connectionController = undefined;
2395
3317
  this._asyncGeneration += 1;
3318
+ this._cancelGuardedVirtualWindowUpdate();
2396
3319
  this._clearLifecycleTasks();
3320
+ this._destroyGuardedVirtualizer(true);
3321
+ this._virtualizationScope = {
3322
+ ...this._virtualizationScope,
3323
+ mountedKeys: [],
3324
+ };
3325
+ Array.from(this._optionsContainer.children)
3326
+ .filter((element) => element.hasAttribute('data-index') || element.hasAttribute('data-virtual-spacer'))
3327
+ .forEach((element) => element.remove());
2397
3328
  // Cleanup observers
2398
3329
  this._resizeObserver?.disconnect();
2399
3330
  this._intersectionObserver?.disconnect();
@@ -2770,8 +3701,16 @@
2770
3701
  return scopedSelector;
2771
3702
  }
2772
3703
  _normalizeCustomOptionAccessibility(optionEl, meta) {
2773
- if (!optionEl.hasAttribute('aria-label') && !optionEl.hasAttribute('aria-labelledby')) {
3704
+ const previousNormalizedLabel = this._customOptionNormalizedLabels.get(optionEl);
3705
+ const currentAriaLabel = optionEl.getAttribute('aria-label');
3706
+ const canRefreshNormalizedLabel = previousNormalizedLabel !== undefined
3707
+ && currentAriaLabel === previousNormalizedLabel;
3708
+ if (!optionEl.hasAttribute('aria-labelledby') && (!currentAriaLabel || canRefreshNormalizedLabel)) {
2774
3709
  optionEl.setAttribute('aria-label', meta.label);
3710
+ this._customOptionNormalizedLabels.set(optionEl, meta.label);
3711
+ }
3712
+ else {
3713
+ this._customOptionNormalizedLabels.delete(optionEl);
2775
3714
  }
2776
3715
  const nestedFocusableSelectors = [
2777
3716
  'a[href]',
@@ -2873,6 +3812,237 @@
2873
3812
  _isOptionSelectionBlocked(item) {
2874
3813
  return Boolean(item?.disabled) && !this._isDisabledOptionSelectable(item);
2875
3814
  }
3815
+ _isPhase2DevRuntime() {
3816
+ const env = globalThis.process?.env?.NODE_ENV;
3817
+ return env !== 'production';
3818
+ }
3819
+ _getDuplicateKeyPolicy() {
3820
+ return this._isPhase2DevRuntime() ? 'throw' : 'warn';
3821
+ }
3822
+ _warnPhase2(message) {
3823
+ if (this._isPhase2DevRuntime() && typeof console !== 'undefined') {
3824
+ console.warn(message);
3825
+ }
3826
+ }
3827
+ _getItemValue(item) {
3828
+ return this._config.serverSide.getValueFromItem?.(item) ?? item?.value ?? item;
3829
+ }
3830
+ _getItemLabel(item) {
3831
+ return this._config.serverSide.getLabelFromItem?.(item) ?? item?.label ?? String(item);
3832
+ }
3833
+ _createEngineItemAdapter() {
3834
+ return createDefaultItemAdapter({
3835
+ getValue: (item) => this._getItemValue(item),
3836
+ getLabel: (item) => this._getItemLabel(item),
3837
+ isDisabled: (item) => Boolean(item?.disabled),
3838
+ getGroupKey: (item) => {
3839
+ const group = item?.group;
3840
+ return group == null ? null : String(group);
3841
+ },
3842
+ onIndexFallback: (message) => this._warnPhase2(message),
3843
+ });
3844
+ }
3845
+ _getBlockedDisabledKeys() {
3846
+ const keys = this._itemRegistry.records
3847
+ .filter((record) => record.disabled && this._isOptionSelectionBlocked(record.item))
3848
+ .map((record) => record.key);
3849
+ for (const entry of this._getSelectedEntries()) {
3850
+ if (this._isOptionSelectionBlocked(entry.item))
3851
+ keys.push(entry.key);
3852
+ }
3853
+ return keys;
3854
+ }
3855
+ _syncEngineSelectionConfig() {
3856
+ const required = Boolean(this._input?.hasAttribute('required'));
3857
+ const disabledKeys = this._getBlockedDisabledKeys();
3858
+ this._engine.dispatch({
3859
+ type: 'SELECTION_CONFIG_CHANGED',
3860
+ multiple: this._config.selection.mode === 'multi',
3861
+ required,
3862
+ allowDeselect: this._config.selection.allowDeselect === true,
3863
+ maxSelections: this._config.selection.maxSelections ?? 0,
3864
+ disabledKeys,
3865
+ });
3866
+ if (this._state) {
3867
+ this._syncLegacySelectionFromEngine();
3868
+ this._syncLegacyActiveFromEngine();
3869
+ this._assertSelectionProjection('selection config');
3870
+ this._assertActiveProjection('selection config');
3871
+ }
3872
+ }
3873
+ _rebuildItemRegistry(items = this._state.loadedItems) {
3874
+ // Build first so duplicate-key rejection leaves the previous runtime intact.
3875
+ const registry = createItemRegistry(items, this._itemAdapter, {
3876
+ duplicateKeyPolicy: this._getDuplicateKeyPolicy(),
3877
+ });
3878
+ const activeKey = this._engine.state.activeKey;
3879
+ const anchorKey = this._rangeAnchorIndex === null ? undefined : this._itemRegistry.indexToKey.get(this._rangeAnchorIndex);
3880
+ this._itemRegistry = registry;
3881
+ this._state.loadedItems = items;
3882
+ this._registryItemsRef = items;
3883
+ const disabledKeys = this._getBlockedDisabledKeys();
3884
+ this._rangeAnchorIndex = anchorKey === undefined ? null : registry.keyToIndex.get(anchorKey) ?? null;
3885
+ this._engine.dispatch({
3886
+ type: 'ITEMS_REGISTERED',
3887
+ keys: registry.records.map((record) => record.key),
3888
+ disabledKeys,
3889
+ });
3890
+ if (activeKey !== null && registry.keyToRecord.get(activeKey)?.disabled) {
3891
+ this._dispatchActiveKey(null, 'programmatic', 'items registered with disabled active key');
3892
+ }
3893
+ else {
3894
+ this._syncLegacyActiveFromEngine();
3895
+ }
3896
+ this._syncLegacySelectionFromEngine();
3897
+ this._syncEngineSelectionConfig();
3898
+ this._assertSelectionProjection('items registered');
3899
+ }
3900
+ _ensureRegistryCurrent() {
3901
+ if (this._registryItemsRef !== this._state.loadedItems
3902
+ || this._itemRegistry.records.length !== this._state.loadedItems.length
3903
+ || this._itemRegistry.records.some((record, index) => record.item !== this._state.loadedItems[index])) {
3904
+ this._rebuildItemRegistry();
3905
+ return;
3906
+ }
3907
+ this._syncLegacySelectionFromEngine();
3908
+ this._syncLegacyActiveFromEngine();
3909
+ this._assertSelectionProjection('registry read');
3910
+ this._assertActiveProjection('registry read');
3911
+ }
3912
+ _getRecordByIndex(index) {
3913
+ const key = this._itemRegistry.indexToKey.get(index);
3914
+ return key === undefined ? null : this._itemRegistry.keyToRecord.get(key) ?? null;
3915
+ }
3916
+ _getSelectedEntries() {
3917
+ const entries = [];
3918
+ if (!this._state)
3919
+ return entries;
3920
+ for (const key of this._engine.state.selectedKeys) {
3921
+ const record = this._itemRegistry.keyToRecord.get(key) ?? this._selectedRecordsByKey.get(key);
3922
+ if (record)
3923
+ entries.push({ key, index: record.index, item: record.item });
3924
+ }
3925
+ return entries;
3926
+ }
3927
+ _syncLegacySelectionFromEngine() {
3928
+ const selectedIndices = new Set();
3929
+ const selectedItems = new Map();
3930
+ const selectedKeys = this._engine.state.selectedKeys;
3931
+ for (const key of [...this._selectedRecordsByKey.keys()]) {
3932
+ if (!selectedKeys.has(key))
3933
+ this._selectedRecordsByKey.delete(key);
3934
+ }
3935
+ for (const key of selectedKeys) {
3936
+ const record = this._itemRegistry.keyToRecord.get(key);
3937
+ if (record)
3938
+ this._selectedRecordsByKey.set(key, record);
3939
+ if (!record)
3940
+ continue;
3941
+ selectedIndices.add(record.index);
3942
+ selectedItems.set(record.index, record.item);
3943
+ }
3944
+ this._state.selectedIndices = selectedIndices;
3945
+ this._state.selectedItems = selectedItems;
3946
+ }
3947
+ _projectedSelectedKeysSnapshot() {
3948
+ return new Set([...this._state.selectedIndices]
3949
+ .map((index) => this._itemRegistry.indexToKey.get(index))
3950
+ .filter((key) => key !== undefined));
3951
+ }
3952
+ _assertSelectionProjection(context) {
3953
+ if (!this._isPhase2DevRuntime())
3954
+ return;
3955
+ const legacyKeys = this._projectedSelectedKeysSnapshot();
3956
+ const engineKeys = this._engine.state.selectedKeys;
3957
+ if (this._state.selectedItems.size !== this._state.selectedIndices.size
3958
+ || [...this._state.selectedIndices].some((index) => !this._state.selectedItems.has(index))
3959
+ || [...engineKeys].some((key) => this._itemRegistry.keyToRecord.has(key) && !legacyKeys.has(key))
3960
+ || [...legacyKeys].some((key) => !engineKeys.has(key))) {
3961
+ throw new Error(`[Smilodon Phase2] Selection projection failed in ${context}: compatibility=${JSON.stringify([...legacyKeys])}, engine=${JSON.stringify([...engineKeys])}`);
3962
+ }
3963
+ }
3964
+ _projectedActiveKeySnapshot() {
3965
+ return this._state.activeIndex < 0
3966
+ ? null
3967
+ : this._itemRegistry.indexToKey.get(this._state.activeIndex) ?? null;
3968
+ }
3969
+ _syncLegacyActiveFromEngine() {
3970
+ const activeKey = this._engine.state.activeKey;
3971
+ this._state.activeIndex = activeKey === null
3972
+ ? -1
3973
+ : this._itemRegistry.keyToIndex.get(activeKey) ?? -1;
3974
+ this._syncLegacyActiveAria();
3975
+ }
3976
+ _assertActiveProjection(context) {
3977
+ if (!this._isPhase2DevRuntime())
3978
+ return;
3979
+ const legacyKey = this._projectedActiveKeySnapshot();
3980
+ const engineKey = this._engine.state.activeKey;
3981
+ if (legacyKey !== engineKey && !Object.is(legacyKey, engineKey)) {
3982
+ throw new Error(`[Smilodon Phase2] Active projection failed in ${context}: compatibility=${String(legacyKey)}, engine=${String(engineKey)}`);
3983
+ }
3984
+ }
3985
+ _dispatchActiveKey(key, reason, context) {
3986
+ const effects = this._engine.dispatch({ type: 'ACTIVE_KEY_CHANGED', key, reason });
3987
+ this._runEngineEffects(effects);
3988
+ this._syncLegacyActiveFromEngine();
3989
+ this._assertActiveProjection(context);
3990
+ }
3991
+ _clearDisabledEngineActive(context) {
3992
+ const activeKey = this._engine.state.activeKey;
3993
+ if (activeKey !== null && this._itemRegistry.keyToRecord.get(activeKey)?.disabled) {
3994
+ this._dispatchActiveKey(null, 'programmatic', context);
3995
+ }
3996
+ else {
3997
+ this._syncLegacyActiveFromEngine();
3998
+ this._assertActiveProjection(context);
3999
+ }
4000
+ }
4001
+ /**
4002
+ * @deprecated Test/backward-compatibility shim. Production active-state authority is engine.activeKey.
4003
+ * Kept for existing renderer tests; component mutation paths dispatch by key.
4004
+ */
4005
+ _mirrorLegacyActive(reason, context) {
4006
+ this._dispatchActiveKey(this._projectedActiveKeySnapshot(), reason, context);
4007
+ }
4008
+ _dispatchSelection(event, context) {
4009
+ this._engine.dispatch(event);
4010
+ this._syncLegacySelectionFromEngine();
4011
+ this._assertSelectionProjection(context);
4012
+ }
4013
+ /**
4014
+ * @deprecated Test/backward-compatibility shim. Production selection authority is engine.selectedKeys.
4015
+ * Kept for existing styling tests; dispatches to engine authority.
4016
+ */
4017
+ _mirrorLegacySelection(event, context) {
4018
+ this._dispatchSelection(event, context);
4019
+ }
4020
+ _requestSelectionReplacement(entries, reason, context) {
4021
+ for (const entry of entries) {
4022
+ const record = this._itemRegistry.keyToRecord.get(entry.key) ?? this._selectedRecordsByKey.get(entry.key);
4023
+ this._selectedRecordsByKey.set(entry.key, record ?? {
4024
+ key: entry.key,
4025
+ item: entry.item,
4026
+ index: entry.index,
4027
+ label: this._getItemLabel(entry.item),
4028
+ value: this._getItemValue(entry.item),
4029
+ disabled: Boolean(entry.item?.disabled),
4030
+ groupKey: entry.item?.group == null
4031
+ ? null
4032
+ : String(entry.item.group),
4033
+ });
4034
+ }
4035
+ this._dispatchSelection({ type: 'REPLACE_SELECTION_REQUEST', keys: entries.map(({ key }) => key), reason }, context);
4036
+ }
4037
+ _registerShadowItems(indices) {
4038
+ const keys = indices.map((index) => this._itemRegistry.indexToKey.get(index)).filter((key) => key !== undefined);
4039
+ this._engine.dispatch({ type: 'ITEMS_REGISTERED', keys, disabledKeys: this._getBlockedDisabledKeys() });
4040
+ this._clearDisabledEngineActive('visible items');
4041
+ this._assertSelectionProjection('visible items');
4042
+ }
4043
+ _syncLegacyActiveAria() {
4044
+ this._syncComboboxAccessibility();
4045
+ }
2876
4046
  _syncStyleConfigVariables() {
2877
4047
  const styles = this._config.styles;
2878
4048
  if (!styles)
@@ -3291,10 +4461,7 @@
3291
4461
  delete inputStyles.maxHeight;
3292
4462
  Object.assign(input.style, inputStyles);
3293
4463
  }
3294
- input.setAttribute('role', 'combobox');
3295
- input.setAttribute('aria-expanded', 'false');
3296
4464
  input.setAttribute('aria-haspopup', 'listbox');
3297
- input.setAttribute('aria-autocomplete', this._config.searchable ? 'list' : 'none');
3298
4465
  return input;
3299
4466
  }
3300
4467
  _createDropdown() {
@@ -3308,11 +4475,6 @@
3308
4475
  if (this._config.styles.dropdown) {
3309
4476
  Object.assign(dropdown.style, this._config.styles.dropdown);
3310
4477
  }
3311
- dropdown.setAttribute('role', 'listbox');
3312
- dropdown.setAttribute('aria-labelledby', `${this._uniqueId}-input`);
3313
- if (this._config.selection.mode === 'multi') {
3314
- dropdown.setAttribute('aria-multiselectable', 'true');
3315
- }
3316
4478
  return dropdown;
3317
4479
  }
3318
4480
  _createOptionsContainer() {
@@ -3328,6 +4490,12 @@
3328
4490
  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;';
3329
4491
  return liveRegion;
3330
4492
  }
4493
+ _createErrorDescription() {
4494
+ const description = document.createElement('div');
4495
+ description.id = `${this._uniqueId}-error`;
4496
+ 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;';
4497
+ return description;
4498
+ }
3331
4499
  _createArrowContainer() {
3332
4500
  const container = document.createElement('div');
3333
4501
  container.className = 'dropdown-arrow-container';
@@ -3374,10 +4542,12 @@
3374
4542
  if (this._liveRegion) {
3375
4543
  this._shadow.appendChild(this._liveRegion);
3376
4544
  }
4545
+ if (this._errorDescription) {
4546
+ this._shadow.appendChild(this._errorDescription);
4547
+ }
3377
4548
  // Set ARIA relationships
3378
4549
  const listboxId = `${this._uniqueId}-listbox`;
3379
4550
  this._dropdown.id = listboxId;
3380
- this._input.setAttribute('aria-controls', listboxId);
3381
4551
  this._input.setAttribute('aria-owns', listboxId);
3382
4552
  this._syncInputContainerMode();
3383
4553
  this._syncClearControlState();
@@ -4227,7 +5397,7 @@
4227
5397
  margin: var(--select-group-header-margin, 0 calc(var(--select-options-padding, 6px) * -1));
4228
5398
  font-weight: var(--select-group-header-weight, 600);
4229
5399
  color: var(--select-group-header-color, var(--select-text-muted));
4230
- background: var(--select-group-header-bg, #ffffff);
5400
+ background: var(--select-group-header-bg, #f3f4f6);
4231
5401
  text-align: var(--select-group-header-text-align, left);
4232
5402
  font-size: var(--select-group-header-font-size, 0.7333em);
4233
5403
  text-transform: var(--select-group-header-text-transform, uppercase);
@@ -4734,6 +5904,25 @@
4734
5904
  box-shadow: var(--select-group-header-shadow, 0 1px 2px rgba(0, 0, 0, 0.3));
4735
5905
  }
4736
5906
 
5907
+ :host(.dark-mode) .group-header,
5908
+ :host([dark-mode]) .group-header,
5909
+ :host([darkmode]) .group-header,
5910
+ :host([data-theme="dark"]) .group-header,
5911
+ :host([theme="dark"]) .group-header {
5912
+ color: var(--select-dark-group-header-color, var(--select-group-header-dark-color, #9ca3af));
5913
+ background: var(--select-dark-group-header-bg, var(--select-group-header-dark-bg, #1a1a2e));
5914
+ border-bottom: var(--select-group-header-border-bottom, 1px solid rgba(255, 255, 255, 0.08));
5915
+ box-shadow: var(--select-group-header-shadow, 0 1px 2px rgba(0, 0, 0, 0.3));
5916
+ }
5917
+
5918
+ :host(.dark-mode) .group-header:not(:first-child),
5919
+ :host([dark-mode]) .group-header:not(:first-child),
5920
+ :host([darkmode]) .group-header:not(:first-child),
5921
+ :host([data-theme="dark"]) .group-header:not(:first-child),
5922
+ :host([theme="dark"]) .group-header:not(:first-child) {
5923
+ border-top-color: var(--select-border);
5924
+ }
5925
+
4737
5926
  :host(.dark-mode) .option.selected::before,
4738
5927
  :host([dark-mode]) .option.selected::before,
4739
5928
  :host([darkmode]) .option.selected::before,
@@ -4831,7 +6020,7 @@
4831
6020
  this._handleOpen();
4832
6021
  }
4833
6022
  // Focus the input (do not prevent default behavior for input itself)
4834
- this._input.focus();
6023
+ this._applyFocusIntent('input', 'input-container-trigger');
4835
6024
  // If we just opened the dropdown, transfer pointer capture to the
4836
6025
  // options container so the subsequent pointerup lands there instead of
4837
6026
  // staying with the input container (which would swallow the event).
@@ -4868,7 +6057,7 @@
4868
6057
  if (!this._state.isOpen) {
4869
6058
  this._handleOpen();
4870
6059
  }
4871
- this._input.focus();
6060
+ this._applyFocusIntent('input', 'input-container-activation');
4872
6061
  });
4873
6062
  this._inputContent.addEventListener('pointermove', (e) => {
4874
6063
  this._updateMultiScrollDrag(e);
@@ -4894,7 +6083,10 @@
4894
6083
  e.stopPropagation();
4895
6084
  });
4896
6085
  // Input focus/blur
4897
- this._input.addEventListener('focus', () => this._handleOpen());
6086
+ this._input.addEventListener('focus', () => {
6087
+ this._runEngineEffects(this._engine.dispatch({ type: 'FOCUS_GAINED' }));
6088
+ this._handleOpen();
6089
+ });
4898
6090
  // When the input loses focus we normally close the dropdown, but
4899
6091
  // clicking an option will blur the input before the option's click
4900
6092
  // handler executes. To avoid the blur timer closing the dropdown
@@ -4902,6 +6094,7 @@
4902
6094
  // interacting with the options container. The close callback checks this
4903
6095
  // flag and skips closing if the user is about to click an option.
4904
6096
  this._input.addEventListener('blur', (e) => {
6097
+ this._runEngineEffects(this._engine.dispatch({ type: 'FOCUS_LOST' }));
4905
6098
  const related = e.relatedTarget;
4906
6099
  if (related && (this._shadow.contains(related) || this._container.contains(related))) {
4907
6100
  return;
@@ -4916,7 +6109,7 @@
4916
6109
  if (active && (this._shadow.contains(active) || this._container.contains(active))) {
4917
6110
  return;
4918
6111
  }
4919
- this._handleClose();
6112
+ this._handleClose('blur');
4920
6113
  }, 150);
4921
6114
  });
4922
6115
  // Input search
@@ -4997,11 +6190,10 @@
4997
6190
  const items = await this._config.serverSide.fetchSelectedItems(this._config.serverSide.initialSelectedValues);
4998
6191
  if (generation !== this._asyncGeneration || !this.isConnected)
4999
6192
  return;
5000
- // Add to state
5001
- items.forEach((item, index) => {
5002
- this._state.selectedItems.set(index, item);
5003
- this._state.selectedIndices.add(index);
6193
+ const fetchedRegistry = createItemRegistry(items, this._itemAdapter, {
6194
+ duplicateKeyPolicy: this._getDuplicateKeyPolicy(),
5004
6195
  });
6196
+ this._requestSelectionReplacement(fetchedRegistry.records, 'external-value-sync', 'initial selected items');
5005
6197
  this._updateInputDisplay();
5006
6198
  }
5007
6199
  catch (error) {
@@ -5015,25 +6207,121 @@
5015
6207
  }
5016
6208
  }
5017
6209
  }
6210
+ _runEngineEffects(effects) {
6211
+ this._effectRunner.run(effects, {
6212
+ focusTrigger: () => {
6213
+ this._applyFocusIntent('input', 'engine-focus-trigger');
6214
+ },
6215
+ syncAria: () => {
6216
+ this._syncPopupAria();
6217
+ },
6218
+ });
6219
+ }
6220
+ _syncPopupAria() {
6221
+ if (!this._input)
6222
+ return;
6223
+ this._syncComboboxAccessibility();
6224
+ }
6225
+ _syncComboboxAccessibility() {
6226
+ if (!this._input || !this._engine || !this._state)
6227
+ return;
6228
+ const accessibilityState = deriveAccessibilityState(this._engine.state, {
6229
+ searchable: this._config.searchable,
6230
+ readonly: !this._config.searchable,
6231
+ invalid: this._hasError,
6232
+ label: {
6233
+ ariaLabel: this.getAttribute('aria-label')?.trim() || null,
6234
+ ariaDescription: this.getAttribute('aria-description')?.trim() || null,
6235
+ },
6236
+ errorMessage: this._errorMessage,
6237
+ errorDescriptionId: this._hasError && this._errorMessage ? this._errorDescription?.id ?? null : null,
6238
+ });
6239
+ const effects = computeAccessibilityEffects(accessibilityState, {
6240
+ controlsId: this._dropdown?.id || null,
6241
+ optionKeys: [],
6242
+ }).filter((effect) => effect.type === 'SYNC_COMBOBOX_ARIA');
6243
+ applyAccessibilityEffects(effects, {
6244
+ combobox: this._input,
6245
+ getOptionByKey: (key) => {
6246
+ if (!this._state.isOpen)
6247
+ return null;
6248
+ const index = this._itemRegistry.keyToIndex.get(key);
6249
+ return index === undefined ? null : this._getOptionElementByIndex(index);
6250
+ },
6251
+ });
6252
+ }
6253
+ _syncListboxAccessibility() {
6254
+ if (!this._dropdown || !this._engine || !this._state)
6255
+ return;
6256
+ const derivedState = deriveAccessibilityState(this._engine.state, {
6257
+ label: { ariaLabel: this.getAttribute('aria-label')?.trim() || null },
6258
+ });
6259
+ const accessibilityState = {
6260
+ ...derivedState,
6261
+ // The component's existing busy lifecycle is not yet mirrored to engine dataStatus.
6262
+ busy: this._state.isBusy,
6263
+ };
6264
+ const effects = computeAccessibilityEffects(accessibilityState, {
6265
+ controlsId: this._dropdown.id || null,
6266
+ optionKeys: [],
6267
+ }).filter((effect) => effect.type === 'SYNC_LISTBOX_ARIA');
6268
+ applyAccessibilityEffects(effects, { listbox: this._dropdown });
6269
+ }
6270
+ _syncRenderedOptionAccessibility() {
6271
+ if (!this._optionsContainer || !this._engine || !this._state)
6272
+ return;
6273
+ const optionTargets = new Map();
6274
+ this._optionsContainer.querySelectorAll('[data-index]').forEach((option) => {
6275
+ const index = Number(option.getAttribute('data-index'));
6276
+ if (!Number.isFinite(index))
6277
+ return;
6278
+ const key = this._itemRegistry.indexToKey.get(index);
6279
+ if (key !== undefined)
6280
+ optionTargets.set(key, option);
6281
+ });
6282
+ if (optionTargets.size === 0)
6283
+ return;
6284
+ const effects = computeAccessibilityEffects(deriveAccessibilityState(this._engine.state), {
6285
+ controlsId: this._dropdown?.id || null,
6286
+ optionKeys: [...optionTargets.keys()],
6287
+ }).filter((effect) => effect.type === 'SYNC_OPTION_ARIA');
6288
+ applyAccessibilityEffects(effects, {
6289
+ getOptionByKey: (key) => optionTargets.get(key) ?? null,
6290
+ });
6291
+ }
6292
+ _applyFocusIntent(target, reason, focusTarget) {
6293
+ const effects = computeAccessibilityEffects(deriveAccessibilityState(this._engine.state), {
6294
+ optionKeys: [],
6295
+ focusIntents: [{ target, reason }],
6296
+ }).filter((effect) => effect.type === 'FOCUS_INTENT');
6297
+ applyAccessibilityEffects(effects, {
6298
+ focusTargets: {
6299
+ input: target === 'input' ? this._input : null,
6300
+ clearButton: target === 'clear-button' ? this._clearControl : null,
6301
+ getActiveOption: () => target === 'active-option' ? focusTarget ?? null : null,
6302
+ },
6303
+ }, { applyFocus: true });
6304
+ }
5018
6305
  _handleOpen() {
5019
- if (!this._config.enabled || this._state.isOpen)
6306
+ if (!this._config.enabled) {
6307
+ this._runEngineEffects(this._engine.dispatch({ type: 'DISABLED_CHANGED', disabled: true }));
6308
+ return;
6309
+ }
6310
+ if (this._state.isOpen)
5020
6311
  return;
5021
6312
  // close any other open selects before proceeding
5022
6313
  EnhancedSelect._instances.forEach(inst => {
5023
6314
  if (inst !== this)
5024
6315
  inst._handleClose();
5025
6316
  });
5026
- // Always focus the input when opening so callers (arrow click,
5027
- // programmatic `open()`, etc.) get the keyboard cursor. This was a
5028
- // frequent source of confusion in #14 where people opened the dropdown
5029
- // but the text field never received focus.
5030
- this._input.focus();
6317
+ const effects = this._engine.dispatch({ type: 'OPEN_REQUEST' });
6318
+ if (!effects.some((effect) => effect.type === 'POPUP_OPENED'))
6319
+ return;
6320
+ this._runEngineEffects(effects);
5031
6321
  this._markOpenStart();
5032
- this._state.isOpen = true;
5033
6322
  this.setAttribute('data-open', 'true');
5034
6323
  this._liftStackingAncestors();
5035
6324
  this._dropdown.style.display = 'block';
5036
- this._input.setAttribute('aria-expanded', 'true');
5037
6325
  this._updateArrowRotation();
5038
6326
  // Render options when opening
5039
6327
  this._renderOptions();
@@ -5044,26 +6332,32 @@
5044
6332
  this._announce('Options expanded');
5045
6333
  // Scroll to selected if configured
5046
6334
  if (this._config.scrollToSelected.enabled) {
6335
+ const keyboardActiveChangeGeneration = this._keyboardActiveChangeGeneration;
6336
+ const canRestoreOpenSelection = () => this._state.isOpen
6337
+ && this._keyboardActiveChangeGeneration === keyboardActiveChangeGeneration;
5047
6338
  // Use requestAnimationFrame for better timing after render
5048
6339
  this._requestLifecycleFrame(() => {
6340
+ if (!canRestoreOpenSelection())
6341
+ return;
5049
6342
  // Double RAF to ensure layout is complete
5050
6343
  this._requestLifecycleFrame(() => {
6344
+ if (!canRestoreOpenSelection())
6345
+ return;
5051
6346
  this._scrollToSelected();
5052
6347
  });
5053
6348
  });
5054
6349
  }
5055
6350
  }
5056
- _handleClose() {
5057
- if (!this._state.isOpen)
6351
+ _handleClose(reason = 'programmatic') {
6352
+ const effects = this._engine.dispatch({ type: 'CLOSE_REQUEST', reason });
6353
+ if (!effects.some((effect) => effect.type === 'POPUP_CLOSED'))
5058
6354
  return;
5059
- this._state.isOpen = false;
5060
6355
  this.removeAttribute('data-open');
5061
6356
  this._restoreLiftedAncestors();
5062
6357
  this._dropdown.style.display = 'none';
5063
6358
  this._dropdown.setAttribute('data-placement', this._resolvedDropdownPlacement);
5064
- this._input.setAttribute('aria-expanded', 'false');
5065
- this._input.removeAttribute('aria-activedescendant');
5066
6359
  this._updateArrowRotation();
6360
+ this._runEngineEffects(effects);
5067
6361
  this._emit('close', {});
5068
6362
  this._config.callbacks.onClose?.();
5069
6363
  this._announce('Options collapsed');
@@ -5074,14 +6368,13 @@
5074
6368
  this._liftStackingAncestors();
5075
6369
  this._dropdown.style.display = 'block';
5076
6370
  this._syncDropdownPlacement();
5077
- this._input.setAttribute('aria-expanded', 'true');
5078
6371
  }
5079
6372
  else {
5080
6373
  this.removeAttribute('data-open');
5081
6374
  this._restoreLiftedAncestors();
5082
6375
  this._dropdown.style.display = 'none';
5083
- this._input.setAttribute('aria-expanded', 'false');
5084
6376
  }
6377
+ this._syncComboboxAccessibility();
5085
6378
  }
5086
6379
  _liftStackingAncestors() {
5087
6380
  this._restoreLiftedAncestors();
@@ -5341,13 +6634,17 @@
5341
6634
  if (!this._state.isOpen) {
5342
6635
  this._handleOpen();
5343
6636
  }
5344
- else if (this._state.activeIndex >= 0) {
5345
- this._selectOption(this._state.activeIndex, { shiftKey: e.shiftKey, toggleKey: e.ctrlKey || e.metaKey });
6637
+ else {
6638
+ const activeKey = this._engine.state.activeKey;
6639
+ const currentIndex = activeKey === null ? -1 : this._itemRegistry.keyToIndex.get(activeKey) ?? -1;
6640
+ if (currentIndex >= 0) {
6641
+ this._selectOption(currentIndex, { shiftKey: e.shiftKey, toggleKey: e.ctrlKey || e.metaKey, reason: 'keyboard' });
6642
+ }
5346
6643
  }
5347
6644
  break;
5348
6645
  case 'Escape':
5349
6646
  e.preventDefault();
5350
- this._handleClose();
6647
+ this._handleClose('escape');
5351
6648
  break;
5352
6649
  case 'Tab':
5353
6650
  if (this._state.isOpen) {
@@ -5373,7 +6670,9 @@
5373
6670
  const selectableIndices = this._getSelectableOptionIndices();
5374
6671
  if (selectableIndices.length === 0)
5375
6672
  return;
5376
- const currentPosition = selectableIndices.indexOf(this._state.activeIndex);
6673
+ const activeKey = this._engine.state.activeKey;
6674
+ const currentIndex = activeKey === null ? -1 : this._itemRegistry.keyToIndex.get(activeKey) ?? -1;
6675
+ const currentPosition = selectableIndices.indexOf(currentIndex);
5377
6676
  const basePosition = currentPosition >= 0
5378
6677
  ? currentPosition
5379
6678
  : delta >= 0
@@ -5383,7 +6682,7 @@
5383
6682
  const next = selectableIndices[nextPosition];
5384
6683
  this._setActive(next);
5385
6684
  if (this._config.selection.mode === 'multi' && opts?.shiftKey) {
5386
- const anchor = this._rangeAnchorIndex ?? this._state.activeIndex;
6685
+ const anchor = this._rangeAnchorIndex ?? currentIndex;
5387
6686
  const anchorIndex = anchor >= 0 ? anchor : next;
5388
6687
  if (this._rangeAnchorIndex === null) {
5389
6688
  this._rangeAnchorIndex = anchorIndex;
@@ -5391,14 +6690,26 @@
5391
6690
  this._selectRange(anchorIndex, next, { clear: !opts?.toggleKey });
5392
6691
  }
5393
6692
  }
5394
- _setActive(index) {
5395
- const option = this._getOptionElementByIndex(index);
5396
- if (!option || (option.getAttribute('aria-disabled') === 'true' && !option.classList.contains('smilodon-option--disabled-focusable'))) {
6693
+ _setActive(index, reason = 'keyboard') {
6694
+ this._ensureRegistryCurrent();
6695
+ const record = this._getRecordByIndex(index);
6696
+ let option = this._getOptionElementByIndex(index);
6697
+ if (!option && record && this._guardedVirtualizer) {
6698
+ this._materializeGuardedVirtualKey(record.key);
6699
+ option = this._getOptionElementByIndex(index);
6700
+ }
6701
+ if (!record || record.disabled || !option || option.getAttribute('aria-disabled') === 'true') {
5397
6702
  return;
5398
6703
  }
6704
+ if (reason === 'keyboard')
6705
+ this._keyboardActiveChangeGeneration += 1;
6706
+ const previousIndex = this._state.activeIndex;
6707
+ this._dispatchActiveKey(record.key, reason, 'set active');
6708
+ if (this._state.activeIndex !== index)
6709
+ return;
5399
6710
  // Clear previous active state
5400
- if (this._state.activeIndex >= 0) {
5401
- const prevOption = this._getOptionElementByIndex(this._state.activeIndex);
6711
+ if (previousIndex >= 0 && previousIndex !== index) {
6712
+ const prevOption = this._getOptionElementByIndex(previousIndex);
5402
6713
  if (prevOption) {
5403
6714
  // Check if it's a custom SelectOption or a lightweight DOM element
5404
6715
  if ('setActive' in prevOption && typeof prevOption.setActive === 'function') {
@@ -5406,11 +6717,10 @@
5406
6717
  }
5407
6718
  else {
5408
6719
  // Lightweight option - remove active class
5409
- prevOption.classList.remove('smilodon-option--active');
6720
+ prevOption.classList.remove('active', 'smilodon-option--active');
5410
6721
  }
5411
6722
  }
5412
6723
  }
5413
- this._state.activeIndex = index;
5414
6724
  // Set new active state
5415
6725
  if (option) {
5416
6726
  // Check if it's a custom SelectOption or a lightweight DOM element
@@ -5419,7 +6729,7 @@
5419
6729
  }
5420
6730
  else {
5421
6731
  // Lightweight option - add active class
5422
- option.classList.add('smilodon-option--active');
6732
+ option.classList.add('active', 'smilodon-option--active');
5423
6733
  }
5424
6734
  if (typeof option.scrollIntoView === 'function') {
5425
6735
  // Don't scroll wildly when just opening with pre-selections
@@ -5429,8 +6739,7 @@
5429
6739
  const total = this._state.loadedItems.length;
5430
6740
  this._announce(`Item ${index + 1} of ${total}`);
5431
6741
  // Update aria-activedescendant using the actual option id when available
5432
- const optionId = option.id || `${this._uniqueId}-option-${index}`;
5433
- this._input.setAttribute('aria-activedescendant', optionId);
6742
+ this._syncLegacyActiveAria();
5434
6743
  }
5435
6744
  }
5436
6745
  _getOptionElementByIndex(index) {
@@ -5441,10 +6750,16 @@
5441
6750
  // Only return elements with data-index or data-sm-selectable attributes
5442
6751
  return Array.from(this._optionsContainer.children).filter((child) => {
5443
6752
  return (child.hasAttribute('data-index') || child.hasAttribute('data-sm-selectable'))
5444
- && (child.getAttribute('aria-disabled') !== 'true' || child.classList.contains('smilodon-option--disabled-focusable'));
6753
+ && child.getAttribute('aria-disabled') !== 'true';
5445
6754
  });
5446
6755
  }
5447
6756
  _getSelectableOptionIndices() {
6757
+ if (this._guardedVirtualizer) {
6758
+ return this._renderPlan.filteredKeys.flatMap((key) => {
6759
+ const record = this._itemRegistry.keyToRecord.get(key);
6760
+ return record && !record.disabled ? [record.index] : [];
6761
+ });
6762
+ }
5448
6763
  return this._getSelectableOptions()
5449
6764
  .map((option) => Number(option.getAttribute('data-sm-index') ?? option.getAttribute('data-index')))
5450
6765
  .filter((index) => Number.isFinite(index));
@@ -5462,7 +6777,7 @@
5462
6777
  keyboardFocus: (index) => {
5463
6778
  this._setActive(index);
5464
6779
  const el = this._getOptionElementByIndex(index);
5465
- el?.focus?.();
6780
+ this._applyFocusIntent('active-option', 'renderer-keyboard-focus', el);
5466
6781
  },
5467
6782
  };
5468
6783
  }
@@ -5477,43 +6792,25 @@
5477
6792
  const getValue = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
5478
6793
  const matchIndex = this._state.loadedItems.findIndex((item) => getValue(item).toLowerCase().startsWith(this._typeBuffer));
5479
6794
  if (matchIndex >= 0) {
5480
- this._setActive(matchIndex);
6795
+ this._setActive(matchIndex, 'search');
5481
6796
  }
5482
6797
  }
5483
6798
  _selectAll() {
5484
6799
  if (this._config.selection.mode !== 'multi')
5485
6800
  return;
6801
+ this._ensureRegistryCurrent();
5486
6802
  const options = this._getSelectableOptions();
5487
- const maxSelections = this._config.selection.maxSelections || 0;
6803
+ const entries = this._getSelectedEntries();
5488
6804
  options.forEach((option) => {
5489
6805
  const optionIndex = Number(option.getAttribute('data-sm-index') ?? option.getAttribute('data-index'));
5490
6806
  if (!Number.isFinite(optionIndex))
5491
6807
  return;
5492
- if (maxSelections > 0 && this._state.selectedIndices.size >= maxSelections) {
5493
- return;
5494
- }
5495
- if (!this._state.selectedIndices.has(optionIndex)) {
5496
- // Check if it's a custom SelectOption or a lightweight DOM element
5497
- if ('getConfig' in option && typeof option.getConfig === 'function') {
5498
- const config = option.getConfig();
5499
- if (this._isOptionSelectionBlocked(config.item))
5500
- return;
5501
- this._state.selectedIndices.add(optionIndex);
5502
- this._state.selectedItems.set(optionIndex, config.item);
5503
- option.setSelected(true);
5504
- }
5505
- else {
5506
- // Lightweight option - get item from data attribute or state
5507
- const item = this._state.loadedItems[optionIndex];
5508
- if (item && !this._isOptionSelectionBlocked(item)) {
5509
- this._state.selectedIndices.add(optionIndex);
5510
- this._state.selectedItems.set(optionIndex, item);
5511
- option.classList.add('smilodon-option--selected');
5512
- option.setAttribute('aria-selected', 'true');
5513
- }
5514
- }
5515
- }
6808
+ const record = this._getRecordByIndex(optionIndex);
6809
+ if (record && !this._isOptionSelectionBlocked(record.item))
6810
+ entries.push(record);
5516
6811
  });
6812
+ this._requestSelectionReplacement(entries, 'keyboard', 'select all');
6813
+ this._renderOptions();
5517
6814
  this._updateInputDisplay();
5518
6815
  this._emitChange();
5519
6816
  this._announce(`Selected all ${options.length} items`);
@@ -5521,82 +6818,101 @@
5521
6818
  _selectRange(start, end, opts) {
5522
6819
  if (this._config.selection.mode !== 'multi')
5523
6820
  return;
5524
- const maxSelections = this._config.selection.maxSelections || 0;
6821
+ this._ensureRegistryCurrent();
5525
6822
  const [min, max] = start < end ? [start, end] : [end, start];
5526
- if (opts?.clear) {
5527
- this._state.selectedIndices.clear();
5528
- this._state.selectedItems.clear();
5529
- }
6823
+ const selectedEntries = this._getSelectedEntries();
6824
+ const entries = opts?.clear
6825
+ ? selectedEntries.filter((entry) => !this._itemRegistry.keyToRecord.has(entry.key))
6826
+ : selectedEntries;
5530
6827
  for (let i = min; i <= max; i += 1) {
5531
- if (maxSelections > 0 && this._state.selectedIndices.size >= maxSelections)
5532
- break;
5533
- const item = this._state.loadedItems[i];
6828
+ const record = this._getRecordByIndex(i);
5534
6829
  const optionEl = this._getOptionElementByIndex(i);
5535
6830
  if (optionEl?.getAttribute('aria-disabled') === 'true' && !optionEl.classList.contains('smilodon-option--disabled-selectable'))
5536
6831
  continue;
5537
- if (!item)
5538
- continue;
5539
- if (this._isOptionSelectionBlocked(item))
6832
+ if (!record || this._isOptionSelectionBlocked(record.item))
5540
6833
  continue;
5541
- this._state.selectedIndices.add(i);
5542
- this._state.selectedItems.set(i, item);
6834
+ entries.push(record);
5543
6835
  }
6836
+ this._requestSelectionReplacement(entries, opts?.reason ?? 'keyboard', 'select range');
5544
6837
  this._renderOptions();
5545
6838
  this._updateInputDisplay();
6839
+ const target = this._getRecordByIndex(end);
6840
+ const selectDetail = target ? this._getSelectEventDetail(target) : null;
6841
+ if (selectDetail)
6842
+ this._emit('select', selectDetail);
5546
6843
  this._emitChange();
5547
6844
  this._announce(`${this._state.selectedIndices.size} items selected`);
6845
+ if (selectDetail)
6846
+ this._config.callbacks.onSelect?.(selectDetail);
6847
+ }
6848
+ _getSelectEventDetail(record) {
6849
+ const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
6850
+ const getLabel = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
6851
+ return {
6852
+ item: record.item,
6853
+ index: record.index,
6854
+ value: getValue(record.item),
6855
+ label: getLabel(record.item),
6856
+ selected: this._engine.state.selectedKeys.has(record.key),
6857
+ multi: this._config.selection.mode === 'multi',
6858
+ };
5548
6859
  }
5549
6860
  _setInitialActiveOption() {
5550
6861
  const selectableIndices = this._getSelectableOptionIndices();
5551
- if (selectableIndices.length === 0)
5552
- return;
5553
6862
  const selected = Array.from(this._state.selectedIndices).sort((a, b) => a - b);
5554
- if (this._config.selection.mode === 'multi' && selected.length === 0) {
5555
- this._state.activeIndex = -1;
5556
- this._input.removeAttribute('aria-activedescendant');
6863
+ if (selectableIndices.length === 0 || (this._config.selection.mode === 'multi' && selected.length === 0)) {
6864
+ this._dispatchActiveKey(null, 'open', 'initial active option');
5557
6865
  return;
5558
6866
  }
5559
6867
  const target = selected.find((index) => selectableIndices.includes(index)) ?? selectableIndices[0];
5560
- this._setActive(target);
6868
+ this._setActive(target, 'open');
5561
6869
  }
5562
6870
  _announce(message) {
5563
- if (this._liveRegion) {
5564
- this._liveRegion.textContent = message;
5565
- this._setLifecycleTimeout(() => {
5566
- if (this._liveRegion)
5567
- this._liveRegion.textContent = '';
5568
- }, 1000);
5569
- }
6871
+ const effects = computeAccessibilityEffects(deriveAccessibilityState(this._engine.state), {
6872
+ optionKeys: [],
6873
+ announcements: [{ politeness: 'polite', message }],
6874
+ }).filter((effect) => effect.type === 'ANNOUNCE');
6875
+ applyAccessibilityEffects(effects, { liveRegion: this._liveRegion });
6876
+ if (!this._liveRegion)
6877
+ return;
6878
+ this._setLifecycleTimeout(() => {
6879
+ const clearEffects = computeAccessibilityEffects(deriveAccessibilityState(this._engine.state), {
6880
+ optionKeys: [],
6881
+ announcements: [{ politeness: 'polite', message: '' }],
6882
+ }).filter((effect) => effect.type === 'ANNOUNCE');
6883
+ applyAccessibilityEffects(clearEffects, { liveRegion: this._liveRegion });
6884
+ }, 1000);
5570
6885
  }
5571
6886
  _selectOption(index, opts) {
5572
6887
  // FIX: Do not rely on this._optionsContainer.children[index] because filtering changes the children
5573
6888
  // Instead, use the index to update state directly
5574
- const item = this._state.loadedItems[index];
5575
- if (!item) {
6889
+ this._ensureRegistryCurrent();
6890
+ const record = this._getRecordByIndex(index);
6891
+ if (!record)
5576
6892
  return;
5577
- }
6893
+ index = record.index;
6894
+ const item = record.item;
5578
6895
  if (this._isOptionSelectionBlocked(item)) {
5579
6896
  return;
5580
6897
  }
5581
- const isCurrentlySelected = this._state.selectedIndices.has(index);
6898
+ const isCurrentlySelected = this._engine.state.selectedKeys.has(record.key);
6899
+ const reason = opts?.reason ?? 'pointer';
5582
6900
  // Keep active/focus styling aligned with the most recently interacted option.
5583
6901
  // Without this, a previously selected item may retain active classes/styles
5584
6902
  // after selecting a different option.
5585
- this._state.activeIndex = index;
6903
+ if (!record.disabled) {
6904
+ this._dispatchActiveKey(record.key, reason === 'keyboard' ? 'keyboard' : 'pointer', 'option selection');
6905
+ }
5586
6906
  if (this._config.selection.mode === 'single') {
5587
- // Single select: clear previous and select new
5588
- const wasSelected = this._state.selectedIndices.has(index);
5589
- this._state.selectedIndices.clear();
5590
- this._state.selectedItems.clear();
5591
- if (!wasSelected || !this._config.selection.allowDeselect) {
5592
- // Select this option
5593
- this._state.selectedIndices.add(index);
5594
- this._state.selectedItems.set(index, item);
5595
- }
6907
+ this._dispatchSelection({
6908
+ type: isCurrentlySelected && this._config.selection.allowDeselect ? 'TOGGLE_KEY_REQUEST' : 'SELECT_KEY_REQUEST',
6909
+ key: record.key,
6910
+ reason,
6911
+ }, 'single option selection');
5596
6912
  // Re-render to update all option styles
5597
6913
  this._renderOptions();
5598
6914
  if (this._config.selection.closeOnSelect) {
5599
- this._handleClose();
6915
+ this._handleClose('selection');
5600
6916
  }
5601
6917
  }
5602
6918
  else {
@@ -5604,35 +6920,27 @@
5604
6920
  const shiftKey = Boolean(opts?.shiftKey);
5605
6921
  if (shiftKey) {
5606
6922
  const anchor = this._rangeAnchorIndex ?? index;
5607
- this._selectRange(anchor, index, { clear: !toggleKey });
6923
+ this._selectRange(anchor, index, { clear: !toggleKey, reason });
5608
6924
  this._rangeAnchorIndex = anchor;
5609
6925
  return;
5610
6926
  }
5611
6927
  // Multi select with toggle
5612
6928
  const maxSelections = this._config.selection.maxSelections || 0;
5613
- if (isCurrentlySelected) {
5614
- // Deselect (toggle off)
5615
- this._state.selectedIndices.delete(index);
5616
- this._state.selectedItems.delete(index);
5617
- }
5618
- else {
5619
- // Select (toggle on)
5620
- if (maxSelections > 0 && this._state.selectedIndices.size >= maxSelections) {
5621
- this._announce(`Maximum ${maxSelections} selections allowed`);
5622
- return; // Max selections reached
5623
- }
5624
- this._state.selectedIndices.add(index);
5625
- this._state.selectedItems.set(index, item);
6929
+ if (!isCurrentlySelected && maxSelections > 0 && this._engine.state.selectedKeys.size >= maxSelections) {
6930
+ this._announce(`Maximum ${maxSelections} selections allowed`);
6931
+ this._renderOptions();
6932
+ return;
5626
6933
  }
6934
+ this._dispatchSelection({ type: 'TOGGLE_KEY_REQUEST', key: record.key, reason }, 'multi option selection');
5627
6935
  // Re-render to update styles (safer than trying to find the element in filtered list)
5628
6936
  this._renderOptions();
5629
6937
  }
5630
6938
  this._rangeAnchorIndex = index;
5631
6939
  this._updateInputDisplay();
6940
+ const selectDetail = this._getSelectEventDetail(record);
6941
+ this._emit('select', selectDetail);
5632
6942
  this._emitChange();
5633
- const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
5634
- const getLabel = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
5635
- const label = getLabel(item);
6943
+ const label = selectDetail.label;
5636
6944
  if (this._config.selection.mode === 'single') {
5637
6945
  this._announce(`Selected ${label}`);
5638
6946
  }
@@ -5641,25 +6949,34 @@
5641
6949
  const action = isCurrentlySelected ? 'Deselected' : 'Selected';
5642
6950
  this._announce(`${action} ${label}. ${selectedCount} selected`);
5643
6951
  }
5644
- this._config.callbacks.onSelect?.({
5645
- item: item,
5646
- index,
5647
- value: getValue(item),
5648
- label: getLabel(item),
5649
- selected: this._state.selectedIndices.has(index),
5650
- });
6952
+ this._config.callbacks.onSelect?.(selectDetail);
5651
6953
  }
5652
- _handleOptionRemove(index) {
5653
- const item = this._state.selectedItems.get(index);
5654
- const option = this._getOptionElementByIndex(index);
5655
- this._state.selectedIndices.delete(index);
5656
- this._state.selectedItems.delete(index);
6954
+ _handleOptionRemove(index, key) {
6955
+ this._ensureRegistryCurrent();
6956
+ const entry = this._getSelectedEntries().find((selected) => key === undefined
6957
+ ? selected.index === index
6958
+ : selected.key === key);
6959
+ if (!entry)
6960
+ return;
6961
+ const item = entry.item;
6962
+ const activeElement = this._shadow.activeElement;
6963
+ const focusedBadge = activeElement instanceof HTMLButtonElement
6964
+ && activeElement.getAttribute('part') === 'chip-remove'
6965
+ ? activeElement.closest('.selection-badge')
6966
+ : null;
6967
+ const hadFocusedChipRemove = focusedBadge !== null;
6968
+ const focusedBadgeIndex = focusedBadge
6969
+ ? Array.from(this._inputContent.querySelectorAll('.selection-badge')).indexOf(focusedBadge)
6970
+ : -1;
6971
+ const option = this._itemRegistry.keyToRecord.has(entry.key)
6972
+ ? this._getOptionElementByIndex(entry.index)
6973
+ : null;
6974
+ this._dispatchSelection({ type: 'DESELECT_KEY_REQUEST', key: entry.key, reason: 'pointer' }, 'remove selected item');
5657
6975
  if (option && 'setSelected' in option && typeof option.setSelected === 'function') {
5658
6976
  option.setSelected(false);
5659
6977
  }
5660
6978
  else if (option) {
5661
6979
  option.classList.remove('selected', 'sm-selected', 'smilodon-option--selected');
5662
- option.setAttribute('aria-selected', 'false');
5663
6980
  const stateTokens = (option.dataset.smState || '')
5664
6981
  .split(' ')
5665
6982
  .map(token => token.trim())
@@ -5674,13 +6991,24 @@
5674
6991
  this._updateInputDisplay();
5675
6992
  this._renderOptions();
5676
6993
  this._emitChange();
6994
+ if (hadFocusedChipRemove && this.isConnected) {
6995
+ const removeButtons = this._inputContent.querySelectorAll('[part="chip-remove"]');
6996
+ if (removeButtons.length > 0) {
6997
+ const nextFocusIndex = Math.min(Math.max(focusedBadgeIndex, 0), removeButtons.length - 1);
6998
+ removeButtons[nextFocusIndex].focus();
6999
+ }
7000
+ else {
7001
+ this._applyFocusIntent('input', 'selected-chip-removed');
7002
+ }
7003
+ }
5677
7004
  const config = option && 'getConfig' in option && typeof option.getConfig === 'function'
5678
7005
  ? option.getConfig()
5679
7006
  : undefined;
5680
- this._emit('remove', { item: config?.item ?? item, index });
7007
+ this._emit('remove', { item: config?.item ?? item, index: entry.index });
5681
7008
  }
5682
7009
  _updateInputDisplay() {
5683
- const selectedItems = Array.from(this._state.selectedItems.values());
7010
+ const selectedEntries = this._getSelectedEntries();
7011
+ const selectedItems = selectedEntries.map(({ item }) => item);
5684
7012
  const getLabel = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
5685
7013
  if (selectedItems.length === 0) {
5686
7014
  this._input.value = '';
@@ -5700,8 +7028,7 @@
5700
7028
  const existingBadges = this._inputContent.querySelectorAll('.selection-badge');
5701
7029
  existingBadges.forEach(badge => badge.remove());
5702
7030
  // Create badges for each selected item
5703
- const selectedEntries = Array.from(this._state.selectedItems.entries());
5704
- selectedEntries.forEach(([index, item]) => {
7031
+ selectedEntries.forEach(({ key, index, item }) => {
5705
7032
  const badge = document.createElement('span');
5706
7033
  badge.className = 'selection-badge';
5707
7034
  if (this._config.styles.classNames?.badge) {
@@ -5744,7 +7071,7 @@
5744
7071
  removeBtn.addEventListener('click', (e) => {
5745
7072
  e.stopPropagation();
5746
7073
  e.preventDefault();
5747
- this._handleOptionRemove(index);
7074
+ this._handleOptionRemove(index, key);
5748
7075
  });
5749
7076
  badge.appendChild(removeBtn);
5750
7077
  }
@@ -5768,7 +7095,9 @@
5768
7095
  if (this._state.selectedIndices.size === 0)
5769
7096
  return;
5770
7097
  const target = this._config.scrollToSelected.multiSelectTarget;
5771
- const indices = Array.from(this._state.selectedIndices).sort((a, b) => a - b);
7098
+ const indices = Array.from(this._state.selectedIndices).filter((index) => index >= 0).sort((a, b) => a - b);
7099
+ if (indices.length === 0)
7100
+ return;
5772
7101
  // For multi-select, find the closest selected item to the current scroll position
5773
7102
  let targetIndex;
5774
7103
  if (this._config.selection.mode === 'multi' && indices.length > 1) {
@@ -5796,7 +7125,14 @@
5796
7125
  targetIndex = target === 'first' ? indices[0] : indices[indices.length - 1];
5797
7126
  }
5798
7127
  // Find and scroll to the target option
5799
- const option = this._getOptionElementByIndex(targetIndex);
7128
+ let option = this._getOptionElementByIndex(targetIndex);
7129
+ if (!option && this._guardedVirtualizer) {
7130
+ const targetKey = this._itemRegistry.indexToKey.get(targetIndex);
7131
+ if (targetKey !== undefined) {
7132
+ this._materializeGuardedVirtualKey(targetKey);
7133
+ option = this._getOptionElementByIndex(targetIndex);
7134
+ }
7135
+ }
5800
7136
  if (option) {
5801
7137
  // Use smooth scrolling with center alignment for better UX
5802
7138
  if (typeof option.scrollIntoView === 'function') {
@@ -5806,7 +7142,7 @@
5806
7142
  });
5807
7143
  }
5808
7144
  // Also set it as active for keyboard navigation
5809
- this._setActive(targetIndex);
7145
+ this._setActive(targetIndex, 'programmatic');
5810
7146
  }
5811
7147
  }
5812
7148
  async _loadMoreItems() {
@@ -5838,12 +7174,7 @@
5838
7174
  }
5839
7175
  _setBusy(busy) {
5840
7176
  this._state.isBusy = busy;
5841
- if (busy) {
5842
- this._dropdown.setAttribute('aria-busy', 'true');
5843
- }
5844
- else {
5845
- this._dropdown.removeAttribute('aria-busy');
5846
- }
7177
+ this._syncListboxAccessibility();
5847
7178
  // Trigger re-render to show/hide busy indicator
5848
7179
  // We use _renderOptions to handle the UI update
5849
7180
  this._renderOptions();
@@ -6012,10 +7343,11 @@
6012
7343
  };
6013
7344
  }
6014
7345
  _emitChange() {
6015
- const selectedItems = Array.from(this._state.selectedItems.values());
7346
+ const selectedEntries = this._getSelectedEntries();
7347
+ const selectedItems = selectedEntries.map(({ item }) => item);
6016
7348
  const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
6017
7349
  const selectedValues = selectedItems.map(getValue);
6018
- const selectedIndices = Array.from(this._state.selectedIndices);
7350
+ const selectedIndices = selectedEntries.map(({ index }) => index).filter((index) => index >= 0);
6019
7351
  this._emit('change', { selectedItems, selectedValues, selectedIndices });
6020
7352
  this._config.callbacks.onChange?.(selectedItems, selectedValues);
6021
7353
  }
@@ -6026,6 +7358,7 @@
6026
7358
  set optionRenderer(renderer) {
6027
7359
  if (this._optionRenderer === renderer)
6028
7360
  return;
7361
+ this._invalidateGuardedMeasurements();
6029
7362
  this._optionRenderer = renderer;
6030
7363
  this._setGlobalStylesMirroring(Boolean(renderer || this._classMap || this._groupHeaderRenderer));
6031
7364
  this._track('style', 'optionRendererChanged', { enabled: Boolean(renderer) });
@@ -6035,12 +7368,12 @@
6035
7368
  * Set items to display in the select
6036
7369
  */
6037
7370
  setItems(items) {
7371
+ this._invalidateGuardedMeasurements();
6038
7372
  const previousLength = this._state.loadedItems.length;
6039
- this._state.loadedItems = items;
6040
- // If grouped items exist, flatten them to items
6041
- if (this._state.groupedItems.length > 0) {
6042
- this._state.loadedItems = this._state.groupedItems.flatMap(group => group.options);
6043
- }
7373
+ this._rebuildItemRegistry(items);
7374
+ this._state.groupedItems = this._groupItemsByProperty(items);
7375
+ if (!this._state.searchQuery)
7376
+ this._updateInputDisplay();
6044
7377
  const newLength = this._state.loadedItems.length;
6045
7378
  // When infinite scroll is active (preserveScrollPosition = true),
6046
7379
  // we need to maintain scroll position during the update
@@ -6072,19 +7405,42 @@
6072
7405
  this._renderOptions();
6073
7406
  }
6074
7407
  }
7408
+ _groupItemsByProperty(items) {
7409
+ const hasGroupData = items.some((item, index) => this._itemAdapter.getGroupKey?.(item, index) !== null);
7410
+ if (!hasGroupData) {
7411
+ return [];
7412
+ }
7413
+ const groups = new Map();
7414
+ items.forEach((item, index) => {
7415
+ const rawGroup = this._itemAdapter.getGroupKey?.(item, index);
7416
+ const label = rawGroup == null ? 'Ungrouped' : String(rawGroup);
7417
+ const options = groups.get(label);
7418
+ if (options) {
7419
+ options.push(item);
7420
+ }
7421
+ else {
7422
+ groups.set(label, [item]);
7423
+ }
7424
+ });
7425
+ return Array.from(groups.entries()).map(([label, options]) => ({ label, options }));
7426
+ }
6075
7427
  /**
6076
7428
  * Set grouped items
6077
7429
  */
6078
7430
  setGroupedItems(groupedItems) {
7431
+ this._destroyGuardedVirtualizer();
7432
+ this._rebuildItemRegistry(groupedItems.flatMap(group => group.options));
6079
7433
  this._state.groupedItems = groupedItems;
6080
- this._state.loadedItems = groupedItems.flatMap(group => group.options);
6081
7434
  this._renderOptions();
7435
+ if (!this._state.searchQuery)
7436
+ this._updateInputDisplay();
6082
7437
  }
6083
7438
  /**
6084
7439
  * Get currently selected items
6085
7440
  */
6086
7441
  getSelectedItems() {
6087
- return Array.from(this._state.selectedItems.values());
7442
+ this._ensureRegistryCurrent();
7443
+ return this._getSelectedEntries().map((entry) => entry.item);
6088
7444
  }
6089
7445
  /**
6090
7446
  * Get all loaded items
@@ -6096,8 +7452,7 @@
6096
7452
  * Get currently selected values
6097
7453
  */
6098
7454
  getSelectedValues() {
6099
- const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
6100
- return this.getSelectedItems().map(getValue);
7455
+ return this.getSelectedItems().map((item) => this._getItemValue(item));
6101
7456
  }
6102
7457
  /**
6103
7458
  * Set selected items by value
@@ -6107,16 +7462,10 @@
6107
7462
  await this._loadSelectedItemsByValues(values);
6108
7463
  }
6109
7464
  else {
6110
- // Select from loaded items
6111
- const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
6112
- this._state.selectedIndices.clear();
6113
- this._state.selectedItems.clear();
6114
- this._state.loadedItems.forEach((item, index) => {
6115
- if (arrayIncludesValue(values, getValue(item)) && !this._isOptionSelectionBlocked(item)) {
6116
- this._state.selectedIndices.add(index);
6117
- this._state.selectedItems.set(index, item);
6118
- }
6119
- });
7465
+ this._ensureRegistryCurrent();
7466
+ const selected = this._itemRegistry.records
7467
+ .filter((record) => arrayIncludesValue(values, record.value) && !this._isOptionSelectionBlocked(record.item));
7468
+ this._requestSelectionReplacement(selected, 'external-value-sync', 'setSelectedValues');
6120
7469
  this._renderOptions();
6121
7470
  this._updateInputDisplay();
6122
7471
  this._emitChange();
@@ -6134,14 +7483,10 @@
6134
7483
  const items = await this._config.serverSide.fetchSelectedItems(values);
6135
7484
  if (generation !== this._asyncGeneration || !this.isConnected)
6136
7485
  return;
6137
- this._state.selectedIndices.clear();
6138
- this._state.selectedItems.clear();
6139
- items.forEach((item, index) => {
6140
- if (this._isOptionSelectionBlocked(item))
6141
- return;
6142
- this._state.selectedIndices.add(index);
6143
- this._state.selectedItems.set(index, item);
7486
+ const fetchedRegistry = createItemRegistry(items, this._itemAdapter, {
7487
+ duplicateKeyPolicy: this._getDuplicateKeyPolicy(),
6144
7488
  });
7489
+ this._requestSelectionReplacement(fetchedRegistry.records, 'external-value-sync', 'fetched selected items');
6145
7490
  this._renderOptions();
6146
7491
  this._updateInputDisplay();
6147
7492
  this._emitChange();
@@ -6165,8 +7510,8 @@
6165
7510
  * Clear all selections
6166
7511
  */
6167
7512
  clear() {
6168
- this._state.selectedIndices.clear();
6169
- this._state.selectedItems.clear();
7513
+ this._ensureRegistryCurrent();
7514
+ this._dispatchSelection({ type: 'CLEAR_SELECTION_REQUEST', reason: 'programmatic' }, 'clear');
6170
7515
  this._renderOptions();
6171
7516
  this._updateInputDisplay();
6172
7517
  this._emitChange();
@@ -6202,8 +7547,17 @@
6202
7547
  * Update component configuration
6203
7548
  */
6204
7549
  updateConfig(config) {
7550
+ this._invalidateGuardedMeasurements();
6205
7551
  const previousMode = this._config.selection.mode;
7552
+ const previousEnabled = this._config.enabled;
6206
7553
  this._config = this._mergeConfig(this._config, config);
7554
+ this._rebuildItemRegistry();
7555
+ if (previousEnabled !== this._config.enabled) {
7556
+ if (!this._config.enabled && this._state.isOpen) {
7557
+ this._handleClose('disabled');
7558
+ }
7559
+ this._runEngineEffects(this._engine.dispatch({ type: 'DISABLED_CHANGED', disabled: !this._config.enabled }));
7560
+ }
6207
7561
  if (previousMode !== this._config.selection.mode &&
6208
7562
  this._config.limitations?.autoMitigateRuntimeModeSwitch) {
6209
7563
  this.clear();
@@ -6221,7 +7575,7 @@
6221
7575
  // Update input state based on new config
6222
7576
  if (this._input) {
6223
7577
  this._input.readOnly = !this._config.searchable;
6224
- this._input.setAttribute('aria-autocomplete', this._config.searchable ? 'list' : 'none');
7578
+ this._syncComboboxAccessibility();
6225
7579
  if (this._state.selectedIndices.size === 0) {
6226
7580
  this._input.placeholder = this._config.placeholder || 'Select an option...';
6227
7581
  }
@@ -6239,14 +7593,7 @@
6239
7593
  }
6240
7594
  }
6241
7595
  this._syncStyleConfigVariables();
6242
- if (this._dropdown) {
6243
- if (this._config.selection.mode === 'multi') {
6244
- this._dropdown.setAttribute('aria-multiselectable', 'true');
6245
- }
6246
- else {
6247
- this._dropdown.removeAttribute('aria-multiselectable');
6248
- }
6249
- }
7596
+ this._syncListboxAccessibility();
6250
7597
  if (this.isConnected) {
6251
7598
  this._syncDirectionConfig();
6252
7599
  this._syncInputContainerMode();
@@ -6309,7 +7656,7 @@
6309
7656
  clearedSelection: shouldClearSelection && hadSelection,
6310
7657
  clearedSearch: shouldClearSearch && hadSearch,
6311
7658
  });
6312
- this._input.focus();
7659
+ this._applyFocusIntent('input', 'clear-control-complete');
6313
7660
  }
6314
7661
  _syncClearControlState() {
6315
7662
  if (!this._clearControl || !this._inputContainer || !this._arrowContainer)
@@ -6335,7 +7682,9 @@
6335
7682
  setError(message) {
6336
7683
  this._hasError = true;
6337
7684
  this._errorMessage = message;
6338
- this._input.setAttribute('aria-invalid', 'true');
7685
+ if (this._errorDescription)
7686
+ this._errorDescription.textContent = message;
7687
+ this._syncComboboxAccessibility();
6339
7688
  this._announce(`Error: ${message}`);
6340
7689
  }
6341
7690
  /**
@@ -6344,20 +7693,22 @@
6344
7693
  clearError() {
6345
7694
  this._hasError = false;
6346
7695
  this._errorMessage = '';
6347
- this._input.removeAttribute('aria-invalid');
7696
+ if (this._errorDescription)
7697
+ this._errorDescription.textContent = '';
7698
+ this._syncComboboxAccessibility();
6348
7699
  }
6349
7700
  /**
6350
7701
  * Set required state
6351
7702
  */
6352
7703
  setRequired(required) {
6353
7704
  if (required) {
6354
- this._input.setAttribute('aria-required', 'true');
6355
7705
  this._input.setAttribute('required', '');
6356
7706
  }
6357
7707
  else {
6358
- this._input.removeAttribute('aria-required');
6359
7708
  this._input.removeAttribute('required');
6360
7709
  }
7710
+ this._syncEngineSelectionConfig();
7711
+ this._syncComboboxAccessibility();
6361
7712
  }
6362
7713
  /**
6363
7714
  * Validate selection (for required fields)
@@ -6374,15 +7725,414 @@
6374
7725
  /**
6375
7726
  * Render options based on current state
6376
7727
  */
7728
+ _deriveVirtualizationScope(filteredIndices) {
7729
+ const keyForIndex = (index) => this._itemRegistry.indexToKey.get(index);
7730
+ const filteredKeys = filteredIndices
7731
+ .map(keyForIndex)
7732
+ .filter((key) => key !== undefined);
7733
+ return {
7734
+ dataKeys: this._itemRegistry.records.map((record) => record.key),
7735
+ filteredKeys,
7736
+ registeredKeys: Array.from(this._engine.state.registeredKeys),
7737
+ // The current chunked path schedules all filtered items for rendering;
7738
+ // this scaffold records that target set until bounded windows are wired.
7739
+ windowKeys: this._renderPlan.intendedRenderKeys.slice(),
7740
+ mountedKeys: this._getMountedVirtualizationKeys(this._optionsContainer.children),
7741
+ selectedKeys: new Set(this._engine.state.selectedKeys),
7742
+ activeKey: this._engine.state.activeKey,
7743
+ };
7744
+ }
7745
+ _getMountedVirtualizationKeys(targets) {
7746
+ const keyForIndex = (index) => this._itemRegistry.indexToKey.get(index);
7747
+ return Array.from(targets)
7748
+ .filter((target) => target instanceof HTMLElement
7749
+ && (target.hasAttribute('data-sm-selectable') || target.hasAttribute('data-selectable')))
7750
+ .map((target) => Number(target.getAttribute('data-sm-index') ?? target.getAttribute('data-index')))
7751
+ .filter(Number.isInteger)
7752
+ .map(keyForIndex)
7753
+ .filter((key) => key !== undefined);
7754
+ }
7755
+ _refreshMountedVirtualizationScope() {
7756
+ this._virtualizationScope = {
7757
+ ...this._virtualizationScope,
7758
+ mountedKeys: this._getMountedVirtualizationKeys(this._optionsContainer.children),
7759
+ registeredKeys: Array.from(this._engine.state.registeredKeys),
7760
+ selectedKeys: new Set(this._engine.state.selectedKeys),
7761
+ activeKey: this._engine.state.activeKey,
7762
+ };
7763
+ }
7764
+ _appendMountedVirtualizationTargets(targets) {
7765
+ const mountedKeys = this._getMountedVirtualizationKeys(targets);
7766
+ this._virtualizationScope = {
7767
+ ...this._virtualizationScope,
7768
+ mountedKeys: [...new Set([...this._virtualizationScope.mountedKeys, ...mountedKeys])],
7769
+ registeredKeys: Array.from(this._engine.state.registeredKeys),
7770
+ selectedKeys: new Set(this._engine.state.selectedKeys),
7771
+ activeKey: this._engine.state.activeKey,
7772
+ };
7773
+ }
7774
+ _createLegacyRenderPlan(filteredIndices) {
7775
+ const indices = [...filteredIndices];
7776
+ const filteredKeys = indices
7777
+ .map((index) => this._itemRegistry.indexToKey.get(index))
7778
+ .filter((key) => key !== undefined);
7779
+ const filteredIndexByKey = new Map();
7780
+ filteredKeys.forEach((key, filteredIndex) => filteredIndexByKey.set(key, filteredIndex));
7781
+ return {
7782
+ mode: 'legacy-full',
7783
+ filteredIndices: indices,
7784
+ filteredKeys,
7785
+ intendedRenderKeys: filteredKeys.slice(),
7786
+ filteredIndexByKey,
7787
+ };
7788
+ }
7789
+ _createVirtualRenderPlan(startIndex, endIndex) {
7790
+ const filteredKeys = this._renderPlan.filteredKeys.slice();
7791
+ const intendedRenderKeys = computeWindowKeys(filteredKeys, startIndex, endIndex);
7792
+ const filteredIndices = intendedRenderKeys
7793
+ .map((key) => this._itemRegistry.keyToIndex.get(key))
7794
+ .filter((index) => index !== undefined);
7795
+ return {
7796
+ mode: 'virtual-window',
7797
+ filteredIndices,
7798
+ filteredKeys,
7799
+ intendedRenderKeys,
7800
+ filteredIndexByKey: new Map(this._renderPlan.filteredIndexByKey),
7801
+ };
7802
+ }
7803
+ _ensureGuardedVirtualizer(filteredKeys) {
7804
+ const keysChanged = this._guardedVirtualizer !== null && (filteredKeys.length !== this._guardedVirtualizerKeys.length
7805
+ || filteredKeys.some((key, index) => !Object.is(key, this._guardedVirtualizerKeys[index])));
7806
+ if (keysChanged)
7807
+ this._destroyGuardedVirtualizer(true);
7808
+ if (!this._guardedVirtualizer) {
7809
+ // The controller only calculates ranges and scroll intents. Give it a
7810
+ // detached container so its internal styling never touches rendered UI.
7811
+ this._guardedVirtualizer = new Virtualizer(document.createElement('div'), filteredKeys.length, (index) => this._renderPlan.filteredKeys[index], {
7812
+ estimatedItemHeight: this._resolveGuardedEstimatedItemHeight(),
7813
+ buffer: 0,
7814
+ measurementThreshold: 0,
7815
+ });
7816
+ this._guardedVirtualScrollTop = this._optionsContainer.scrollTop;
7817
+ this._guardedVirtualViewportHeight = this._resolveGuardedViewportHeight();
7818
+ this._optionsContainer.addEventListener('scroll', this._onGuardedVirtualScroll, { passive: true });
7819
+ this._guardedScrollListenerAttached = true;
7820
+ }
7821
+ this._guardedVirtualizerKeys = [...filteredKeys];
7822
+ return this._guardedVirtualizer;
7823
+ }
7824
+ _resolveGuardedEstimatedItemHeight() {
7825
+ const configuredHeight = this._config.estimatedItemHeight;
7826
+ if (typeof configuredHeight === 'number' && Number.isFinite(configuredHeight) && configuredHeight > 0) {
7827
+ return configuredHeight;
7828
+ }
7829
+ const renderedOption = this._optionsContainer.querySelector('[part="option"]');
7830
+ const measuredHeight = renderedOption?.getBoundingClientRect().height || renderedOption?.offsetHeight;
7831
+ if (typeof measuredHeight === 'number' && Number.isFinite(measuredHeight) && measuredHeight > 0) {
7832
+ return measuredHeight;
7833
+ }
7834
+ return 48;
7835
+ }
7836
+ _resolveGuardedViewportHeight() {
7837
+ const candidates = [
7838
+ this._optionsContainer.clientHeight,
7839
+ this._optionsContainer.getBoundingClientRect().height,
7840
+ ];
7841
+ return candidates.find((height) => Number.isFinite(height) && height > 0) ?? 0;
7842
+ }
7843
+ _clampGuardedScrollPosition(itemCount, viewportHeight) {
7844
+ if (!this._guardedVirtualizer)
7845
+ return 0;
7846
+ const totalHeight = this._guardedVirtualizer.cumulativeOffset(itemCount);
7847
+ const maxScrollTop = Math.max(0, totalHeight - viewportHeight);
7848
+ const scrollTop = Math.min(Math.max(0, this._guardedVirtualScrollTop), maxScrollTop);
7849
+ this._guardedVirtualScrollTop = scrollTop;
7850
+ if (this._optionsContainer.scrollTop !== scrollTop) {
7851
+ this._optionsContainer.scrollTop = scrollTop;
7852
+ }
7853
+ return scrollTop;
7854
+ }
7855
+ _createGuardedSpacer(position, height) {
7856
+ const spacer = document.createElement('div');
7857
+ spacer.setAttribute('data-virtual-spacer', position);
7858
+ spacer.setAttribute('aria-hidden', 'true');
7859
+ spacer.setAttribute('role', 'presentation');
7860
+ spacer.style.height = `${Number.isFinite(height) ? Math.max(0, height) : 0}px`;
7861
+ spacer.style.minHeight = '0';
7862
+ spacer.style.flex = '0 0 auto';
7863
+ spacer.style.pointerEvents = 'none';
7864
+ return spacer;
7865
+ }
7866
+ _appendGuardedTopSpacer() {
7867
+ const virtualizer = this._guardedVirtualizer;
7868
+ const window = this._guardedVirtualWindow;
7869
+ if (!virtualizer || !window)
7870
+ return;
7871
+ this._optionsContainer.appendChild(this._createGuardedSpacer('top', virtualizer.cumulativeOffset(window.startIndex)));
7872
+ }
7873
+ _appendGuardedBottomSpacer() {
7874
+ const virtualizer = this._guardedVirtualizer;
7875
+ const window = this._guardedVirtualWindow;
7876
+ if (!virtualizer || !window)
7877
+ return;
7878
+ const totalHeight = virtualizer.cumulativeOffset(this._renderPlan.filteredKeys.length);
7879
+ const endOffset = virtualizer.cumulativeOffset(window.endIndex);
7880
+ this._optionsContainer.appendChild(this._createGuardedSpacer('bottom', Math.max(0, totalHeight - endOffset)));
7881
+ }
7882
+ _resolveGuardedOverscan() {
7883
+ return 2;
7884
+ }
7885
+ _applyGuardedWindowUpdate(update, overscan = 0) {
7886
+ if (!this._guardedVirtualizer)
7887
+ return false;
7888
+ this._guardedVirtualScrollTop = update.scrollTop;
7889
+ this._guardedVirtualViewportHeight = update.viewportHeight;
7890
+ const itemCount = this._renderPlan.filteredKeys.length;
7891
+ const nextWindow = {
7892
+ startIndex: Math.max(0, update.window.startIndex - overscan),
7893
+ endIndex: Math.min(itemCount, update.window.endIndex + 1 + overscan),
7894
+ };
7895
+ const changed = this._guardedVirtualWindow?.startIndex !== nextWindow.startIndex
7896
+ || this._guardedVirtualWindow?.endIndex !== nextWindow.endIndex;
7897
+ this._guardedVirtualWindow = nextWindow;
7898
+ return changed;
7899
+ }
7900
+ _scheduleGuardedVirtualWindowUpdate() {
7901
+ if (!this._guardedVirtualizer || this._guardedVirtualWindowRafId !== null)
7902
+ return;
7903
+ this._guardedVirtualWindowRafId = this._requestLifecycleFrame(() => {
7904
+ this._guardedVirtualWindowRafId = null;
7905
+ const virtualizer = this._guardedVirtualizer;
7906
+ if (!virtualizer)
7907
+ return;
7908
+ const update = virtualizer.updateWindow(this._optionsContainer.scrollTop, this._resolveGuardedViewportHeight());
7909
+ this._guardedVirtualOverscan = this._resolveGuardedOverscan();
7910
+ if (update && this._applyGuardedWindowUpdate(update, this._guardedVirtualOverscan)) {
7911
+ this._renderOptions();
7912
+ }
7913
+ });
7914
+ }
7915
+ _cancelGuardedVirtualWindowUpdate() {
7916
+ if (this._guardedVirtualWindowRafId === null)
7917
+ return;
7918
+ cancelAnimationFrame(this._guardedVirtualWindowRafId);
7919
+ this._lifecycleRafs.delete(this._guardedVirtualWindowRafId);
7920
+ this._guardedVirtualWindowRafId = null;
7921
+ }
7922
+ _applyGuardedScrollResult(result) {
7923
+ if (!result || !this._guardedVirtualizer)
7924
+ return false;
7925
+ this._guardedVirtualScrollTop = result.scrollTop;
7926
+ this._optionsContainer.scrollTop = result.scrollTop;
7927
+ const update = this._guardedVirtualizer.updateWindow(this._guardedVirtualScrollTop, this._guardedVirtualViewportHeight);
7928
+ if (!update)
7929
+ return false;
7930
+ this._guardedVirtualWindow = {
7931
+ startIndex: update.window.startIndex,
7932
+ endIndex: update.window.endIndex + 1,
7933
+ };
7934
+ this._guardedVirtualOverscan = 0;
7935
+ return true;
7936
+ }
7937
+ _updateGuardedVirtualWindow(scrollTop, viewportHeight) {
7938
+ this._guardedVirtualizationRequested = true;
7939
+ const virtualizer = this._ensureGuardedVirtualizer(this._renderPlan.filteredKeys);
7940
+ this._guardedVirtualScrollTop = scrollTop;
7941
+ this._guardedVirtualViewportHeight = viewportHeight;
7942
+ const update = virtualizer.updateWindow(scrollTop, viewportHeight);
7943
+ if (!update)
7944
+ return false;
7945
+ this._guardedVirtualOverscan = 0;
7946
+ this._applyGuardedWindowUpdate(update, this._guardedVirtualOverscan);
7947
+ this._optionsContainer.scrollTop = update.scrollTop;
7948
+ return true;
7949
+ }
7950
+ _destroyGuardedVirtualizer(preserveRequestedMode = false) {
7951
+ this._cancelGuardedVirtualWindowUpdate();
7952
+ this._guardedMeasurementGeneration += 1;
7953
+ if (this._guardedScrollListenerAttached) {
7954
+ this._optionsContainer.removeEventListener('scroll', this._onGuardedVirtualScroll);
7955
+ this._guardedScrollListenerAttached = false;
7956
+ }
7957
+ this._guardedVirtualizer?.destroy();
7958
+ this._guardedVirtualizer = null;
7959
+ this._teardownGuardedOptionResizeObserver();
7960
+ if (!preserveRequestedMode)
7961
+ this._guardedVirtualizationRequested = false;
7962
+ this._guardedVirtualizerKeys = [];
7963
+ this._guardedVirtualWindow = null;
7964
+ this._guardedVirtualScrollTop = 0;
7965
+ this._guardedVirtualViewportHeight = 0;
7966
+ this._guardedVirtualOverscan = 0;
7967
+ }
7968
+ _invalidateGuardedMeasurements() {
7969
+ if (this._guardedVirtualizer)
7970
+ this._destroyGuardedVirtualizer(true);
7971
+ }
7972
+ _createGuardedOptionResizeObserver(generation) {
7973
+ if (typeof ResizeObserver === 'undefined')
7974
+ return;
7975
+ this._guardedOptionResizeObserver = new ResizeObserver((entries) => {
7976
+ if (generation !== this._guardedMeasurementGeneration
7977
+ || !this._guardedVirtualizer
7978
+ || !this._guardedVirtualizationRequested
7979
+ || !this.isConnected)
7980
+ return;
7981
+ const virtualizer = this._guardedVirtualizer;
7982
+ const scrollTop = this._optionsContainer.scrollTop;
7983
+ const viewportHeight = this._resolveGuardedViewportHeight();
7984
+ const anchor = this._captureGuardedScrollAnchor(virtualizer, scrollTop, viewportHeight);
7985
+ let changed = false;
7986
+ for (const entry of entries) {
7987
+ const option = entry.target;
7988
+ if (!(option instanceof HTMLElement) || !this._guardedObservedOptions.has(option))
7989
+ continue;
7990
+ if (!option.isConnected || !this._optionsContainer.contains(option))
7991
+ continue;
7992
+ const meta = this._guardedOptionMeasurements.get(option);
7993
+ if (!meta || meta.generation !== generation)
7994
+ continue;
7995
+ const dataIndex = Number(option.getAttribute('data-index'));
7996
+ if (!Number.isInteger(dataIndex) || !Object.is(this._itemRegistry.indexToKey.get(dataIndex), meta.key))
7997
+ continue;
7998
+ const currentIndex = this._renderPlan.filteredIndexByKey.get(meta.key);
7999
+ if (currentIndex === undefined || currentIndex !== meta.index)
8000
+ continue;
8001
+ const reportedHeight = entry.borderBoxSize?.[0]?.blockSize;
8002
+ const height = typeof reportedHeight === 'number' ? reportedHeight : entry.contentRect.height;
8003
+ if (!Number.isFinite(height) || height <= 0)
8004
+ continue;
8005
+ changed = virtualizer.measureItem(meta.index, height) || changed;
8006
+ }
8007
+ if (!changed)
8008
+ return;
8009
+ if (anchor) {
8010
+ const currentAnchorIndex = this._renderPlan.filteredIndexByKey.get(anchor.key);
8011
+ if (currentAnchorIndex !== undefined) {
8012
+ const anchoredScrollTop = Math.max(0, virtualizer.cumulativeOffset(currentAnchorIndex) + anchor.offset);
8013
+ this._guardedVirtualScrollTop = anchoredScrollTop;
8014
+ this._optionsContainer.scrollTop = anchoredScrollTop;
8015
+ }
8016
+ }
8017
+ const update = virtualizer.updateWindow(this._optionsContainer.scrollTop, viewportHeight);
8018
+ if (update)
8019
+ this._applyGuardedWindowUpdate(update, this._guardedVirtualOverscan);
8020
+ this._renderOptions();
8021
+ });
8022
+ }
8023
+ _captureGuardedScrollAnchor(virtualizer, scrollTop, viewportHeight) {
8024
+ const viewportTop = this._optionsContainer.getBoundingClientRect().top + this._optionsContainer.clientTop;
8025
+ const viewportBottom = viewportTop + viewportHeight;
8026
+ const visible = Array.from(this._guardedObservedOptions)
8027
+ .map((option) => ({ option, rect: option.getBoundingClientRect() }))
8028
+ .filter(({ rect }) => rect.height > 0 && rect.bottom > viewportTop && rect.top < viewportBottom)
8029
+ .sort((left, right) => left.rect.top - right.rect.top)[0];
8030
+ const visibleMeta = visible ? this._guardedOptionMeasurements.get(visible.option) : undefined;
8031
+ if (visibleMeta && visibleMeta.generation === this._guardedMeasurementGeneration) {
8032
+ return {
8033
+ key: visibleMeta.key,
8034
+ offset: scrollTop - virtualizer.cumulativeOffset(visibleMeta.index),
8035
+ };
8036
+ }
8037
+ if (this._renderPlan.filteredKeys.length === 0)
8038
+ return null;
8039
+ const index = virtualizer.computeWindow(scrollTop, 0).startIndex;
8040
+ const key = this._renderPlan.filteredKeys[index];
8041
+ return key === undefined ? null : {
8042
+ key,
8043
+ offset: scrollTop - virtualizer.cumulativeOffset(index),
8044
+ };
8045
+ }
8046
+ _syncGuardedOptionResizeTargets() {
8047
+ const virtualizer = this._guardedVirtualizer;
8048
+ if (!virtualizer || !this._guardedVirtualizationRequested || !this.isConnected)
8049
+ return;
8050
+ const candidates = [];
8051
+ for (const child of Array.from(this._optionsContainer.children)) {
8052
+ if (!(child instanceof HTMLElement) || !child.hasAttribute('data-index'))
8053
+ continue;
8054
+ const dataIndex = Number(child.getAttribute('data-index'));
8055
+ if (!Number.isInteger(dataIndex))
8056
+ continue;
8057
+ const key = this._itemRegistry.indexToKey.get(dataIndex);
8058
+ const index = key === undefined ? undefined : this._renderPlan.filteredIndexByKey.get(key);
8059
+ if (key === undefined || index === undefined)
8060
+ continue;
8061
+ candidates.push({ option: child, key, index });
8062
+ }
8063
+ const reusedTarget = candidates.some(({ option }) => this._guardedObserverSeenOptions.has(option));
8064
+ if (reusedTarget && this._guardedOptionResizeObserver) {
8065
+ this._guardedMeasurementGeneration += 1;
8066
+ this._teardownGuardedOptionResizeObserver();
8067
+ }
8068
+ if (!this._guardedOptionResizeObserver) {
8069
+ this._createGuardedOptionResizeObserver(this._guardedMeasurementGeneration);
8070
+ }
8071
+ const observer = this._guardedOptionResizeObserver;
8072
+ if (!observer)
8073
+ return;
8074
+ const current = new Set();
8075
+ for (const { option, key, index } of candidates) {
8076
+ current.add(option);
8077
+ this._guardedOptionMeasurements.set(option, {
8078
+ key,
8079
+ index,
8080
+ generation: this._guardedMeasurementGeneration,
8081
+ });
8082
+ if (!this._guardedObservedOptions.has(option)) {
8083
+ observer.observe(option);
8084
+ this._guardedObserverSeenOptions.add(option);
8085
+ }
8086
+ }
8087
+ for (const previous of this._guardedObservedOptions) {
8088
+ if (!current.has(previous))
8089
+ observer.unobserve(previous);
8090
+ }
8091
+ this._guardedObservedOptions = current;
8092
+ }
8093
+ _teardownGuardedOptionResizeObserver() {
8094
+ for (const option of this._guardedObservedOptions) {
8095
+ this._guardedOptionResizeObserver?.unobserve(option);
8096
+ }
8097
+ this._guardedObservedOptions.clear();
8098
+ this._guardedObserverSeenOptions = new WeakSet();
8099
+ this._guardedOptionResizeObserver?.disconnect();
8100
+ this._guardedOptionResizeObserver = null;
8101
+ this._guardedOptionMeasurements = new WeakMap();
8102
+ }
8103
+ _materializeGuardedVirtualKey(key) {
8104
+ if (!this._guardedVirtualizer)
8105
+ return false;
8106
+ const targetIndex = this._renderPlan.filteredIndexByKey.get(key);
8107
+ if (targetIndex === undefined)
8108
+ return false;
8109
+ this._ensureGuardedVirtualizer(this._renderPlan.filteredKeys);
8110
+ const result = this._guardedVirtualizer.scrollToKey(key, (candidate) => this._renderPlan.filteredIndexByKey.get(candidate));
8111
+ if (!this._applyGuardedScrollResult(result))
8112
+ return false;
8113
+ this._renderOptions();
8114
+ return true;
8115
+ }
8116
+ _refreshVirtualizationScope(filteredIndices) {
8117
+ this._virtualizationScope = this._deriveVirtualizationScope(filteredIndices);
8118
+ }
6377
8119
  _renderOptions() {
8120
+ this._ensureRegistryCurrent();
8121
+ const scrollTopBeforeRender = this._optionsContainer.scrollTop;
6378
8122
  this._renderCycleId += 1;
6379
8123
  const renderCycleId = this._renderCycleId;
8124
+ if (this._guardedVirtualizer) {
8125
+ this._guardedVirtualScrollTop = this._optionsContainer.scrollTop;
8126
+ }
6380
8127
  // Cleanup observer
6381
8128
  if (this._loadMoreTrigger && this._intersectionObserver) {
6382
8129
  this._intersectionObserver.unobserve(this._loadMoreTrigger);
6383
8130
  }
8131
+ this._unobserveGuardedOptionResizeTargets();
6384
8132
  // Clear options container
6385
8133
  this._optionsContainer.innerHTML = '';
8134
+ let filteredIndicesForScope = [];
8135
+ let guardedScrollTopToRestore = null;
6386
8136
  // Ensure dropdown only contains options container (cleanup legacy direct children)
6387
8137
  // We need to preserve optionsContainer, so we can't just clear dropdown.innerHTML
6388
8138
  // But we can check if there are other children and remove them
@@ -6397,6 +8147,10 @@
6397
8147
  }
6398
8148
  // Show searching state (exclusive state)
6399
8149
  if (this._state.isSearching) {
8150
+ this._registerShadowItems([]);
8151
+ this._renderPlan = this._createLegacyRenderPlan([]);
8152
+ this._refreshVirtualizationScope(filteredIndicesForScope);
8153
+ this._syncLegacyActiveAria();
6400
8154
  const searching = document.createElement('div');
6401
8155
  searching.className = 'searching-state';
6402
8156
  searching.setAttribute('part', 'loading');
@@ -6408,8 +8162,17 @@
6408
8162
  const getLabel = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
6409
8163
  // Filter items by search query
6410
8164
  const query = this._state.searchQuery.toLowerCase();
8165
+ if (this._guardedMeasurementQuery !== null && this._guardedMeasurementQuery !== query) {
8166
+ this._invalidateGuardedMeasurements();
8167
+ }
8168
+ this._guardedMeasurementQuery = query;
6411
8169
  // Handle Grouped Items Rendering (when no search query)
6412
8170
  if (this._state.groupedItems.length > 0 && !query) {
8171
+ this._destroyGuardedVirtualizer();
8172
+ this._renderPlan = this._createLegacyRenderPlan(this._itemRegistry.records.map((record) => record.index));
8173
+ filteredIndicesForScope = this._renderPlan.filteredIndices;
8174
+ this._registerShadowItems(filteredIndicesForScope);
8175
+ this._refreshVirtualizationScope(filteredIndicesForScope);
6413
8176
  this._state.groupedItems.forEach((group, groupIndex) => {
6414
8177
  let header;
6415
8178
  if (this.groupHeaderRenderer) {
@@ -6447,7 +8210,7 @@
6447
8210
  }
6448
8211
  else {
6449
8212
  // Normal rendering (flat list or filtered)
6450
- const filteredIndices = [];
8213
+ const computedFilteredIndices = [];
6451
8214
  this._state.loadedItems.forEach((item, index) => {
6452
8215
  if (query) {
6453
8216
  try {
@@ -6459,8 +8222,40 @@
6459
8222
  return;
6460
8223
  }
6461
8224
  }
6462
- filteredIndices.push(index);
8225
+ computedFilteredIndices.push(index);
6463
8226
  });
8227
+ this._renderPlan = this._createLegacyRenderPlan(computedFilteredIndices);
8228
+ filteredIndicesForScope = this._renderPlan.filteredIndices;
8229
+ this._registerShadowItems(filteredIndicesForScope);
8230
+ if (this._guardedVirtualizationRequested && !this._guardedVirtualizer) {
8231
+ this._ensureGuardedVirtualizer(this._renderPlan.filteredKeys);
8232
+ this._guardedVirtualViewportHeight = this._resolveGuardedViewportHeight();
8233
+ // A data reorder/filter may have invalidated the old virtualizer, but
8234
+ // the physical position is still available before the DOM is cleared.
8235
+ this._guardedVirtualScrollTop = scrollTopBeforeRender;
8236
+ }
8237
+ if (this._guardedVirtualizer) {
8238
+ const virtualizer = this._ensureGuardedVirtualizer(this._renderPlan.filteredKeys);
8239
+ const measuredViewportHeight = this._resolveGuardedViewportHeight();
8240
+ if (measuredViewportHeight > 0) {
8241
+ this._guardedVirtualViewportHeight = measuredViewportHeight;
8242
+ }
8243
+ const scrollTop = this._clampGuardedScrollPosition(this._renderPlan.filteredKeys.length, this._guardedVirtualViewportHeight);
8244
+ guardedScrollTopToRestore = scrollTop;
8245
+ const update = virtualizer.updateWindow(scrollTop, this._guardedVirtualViewportHeight);
8246
+ if (update) {
8247
+ this._applyGuardedWindowUpdate(update, this._guardedVirtualOverscan);
8248
+ }
8249
+ else {
8250
+ this._guardedVirtualWindow = null;
8251
+ }
8252
+ }
8253
+ if (this._guardedVirtualWindow) {
8254
+ this._renderPlan = this._createVirtualRenderPlan(this._guardedVirtualWindow.startIndex, this._guardedVirtualWindow.endIndex);
8255
+ }
8256
+ const filteredIndices = this._renderPlan.filteredIndices;
8257
+ this._refreshVirtualizationScope(filteredIndicesForScope);
8258
+ this._appendGuardedTopSpacer();
6464
8259
  if (filteredIndices.length === 0 && !this._state.isBusy) {
6465
8260
  const empty = document.createElement('div');
6466
8261
  empty.setAttribute('part', 'no-results');
@@ -6474,7 +8269,8 @@
6474
8269
  this._optionsContainer.appendChild(empty);
6475
8270
  }
6476
8271
  else {
6477
- const shouldIncrementalRender = this._config.virtualize !== false
8272
+ const shouldIncrementalRender = !this._guardedVirtualizer
8273
+ && this._config.virtualize !== false
6478
8274
  && this._state.groupedItems.length === 0
6479
8275
  && filteredIndices.length > 300;
6480
8276
  if (shouldIncrementalRender) {
@@ -6482,7 +8278,7 @@
6482
8278
  let cursor = 0;
6483
8279
  let maxRenderTarget = 0;
6484
8280
  if (this._state.selectedIndices.size > 0 && this._config.scrollToSelected.enabled) {
6485
- const indices = Array.from(this._state.selectedIndices).sort((a, b) => a - b);
8281
+ const indices = Array.from(this._state.selectedIndices).filter((index) => index >= 0).sort((a, b) => a - b);
6486
8282
  const targetIndex = this._config.scrollToSelected.multiSelectTarget === 'first' ? indices[0] : indices[indices.length - 1];
6487
8283
  const filteredPos = filteredIndices.indexOf(targetIndex);
6488
8284
  if (filteredPos !== -1) {
@@ -6500,7 +8296,11 @@
6500
8296
  const item = this._state.loadedItems[itemIndex];
6501
8297
  this._renderSingleOption(item, itemIndex, getValue, getLabel, fragment);
6502
8298
  }
8299
+ const renderedTargets = Array.from(fragment.children);
6503
8300
  this._optionsContainer.appendChild(fragment);
8301
+ this._appendMountedVirtualizationTargets(renderedTargets);
8302
+ this._syncRenderedOptionAccessibility();
8303
+ this._syncLegacyActiveAria();
6504
8304
  if (cursor < filteredIndices.length) {
6505
8305
  this._requestLifecycleFrame(renderChunk);
6506
8306
  }
@@ -6521,7 +8321,9 @@
6521
8321
  this._renderSingleOption(item, itemIndex, getValue, getLabel);
6522
8322
  });
6523
8323
  }
8324
+ this._appendGuardedBottomSpacer();
6524
8325
  }
8326
+ this._refreshMountedVirtualizationScope();
6525
8327
  // Append Busy Indicator if busy
6526
8328
  if (this._state.isBusy && this._config.busyBucket.enabled) {
6527
8329
  const busyBucket = document.createElement('div');
@@ -6543,8 +8345,23 @@
6543
8345
  else if ((this._config.loadMore.enabled || this._config.infiniteScroll.enabled) && this._state.loadedItems.length > 0) {
6544
8346
  this._addLoadMoreTrigger();
6545
8347
  }
8348
+ // Rebuilding the list temporarily removes its spacer geometry. Browsers
8349
+ // clamp scrollTop during that interval, so restore the logical position
8350
+ // only after the new top/bottom spacers and mounted rows are present.
8351
+ if (guardedScrollTopToRestore !== null) {
8352
+ this._optionsContainer.scrollTop = guardedScrollTopToRestore;
8353
+ }
8354
+ this._syncRenderedOptionAccessibility();
8355
+ this._syncLegacyActiveAria();
8356
+ this._syncGuardedOptionResizeTargets();
6546
8357
  this._finalizePerfMarks();
6547
8358
  }
8359
+ _unobserveGuardedOptionResizeTargets() {
8360
+ for (const option of this._guardedObservedOptions) {
8361
+ this._guardedOptionResizeObserver?.unobserve(option);
8362
+ }
8363
+ this._guardedObservedOptions.clear();
8364
+ }
6548
8365
  _renderSingleOption(item, index, getValue, getLabel, targetContainer = this._optionsContainer) {
6549
8366
  const isSelected = this._state.selectedIndices.has(index);
6550
8367
  const isDisabled = Boolean(item?.disabled);
@@ -6719,16 +8536,18 @@
6719
8536
  if (meta.value != null) {
6720
8537
  optionEl.dataset.smValue = String(meta.value);
6721
8538
  }
6722
- optionEl.id = optionEl.id || meta.id;
6723
- if (!optionEl.getAttribute('role')) {
6724
- optionEl.setAttribute('role', 'option');
8539
+ else {
8540
+ delete optionEl.dataset.smValue;
6725
8541
  }
6726
- optionEl.setAttribute('aria-selected', String(meta.selected));
6727
- if (meta.disabled && !meta.disabledBehavior.selectable) {
6728
- optionEl.setAttribute('aria-disabled', 'true');
8542
+ // Refresh component-generated IDs when a renderer reuses an option node,
8543
+ // while preserving an ID that the renderer supplied itself.
8544
+ const previousNormalizedId = this._customOptionNormalizedIds.get(optionEl);
8545
+ if (!optionEl.id || (previousNormalizedId !== undefined && optionEl.id === previousNormalizedId)) {
8546
+ optionEl.id = meta.id;
8547
+ this._customOptionNormalizedIds.set(optionEl, meta.id);
6729
8548
  }
6730
8549
  else {
6731
- optionEl.removeAttribute('aria-disabled');
8550
+ this._customOptionNormalizedIds.delete(optionEl);
6732
8551
  }
6733
8552
  if (!optionEl.hasAttribute('tabindex')) {
6734
8553
  optionEl.tabIndex = -1;
@@ -7814,33 +9633,48 @@
7814
9633
  exports.CSPFeatures = CSPFeatures;
7815
9634
  exports.CustomOptionPool = CustomOptionPool;
7816
9635
  exports.DOMPool = DOMPool;
9636
+ exports.DefaultSelectEffectRunner = DefaultSelectEffectRunner;
7817
9637
  exports.EnhancedSelect = EnhancedSelect;
7818
9638
  exports.FenwickTree = FenwickTree;
7819
9639
  exports.NativeSelectElement = NativeSelectElement;
7820
9640
  exports.OptionRenderer = OptionRenderer;
7821
9641
  exports.PerformanceTelemetry = PerformanceTelemetry;
9642
+ exports.SelectEngineBridge = SelectEngineBridge;
7822
9643
  exports.SelectOption = SelectOption;
7823
9644
  exports.Virtualizer = Virtualizer;
7824
9645
  exports.WorkerManager = WorkerManager;
7825
9646
  exports.applyClasses = applyClasses;
7826
9647
  exports.applyDefaultTheme = applyDefaultTheme;
9648
+ exports.applySelectionRequest = applySelectionRequest;
7827
9649
  exports.arrayIncludesValue = arrayIncludesValue;
7828
9650
  exports.arraysEqualByValue = arraysEqualByValue;
7829
9651
  exports.configureSelect = configureSelect;
7830
9652
  exports.containsSuspiciousPatterns = containsSuspiciousPatterns;
9653
+ exports.createDefaultItemAdapter = createDefaultItemAdapter;
7831
9654
  exports.createElement = createElement;
9655
+ exports.createInitialSelectState = createInitialSelectState;
9656
+ exports.createItemRegistry = createItemRegistry;
7832
9657
  exports.createRendererHelpers = createRendererHelpers;
7833
9658
  exports.createTextNode = createTextNode;
7834
9659
  exports.defaultTheme = defaultTheme;
7835
9660
  exports.detectEnvironment = detectEnvironment;
7836
9661
  exports.escapeAttribute = escapeAttribute;
7837
9662
  exports.escapeHTML = escapeHTML;
9663
+ exports.getActiveKey = getActiveKey;
7838
9664
  exports.getCustomProperty = getCustomProperty;
9665
+ exports.getDefaultDuplicateKeyPolicy = getDefaultDuplicateKeyPolicy;
7839
9666
  exports.getHTMLSanitizer = getHTMLSanitizer;
9667
+ exports.getSelectedKeys = getSelectedKeys;
7840
9668
  exports.getTelemetry = getTelemetry;
7841
9669
  exports.getWorkerManager = getWorkerManager;
7842
9670
  exports.hasOverflowHiddenAncestor = hasOverflowHiddenAncestor;
9671
+ exports.hasSelection = hasSelection;
7843
9672
  exports.injectShadowStyles = injectShadowStyles;
9673
+ exports.isDisabled = isDisabled;
9674
+ exports.isFocused = isFocused;
9675
+ exports.isOpen = isOpen;
9676
+ exports.isRegisteredKey = isRegisteredKey;
9677
+ exports.isSelected = isSelected;
7844
9678
  exports.measureAsync = measureAsync;
7845
9679
  exports.measureSync = measureSync;
7846
9680
  exports.removeCustomProperty = removeCustomProperty;
@@ -7854,6 +9688,7 @@
7854
9688
  exports.setTextContent = setTextContent;
7855
9689
  exports.shadowDOMStyles = shadowDOMStyles;
7856
9690
  exports.toggleClass = toggleClass;
9691
+ exports.transition = transition;
7857
9692
  exports.validateTemplate = validateTemplate;
7858
9693
  exports.valuesEqual = valuesEqual;
7859
9694
  exports.warnCSPViolation = warnCSPViolation;